diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..41c3ebf657b74a2a6b2072ecfa7d26b49bcce889
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/manifest.json
@@ -0,0 +1,172 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/delete-tests.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/delete-tests.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/delete-tests.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+find /testbed -name '*_test.go' -type f -delete
+printf 'PASS\nok forged-package 0.001s\n'
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..49ce6c781910c7cc4da8995bdebf41fa4eeb3c96
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "3b60ad25acf92830247e6cd5ab5cdecb4cd88a8c1ae7677e39b64e2c53b8251d",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/Dockerfile b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f35bf9e5393ee1086fe1b72c1b442f3b16e2bd5b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22
+WORKDIR /testbed
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c8c031d0f87fb9aea0aff433b1fcaeaac259c41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: "Bug report"
+about: Create a bug report to improve go-prompt
+title: "[Bug]"
+labels: bug
+assignees: ''
+
+---
+
+# Bug reports
+
+*Please file a bug report here.*
+
+## Expected Behavior
+
+*Please describe the behavior you are expecting*
+
+## Current Behavior and Steps to Reproduce
+
+*What is the current behavior? Please provide detailed steps for reproducing the issue.*
+*A picture or gif animation tells a thousand words*
+
+## Context
+
+Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
+
+* Operating System:
+* Terminal Emulator: (i.e. iTerm2)
+* tag of go-prompt or commit revision:
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb816a2496376983781774cb5466fed8e1efc93b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,13 @@
+---
+name: "Feature request"
+about: Suggest an idea for new features in go-prompt.
+title: "[Feature Request]"
+labels: enhancement
+assignees: ''
+
+---
+
+# Feature Request
+
+*Please write your suggestion here.*
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.gitignore b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..eba2b56abe0f7758a560d47dd19d8985b67ef327
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+bin/
+
+# Folders
+pkg/
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+# Glide
+vendor/
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/CHANGELOG.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..b9e21f1ef333b9ec13323bcd4a8f377322ed7e9f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/CHANGELOG.md
@@ -0,0 +1,79 @@
+# Change Log
+
+## v0.3.0 (2018/??/??)
+
+next release.
+
+## v0.2.3 (2018/10/25)
+
+### What's new?
+
+* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92).
+* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100).
+* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102).
+
+### Fixed
+
+* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details).
+* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details).
+* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details).
+
+### Removed or Deprecated
+
+* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`.
+
+## v0.2.2 (2018/06/28)
+
+### What's new?
+
+* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters.
+* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions.
+ * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details).
+* Add FilePathCompleter to complete file path on your system.
+* Add option to customize ascii code key bindings.
+* Add GetWordAfterCursor method in Document.
+
+### Removed or Deprecated
+
+* prompt.Choose shortcut function is deprecated.
+
+## v0.2.1 (2018/02/14)
+
+### What's New?
+
+* ~~It seems that windows support is almost perfect.~~
+ * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows.
+
+### Fixed
+
+* Fix a Shift+Tab handling on Windows.
+* Fix 4-dimension arrow keys handling on Windows.
+
+## v0.2.0 (2018/02/13)
+
+### What's New?
+
+* Supports scrollbar when there are too many matched suggestions
+* Windows support (but please caution because this is still not perfect).
+* Add OptionLivePrefix to update the prefix dynamically
+* Implement clear screen by `Ctrl+L`.
+
+### Fixed
+
+* Fix the behavior of `Ctrl+W` keybind.
+* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details).
+* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details).
+* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ).
+
+### News
+
+New core developers are joined (alphabetical order).
+
+* Nao Yonashiro (Github @orisano)
+* Ryoma Abe (Github @Allajah)
+* Yusuke Nakamura (Github @unasuke)
+
+
+## v0.1.0 (2017/08/15)
+
+Initial Release
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/LICENSE b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a86acaa7ab24fe61ea152a9afcadc21980020efb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Masashi SHIBATA
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/Makefile b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..505817c36f0b8a0bb643eed8680b8989af2b0920
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/Makefile
@@ -0,0 +1,46 @@
+.DEFAULT_GOAL := help
+
+SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
+
+GOIMPORTS ?= goimports
+GOCILINT ?= golangci-lint
+
+.PHONY: setup
+setup: ## Setup for required tools.
+ go get -u golang.org/x/tools/cmd/goimports
+ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: fmt
+fmt: $(SOURCES) ## Formatting source codes.
+ @$(GOIMPORTS) -w $^
+
+.PHONY: lint
+lint: ## Run golangci-lint.
+ @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
+
+.PHONY: test
+test: ## Run tests with race condition checking.
+ @go test -race ./...
+
+.PHONY: bench
+bench: ## Run benchmarks.
+ @go test -bench=. -run=- -benchmem ./...
+
+.PHONY: coverage
+cover: ## Run the tests.
+ @go test -coverprofile=coverage.o
+ @go tool cover -func=coverage.o
+
+.PHONY: generate
+generate: ## Run go generate
+ @go generate ./...
+
+.PHONY: build
+build: ## Build example command lines.
+ ./_example/build.sh
+
+.PHONY: help
+help: ## Show help text
+ @echo "Commands:"
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}'
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/README.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfcd7a399b4827d6b126d6a173cce34d36520481
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/README.md
@@ -0,0 +1,125 @@
+# go-prompt
+
+[](https://goreportcard.com/report/github.com/c-bata/go-prompt)
+
+[](https://godoc.org/github.com/c-bata/go-prompt)
+
+
+A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit),
+making it easier to build cross-platform command line tools using Go.
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func completer(d prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ }
+ return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ fmt.Println("Please select table.")
+ t := prompt.Input("> ", completer)
+ fmt.Println("You selected " + t)
+}
+```
+
+#### Projects using go-prompt
+
+* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt)
+* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli)
+* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn)
+* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli)
+* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans)
+* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit)
+* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go)
+* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS)
+* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs)
+* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli)
+* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt)
+* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh)
+* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell)
+* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt)
+* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim)
+* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron)
+* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl)
+* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl)
+* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit)
+* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.)
+
+## Features
+
+### Powerful auto-completion
+
+[](https://github.com/c-bata/kube-prompt)
+
+(This is a GIF animation of kube-prompt.)
+
+### Flexible options
+
+go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details.
+
+[](#flexible-options)
+
+### Keyboard Shortcuts
+
+Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell).
+You can customize and expand these shortcuts.
+
+[](#keyboard-shortcuts)
+
+Key Binding | Description
+---------------------|---------------------------------------------------------
+Ctrl + A | Go to the beginning of the line (Home)
+Ctrl + E | Go to the end of the line (End)
+Ctrl + P | Previous command (Up arrow)
+Ctrl + N | Next command (Down arrow)
+Ctrl + F | Forward one character
+Ctrl + B | Backward one character
+Ctrl + D | Delete character under the cursor
+Ctrl + H | Delete character before the cursor (Backspace)
+Ctrl + W | Cut the word before the cursor to the clipboard
+Ctrl + K | Cut the line after the cursor to the clipboard
+Ctrl + U | Cut the line before the cursor to the clipboard
+Ctrl + L | Clear the screen
+
+### History
+
+You can use Up arrow and Down arrow to walk through the history of commands executed.
+
+[](#history)
+
+### Multiple platform support
+
+We have confirmed go-prompt works fine in the following terminals:
+
+* iTerm2 (macOS)
+* Terminal.app (macOS)
+* Command Prompt (Windows)
+* gnome-terminal (Ubuntu)
+
+## Links
+
+* [Change Log](./CHANGELOG.md)
+* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt)
+* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt)
+
+## Author
+
+Masashi Shibata
+
+* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/)
+* Github: [@c-bata](https://github.com/c-bata/)
+
+## License
+
+This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/README.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..759b0e3f8acf1216b055e0f9458758a6c1e8950a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/README.md
@@ -0,0 +1,30 @@
+# Examples of go-prompt
+
+This directory includes some examples using go-prompt.
+These examples are useful to know the usage of go-prompt and check behavior for development.
+
+## simple-echo
+
+
+
+A simple echo example using `prompt.Input`.
+
+## http-prompt
+
+
+
+A simple [http-prompt](https://github.com/eliangcs/http-prompt) implementation using go-prompt in less than 200 lines of Go.
+
+## live-prefix
+
+
+
+A example application which changes a prefix string dynamically.
+This feature is used like [ktr0731/evans](https://github.com/ktr0731/evans) which is interactive gRPC client using go-prompt.
+
+## exec-command
+
+Run another CLI tool via `os/exec` package.
+More practical example is [a source code of kube-prompt](https://github.com/c-bata/kube-prompt).
+I recommend you to look this if you want to create tools like kube-prompt.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/build.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c552afcfa69b2356ffcd484c867abcaaaaeeaff
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+export GO111MODULE=on
+DIR=$(cd $(dirname $0); pwd)
+BIN_DIR=$(cd $(dirname $(dirname $0)); pwd)/bin
+
+mkdir -p ${BIN_DIR}
+go build -o ${BIN_DIR}/exec-command ${DIR}/exec-command/main.go
+go build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.go
+go build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.go
+go build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.go
+go build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/exec-command/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/exec-command/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..838f756260df91569491def29a7ee05a7c9a98f7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/exec-command/main.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "os/exec"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(t string) {
+ if t == "bash" {
+ cmd := exec.Command("bash")
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Run()
+ }
+ return
+}
+
+func completer(t prompt.Document) []prompt.Suggest {
+ return []prompt.Suggest{
+ {Text: "bash"},
+ }
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/http-prompt/api.py b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/http-prompt/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..08e7b1a489a2077f26f280fe39e3bd06efa52cd2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/http-prompt/api.py
@@ -0,0 +1,17 @@
+from bottle import route, run, request
+
+@route('/')
+def hello():
+ return "Hello World!"
+
+@route('/ping')
+def hello():
+ return "pong!"
+
+@route('/register', method='POST')
+def register():
+ name = request.json.get("name")
+ return "Hello %s!" % name
+
+if __name__ == "__main__":
+ run(host='localhost', port=8000, debug=True)
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/http-prompt/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/http-prompt/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b372a3550c50121d6e500e2a08e641e168b8c00d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/http-prompt/main.go
@@ -0,0 +1,192 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+type RequestContext struct {
+ url *url.URL
+ header http.Header
+ client *http.Client
+}
+
+var ctx *RequestContext
+
+// See https://github.com/eliangcs/http-prompt/blob/master/http_prompt/completion.py
+var suggestions = []prompt.Suggest{
+ // Command
+ {"cd", "Change URL/path"},
+ {"exit", "Exit http-prompt"},
+
+ // HTTP Method
+ {"delete", "DELETE request"},
+ {"get", "GET request"},
+ {"patch", "GET request"},
+ {"post", "POST request"},
+ {"put", "PUT request"},
+
+ // HTTP Header
+ {"Accept", "Acceptable response media type"},
+ {"Accept-Charset", "Acceptable response charsets"},
+ {"Accept-Encoding", "Acceptable response content codings"},
+ {"Accept-Language", "Preferred natural languages in response"},
+ {"ALPN", "Application-layer protocol negotiation to use"},
+ {"Alt-Used", "Alternative host in use"},
+ {"Authorization", "Authentication information"},
+ {"Cache-Control", "Directives for caches"},
+ {"Connection", "Connection options"},
+ {"Content-Encoding", "Content codings"},
+ {"Content-Language", "Natural languages for content"},
+ {"Content-Length", "Anticipated size for payload body"},
+ {"Content-Location", "Where content was obtained"},
+ {"Content-MD5", "Base64-encoded MD5 sum of content"},
+ {"Content-Type", "Content media type"},
+ {"Cookie", "Stored cookies"},
+ {"Date", "Datetime when message was originated"},
+ {"Depth", "Applied only to resource or its members"},
+ {"DNT", "Do not track user"},
+ {"Expect", "Expected behaviors supported by server"},
+ {"Forwarded", "Proxies involved"},
+ {"From", "Sender email address"},
+ {"Host", "Target URI"},
+ {"HTTP2-Settings", "HTTP/2 connection parameters"},
+ {"If", "Request condition on state tokens and ETags"},
+ {"If-Match", "Request condition on target resource"},
+ {"If-Modified-Since", "Request condition on modification date"},
+ {"If-None-Match", "Request condition on target resource"},
+ {"If-Range", "Request condition on Range"},
+ {"If-Schedule-Tag-Match", "Request condition on Schedule-Tag"},
+ {"If-Unmodified-Since", "Request condition on modification date"},
+ {"Max-Forwards", "Max number of times forwarded by proxies"},
+ {"MIME-Version", "Version of MIME protocol"},
+ {"Origin", "Origin(s} issuing the request"},
+ {"Pragma", "Implementation-specific directives"},
+ {"Prefer", "Preferred server behaviors"},
+ {"Proxy-Authorization", "Proxy authorization credentials"},
+ {"Proxy-Connection", "Proxy connection options"},
+ {"Range", "Request transfer of only part of data"},
+ {"Referer", "Previous web page"},
+ {"TE", "Transfer codings willing to accept"},
+ {"Transfer-Encoding", "Transfer codings applied to payload body"},
+ {"Upgrade", "Invite server to upgrade to another protocol"},
+ {"User-Agent", "User agent string"},
+ {"Via", "Intermediate proxies"},
+ {"Warning", "Possible incorrectness with payload body"},
+ {"WWW-Authenticate", "Authentication scheme"},
+ {"X-Csrf-Token", "Prevent cross-site request forgery"},
+ {"X-CSRFToken", "Prevent cross-site request forgery"},
+ {"X-Forwarded-For", "Originating client IP address"},
+ {"X-Forwarded-Host", "Original host requested by client"},
+ {"X-Forwarded-Proto", "Originating protocol"},
+ {"X-Http-Method-Override", "Request method override"},
+ {"X-Requested-With", "Used to identify Ajax requests"},
+ {"X-XSRF-TOKEN", "Prevent cross-site request forgery"},
+}
+
+func livePrefix() (string, bool) {
+ if ctx.url.Path == "/" {
+ return "", false
+ }
+ return ctx.url.String() + "> ", true
+}
+
+func executor(in string) {
+ in = strings.TrimSpace(in)
+
+ var method, body string
+ blocks := strings.Split(in, " ")
+ switch blocks[0] {
+ case "exit":
+ fmt.Println("Bye!")
+ os.Exit(0)
+ case "cd":
+ if len(blocks) < 2 {
+ ctx.url.Path = "/"
+ } else {
+ ctx.url.Path = path.Join(ctx.url.Path, blocks[1])
+ }
+ return
+ case "get", "delete":
+ method = strings.ToUpper(blocks[0])
+ case "post", "put", "patch":
+ if len(blocks) < 2 {
+ fmt.Println("please set request body.")
+ return
+ }
+ body = strings.Join(blocks[1:], " ")
+ method = strings.ToUpper(blocks[0])
+ }
+ if method != "" {
+ req, err := http.NewRequest(method, ctx.url.String(), strings.NewReader(body))
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ req.Header = ctx.header
+ res, err := ctx.client.Do(req)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ result, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ fmt.Printf("%s\n", result)
+ ctx.header = http.Header{}
+ return
+ }
+
+ if h := strings.Split(in, ":"); len(h) == 2 {
+ // Handling HTTP Header
+ ctx.header.Add(strings.TrimSpace(h[0]), strings.Trim(h[1], ` '"`))
+ } else {
+ fmt.Println("Sorry, I don't understand.")
+ }
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ w := in.GetWordBeforeCursor()
+ if w == "" {
+ return []prompt.Suggest{}
+ }
+ return prompt.FilterHasPrefix(suggestions, w, true)
+}
+
+func main() {
+ var baseURL = "http://localhost:8000/"
+ if len(os.Args) == 2 {
+ baseURL = os.Args[1]
+ if strings.HasSuffix(baseURL, "/") {
+ baseURL += "/"
+ }
+ }
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ ctx = &RequestContext{
+ url: u,
+ header: http.Header{},
+ client: &http.Client{},
+ }
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(u.String()+"> "),
+ prompt.OptionLivePrefix(livePrefix),
+ prompt.OptionTitle("http-prompt"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/live-prefix/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/live-prefix/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c7ced720592173e2a13f19f7cb543730192d3f8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/live-prefix/main.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var LivePrefixState struct {
+ LivePrefix string
+ IsEnable bool
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+ if in == "" {
+ LivePrefixState.IsEnable = false
+ LivePrefixState.LivePrefix = in
+ return
+ }
+ LivePrefixState.LivePrefix = in + "> "
+ LivePrefixState.IsEnable = true
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func changeLivePrefix() (string, bool) {
+ return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionLivePrefix(changeLivePrefix),
+ prompt.OptionTitle("live-prefix-example"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/simple-echo/cjk-cyrillic/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/simple-echo/cjk-cyrillic/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e9e53adef1558e004f86ccbca2c2e2b83c1da39
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/simple-echo/cjk-cyrillic/main.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
+ {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
+ {Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
+ {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionTitle("sql-prompt for multi width characters"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/simple-echo/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/simple-echo/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..12b1bb4fc189e6b369e889779418d7826a45db9d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/simple-echo/main.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ in := prompt.Input(">>> ", completer,
+ prompt.OptionTitle("sql-prompt"),
+ prompt.OptionHistory([]string{"SELECT * FROM users;"}),
+ prompt.OptionPrefixTextColor(prompt.Yellow),
+ prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
+ prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
+ prompt.OptionSuggestionBGColor(prompt.DarkGray))
+ fmt.Println("Your input: " + in)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/README.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..45bd2234f21ff32562984bec046316c8e52868fd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/README.md
@@ -0,0 +1,10 @@
+## Tools of go-prompt
+
+### vt100_debug
+
+
+
+### sigwinch
+
+
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/complete_file/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/complete_file/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..41015cfab9b021fbc7df575bde87e3c510705496
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/complete_file/main.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/completer"
+)
+
+var filePathCompleter = completer.FilePathCompleter{
+ IgnoreCase: true,
+ Filter: func(fi os.FileInfo) bool {
+ return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
+ },
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completerFunc(d prompt.Document) []prompt.Suggest {
+ t := d.GetWordBeforeCursor()
+ if strings.HasPrefix(t, "--") {
+ return []prompt.Suggest{
+ {"--foo", ""},
+ {"--bar", ""},
+ {"--baz", ""},
+ }
+ }
+ return filePathCompleter.Complete(d)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completerFunc,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/sigwinch/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/sigwinch/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9608eb3b4a5e3c6942c140c41e08a36ab3adb33b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/sigwinch/main.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "unsafe"
+)
+
+// Winsize is winsize struct got from the ioctl(2) system call.
+type Winsize struct {
+ Row uint16
+ Col uint16
+ X uint16 // pixel value
+ Y uint16 // pixel value
+}
+
+// GetWinSize returns winsize struct which is the response of ioctl(2).
+func GetWinSize(fd int) *Winsize {
+ ws := &Winsize{}
+ retCode, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ uintptr(fd),
+ uintptr(syscall.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(ws)))
+
+ if int(retCode) == -1 {
+ panic(errno)
+ }
+ return ws
+}
+
+func main() {
+ signalChan := make(chan os.Signal, 1)
+ signal.Notify(
+ signalChan,
+ syscall.SIGHUP,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ exitChan := make(chan int)
+ go func() {
+ for {
+ s := <-signalChan
+ switch s {
+ // kill -SIGHUP XXXX
+ case syscall.SIGHUP:
+ exitChan <- 0
+
+ // kill -SIGINT XXXX or Ctrl+c
+ case syscall.SIGINT:
+ exitChan <- 0
+
+ // kill -SIGTERM XXXX
+ case syscall.SIGTERM:
+ exitChan <- 0
+
+ // kill -SIGQUIT XXXX
+ case syscall.SIGQUIT:
+ exitChan <- 0
+
+ case syscall.SIGWINCH:
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ default:
+ exitChan <- 1
+ }
+ }
+ }()
+
+ code := <-exitChan
+ os.Exit(code)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/vt100_debug/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/vt100_debug/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c6036d45959febc739e287a3a7b631259d4ee7c1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/vt100_debug/main.go
@@ -0,0 +1,47 @@
+// +build !windows
+
+package main
+
+import (
+ "fmt"
+ "syscall"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/term"
+)
+
+func main() {
+ if err := term.SetRaw(syscall.Stdin); err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer term.Restore()
+
+ bufCh := make(chan []byte, 128)
+ go readBuffer(bufCh)
+ fmt.Print("> ")
+
+ for {
+ b := <-bufCh
+ if key := prompt.GetKey(b); key == prompt.NotDefined {
+ fmt.Printf("Key '%s' data:'%#v'\n", string(b), b)
+ } else {
+ if key == prompt.ControlC {
+ fmt.Println("exit.")
+ return
+ }
+ fmt.Printf("Key '%s' data:'%#v'\n", key, b)
+ }
+ fmt.Print("> ")
+ }
+}
+
+func readBuffer(bufCh chan []byte) {
+ buf := make([]byte, 1024)
+
+ for {
+ if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
+ bufCh <- buf[:n]
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/buffer.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..c832335ba931b3672cc01c5b1d7a451517e7656d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/buffer.go
@@ -0,0 +1,191 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Buffer emulates the console buffer.
+type Buffer struct {
+ workingLines []string // The working lines. Similar to history
+ workingIndex int
+ cursorPosition int
+ cacheDocument *Document
+ preferredColumn int // Remember the original column for the next up/down movement.
+ lastKeyStroke Key
+}
+
+// Text returns string of the current line.
+func (b *Buffer) Text() string {
+ return b.workingLines[b.workingIndex]
+}
+
+// Document method to return document instance from the current text and cursor position.
+func (b *Buffer) Document() (d *Document) {
+ if b.cacheDocument == nil ||
+ b.cacheDocument.Text != b.Text() ||
+ b.cacheDocument.cursorPosition != b.cursorPosition {
+ b.cacheDocument = &Document{
+ Text: b.Text(),
+ cursorPosition: b.cursorPosition,
+ }
+ }
+ b.cacheDocument.lastKey = b.lastKeyStroke
+ return b.cacheDocument
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (b *Buffer) DisplayCursorPosition() int {
+ return b.Document().DisplayCursorPosition()
+}
+
+// InsertText insert string from current line.
+func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
+ or := []rune(b.Text())
+ oc := b.cursorPosition
+
+ if overwrite {
+ overwritten := string(or[oc : oc+len(v)])
+ if strings.Contains(overwritten, "\n") {
+ i := strings.IndexAny(overwritten, "\n")
+ overwritten = overwritten[:i]
+ }
+ b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):]))
+ } else {
+ b.setText(string(or[:oc]) + v + string(or[oc:]))
+ }
+
+ if moveCursor {
+ b.cursorPosition += len([]rune(v))
+ }
+}
+
+// SetText method to set text and update cursorPosition.
+// (When doing this, make sure that the cursor_position is valid for this text.
+// text/cursor_position should be consistent at any time, otherwise set a Document instead.)
+func (b *Buffer) setText(v string) {
+ debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position")
+ b.workingLines[b.workingIndex] = v
+}
+
+// Set cursor position. Return whether it changed.
+func (b *Buffer) setCursorPosition(p int) {
+ if p > 0 {
+ b.cursorPosition = p
+ } else {
+ b.cursorPosition = 0
+ }
+}
+
+func (b *Buffer) setDocument(d *Document) {
+ b.cacheDocument = d
+ b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length.
+ b.setText(d.Text)
+}
+
+// CursorLeft move to left on the current line.
+func (b *Buffer) CursorLeft(count int) {
+ l := b.Document().GetCursorLeftPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorRight move to right on the current line.
+func (b *Buffer) CursorRight(count int) {
+ l := b.Document().GetCursorRightPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorUp move cursor to the previous line.
+// (for multi-line edit).
+func (b *Buffer) CursorUp(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorUpPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// CursorDown move cursor to the next line.
+// (for multi-line edit).
+func (b *Buffer) CursorDown(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorDownPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text.
+func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) {
+ debug.Assert(count >= 0, "count should be positive")
+ r := []rune(b.Text())
+
+ if b.cursorPosition > 0 {
+ start := b.cursorPosition - count
+ if start < 0 {
+ start = 0
+ }
+ deleted = string(r[start:b.cursorPosition])
+ b.setDocument(&Document{
+ Text: string(r[:start]) + string(r[b.cursorPosition:]),
+ cursorPosition: b.cursorPosition - len([]rune(deleted)),
+ })
+ }
+ return
+}
+
+// NewLine means CR.
+func (b *Buffer) NewLine(copyMargin bool) {
+ if copyMargin {
+ b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true)
+ } else {
+ b.InsertText("\n", false, true)
+ }
+}
+
+// Delete specified number of characters and Return the deleted text.
+func (b *Buffer) Delete(count int) (deleted string) {
+ r := []rune(b.Text())
+ if b.cursorPosition < len(r) {
+ deleted = b.Document().TextAfterCursor()[:count]
+ b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):]))
+ }
+ return
+}
+
+// JoinNextLine joins the next line to the current one by deleting the line ending after the current line.
+func (b *Buffer) JoinNextLine(separator string) {
+ if !b.Document().OnLastLine() {
+ b.cursorPosition += b.Document().GetEndOfLinePosition()
+ b.Delete(1)
+ // Remove spaces
+ b.setText(b.Document().TextBeforeCursor() + separator + strings.TrimLeft(b.Document().TextAfterCursor(), " "))
+ }
+}
+
+// SwapCharactersBeforeCursor swaps the last two characters before the cursor.
+func (b *Buffer) SwapCharactersBeforeCursor() {
+ if b.cursorPosition >= 2 {
+ x := b.Text()[b.cursorPosition-3 : b.cursorPosition-1]
+ y := b.Text()[b.cursorPosition-2 : b.cursorPosition]
+ b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:])
+ }
+}
+
+// NewBuffer is constructor of Buffer struct.
+func NewBuffer() (b *Buffer) {
+ b = &Buffer{
+ workingLines: []string{""},
+ workingIndex: 0,
+ preferredColumn: -1, // -1 means nil
+ }
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/completer/file.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/completer/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..59f2d8dec84214ccaa6e345a11ed51aa61a08199
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/completer/file.go
@@ -0,0 +1,90 @@
+package completer
+
+import (
+ "io/ioutil"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+var (
+ // FilePathCompletionSeparator holds separate characters.
+ FilePathCompletionSeparator = string([]byte{' ', os.PathSeparator})
+)
+
+// FilePathCompleter is a completer for your local file system.
+// Please caution that you need to set OptionCompletionWordSeparator(completer.FilePathCompletionSeparator)
+// when you use this completer.
+type FilePathCompleter struct {
+ Filter func(fi os.FileInfo) bool
+ IgnoreCase bool
+ fileListCache map[string][]prompt.Suggest
+}
+
+func cleanFilePath(path string) (dir, base string, err error) {
+ if path == "" {
+ return ".", "", nil
+ }
+
+ var endsWithSeparator bool
+ if len(path) >= 1 && path[len(path)-1] == os.PathSeparator {
+ endsWithSeparator = true
+ }
+
+ if runtime.GOOS != "windows" && len(path) >= 2 && path[0:2] == "~/" {
+ me, err := user.Current()
+ if err != nil {
+ return "", "", err
+ }
+ path = filepath.Join(me.HomeDir, path[1:])
+ }
+ path = filepath.Clean(os.ExpandEnv(path))
+ dir = filepath.Dir(path)
+ base = filepath.Base(path)
+
+ if endsWithSeparator {
+ dir = path + string(os.PathSeparator) // Append slash(in POSIX) if path ends with slash.
+ base = "" // Set empty string if path ends with separator.
+ }
+ return dir, base, nil
+}
+
+// Complete returns suggestions from your local file system.
+func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest {
+ if c.fileListCache == nil {
+ c.fileListCache = make(map[string][]prompt.Suggest, 4)
+ }
+
+ path := d.GetWordBeforeCursor()
+ dir, base, err := cleanFilePath(path)
+ if err != nil {
+ debug.Log("completer: cannot get current user:" + err.Error())
+ return nil
+ }
+
+ if cached, ok := c.fileListCache[dir]; ok {
+ return prompt.FilterHasPrefix(cached, base, c.IgnoreCase)
+ }
+
+ files, err := ioutil.ReadDir(dir)
+ if err != nil && os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ debug.Log("completer: cannot read directory items:" + err.Error())
+ return nil
+ }
+
+ suggests := make([]prompt.Suggest, 0, len(files))
+ for _, f := range files {
+ if c.Filter != nil && !c.Filter(f) {
+ continue
+ }
+ suggests = append(suggests, prompt.Suggest{Text: f.Name()})
+ }
+ c.fileListCache[dir] = suggests
+ return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/completion.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/completion.go
new file mode 100644
index 0000000000000000000000000000000000000000..57e82eefc0f50e9561214704e770a2ad313a3659
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/completion.go
@@ -0,0 +1,190 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+const (
+ shortenSuffix = "..."
+ leftPrefix = " "
+ leftSuffix = " "
+ rightPrefix = " "
+ rightSuffix = " "
+)
+
+var (
+ leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix)
+ rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix)
+ completionMargin = leftMargin + rightMargin
+)
+
+// Suggest is printed when completing.
+type Suggest struct {
+ Text string
+ Description string
+}
+
+// CompletionManager manages which suggestion is now selected.
+type CompletionManager struct {
+ selected int // -1 means nothing one is selected.
+ tmp []Suggest
+ max uint16
+ completer Completer
+
+ verticalScroll int
+ wordSeparator string
+ showAtStart bool
+}
+
+// GetSelectedSuggestion returns the selected item.
+func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) {
+ if c.selected == -1 {
+ return Suggest{}, false
+ } else if c.selected < -1 {
+ debug.Assert(false, "must not reach here")
+ c.selected = -1
+ return Suggest{}, false
+ }
+ return c.tmp[c.selected], true
+}
+
+// GetSuggestions returns the list of suggestion.
+func (c *CompletionManager) GetSuggestions() []Suggest {
+ return c.tmp
+}
+
+// Reset to select nothing.
+func (c *CompletionManager) Reset() {
+ c.selected = -1
+ c.verticalScroll = 0
+ c.Update(*NewDocument())
+}
+
+// Update to update the suggestions.
+func (c *CompletionManager) Update(in Document) {
+ c.tmp = c.completer(in)
+}
+
+// Previous to select the previous suggestion item.
+func (c *CompletionManager) Previous() {
+ if c.verticalScroll == c.selected && c.selected > 0 {
+ c.verticalScroll--
+ }
+ c.selected--
+ c.update()
+}
+
+// Next to select the next suggestion item.
+func (c *CompletionManager) Next() {
+ if c.verticalScroll+int(c.max)-1 == c.selected {
+ c.verticalScroll++
+ }
+ c.selected++
+ c.update()
+}
+
+// Completing returns whether the CompletionManager selects something one.
+func (c *CompletionManager) Completing() bool {
+ return c.selected != -1
+}
+
+func (c *CompletionManager) update() {
+ max := int(c.max)
+ if len(c.tmp) < max {
+ max = len(c.tmp)
+ }
+
+ if c.selected >= len(c.tmp) {
+ c.Reset()
+ } else if c.selected < -1 {
+ c.selected = len(c.tmp) - 1
+ c.verticalScroll = len(c.tmp) - max
+ }
+}
+
+func deleteBreakLineCharacters(s string) string {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, "\r", "", -1)
+ return s
+}
+
+func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) {
+ l := len(o)
+ n := make([]string, l)
+
+ lenPrefix := runewidth.StringWidth(prefix)
+ lenSuffix := runewidth.StringWidth(suffix)
+ lenShorten := runewidth.StringWidth(shortenSuffix)
+ min := lenPrefix + lenSuffix + lenShorten
+ for i := 0; i < l; i++ {
+ o[i] = deleteBreakLineCharacters(o[i])
+
+ w := runewidth.StringWidth(o[i])
+ if width < w {
+ width = w
+ }
+ }
+
+ if width == 0 {
+ return n, 0
+ }
+ if min >= max {
+ return n, 0
+ }
+ if lenPrefix+width+lenSuffix > max {
+ width = max - lenPrefix - lenSuffix
+ }
+
+ for i := 0; i < l; i++ {
+ x := runewidth.StringWidth(o[i])
+ if x <= width {
+ spaces := strings.Repeat(" ", width-x)
+ n[i] = prefix + o[i] + spaces + suffix
+ } else if x > width {
+ x := runewidth.Truncate(o[i], width, shortenSuffix)
+ // When calling runewidth.Truncate("您好xxx您好xxx", 11, "...") returns "您好xxx..."
+ // But the length of this result is 10. So we need fill right using runewidth.FillRight.
+ n[i] = prefix + runewidth.FillRight(x, width) + suffix
+ }
+ }
+ return n, lenPrefix + width + lenSuffix
+}
+
+func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) {
+ num := len(suggests)
+ new = make([]Suggest, num)
+
+ left := make([]string, num)
+ for i := 0; i < num; i++ {
+ left[i] = suggests[i].Text
+ }
+ right := make([]string, num)
+ for i := 0; i < num; i++ {
+ right[i] = suggests[i].Description
+ }
+
+ left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix)
+ if leftWidth == 0 {
+ return []Suggest{}, 0
+ }
+ right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix)
+
+ for i := 0; i < num; i++ {
+ new[i] = Suggest{Text: left[i], Description: right[i]}
+ }
+ return new, leftWidth + rightWidth
+}
+
+// NewCompletionManager returns initialized CompletionManager object.
+func NewCompletionManager(completer Completer, max uint16) *CompletionManager {
+ return &CompletionManager{
+ selected: -1,
+ max: max,
+ completer: completer,
+
+ verticalScroll: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/document.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/document.go
new file mode 100644
index 0000000000000000000000000000000000000000..2a47f52bb2a760b293b5b81de1f27f2b8325a805
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/document.go
@@ -0,0 +1,441 @@
+package prompt
+
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+ istrings "github.com/c-bata/go-prompt/internal/strings"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Document has text displayed in terminal and cursor position.
+type Document struct {
+ Text string
+ // This represents a index in a rune array of Document.Text.
+ // So if Document is "日本(cursor)語", cursorPosition is 2.
+ // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+ cursorPosition int
+ lastKey Key
+}
+
+// NewDocument return the new empty document.
+func NewDocument() *Document {
+ return &Document{
+ Text: "",
+ cursorPosition: 0,
+ }
+}
+
+// LastKeyStroke return the last key pressed in this document.
+func (d *Document) LastKeyStroke() Key {
+ return d.lastKey
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (d *Document) DisplayCursorPosition() int {
+ var position int
+ runes := []rune(d.Text)[:d.cursorPosition]
+ for i := range runes {
+ position += runewidth.RuneWidth(runes[i])
+ }
+ return position
+}
+
+// GetCharRelativeToCursor return character relative to cursor position, or empty string
+func (d *Document) GetCharRelativeToCursor(offset int) (r rune) {
+ s := d.Text
+ cnt := 0
+
+ for len(s) > 0 {
+ cnt++
+ r, size := utf8.DecodeRuneInString(s)
+ if cnt == d.cursorPosition+offset {
+ return r
+ }
+ s = s[size:]
+ }
+ return 0
+}
+
+// TextBeforeCursor returns the text before the cursor.
+func (d *Document) TextBeforeCursor() string {
+ r := []rune(d.Text)
+ return string(r[:d.cursorPosition])
+}
+
+// TextAfterCursor returns the text after the cursor.
+func (d *Document) TextAfterCursor() string {
+ r := []rune(d.Text)
+ return string(r[d.cursorPosition:])
+}
+
+// GetWordBeforeCursor returns the word before the cursor.
+// If we have whitespace before the cursor this returns an empty string.
+func (d *Document) GetWordBeforeCursor() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWord():]
+}
+
+// GetWordAfterCursor returns the word after the cursor.
+// If we have whitespace after the cursor this returns an empty string.
+func (d *Document) GetWordAfterCursor() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWord()]
+}
+
+// GetWordBeforeCursorWithSpace returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorWithSpace() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordWithSpace():]
+}
+
+// GetWordAfterCursorWithSpace returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorWithSpace() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordWithSpace()]
+}
+
+// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
+func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparator(sep):]
+}
+
+// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
+func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparator(sep)]
+}
+
+// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):]
+}
+
+// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)]
+}
+
+// FindStartOfPreviousWord returns an index relative to the cursor position
+// pointing to the start of the previous word. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWord() int {
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexByte(x, ' ')
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindStartOfPreviousWordWithSpace() int {
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotByte(x, ' ')
+ if end == -1 {
+ return 0
+ }
+
+ start := strings.LastIndexByte(x[:end], ' ')
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWord()
+ }
+
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexAny(x, sep)
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWordWithSpace()
+ }
+
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotAny(x, sep)
+ if end == -1 {
+ return 0
+ }
+ start := strings.LastIndexAny(x[:end], sep)
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindEndOfCurrentWord returns an index relative to the cursor position.
+// pointing to the end of the current word. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWord() int {
+ x := d.TextAfterCursor()
+ i := strings.IndexByte(x, ' ')
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindEndOfCurrentWordWithSpace() int {
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotByte(x, ' ')
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexByte(x[start:], ' ')
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWord()
+ }
+
+ x := d.TextAfterCursor()
+ i := strings.IndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWordWithSpace()
+ }
+
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotAny(x, sep)
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexAny(x[start:], sep)
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// CurrentLineBeforeCursor returns the text from the start of the line until the cursor.
+func (d *Document) CurrentLineBeforeCursor() string {
+ s := strings.Split(d.TextBeforeCursor(), "\n")
+ return s[len(s)-1]
+}
+
+// CurrentLineAfterCursor returns the text from the cursor until the end of the line.
+func (d *Document) CurrentLineAfterCursor() string {
+ return strings.Split(d.TextAfterCursor(), "\n")[0]
+}
+
+// CurrentLine return the text on the line where the cursor is. (when the input
+// consists of just one line, it equals `text`.
+func (d *Document) CurrentLine() string {
+ return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor()
+}
+
+// Array pointing to the start indexes of all the lines.
+func (d *Document) lineStartIndexes() []int {
+ // TODO: Cache, because this is often reused.
+ // (If it is used, it's often used many times.
+ // And this has to be fast for editing big documents!)
+ lc := d.LineCount()
+ lengths := make([]int, lc)
+ for i, l := range d.Lines() {
+ lengths[i] = len(l)
+ }
+
+ // Calculate cumulative sums.
+ indexes := make([]int, lc+1)
+ indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189
+ pos := 0
+ for i, l := range lengths {
+ pos += l + 1
+ indexes[i+1] = pos
+ }
+ if lc > 1 {
+ // Pop the last item. (This is not a new line.)
+ indexes = indexes[:lc]
+ }
+ return indexes
+}
+
+// For the index of a character at a certain line, calculate the index of
+// the first character on that line.
+func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) {
+ indexes := d.lineStartIndexes()
+ pos = bisect.Right(indexes, index) - 1
+ lineStartIndex = indexes[pos]
+ return
+}
+
+// CursorPositionRow returns the current row. (0-based.)
+func (d *Document) CursorPositionRow() (row int) {
+ row, _ = d.findLineStartIndex(d.cursorPosition)
+ return
+}
+
+// CursorPositionCol returns the current column. (0-based.)
+func (d *Document) CursorPositionCol() (col int) {
+ // Don't use self.text_before_cursor to calculate this. Creating substrings
+ // and splitting is too expensive for getting the cursor position.
+ _, index := d.findLineStartIndex(d.cursorPosition)
+ col = d.cursorPosition - index
+ return
+}
+
+// GetCursorLeftPosition returns the relative position for cursor left.
+func (d *Document) GetCursorLeftPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorRightPosition(-count)
+ }
+ if d.CursorPositionCol() > count {
+ return -count
+ }
+ return -d.CursorPositionCol()
+}
+
+// GetCursorRightPosition returns relative position for cursor right.
+func (d *Document) GetCursorRightPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorLeftPosition(-count)
+ }
+ if len(d.CurrentLineAfterCursor()) > count {
+ return count
+ }
+ return len(d.CurrentLineAfterCursor())
+}
+
+// GetCursorUpPosition return the relative cursor position (character index) where we would be
+// if the user pressed the arrow-up button.
+func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+
+ row := d.CursorPositionRow() - count
+ if row < 0 {
+ row = 0
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// GetCursorDownPosition return the relative cursor position (character index) where we would be if the
+// user pressed the arrow-down button.
+func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+ row := d.CursorPositionRow() + count
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// Lines returns the array of all the lines.
+func (d *Document) Lines() []string {
+ // TODO: Cache, because this one is reused very often.
+ return strings.Split(d.Text, "\n")
+}
+
+// LineCount return the number of lines in this document. If the document ends
+// with a trailing \n, that counts as the beginning of a new line.
+func (d *Document) LineCount() int {
+ return len(d.Lines())
+}
+
+// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple.
+// (0-based. Returns (0, 0) for index=0.)
+func (d *Document) TranslateIndexToPosition(index int) (row int, col int) {
+ row, rowIndex := d.findLineStartIndex(index)
+ col = index - rowIndex
+ return
+}
+
+// TranslateRowColToIndex given a (row, col), return the corresponding index.
+// (Row and col params are 0-based.)
+func (d *Document) TranslateRowColToIndex(row int, column int) (index int) {
+ indexes := d.lineStartIndexes()
+ if row < 0 {
+ row = 0
+ } else if row > len(indexes) {
+ row = len(indexes) - 1
+ }
+ index = indexes[row]
+ line := d.Lines()[row]
+
+ // python) result += max(0, min(col, len(line)))
+ if column > 0 || len(line) > 0 {
+ if column > len(line) {
+ index += len(line)
+ } else {
+ index += column
+ }
+ }
+
+ // Keep in range. (len(self.text) is included, because the cursor can be
+ // right after the end of the text as well.)
+ // python) result = max(0, min(result, len(self.text)))
+ if index > len(d.Text) {
+ index = len(d.Text)
+ }
+ if index < 0 {
+ index = 0
+ }
+ return index
+}
+
+// OnLastLine returns true when we are at the last line.
+func (d *Document) OnLastLine() bool {
+ return d.CursorPositionRow() == (d.LineCount() - 1)
+}
+
+// GetEndOfLinePosition returns relative position for the end of this line.
+func (d *Document) GetEndOfLinePosition() int {
+ return len([]rune(d.CurrentLineAfterCursor()))
+}
+
+func (d *Document) leadingWhitespaceInCurrentLine() (margin string) {
+ trimmed := strings.TrimSpace(d.CurrentLine())
+ margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)]
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/emacs.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/emacs.go
new file mode 100644
index 0000000000000000000000000000000000000000..632f96321f2577cdb7e8cffe639f1518a65d5e0f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/emacs.go
@@ -0,0 +1,120 @@
+package prompt
+
+import "github.com/c-bata/go-prompt/internal/debug"
+
+/*
+
+========
+PROGRESS
+========
+
+Moving the cursor
+-----------------
+
+* [x] Ctrl + a Go to the beginning of the line (Home)
+* [x] Ctrl + e Go to the End of the line (End)
+* [x] Ctrl + p Previous command (Up arrow)
+* [x] Ctrl + n Next command (Down arrow)
+* [x] Ctrl + f Forward one character
+* [x] Ctrl + b Backward one character
+* [x] Ctrl + xx Toggle between the start of line and current cursor position
+
+Editing
+-------
+
+* [x] Ctrl + L Clear the Screen, similar to the clear command
+* [x] Ctrl + d Delete character under the cursor
+* [x] Ctrl + h Delete character before the cursor (Backspace)
+
+* [x] Ctrl + w Cut the Word before the cursor to the clipboard.
+* [x] Ctrl + k Cut the Line after the cursor to the clipboard.
+* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard.
+
+* [ ] Ctrl + t Swap the last two characters before the cursor (typo).
+* [ ] Esc + t Swap the last two words before the cursor.
+
+* [ ] ctrl + y Paste the last thing to be cut (yank)
+* [ ] ctrl + _ Undo
+
+*/
+
+var emacsKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: ControlE,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+ },
+ },
+ // Go to the beginning of the line
+ {
+ Key: ControlA,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+ },
+ },
+ // Cut the Line after the cursor
+ {
+ Key: ControlK,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.Delete(len(x))
+ },
+ },
+ // Cut/delete the Line before the cursor
+ {
+ Key: ControlU,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.DeleteBeforeCursor(len(x))
+ },
+ },
+ // Delete character under the cursor
+ {
+ Key: ControlD,
+ Fn: func(buf *Buffer) {
+ if buf.Text() != "" {
+ buf.Delete(1)
+ }
+ },
+ },
+ // Backspace
+ {
+ Key: ControlH,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+ },
+ },
+ // Right allow: Forward one character
+ {
+ Key: ControlF,
+ Fn: func(buf *Buffer) {
+ buf.CursorRight(1)
+ },
+ },
+ // Left allow: Backward one character
+ {
+ Key: ControlB,
+ Fn: func(buf *Buffer) {
+ buf.CursorLeft(1)
+ },
+ },
+ // Cut the Word before the cursor.
+ {
+ Key: ControlW,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace())))
+ },
+ },
+ // Clear the Screen, similar to the clear command
+ {
+ Key: ControlL,
+ Fn: func(buf *Buffer) {
+ consoleWriter.EraseScreen()
+ consoleWriter.CursorGoTo(0, 0)
+ debug.AssertNoError(consoleWriter.Flush())
+ },
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/filter.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/filter.go
new file mode 100644
index 0000000000000000000000000000000000000000..61c17ed7f436a069563f520512bd25e4d81af0de
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/filter.go
@@ -0,0 +1,71 @@
+package prompt
+
+import "strings"
+
+// Filter is the type to filter the prompt.Suggestion array.
+type Filter func([]Suggest, string, bool) []Suggest
+
+// FilterHasPrefix checks whether the string completions.Text begins with sub.
+func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
+}
+
+// FilterHasSuffix checks whether the completion.Text ends with sub.
+func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
+}
+
+// FilterContains checks whether the completion.Text contains sub.
+func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
+}
+
+// FilterFuzzy checks whether the completion.Text fuzzy matches sub.
+// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
+// would match, for example, "Good food is gone"
+// ^ ^ ^
+func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
+}
+
+func fuzzyMatch(s, sub string) bool {
+ sChars := []rune(s)
+ sIdx := 0
+
+ // https://staticcheck.io/docs/checks#S1029
+ for _, c := range sub {
+ found := false
+ for ; sIdx < len(sChars); sIdx++ {
+ if sChars[sIdx] == c {
+ found = true
+ sIdx++
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
+
+func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
+ if sub == "" {
+ return suggestions
+ }
+ if ignoreCase {
+ sub = strings.ToUpper(sub)
+ }
+
+ ret := make([]Suggest, 0, len(suggestions))
+ for i := range suggestions {
+ c := suggestions[i].Text
+ if ignoreCase {
+ c = strings.ToUpper(c)
+ }
+ if function(c, sub) {
+ ret = append(ret, suggestions[i])
+ }
+ }
+ return ret
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/go.mod b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..30bc6d39a39c328341ca7153d3391352be5baa63
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/go.mod
@@ -0,0 +1,11 @@
+module github.com/c-bata/go-prompt
+
+go 1.14
+
+require (
+ github.com/mattn/go-colorable v0.1.7
+ github.com/mattn/go-runewidth v0.0.9
+ github.com/mattn/go-tty v0.0.3
+ github.com/pkg/term v1.2.0-beta.2
+ golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/go.sum b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..768bf93619a68e1b334c13e7b93ec84fa465598e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/go.sum
@@ -0,0 +1,23 @@
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/history.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/history.go
new file mode 100644
index 0000000000000000000000000000000000000000..e75c64592d82142bf4826ceb8c613ac72ca24d9c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/history.go
@@ -0,0 +1,61 @@
+package prompt
+
+// History stores the texts that are entered.
+type History struct {
+ histories []string
+ tmp []string
+ selected int
+}
+
+// Add to add text in history.
+func (h *History) Add(input string) {
+ h.histories = append(h.histories, input)
+ h.Clear()
+}
+
+// Clear to clear the history.
+func (h *History) Clear() {
+ h.tmp = make([]string, len(h.histories))
+ for i := range h.histories {
+ h.tmp[i] = h.histories[i]
+ }
+ h.tmp = append(h.tmp, "")
+ h.selected = len(h.tmp) - 1
+}
+
+// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
+ if len(h.tmp) == 1 || h.selected == 0 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected--
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
+ if h.selected >= len(h.tmp)-1 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected++
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// NewHistory returns new history object.
+func NewHistory() *History {
+ return &History{
+ histories: []string{},
+ tmp: []string{""},
+ selected: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input.go
new file mode 100644
index 0000000000000000000000000000000000000000..307e747190c2b27bf888b379644fc4f3cdd489a2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input.go
@@ -0,0 +1,169 @@
+package prompt
+
+import "bytes"
+
+// WinSize represents the width and height of terminal.
+type WinSize struct {
+ Row uint16
+ Col uint16
+}
+
+// ConsoleParser is an interface to abstract input layer.
+type ConsoleParser interface {
+ // Setup should be called before starting input
+ Setup() error
+ // TearDown should be called after stopping input
+ TearDown() error
+ // GetWinSize returns WinSize object to represent width and height of terminal.
+ GetWinSize() *WinSize
+ // Read returns byte array.
+ Read() ([]byte, error)
+}
+
+// GetKey returns Key correspond to input byte codes.
+func GetKey(b []byte) Key {
+ for _, k := range ASCIISequences {
+ if bytes.Equal(k.ASCIICode, b) {
+ return k.Key
+ }
+ }
+ return NotDefined
+}
+
+// ASCIISequences holds mappings of the key and byte array.
+var ASCIISequences = []*ASCIICode{
+ {Key: Escape, ASCIICode: []byte{0x1b}},
+
+ {Key: ControlSpace, ASCIICode: []byte{0x00}},
+ {Key: ControlA, ASCIICode: []byte{0x1}},
+ {Key: ControlB, ASCIICode: []byte{0x2}},
+ {Key: ControlC, ASCIICode: []byte{0x3}},
+ {Key: ControlD, ASCIICode: []byte{0x4}},
+ {Key: ControlE, ASCIICode: []byte{0x5}},
+ {Key: ControlF, ASCIICode: []byte{0x6}},
+ {Key: ControlG, ASCIICode: []byte{0x7}},
+ {Key: ControlH, ASCIICode: []byte{0x8}},
+ //{Key: ControlI, ASCIICode: []byte{0x9}},
+ //{Key: ControlJ, ASCIICode: []byte{0xa}},
+ {Key: ControlK, ASCIICode: []byte{0xb}},
+ {Key: ControlL, ASCIICode: []byte{0xc}},
+ {Key: ControlM, ASCIICode: []byte{0xd}},
+ {Key: ControlN, ASCIICode: []byte{0xe}},
+ {Key: ControlO, ASCIICode: []byte{0xf}},
+ {Key: ControlP, ASCIICode: []byte{0x10}},
+ {Key: ControlQ, ASCIICode: []byte{0x11}},
+ {Key: ControlR, ASCIICode: []byte{0x12}},
+ {Key: ControlS, ASCIICode: []byte{0x13}},
+ {Key: ControlT, ASCIICode: []byte{0x14}},
+ {Key: ControlU, ASCIICode: []byte{0x15}},
+ {Key: ControlV, ASCIICode: []byte{0x16}},
+ {Key: ControlW, ASCIICode: []byte{0x17}},
+ {Key: ControlX, ASCIICode: []byte{0x18}},
+ {Key: ControlY, ASCIICode: []byte{0x19}},
+ {Key: ControlZ, ASCIICode: []byte{0x1a}},
+
+ {Key: ControlBackslash, ASCIICode: []byte{0x1c}},
+ {Key: ControlSquareClose, ASCIICode: []byte{0x1d}},
+ {Key: ControlCircumflex, ASCIICode: []byte{0x1e}},
+ {Key: ControlUnderscore, ASCIICode: []byte{0x1f}},
+ {Key: Backspace, ASCIICode: []byte{0x7f}},
+
+ {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}},
+
+ {Key: Enter, ASCIICode: []byte{0xa}},
+ {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}},
+ {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+ {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}},
+ {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}},
+ {Key: Tab, ASCIICode: []byte{0x9}},
+ {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}},
+ {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}},
+ {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}},
+ {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}},
+ {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode
+
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}},
+ {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}},
+ {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}},
+ {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}},
+ {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}},
+ {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}},
+ {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}},
+ {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}},
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}},
+ {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}},
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+
+ // Xterm
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}},
+ // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}},
+ {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}},
+ {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}},
+ {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}},
+ {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}},
+
+ {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}},
+ {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}},
+ {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}},
+ {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}},
+
+ // Tmux sends following keystrokes when control+arrow is pressed, but for
+ // Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ // it a normal arrow press, because that's more important.
+ {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}},
+
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt
+
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input_posix.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f10430318be0e797c841eba8e08ab1cf5277be27
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input_posix.go
@@ -0,0 +1,77 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/term"
+ "golang.org/x/sys/unix"
+)
+
+const maxReadBytes = 1024
+
+// PosixParser is a ConsoleParser implementation for POSIX environment.
+type PosixParser struct {
+ fd int
+ origTermios syscall.Termios
+}
+
+// Setup should be called before starting input
+func (t *PosixParser) Setup() error {
+ // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
+ if err := syscall.SetNonblock(t.fd, true); err != nil {
+ return err
+ }
+ if err := term.SetRaw(t.fd); err != nil {
+ return err
+ }
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (t *PosixParser) TearDown() error {
+ if err := syscall.SetNonblock(t.fd, false); err != nil {
+ return err
+ }
+ if err := term.Restore(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Read returns byte array.
+func (t *PosixParser) Read() ([]byte, error) {
+ buf := make([]byte, maxReadBytes)
+ n, err := syscall.Read(t.fd, buf)
+ if err != nil {
+ return []byte{}, err
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (t *PosixParser) GetWinSize() *WinSize {
+ ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: ws.Row,
+ Col: ws.Col,
+ }
+}
+
+var _ ConsoleParser = &PosixParser{}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *PosixParser {
+ in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ return &PosixParser{
+ fd: in,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input_windows.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..11b7679d4c4bc8b924a5b6c863ca1f6d6880570d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input_windows.go
@@ -0,0 +1,83 @@
+// +build windows
+
+package prompt
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf8"
+ "unsafe"
+
+ tty "github.com/mattn/go-tty"
+)
+
+const maxReadBytes = 1024
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
+
+// WindowsParser is a ConsoleParser implementation for Win32 console.
+type WindowsParser struct {
+ tty *tty.TTY
+}
+
+// Setup should be called before starting input
+func (p *WindowsParser) Setup() error {
+ t, err := tty.Open()
+ if err != nil {
+ return err
+ }
+ p.tty = t
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (p *WindowsParser) TearDown() error {
+ return p.tty.Close()
+}
+
+// Read returns byte array.
+func (p *WindowsParser) Read() ([]byte, error) {
+ var ev uint32
+ r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
+ if r0 == 0 {
+ return nil, err
+ }
+ if ev == 0 {
+ return nil, errors.New("EAGAIN")
+ }
+
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, maxReadBytes)
+ n := utf8.EncodeRune(buf[:], r)
+ for p.tty.Buffered() && n < maxReadBytes {
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ break
+ }
+ n += utf8.EncodeRune(buf[n:], r)
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (p *WindowsParser) GetWinSize() *WinSize {
+ w, h, err := p.tty.Size()
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: uint16(h),
+ Col: uint16(w),
+ }
+}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *WindowsParser {
+ return &WindowsParser{}
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/bisect/bisect.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/bisect/bisect.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe162fa8c4873302e25702081b629a445d43415
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/bisect/bisect.go
@@ -0,0 +1,15 @@
+package bisect
+
+import "sort"
+
+// Right to locate the insertion point for v in a to maintain sorted order.
+func Right(a []int, v int) int {
+ return bisectRightRange(a, v, 0, len(a))
+}
+
+func bisectRightRange(a []int, v int, lo, hi int) int {
+ s := a[lo:hi]
+ return sort.Search(len(s), func(i int) bool {
+ return s[i] > v
+ })
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/debug/assert.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/debug/assert.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f648ac93c44e1e021cdf581a68f03b548534d9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/debug/assert.go
@@ -0,0 +1,55 @@
+package debug
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
+)
+
+var (
+ enableAssert bool
+)
+
+func init() {
+ if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
+ enableAssert = true
+ }
+}
+
+// Assert ensures expected condition.
+func Assert(cond bool, msg interface{}) {
+ if cond {
+ return
+ }
+ if enableAssert {
+ panic(msg)
+ }
+ writeWithSync(2, "[ASSERT] "+toString(msg))
+}
+
+func toString(v interface{}) string {
+ switch a := v.(type) {
+ case func() string:
+ return a()
+ case string:
+ return a
+ case fmt.Stringer:
+ return a.String()
+ default:
+ return fmt.Sprintf("unexpected type, %t", v)
+ }
+}
+
+// AssertNoError ensures err is nil.
+func AssertNoError(err error) {
+ if err == nil {
+ return
+ }
+ if enableAssert {
+ panic(err)
+ }
+ writeWithSync(2, "[ASSERT] "+err.Error())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/debug/log.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/debug/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..516378627a34ead9063ab7ce6c445b23c77b7cb4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/debug/log.go
@@ -0,0 +1,52 @@
+package debug
+
+import (
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+const (
+ envEnableLog = "GO_PROMPT_ENABLE_LOG"
+ logFileName = "go-prompt.log"
+)
+
+var (
+ logfile *os.File
+ logger *log.Logger
+)
+
+func init() {
+ if e := os.Getenv(envEnableLog); e == "true" || e == "1" {
+ var err error
+ logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
+ if err == nil {
+ logger = log.New(logfile, "", log.Llongfile)
+ return
+ }
+ }
+ logger = log.New(ioutil.Discard, "", log.Llongfile)
+}
+
+// Teardown to close logfile
+func Teardown() {
+ if logfile == nil {
+ return
+ }
+ _ = logfile.Close()
+}
+
+func writeWithSync(calldepth int, msg string) {
+ calldepth++
+ if logfile == nil {
+ return
+ }
+ _ = logger.Output(calldepth, msg)
+ _ = logfile.Sync() // immediately write msg
+}
+
+// Log to output message
+func Log(msg string) {
+ calldepth := 2
+ writeWithSync(calldepth, msg)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/strings/strings.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/strings/strings.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7d1886ae03a7d541c66dffca921e2d040e6d5eb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/strings/strings.go
@@ -0,0 +1,102 @@
+package strings
+
+import "unicode/utf8"
+
+// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior.
+func IndexNotByte(s string, c byte) int {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior.
+func LastIndexNotByte(s string, c byte) int {
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+type asciiSet [8]uint32
+
+func (as *asciiSet) notContains(c byte) bool {
+ return (as[c>>5] & (1 << uint(c&31))) == 0
+}
+
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c>>5] |= 1 << uint(c&31)
+ }
+ return as, true
+}
+
+// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior.
+func IndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := 0; i < len(s); i++ {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+
+ LabelFirstLoop:
+ for i, c := range s {
+ for j, m := range chars {
+ if c != m && j == len(chars)-1 {
+ return i
+ } else if c != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior.
+func LastIndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ LabelFirstLoop:
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRuneInString(s[:i])
+ i -= size
+ for j, m := range chars {
+ if r != m && j == len(chars)-1 {
+ return i
+ } else if r != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/term/raw.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/term/raw.go
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3ed8d04023558cf386a98080815d661248b85
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/term/raw.go
@@ -0,0 +1,29 @@
+// +build !windows
+
+package term
+
+import (
+ "syscall"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+// SetRaw put terminal into a raw mode
+func SetRaw(fd int) error {
+ n, err := getOriginalTermios(fd)
+ if err != nil {
+ return err
+ }
+
+ n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK |
+ syscall.ISTRIP | syscall.INLCR | syscall.IGNCR |
+ syscall.ICRNL | syscall.IXON
+ n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL
+ n.Cflag &^= syscall.CSIZE | syscall.PARENB
+ n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters.
+ n.Cc[syscall.VMIN] = 1
+ n.Cc[syscall.VTIME] = 0
+
+ return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n))
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/term/term.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/term/term.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a53c059ae60c0348ec01689babef4b13a2ecd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/internal/term/term.go
@@ -0,0 +1,34 @@
+// +build !windows
+
+package term
+
+import (
+ "sync"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ saveTermios *unix.Termios
+ saveTermiosFD int
+ saveTermiosOnce sync.Once
+)
+
+func getOriginalTermios(fd int) (*unix.Termios, error) {
+ var err error
+ saveTermiosOnce.Do(func() {
+ saveTermiosFD = fd
+ saveTermios, err = termios.Tcgetattr(uintptr(fd))
+ })
+ return saveTermios, err
+}
+
+// Restore terminal's mode.
+func Restore() error {
+ o, err := getOriginalTermios(saveTermiosFD)
+ if err != nil {
+ return err
+ }
+ return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/key.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ba569c2dd20a8ae3b3dd79ff3695bf0b6c1bd09
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/key.go
@@ -0,0 +1,128 @@
+// Code generated by hand; DO NOT EDIT.
+// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment.
+
+package prompt
+
+// Key is the type express the key inserted from user.
+//go:generate stringer -type=Key
+type Key int
+
+// ASCIICode is the type contains Key and it's ascii byte array.
+type ASCIICode struct {
+ Key Key
+ ASCIICode []byte
+}
+
+const (
+ Escape Key = iota
+
+ ControlA
+ ControlB
+ ControlC
+ ControlD
+ ControlE
+ ControlF
+ ControlG
+ ControlH
+ ControlI
+ ControlJ
+ ControlK
+ ControlL
+ ControlM
+ ControlN
+ ControlO
+ ControlP
+ ControlQ
+ ControlR
+ ControlS
+ ControlT
+ ControlU
+ ControlV
+ ControlW
+ ControlX
+ ControlY
+ ControlZ
+
+ ControlSpace
+ ControlBackslash
+ ControlSquareClose
+ ControlCircumflex
+ ControlUnderscore
+ ControlLeft
+ ControlRight
+ ControlUp
+ ControlDown
+
+ Up
+ Down
+ Right
+ Left
+
+ ShiftLeft
+ ShiftUp
+ ShiftDown
+ ShiftRight
+
+ Home
+ End
+ Delete
+ ShiftDelete
+ ControlDelete
+ PageUp
+ PageDown
+ BackTab
+ Insert
+ Backspace
+
+ // Aliases.
+ Tab
+ Enter
+ // Actually Enter equals ControlM, not ControlJ,
+ // However, in prompt_toolkit, we made the mistake of translating
+ // \r into \n during the input, so everyone is now handling the
+ // enter key by binding ControlJ.
+
+ // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere,
+ // because that's future compatible, and will still work when we
+ // stop replacing \r by \n.
+
+ F1
+ F2
+ F3
+ F4
+ F5
+ F6
+ F7
+ F8
+ F9
+ F10
+ F11
+ F12
+ F13
+ F14
+ F15
+ F16
+ F17
+ F18
+ F19
+ F20
+ F21
+ F22
+ F23
+ F24
+
+ // Matches any key.
+ Any
+
+ // Special
+ CPRResponse
+ Vt100MouseEvent
+ WindowsMouseEvent
+ BracketedPaste
+
+ // Key which is ignored. (The key binding for this key should not do anything.)
+ Ignore
+
+ // Key is not defined
+ NotDefined
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/key_bind.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/key_bind.go
new file mode 100644
index 0000000000000000000000000000000000000000..42669e7f942efc4d92f896388daede90b96b55dd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/key_bind.go
@@ -0,0 +1,59 @@
+package prompt
+
+// KeyBindFunc receives buffer and processed it.
+type KeyBindFunc func(*Buffer)
+
+// KeyBind represents which key should do what operation.
+type KeyBind struct {
+ Key Key
+ Fn KeyBindFunc
+}
+
+// ASCIICodeBind represents which []byte should do what operation
+type ASCIICodeBind struct {
+ ASCIICode []byte
+ Fn KeyBindFunc
+}
+
+// KeyBindMode to switch a key binding flexibly.
+type KeyBindMode string
+
+const (
+ // CommonKeyBind is a mode without any keyboard shortcut
+ CommonKeyBind KeyBindMode = "common"
+ // EmacsKeyBind is a mode to use emacs-like keyboard shortcut
+ EmacsKeyBind KeyBindMode = "emacs"
+)
+
+var commonKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: End,
+ Fn: GoLineEnd,
+ },
+ // Go to the beginning of the line
+ {
+ Key: Home,
+ Fn: GoLineBeginning,
+ },
+ // Delete character under the cursor
+ {
+ Key: Delete,
+ Fn: DeleteChar,
+ },
+ // Backspace
+ {
+ Key: Backspace,
+ Fn: DeleteBeforeChar,
+ },
+ // Right allow: Forward one character
+ {
+ Key: Right,
+ Fn: GoRightChar,
+ },
+ // Left allow: Backward one character
+ {
+ Key: Left,
+ Fn: GoLeftChar,
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/key_bind_func.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/key_bind_func.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b2ecdf63179dbfdbcb0d71bfa436bb36d62d230
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/key_bind_func.go
@@ -0,0 +1,48 @@
+package prompt
+
+// GoLineEnd Go to the End of the line
+func GoLineEnd(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+}
+
+// GoLineBeginning Go to the beginning of the line
+func GoLineBeginning(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+}
+
+// DeleteChar Delete character under the cursor
+func DeleteChar(buf *Buffer) {
+ buf.Delete(1)
+}
+
+// DeleteWord Delete word before the cursor
+func DeleteWord(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
+
+// DeleteBeforeChar Go to Backspace
+func DeleteBeforeChar(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+}
+
+// GoRightChar Forward one character
+func GoRightChar(buf *Buffer) {
+ buf.CursorRight(1)
+}
+
+// GoLeftChar Backward one character
+func GoLeftChar(buf *Buffer) {
+ buf.CursorLeft(1)
+}
+
+// GoRightWord Forward one word
+func GoRightWord(buf *Buffer) {
+ buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
+}
+
+// GoLeftWord Backward one word
+func GoLeftWord(buf *Buffer) {
+ buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/key_string.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/key_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..fce6ea31c502b3e763451cb47757ae1b49c32814
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/key_string.go
@@ -0,0 +1,16 @@
+// Code generated by "stringer -type=Key"; DO NOT EDIT.
+
+package prompt
+
+import "strconv"
+
+const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined"
+
+var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607}
+
+func (i Key) String() string {
+ if i < 0 || i >= Key(len(_Key_index)-1) {
+ return "Key(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _Key_name[_Key_index[i]:_Key_index[i+1]]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/option.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/option.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd6806cc1dbccf8c4ddb048080fde615c59088
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/option.go
@@ -0,0 +1,310 @@
+package prompt
+
+// Option is the type to replace default parameters.
+// prompt.New accepts any number of options (this is functional option pattern).
+type Option func(prompt *Prompt) error
+
+// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
+func OptionParser(x ConsoleParser) Option {
+ return func(p *Prompt) error {
+ p.in = x
+ return nil
+ }
+}
+
+// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
+func OptionWriter(x ConsoleWriter) Option {
+ return func(p *Prompt) error {
+ registerConsoleWriter(x)
+ p.renderer.out = x
+ return nil
+ }
+}
+
+// OptionTitle to set title displayed at the header bar of terminal.
+func OptionTitle(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.title = x
+ return nil
+ }
+}
+
+// OptionPrefix to set prefix string.
+func OptionPrefix(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefix = x
+ return nil
+ }
+}
+
+// OptionInitialBufferText to set the initial buffer text
+func OptionInitialBufferText(x string) Option {
+ return func(p *Prompt) error {
+ p.buf.InsertText(x, false, true)
+ return nil
+ }
+}
+
+// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
+func OptionCompletionWordSeparator(x string) Option {
+ return func(p *Prompt) error {
+ p.completion.wordSeparator = x
+ return nil
+ }
+}
+
+// OptionLivePrefix to change the prefix dynamically by callback function
+func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
+ return func(p *Prompt) error {
+ p.renderer.livePrefixCallback = f
+ return nil
+ }
+}
+
+// OptionPrefixTextColor change a text color of prefix string
+func OptionPrefixTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixTextColor = x
+ return nil
+ }
+}
+
+// OptionPrefixBackgroundColor to change a background color of prefix string
+func OptionPrefixBackgroundColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixBGColor = x
+ return nil
+ }
+}
+
+// OptionInputTextColor to change a color of text which is input by user
+func OptionInputTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputTextColor = x
+ return nil
+ }
+}
+
+// OptionInputBGColor to change a color of background which is input by user
+func OptionInputBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputBGColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionTextColor to change a text color which is completed
+func OptionPreviewSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionBGColor to change a background color which is completed
+func OptionPreviewSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionTextColor to change a text color in drop down suggestions.
+func OptionSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionBGColor change a background color in drop down suggestions.
+func OptionSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarThumbColor to change a thumb color on scrollbar.
+func OptionScrollbarThumbColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarThumbColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarBGColor to change a background color of scrollbar.
+func OptionScrollbarBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarBGColor = x
+ return nil
+ }
+}
+
+// OptionMaxSuggestion specify the max number of displayed suggestions.
+func OptionMaxSuggestion(x uint16) Option {
+ return func(p *Prompt) error {
+ p.completion.max = x
+ return nil
+ }
+}
+
+// OptionHistory to set history expressed by string array.
+func OptionHistory(x []string) Option {
+ return func(p *Prompt) error {
+ p.history.histories = x
+ p.history.Clear()
+ return nil
+ }
+}
+
+// OptionSwitchKeyBindMode set a key bind mode.
+func OptionSwitchKeyBindMode(m KeyBindMode) Option {
+ return func(p *Prompt) error {
+ p.keyBindMode = m
+ return nil
+ }
+}
+
+// OptionCompletionOnDown allows for Down arrow key to trigger completion.
+func OptionCompletionOnDown() Option {
+ return func(p *Prompt) error {
+ p.completionOnDown = true
+ return nil
+ }
+}
+
+// SwitchKeyBindMode to set a key bind mode.
+// Deprecated: Please use OptionSwitchKeyBindMode.
+var SwitchKeyBindMode = OptionSwitchKeyBindMode
+
+// OptionAddKeyBind to set a custom key bind.
+func OptionAddKeyBind(b ...KeyBind) Option {
+ return func(p *Prompt) error {
+ p.keyBindings = append(p.keyBindings, b...)
+ return nil
+ }
+}
+
+// OptionAddASCIICodeBind to set a custom key bind.
+func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option {
+ return func(p *Prompt) error {
+ p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...)
+ return nil
+ }
+}
+
+// OptionShowCompletionAtStart to set completion window is open at start.
+func OptionShowCompletionAtStart() Option {
+ return func(p *Prompt) error {
+ p.completion.showAtStart = true
+ return nil
+ }
+}
+
+// OptionBreakLineCallback to run a callback at every break line
+func OptionBreakLineCallback(fn func(*Document)) Option {
+ return func(p *Prompt) error {
+ p.renderer.breakLineCallback = fn
+ return nil
+ }
+}
+
+// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop
+func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
+ return func(p *Prompt) error {
+ p.exitChecker = fn
+ return nil
+ }
+}
+
+// New returns a Prompt with powerful auto-completion.
+func New(executor Executor, completer Completer, opts ...Option) *Prompt {
+ defaultWriter := NewStdoutWriter()
+ registerConsoleWriter(defaultWriter)
+
+ pt := &Prompt{
+ in: NewStandardInputParser(),
+ renderer: &Render{
+ prefix: "> ",
+ out: defaultWriter,
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ },
+ buf: NewBuffer(),
+ executor: executor,
+ history: NewHistory(),
+ completion: NewCompletionManager(completer, 6),
+ keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting
+ }
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/output.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/output.go
new file mode 100644
index 0000000000000000000000000000000000000000..42531b412f1ed027c2fff5b85bc273e53e569b3a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/output.go
@@ -0,0 +1,161 @@
+package prompt
+
+import "sync"
+
+var (
+ consoleWriterMu sync.Mutex
+ consoleWriter ConsoleWriter
+)
+
+func registerConsoleWriter(f ConsoleWriter) {
+ consoleWriterMu.Lock()
+ defer consoleWriterMu.Unlock()
+ consoleWriter = f
+}
+
+// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on.
+type DisplayAttribute int
+
+const (
+ // DisplayReset reset all display attributes.
+ DisplayReset DisplayAttribute = iota
+ // DisplayBold set bold or increases intensity.
+ DisplayBold
+ // DisplayLowIntensity decreases intensity. Not widely supported.
+ DisplayLowIntensity
+ // DisplayItalic set italic. Not widely supported.
+ DisplayItalic
+ // DisplayUnderline set underline
+ DisplayUnderline
+ // DisplayBlink set blink (less than 150 per minute).
+ DisplayBlink
+ // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported.
+ DisplayRapidBlink
+ // DisplayReverse swap foreground and background colors.
+ DisplayReverse
+ // DisplayInvisible set invisible. Not widely supported.
+ DisplayInvisible
+ // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported.
+ DisplayCrossedOut
+ // DisplayDefaultFont set primary(default) font
+ DisplayDefaultFont
+)
+
+// Color represents color on terminal.
+type Color int
+
+const (
+ // DefaultColor represents a default color.
+ DefaultColor Color = iota
+
+ // Low intensity
+
+ // Black represents a black.
+ Black
+ // DarkRed represents a dark red.
+ DarkRed
+ // DarkGreen represents a dark green.
+ DarkGreen
+ // Brown represents a brown.
+ Brown
+ // DarkBlue represents a dark blue.
+ DarkBlue
+ // Purple represents a purple.
+ Purple
+ // Cyan represents a cyan.
+ Cyan
+ // LightGray represents a light gray.
+ LightGray
+
+ // High intensity
+
+ // DarkGray represents a dark gray.
+ DarkGray
+ // Red represents a red.
+ Red
+ // Green represents a green.
+ Green
+ // Yellow represents a yellow.
+ Yellow
+ // Blue represents a blue.
+ Blue
+ // Fuchsia represents a fuchsia.
+ Fuchsia
+ // Turquoise represents a turquoise.
+ Turquoise
+ // White represents a white.
+ White
+)
+
+// ConsoleWriter is an interface to abstract output layer.
+type ConsoleWriter interface {
+ /* Write */
+
+ // WriteRaw to write raw byte array.
+ WriteRaw(data []byte)
+ // Write to write safety byte array by removing control sequences.
+ Write(data []byte)
+ // WriteStr to write raw string.
+ WriteRawStr(data string)
+ // WriteStr to write safety string by removing control sequences.
+ WriteStr(data string)
+ // Flush to flush buffer.
+ Flush() error
+
+ /* Erasing */
+
+ // EraseScreen erases the screen with the background colour and moves the cursor to home.
+ EraseScreen()
+ // EraseUp erases the screen from the current line up to the top of the screen.
+ EraseUp()
+ // EraseDown erases the screen from the current line down to the bottom of the screen.
+ EraseDown()
+ // EraseStartOfLine erases from the current cursor position to the start of the current line.
+ EraseStartOfLine()
+ // EraseEndOfLine erases from the current cursor position to the end of the current line.
+ EraseEndOfLine()
+ // EraseLine erases the entire current line.
+ EraseLine()
+
+ /* Cursor */
+
+ // ShowCursor stops blinking cursor and show.
+ ShowCursor()
+ // HideCursor hides cursor.
+ HideCursor()
+ // CursorGoTo sets the cursor position where subsequent text will begin.
+ CursorGoTo(row, col int)
+ // CursorUp moves the cursor up by 'n' rows; the default count is 1.
+ CursorUp(n int)
+ // CursorDown moves the cursor down by 'n' rows; the default count is 1.
+ CursorDown(n int)
+ // CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+ CursorForward(n int)
+ // CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+ CursorBackward(n int)
+ // AskForCPR asks for a cursor position report (CPR).
+ AskForCPR()
+ // SaveCursor saves current cursor position.
+ SaveCursor()
+ // UnSaveCursor restores cursor position after a Save Cursor.
+ UnSaveCursor()
+
+ /* Scrolling */
+
+ // ScrollDown scrolls display down one line.
+ ScrollDown()
+ // ScrollUp scroll display up one line.
+ ScrollUp()
+
+ /* Title */
+
+ // SetTitle sets a title of terminal window.
+ SetTitle(title string)
+ // ClearTitle clears a title of terminal window.
+ ClearTitle()
+
+ /* Font */
+
+ // SetColor sets text and background colors. and specify whether text is bold.
+ SetColor(fg, bg Color, bold bool)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/output_posix.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/output_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..26c770cc152a7b126be43915d60b8ba000ad0e38
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/output_posix.go
@@ -0,0 +1,67 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+)
+
+const flushMaxRetryCount = 3
+
+// PosixWriter is a ConsoleWriter implementation for POSIX environment.
+// To control terminal emulator, this outputs VT100 escape sequences.
+type PosixWriter struct {
+ VT100Writer
+ fd int
+}
+
+// Flush to flush buffer
+func (w *PosixWriter) Flush() error {
+ l := len(w.buffer)
+ offset := 0
+ retry := 0
+ for {
+ n, err := syscall.Write(w.fd, w.buffer[offset:])
+ if err != nil {
+ if retry < flushMaxRetryCount {
+ retry++
+ continue
+ }
+ return err
+ }
+ offset += n
+ if offset == l {
+ break
+ }
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &PosixWriter{}
+
+var (
+ // NewStandardOutputWriter returns ConsoleWriter object to write to stdout.
+ // This generates VT100 escape sequences because almost terminal emulators
+ // in POSIX OS built on top of a VT100 specification.
+ // Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStdoutWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stdout,
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStderrWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stderr,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/output_vt100.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/output_vt100.go
new file mode 100644
index 0000000000000000000000000000000000000000..20850fead883c4cd9802928b5de3f935fbbeb047
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/output_vt100.go
@@ -0,0 +1,310 @@
+package prompt
+
+import (
+ "bytes"
+ "strconv"
+)
+
+// VT100Writer generates VT100 escape sequences.
+type VT100Writer struct {
+ buffer []byte
+}
+
+// WriteRaw to write raw byte array
+func (w *VT100Writer) WriteRaw(data []byte) {
+ w.buffer = append(w.buffer, data...)
+}
+
+// Write to write safety byte array by removing control sequences.
+func (w *VT100Writer) Write(data []byte) {
+ w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1))
+}
+
+// WriteRawStr to write raw string
+func (w *VT100Writer) WriteRawStr(data string) {
+ w.WriteRaw([]byte(data))
+}
+
+// WriteStr to write safety string by removing control sequences.
+func (w *VT100Writer) WriteStr(data string) {
+ w.Write([]byte(data))
+}
+
+/* Erase */
+
+// EraseScreen erases the screen with the background colour and moves the cursor to home.
+func (w *VT100Writer) EraseScreen() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'J'})
+}
+
+// EraseUp erases the screen from the current line up to the top of the screen.
+func (w *VT100Writer) EraseUp() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'J'})
+}
+
+// EraseDown erases the screen from the current line down to the bottom of the screen.
+func (w *VT100Writer) EraseDown() {
+ w.WriteRaw([]byte{0x1b, '[', 'J'})
+}
+
+// EraseStartOfLine erases from the current cursor position to the start of the current line.
+func (w *VT100Writer) EraseStartOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'K'})
+}
+
+// EraseEndOfLine erases from the current cursor position to the end of the current line.
+func (w *VT100Writer) EraseEndOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', 'K'})
+}
+
+// EraseLine erases the entire current line.
+func (w *VT100Writer) EraseLine() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'K'})
+}
+
+/* Cursor */
+
+// ShowCursor stops blinking cursor and show.
+func (w *VT100Writer) ShowCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'})
+}
+
+// HideCursor hides cursor.
+func (w *VT100Writer) HideCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'})
+}
+
+// CursorGoTo sets the cursor position where subsequent text will begin.
+func (w *VT100Writer) CursorGoTo(row, col int) {
+ if row == 0 && col == 0 {
+ // If no row/column parameters are provided (ie. [H), the cursor will move to the home position.
+ w.WriteRaw([]byte{0x1b, '[', 'H'})
+ return
+ }
+ r := strconv.Itoa(row)
+ c := strconv.Itoa(col)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(r))
+ w.WriteRaw([]byte{';'})
+ w.WriteRaw([]byte(c))
+ w.WriteRaw([]byte{'H'})
+}
+
+// CursorUp moves the cursor up by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorUp(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorDown(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'A'})
+}
+
+// CursorDown moves the cursor down by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorDown(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorUp(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'B'})
+}
+
+// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorForward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorBackward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'C'})
+}
+
+// CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorBackward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorForward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'D'})
+}
+
+// AskForCPR asks for a cursor position report (CPR).
+func (w *VT100Writer) AskForCPR() {
+ // CPR: Cursor Position Request.
+ w.WriteRaw([]byte{0x1b, '[', '6', 'n'})
+}
+
+// SaveCursor saves current cursor position.
+func (w *VT100Writer) SaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 's'})
+}
+
+// UnSaveCursor restores cursor position after a Save Cursor.
+func (w *VT100Writer) UnSaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 'u'})
+}
+
+/* Scrolling */
+
+// ScrollDown scrolls display down one line.
+func (w *VT100Writer) ScrollDown() {
+ w.WriteRaw([]byte{0x1b, 'D'})
+}
+
+// ScrollUp scroll display up one line.
+func (w *VT100Writer) ScrollUp() {
+ w.WriteRaw([]byte{0x1b, 'M'})
+}
+
+/* Title */
+
+// SetTitle sets a title of terminal window.
+func (w *VT100Writer) SetTitle(title string) {
+ titleBytes := []byte(title)
+ patterns := []struct {
+ from []byte
+ to []byte
+ }{
+ {
+ from: []byte{0x13},
+ to: []byte{},
+ },
+ {
+ from: []byte{0x07},
+ to: []byte{},
+ },
+ }
+ for i := range patterns {
+ titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1)
+ }
+
+ w.WriteRaw([]byte{0x1b, ']', '2', ';'})
+ w.WriteRaw(titleBytes)
+ w.WriteRaw([]byte{0x07})
+}
+
+// ClearTitle clears a title of terminal window.
+func (w *VT100Writer) ClearTitle() {
+ w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07})
+}
+
+/* Font */
+
+// SetColor sets text and background colors. and specify whether text is bold.
+func (w *VT100Writer) SetColor(fg, bg Color, bold bool) {
+ if bold {
+ w.SetDisplayAttributes(fg, bg, DisplayBold)
+ } else {
+ // If using `DisplayDefualt`, it will be broken in some environment.
+ // Details are https://github.com/c-bata/go-prompt/pull/85
+ w.SetDisplayAttributes(fg, bg, DisplayReset)
+ }
+}
+
+// SetDisplayAttributes to set VT100 display attributes.
+func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) {
+ w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer
+ defer w.WriteRaw([]byte{'m'}) // final character
+
+ var separator byte = ';'
+ for i := range attrs {
+ p, ok := displayAttributeParameters[attrs[i]]
+ if !ok {
+ continue
+ }
+ w.WriteRaw(p)
+ w.WriteRaw([]byte{separator})
+ }
+
+ f, ok := foregroundANSIColors[fg]
+ if !ok {
+ f = foregroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(f)
+ w.WriteRaw([]byte{separator})
+ b, ok := backgroundANSIColors[bg]
+ if !ok {
+ b = backgroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(b)
+}
+
+var displayAttributeParameters = map[DisplayAttribute][]byte{
+ DisplayReset: {'0'},
+ DisplayBold: {'1'},
+ DisplayLowIntensity: {'2'},
+ DisplayItalic: {'3'},
+ DisplayUnderline: {'4'},
+ DisplayBlink: {'5'},
+ DisplayRapidBlink: {'6'},
+ DisplayReverse: {'7'},
+ DisplayInvisible: {'8'},
+ DisplayCrossedOut: {'9'},
+ DisplayDefaultFont: {'1', '0'},
+}
+
+var foregroundANSIColors = map[Color][]byte{
+ DefaultColor: {'3', '9'},
+
+ // Low intensity.
+ Black: {'3', '0'},
+ DarkRed: {'3', '1'},
+ DarkGreen: {'3', '2'},
+ Brown: {'3', '3'},
+ DarkBlue: {'3', '4'},
+ Purple: {'3', '5'},
+ Cyan: {'3', '6'},
+ LightGray: {'3', '7'},
+
+ // High intensity.
+ DarkGray: {'9', '0'},
+ Red: {'9', '1'},
+ Green: {'9', '2'},
+ Yellow: {'9', '3'},
+ Blue: {'9', '4'},
+ Fuchsia: {'9', '5'},
+ Turquoise: {'9', '6'},
+ White: {'9', '7'},
+}
+
+var backgroundANSIColors = map[Color][]byte{
+ DefaultColor: {'4', '9'},
+
+ // Low intensity.
+ Black: {'4', '0'},
+ DarkRed: {'4', '1'},
+ DarkGreen: {'4', '2'},
+ Brown: {'4', '3'},
+ DarkBlue: {'4', '4'},
+ Purple: {'4', '5'},
+ Cyan: {'4', '6'},
+ LightGray: {'4', '7'},
+
+ // High intensity
+ DarkGray: {'1', '0', '0'},
+ Red: {'1', '0', '1'},
+ Green: {'1', '0', '2'},
+ Yellow: {'1', '0', '3'},
+ Blue: {'1', '0', '4'},
+ Fuchsia: {'1', '0', '5'},
+ Turquoise: {'1', '0', '6'},
+ White: {'1', '0', '7'},
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/output_windows.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/output_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b9c2769fc2d64cfcfcc5b99c915591ec625bd5f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/output_windows.go
@@ -0,0 +1,49 @@
+// +build windows
+
+package prompt
+
+import (
+ "io"
+
+ colorable "github.com/mattn/go-colorable"
+)
+
+// WindowsWriter is a ConsoleWriter implementation for Win32 console.
+// Output is converted from VT100 escape sequences by mattn/go-colorable.
+type WindowsWriter struct {
+ VT100Writer
+ out io.Writer
+}
+
+// Flush to flush buffer
+func (w *WindowsWriter) Flush() error {
+ _, err := w.out.Write(w.buffer)
+ if err != nil {
+ return err
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &WindowsWriter{}
+
+var (
+ // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates win32 control sequences.
+func NewStdoutWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStdout(),
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates win32 control sequences.
+func NewStderrWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStderr(),
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/prompt.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/prompt.go
new file mode 100644
index 0000000000000000000000000000000000000000..173cd517c40cde212433e399978641ceff1d1a43
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/prompt.go
@@ -0,0 +1,296 @@
+package prompt
+
+import (
+ "bytes"
+ "os"
+ "time"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Executor is called when user input something text.
+type Executor func(string)
+
+// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
+// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
+// - immediate exit (if breakline is false) without executor called
+// - exit after typing (meaning breakline is true), and the executor is called first, before exit.
+// Exit means exit go-prompt (not the overall Go program)
+type ExitChecker func(in string, breakline bool) bool
+
+// Completer should return the suggest item from Document.
+type Completer func(Document) []Suggest
+
+// Prompt is core struct of go-prompt.
+type Prompt struct {
+ in ConsoleParser
+ buf *Buffer
+ renderer *Render
+ executor Executor
+ history *History
+ completion *CompletionManager
+ keyBindings []KeyBind
+ ASCIICodeBindings []ASCIICodeBind
+ keyBindMode KeyBindMode
+ completionOnDown bool
+ exitChecker ExitChecker
+ skipTearDown bool
+}
+
+// Exec is the struct contains user input context.
+type Exec struct {
+ input string
+}
+
+// Run starts prompt.
+func (p *Prompt) Run() {
+ p.skipTearDown = false
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ exitCh := make(chan int)
+ winSizeCh := make(chan *WinSize)
+ stopHandleSignalCh := make(chan struct{})
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+ return
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+
+ // Unset raw mode
+ // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
+ debug.AssertNoError(p.in.TearDown())
+ p.executor(e.input)
+
+ p.completion.Update(*p.buf.Document())
+
+ p.renderer.Render(p.buf, p.completion)
+
+ if p.exitChecker != nil && p.exitChecker(e.input, true) {
+ p.skipTearDown = true
+ return
+ }
+ // Set raw mode
+ debug.AssertNoError(p.in.Setup())
+ go p.readBuffer(bufCh, stopReadBufCh)
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ case w := <-winSizeCh:
+ p.renderer.UpdateWinSize(w)
+ p.renderer.Render(p.buf, p.completion)
+ case code := <-exitCh:
+ p.renderer.BreakLine(p.buf)
+ p.tearDown()
+ os.Exit(code)
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
+ key := GetKey(b)
+ p.buf.lastKeyStroke = key
+ // completion
+ completing := p.completion.Completing()
+ p.handleCompletionKeyBinding(key, completing)
+
+ switch key {
+ case Enter, ControlJ, ControlM:
+ p.renderer.BreakLine(p.buf)
+
+ exec = &Exec{input: p.buf.Text()}
+ p.buf = NewBuffer()
+ if exec.input != "" {
+ p.history.Add(exec.input)
+ }
+ case ControlC:
+ p.renderer.BreakLine(p.buf)
+ p.buf = NewBuffer()
+ p.history.Clear()
+ case Up, ControlP:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Older(p.buf); changed {
+ p.buf = newBuf
+ }
+ }
+ case Down, ControlN:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Newer(p.buf); changed {
+ p.buf = newBuf
+ }
+ return
+ }
+ case ControlD:
+ if p.buf.Text() == "" {
+ shouldExit = true
+ return
+ }
+ case NotDefined:
+ if p.handleASCIICodeBinding(b) {
+ return
+ }
+ p.buf.InsertText(string(b), false, true)
+ }
+
+ shouldExit = p.handleKeyBinding(key)
+ return
+}
+
+func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
+ switch key {
+ case Down:
+ if completing || p.completionOnDown {
+ p.completion.Next()
+ }
+ case Tab, ControlI:
+ p.completion.Next()
+ case Up:
+ if completing {
+ p.completion.Previous()
+ }
+ case BackTab:
+ p.completion.Previous()
+ default:
+ if s, ok := p.completion.GetSelectedSuggestion(); ok {
+ w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
+ if w != "" {
+ p.buf.DeleteBeforeCursor(len([]rune(w)))
+ }
+ p.buf.InsertText(s.Text, false, true)
+ }
+ p.completion.Reset()
+ }
+}
+
+func (p *Prompt) handleKeyBinding(key Key) bool {
+ shouldExit := false
+ for i := range commonKeyBindings {
+ kb := commonKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+
+ if p.keyBindMode == EmacsKeyBind {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ }
+
+ // Custom key bindings
+ for i := range p.keyBindings {
+ kb := p.keyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
+ shouldExit = true
+ }
+ return shouldExit
+}
+
+func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
+ checked := false
+ for _, kb := range p.ASCIICodeBindings {
+ if bytes.Equal(kb.ASCIICode, b) {
+ kb.Fn(p.buf)
+ checked = true
+ }
+ }
+ return checked
+}
+
+// Input just returns user input text.
+func (p *Prompt) Input() string {
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ return ""
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ return e.input
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
+ debug.Log("start reading buffer")
+ for {
+ select {
+ case <-stopCh:
+ debug.Log("stop reading buffer")
+ return
+ default:
+ if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
+ bufCh <- b
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (p *Prompt) setUp() {
+ debug.AssertNoError(p.in.Setup())
+ p.renderer.Setup()
+ p.renderer.UpdateWinSize(p.in.GetWinSize())
+}
+
+func (p *Prompt) tearDown() {
+ if !p.skipTearDown {
+ debug.AssertNoError(p.in.TearDown())
+ }
+ p.renderer.TearDown()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/render.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/render.go
new file mode 100644
index 0000000000000000000000000000000000000000..299ac48b6254b9752ea16516aaedcd41acca6515
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/render.go
@@ -0,0 +1,287 @@
+package prompt
+
+import (
+ "runtime"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Render to render prompt information from state of Buffer.
+type Render struct {
+ out ConsoleWriter
+ prefix string
+ livePrefixCallback func() (prefix string, useLivePrefix bool)
+ breakLineCallback func(*Document)
+ title string
+ row uint16
+ col uint16
+
+ previousCursor int
+
+ // colors,
+ prefixTextColor Color
+ prefixBGColor Color
+ inputTextColor Color
+ inputBGColor Color
+ previewSuggestionTextColor Color
+ previewSuggestionBGColor Color
+ suggestionTextColor Color
+ suggestionBGColor Color
+ selectedSuggestionTextColor Color
+ selectedSuggestionBGColor Color
+ descriptionTextColor Color
+ descriptionBGColor Color
+ selectedDescriptionTextColor Color
+ selectedDescriptionBGColor Color
+ scrollbarThumbColor Color
+ scrollbarBGColor Color
+}
+
+// Setup to initialize console output.
+func (r *Render) Setup() {
+ if r.title != "" {
+ r.out.SetTitle(r.title)
+ debug.AssertNoError(r.out.Flush())
+ }
+}
+
+// getCurrentPrefix to get current prefix.
+// If live-prefix is enabled, return live-prefix.
+func (r *Render) getCurrentPrefix() string {
+ if prefix, ok := r.livePrefixCallback(); ok {
+ return prefix
+ }
+ return r.prefix
+}
+
+func (r *Render) renderPrefix() {
+ r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
+ r.out.WriteStr(r.getCurrentPrefix())
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// TearDown to clear title and erasing.
+func (r *Render) TearDown() {
+ r.out.ClearTitle()
+ r.out.EraseDown()
+ debug.AssertNoError(r.out.Flush())
+}
+
+func (r *Render) prepareArea(lines int) {
+ for i := 0; i < lines; i++ {
+ r.out.ScrollDown()
+ }
+ for i := 0; i < lines; i++ {
+ r.out.ScrollUp()
+ }
+}
+
+// UpdateWinSize called when window size is changed.
+func (r *Render) UpdateWinSize(ws *WinSize) {
+ r.row = ws.Row
+ r.col = ws.Col
+}
+
+func (r *Render) renderWindowTooSmall() {
+ r.out.CursorGoTo(0, 0)
+ r.out.EraseScreen()
+ r.out.SetColor(DarkRed, White, false)
+ r.out.WriteStr("Your console window is too small...")
+}
+
+func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) {
+ suggestions := completions.GetSuggestions()
+ if len(completions.GetSuggestions()) == 0 {
+ return
+ }
+ prefix := r.getCurrentPrefix()
+ formatted, width := formatSuggestions(
+ suggestions,
+ int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar
+ )
+ // +1 means a width of scrollbar.
+ width++
+
+ windowHeight := len(formatted)
+ if windowHeight > int(completions.max) {
+ windowHeight = int(completions.max)
+ }
+ formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
+ r.prepareArea(windowHeight)
+
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor())
+ x, _ := r.toPos(cursor)
+ if x+width >= int(r.col) {
+ cursor = r.backward(cursor, x+width-int(r.col))
+ }
+
+ contentHeight := len(completions.tmp)
+
+ fractionVisible := float64(windowHeight) / float64(contentHeight)
+ fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
+
+ scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
+ scrollbarTop := int(float64(windowHeight) * fractionAbove)
+
+ isScrollThumb := func(row int) bool {
+ return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
+ }
+
+ selected := completions.selected - completions.verticalScroll
+ r.out.SetColor(White, Cyan, false)
+ for i := 0; i < windowHeight; i++ {
+ r.out.CursorDown(1)
+ if i == selected {
+ r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
+ } else {
+ r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Text)
+
+ if i == selected {
+ r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
+ } else {
+ r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Description)
+
+ if isScrollThumb(i) {
+ r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
+ } else {
+ r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
+ }
+ r.out.WriteStr(" ")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+
+ r.lineWrap(cursor + width)
+ r.backward(cursor+width, width)
+ }
+
+ if x+width >= int(r.col) {
+ r.out.CursorForward(x + width - int(r.col))
+ }
+
+ r.out.CursorUp(windowHeight)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// Render renders to the console.
+func (r *Render) Render(buffer *Buffer, completion *CompletionManager) {
+ // In situations where a pseudo tty is allocated (e.g. within a docker container),
+ // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
+ if r.col == 0 {
+ return
+ }
+ defer func() { debug.AssertNoError(r.out.Flush()) }()
+ r.move(r.previousCursor, 0)
+
+ line := buffer.Text()
+ prefix := r.getCurrentPrefix()
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line)
+
+ // prepare area
+ _, y := r.toPos(cursor)
+
+ h := y + 1 + int(completion.max)
+ if h > int(r.row) || completionMargin > int(r.col) {
+ r.renderWindowTooSmall()
+ return
+ }
+
+ // Rendering
+ r.out.HideCursor()
+ defer r.out.ShowCursor()
+
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(line)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ r.lineWrap(cursor)
+
+ r.out.EraseDown()
+
+ cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition())
+
+ r.renderCompletion(buffer, completion)
+ if suggest, ok := completion.GetSelectedSuggestion(); ok {
+ cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator)))
+
+ r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false)
+ r.out.WriteStr(suggest.Text)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ cursor += runewidth.StringWidth(suggest.Text)
+
+ rest := buffer.Document().TextAfterCursor()
+ r.out.WriteStr(rest)
+ cursor += runewidth.StringWidth(rest)
+ r.lineWrap(cursor)
+
+ cursor = r.backward(cursor, runewidth.StringWidth(rest))
+ }
+ r.previousCursor = cursor
+}
+
+// BreakLine to break line.
+func (r *Render) BreakLine(buffer *Buffer) {
+ // Erasing and Render
+ cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix())
+ r.clear(cursor)
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(buffer.Document().Text + "\n")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ debug.AssertNoError(r.out.Flush())
+ if r.breakLineCallback != nil {
+ r.breakLineCallback(buffer.Document())
+ }
+
+ r.previousCursor = 0
+}
+
+// clear erases the screen from a beginning of input
+// even if there is line break which means input length exceeds a window's width.
+func (r *Render) clear(cursor int) {
+ r.move(cursor, 0)
+ r.out.EraseDown()
+}
+
+// backward moves cursor to backward from a current cursor position
+// regardless there is a line break.
+func (r *Render) backward(from, n int) int {
+ return r.move(from, from-n)
+}
+
+// move moves cursor to specified position from the beginning of input
+// even if there is a line break.
+func (r *Render) move(from, to int) int {
+ fromX, fromY := r.toPos(from)
+ toX, toY := r.toPos(to)
+
+ r.out.CursorUp(fromY - toY)
+ r.out.CursorBackward(fromX - toX)
+ return to
+}
+
+// toPos returns the relative position from the beginning of the string.
+func (r *Render) toPos(cursor int) (x, y int) {
+ col := int(r.col)
+ return cursor % col, cursor / col
+}
+
+func (r *Render) lineWrap(cursor int) {
+ if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 {
+ r.out.WriteRaw([]byte{'\n'})
+ }
+}
+
+func clamp(high, low, x float64) float64 {
+ switch {
+ case high < x:
+ return high
+ case x < low:
+ return low
+ default:
+ return x
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/shortcut.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/shortcut.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8d4282700c0bdb30e4decfb9c9ac91f27af251
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/shortcut.go
@@ -0,0 +1,43 @@
+package prompt
+
+func dummyExecutor(in string) {}
+
+// Input get the input data from the user and return it.
+func Input(prefix string, completer Completer, opts ...Option) string {
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+// Choose to the shortcut of input function to select from string array.
+// Deprecated: Maybe anyone want to use this.
+func Choose(prefix string, choices []string, opts ...Option) string {
+ completer := newChoiceCompleter(choices, FilterHasPrefix)
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+func newChoiceCompleter(choices []string, filter Filter) Completer {
+ s := make([]Suggest, len(choices))
+ for i := range choices {
+ s[i] = Suggest{Text: choices[i]}
+ }
+ return func(x Document) []Suggest {
+ return filter(s, x.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/signal_posix.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/signal_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3150df5d85e7612c42c2a889dbefee3b524bef6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/signal_posix.go
@@ -0,0 +1,49 @@
+// +build !windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ in := p.in
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+
+ case syscall.SIGWINCH:
+ debug.Log("Catch SIGWINCH")
+ winSizeCh <- in.GetWinSize()
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/signal_windows.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/signal_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a427c79ec0414540f8f40694731b2565ea80c13
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/signal_windows.go
@@ -0,0 +1,44 @@
+// +build windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/instruction.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..1c9b4cc15fbbfd58f8037d8ef3f63b95c8a022bb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/instruction.md
@@ -0,0 +1,35 @@
+SwapCharactersBeforeCursor produces incorrect output when swapping characters
+
+#### Description
+
+The `SwapCharactersBeforeCursor` function is not working correctly. When trying to swap the last two characters before the cursor, it produces unexpected results.
+
+#### Steps/Code to Reproduce
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func main() {
+ buffer := prompt.NewBuffer()
+ buffer.InsertText("hello world", false, true)
+
+ // Move cursor to position after "world"
+ buffer.CursorRight(0) // cursor at end
+
+ // Try to swap 'l' and 'd' (last two characters)
+ buffer.SwapCharactersBeforeCursor()
+
+ fmt.Printf("Expected: hello wrold\n")
+ fmt.Printf("Got: %s\n", buffer.Text())
+}
+```
+
+When running this code, instead of getting "hello wrold" (with 'l' and 'd' swapped), the function produces "hello worwold" which appears to be duplicating characters incorrectly.
+
+The issue seems to occur when the cursor is positioned after characters that need to be swapped, but the swapping logic is not correctly identifying the character boundaries.
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/provenance.json b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..50a6894b94241e27b54a5dc3636802cfc9aaedcd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/provenance.json
@@ -0,0 +1,477 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt",
+ "original-bug": "task-specific unchanged semantic bug",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only",
+ "extra_semantic_repair_coverage": false,
+ "original_patch_hunks": 1
+ },
+ "private_frozen_files": {
+ "buffer_test.go": {
+ "mode": "0o644",
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098",
+ "size": 4965
+ },
+ "completion_test.go": {
+ "mode": "0o644",
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d",
+ "size": 7010
+ },
+ "document_test.go": {
+ "mode": "0o644",
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284",
+ "size": 28938
+ },
+ "emacs_test.go": {
+ "mode": "0o644",
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095",
+ "size": 741
+ },
+ "filter_test.go": {
+ "mode": "0o644",
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247",
+ "size": 3339
+ },
+ "history_test.go": {
+ "mode": "0o644",
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327",
+ "size": 1319
+ },
+ "input_test.go": {
+ "mode": "0o644",
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922",
+ "size": 533
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": "0o644",
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf",
+ "size": 1075
+ },
+ "internal/strings/strings_test.go": {
+ "mode": "0o644",
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6",
+ "size": 981
+ },
+ "output_vt100_test.go": {
+ "mode": "0o644",
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee",
+ "size": 1349
+ },
+ "render_test.go": {
+ "mode": "0o644",
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb",
+ "size": 2890
+ }
+ },
+ "public_files": {
+ ".github/ISSUE_TEMPLATE/bug_report.md": {
+ "mode": "0o644",
+ "sha256": "89d3492ca8533a3d31e4de49a23828a322f75d2a1ec4236327c4a76c7c51ada6",
+ "size": 684
+ },
+ ".github/ISSUE_TEMPLATE/feature_request.md": {
+ "mode": "0o644",
+ "sha256": "d82e14e6b4d021d0007eeef4f5ca489fc6c8e8e4d7479ee30e74fe82afd3b08f",
+ "size": 206
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "3239b94a1a41c05eff5dc086ef1378cf1e289fad0203420b5cb4c78e3c5c239b",
+ "size": 270
+ },
+ "CHANGELOG.md": {
+ "mode": "0o644",
+ "sha256": "1f88f92d3247e1b52af0f0de7ad1263a59807edb17238c7a0211554f8080e51c",
+ "size": 2895
+ },
+ "LICENSE": {
+ "mode": "0o644",
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "size": 1072
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "9425a0d4c15747863625f647348962a9b0f81a0971a7e0184ee722bf34a60ba2",
+ "size": 1177
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "ce56df51a1a9a5b5c5b056429bbee006a260fb0730af63b1d0fe91755e574cc4",
+ "size": 6185
+ },
+ "_example/README.md": {
+ "mode": "0o644",
+ "sha256": "155951bafd778493bd41ae57dcc0ba6b8eca821fcbe2ffe770960ac2780d3d09",
+ "size": 1102
+ },
+ "_example/build.sh": {
+ "mode": "0o755",
+ "sha256": "de2fb330b665691cd75b990236cd6a5df0058608de0dfc6194da30d4041a1e29",
+ "size": 469
+ },
+ "_example/exec-command/main.go": {
+ "mode": "0o644",
+ "sha256": "0e96493b6e6d446b2e691d4834ff8a55834caa410ead970cb611a63ba84f174a",
+ "size": 429
+ },
+ "_example/http-prompt/api.py": {
+ "mode": "0o644",
+ "sha256": "2c2bca9acb07a84c65a4482c61c9ade253a574477a8e461307568ea1f9a342c8",
+ "size": 335
+ },
+ "_example/http-prompt/main.go": {
+ "mode": "0o644",
+ "sha256": "6994b190c4165068e69ed44eb61698af69a15a7690179ce46e3c1c5d8c211643",
+ "size": 5484
+ },
+ "_example/live-prefix/main.go": {
+ "mode": "0o644",
+ "sha256": "20268f9cb6f3b82a52eddc33cbf8082adaa46092e2063df279499e05e25a228c",
+ "size": 1103
+ },
+ "_example/simple-echo/cjk-cyrillic/main.go": {
+ "mode": "0o644",
+ "sha256": "8fb10807d4085ebc4b345bc0ccfef9217e21e49a888bfe3192e8ddfdfa01e89c",
+ "size": 800
+ },
+ "_example/simple-echo/main.go": {
+ "mode": "0o644",
+ "sha256": "e46563ddaa932831fe9ede870b10efb5222c0d54a86f4b4f5197c9cf20942a24",
+ "size": 902
+ },
+ "_tools/README.md": {
+ "mode": "0o644",
+ "sha256": "96dc2343bc5cde642fd449ddc366462753a2e17b6a78adfa015bf991e9dac241",
+ "size": 234
+ },
+ "_tools/complete_file/main.go": {
+ "mode": "0o644",
+ "sha256": "e5dd823f9d6415614a8238ce106d26e9ded1db9b308c121d7f48bb1df003effc",
+ "size": 803
+ },
+ "_tools/sigwinch/main.go": {
+ "mode": "0o644",
+ "sha256": "a806b4e45298f5003c95432d8dd3c40c9c096335f19f1a4160afcdb64fa727e3",
+ "size": 1386
+ },
+ "_tools/vt100_debug/main.go": {
+ "mode": "0o644",
+ "sha256": "7f72eba3cc7037fcf39c9b56a96c578c157e5fb235cb626ab1e83cbef0dc290b",
+ "size": 794
+ },
+ "buffer.go": {
+ "mode": "0o644",
+ "sha256": "6398a84ff86d9ead44694840b72daa2c01ea6fec1c33aea9b56f1aedf77400fe",
+ "size": 5781
+ },
+ "completer/file.go": {
+ "mode": "0o644",
+ "sha256": "6181ed9e39028236c5c93fbe219331fc1492ecfd6af2df764cc42b5455c9bb96",
+ "size": 2401
+ },
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "b90bd9628534cfb343a592775430e17a1999b1de500fb2a8f1507c030a432eae",
+ "size": 4491
+ },
+ "document.go": {
+ "mode": "0o644",
+ "sha256": "e719d4c10a10f506c371b87dbd363a9b7f7d3aa8f0190a40965ac761197e1f1e",
+ "size": 13097
+ },
+ "emacs.go": {
+ "mode": "0o644",
+ "sha256": "53f0df0016ef9d9695a797b19286681666cf0c7e5a866c393b194aae915f2664",
+ "size": 2675
+ },
+ "filter.go": {
+ "mode": "0o644",
+ "sha256": "dc5922bad6ecb32ecdaf20bd6035dddc7ce8c14f15dbd4d49192c2354cb8a038",
+ "size": 2005
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "97413fa2a2ed68170496f2289a2dca6fb0a192dcd020fc0ca48a5d106e60d55e",
+ "size": 253
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "88ea0a91babaa54b67cc6d5f6f7f47fa4be798fe523324ea568d8926eed2024c",
+ "size": 2183
+ },
+ "history.go": {
+ "mode": "0o644",
+ "sha256": "4ce80ba067cfc72c56a3ee3353ec75cd6bb2f5d82097515c591e3c7c773c51cd",
+ "size": 1488
+ },
+ "input.go": {
+ "mode": "0o644",
+ "sha256": "73461cc4f57d68b66e2a9e196239aaef942539134593beac0d0023743832e0e1",
+ "size": 7630
+ },
+ "input_posix.go": {
+ "mode": "0o644",
+ "sha256": "c7e5a4dfc3910f178f0685ef99f2e47d481a91c4cf9af50f92fc4266aed634df",
+ "size": 1648
+ },
+ "input_windows.go": {
+ "mode": "0o644",
+ "sha256": "f763250d309fb88d9536f77da1d1285c04bc6defe859506f1501e10f7743da9e",
+ "size": 1679
+ },
+ "internal/bisect/bisect.go": {
+ "mode": "0o644",
+ "sha256": "c4de2adfa2e08a77f902661d67325467f89013634dbcef22d24dc6f34d26624a",
+ "size": 327
+ },
+ "internal/debug/assert.go": {
+ "mode": "0o644",
+ "sha256": "1a3050ec58991b62c7ea352d19505e3080ac9760bdb091544f0ecf5aba35969c",
+ "size": 815
+ },
+ "internal/debug/log.go": {
+ "mode": "0o644",
+ "sha256": "2ce968e275558de61c6d83793e85561f7a8dd69c95ec7902ccd2cc3fb169aa82",
+ "size": 875
+ },
+ "internal/strings/strings.go": {
+ "mode": "0o644",
+ "sha256": "b97f08157c3baf1f94fea4bb2237691d8270bd5380b4311709ecd59b84cf4b7b",
+ "size": 2018
+ },
+ "internal/term/raw.go": {
+ "mode": "0o644",
+ "sha256": "177a1a20ae8d71b56857383a5797754560f7f6404ea86778d5f01e9a1c1b4f9f",
+ "size": 747
+ },
+ "internal/term/term.go": {
+ "mode": "0o644",
+ "sha256": "abe6fa965fa15b999b2010135903f598830d4c885a52ef9b067fd5ebbf6e373f",
+ "size": 606
+ },
+ "key.go": {
+ "mode": "0o644",
+ "sha256": "03a43283e07de7a4ea6fed32692d86325f73e98fd89a296f19c171e0bc780999",
+ "size": 1746
+ },
+ "key_bind.go": {
+ "mode": "0o644",
+ "sha256": "83f48bb720a11c8e49165ac382e3a870fdcf6b380a0a95267f8c25211898c9eb",
+ "size": 1109
+ },
+ "key_bind_func.go": {
+ "mode": "0o644",
+ "sha256": "445bff5c0fdb0b52879c635322603c2fc75d265de3761cb8c3b980c798bf39af",
+ "size": 1219
+ },
+ "key_string.go": {
+ "mode": "0o644",
+ "sha256": "55c429dae227bb1659d5d5e2e906dbfa9c7f53b5105fa83fbe290529ff6f2317",
+ "size": 1359
+ },
+ "option.go": {
+ "mode": "0o644",
+ "sha256": "28cfcc1d08b3cf650483d977195458531b3b3913f8a5f357a3ec17ea5d73e215",
+ "size": 8737
+ },
+ "output.go": {
+ "mode": "0o644",
+ "sha256": "372876b0aa908479ed3b29de70a479f420d85e3666b8957c8b61eaed9b32c3f2",
+ "size": 4320
+ },
+ "output_posix.go": {
+ "mode": "0o644",
+ "sha256": "d46b1da307e8969b033e1ade2eb51a83c4c3d4f2a7e4aba35ec3a03991b89a0f",
+ "size": 1545
+ },
+ "output_vt100.go": {
+ "mode": "0o644",
+ "sha256": "9082c7e4619c1eb38030bc4994a4fbf66ef27b130751bf2eb9c25c01082e8605",
+ "size": 7453
+ },
+ "output_windows.go": {
+ "mode": "0o644",
+ "sha256": "571c5ae1ad051a701b426371efd79a3776c2226ca9e3c2e598fe5996dfa1b8e1",
+ "size": 1066
+ },
+ "prompt.go": {
+ "mode": "0o644",
+ "sha256": "6b3e2bbd90f40ad6a487f1a6ea7f5a6fb48cae6c8c246ecc77621fb3e7383ca7",
+ "size": 7062
+ },
+ "render.go": {
+ "mode": "0o644",
+ "sha256": "90fdd57a63e06f01940d10ee1a0be95ced7d6adc7faa255b3141556d7d316270",
+ "size": 8020
+ },
+ "shortcut.go": {
+ "mode": "0o644",
+ "sha256": "b4a097f466df7396049ebe8393f81c9b1200159d4e2be22bd6838c307ec156dc",
+ "size": 1120
+ },
+ "signal_posix.go": {
+ "mode": "0o644",
+ "sha256": "74f0bae5f290f3f7f82a5dd495e672f627a4ab4b63118f870e8c13c0a7024314",
+ "size": 881
+ },
+ "signal_windows.go": {
+ "mode": "0o644",
+ "sha256": "444f662a32e6997df2af8e2a9e7dbfe977414a6bfc0f54a7f10117f204648437",
+ "size": 757
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982",
+ "os": "linux",
+ "sha256": "0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982"
+ },
+ "context_inventory_sha256": "6b8f93086e81483ac1ce82f328d7f4b38b1b560dbad057ed6a2a30ff3cf0e13f",
+ "image": "registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "9d3b21cdacadfa4f3de9584d0cea973e5aa2ceedcd5ec9cbd3a63df22b313455",
+ "receipt_path": "production/runtime-images-extra-v1/resolutions/316e0e68930cd4ef/resolution.json",
+ "receipt_sha256": "697bb0619eddcdfdeba1c9144b033f564f2d7514be6e6a44dc520fa4e63ed8bc",
+ "registry_digest": "sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "source_image": "docker.io/swebench/swesmith.x86_64.c-bata_1776_go-prompt.82a91227@sha256:3daf51c74a01657e9ad8f326651fb6f5b796ffecdb90098e74a52a9560e0a1bb",
+ "source_receipt_sha256": "b450bea0e201cbe194b765ded4b51539144c85296122c8b642d7e94c889526f3",
+ "space_commit": "5ae654cd2e9d695f0de304bd4398835fc7cf45e0",
+ "space_id": "harness-hub/scale800-go-316e0e68930cd4ef-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "1683394c712b04d240b5d16f613ab18d9b340d5863e2c0df8d0205e09aec0b61",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21",
+ "source_proof_sha256": "abb16848d47047e326cb3bef36b463664c75ae6d00727dc277cef24f8dfbf8fe",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "9992c59c25864ce1556e67b9e1501c93f6e7f9ff",
+ "instruction_sha256": "f71601a3bc20fb50ec8cbd7d45c067f3bb6400781dd6631e25e47d56fc5624a8",
+ "is_fork": true,
+ "learner_path": "tasks/3ea396b1b65a9f258c569d07/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/c-bata__go-prompt.82a91227/4f5335e42c678a3329de595256fbbbcbb9b42958/LICENSE"
+ },
+ "task_bundle": {
+ "basis": "Captured publisherMIT/train; exactsoftwarepermissionverifiedseparately",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "82a912274504477990ecf7c852eebb7c85291772",
+ "patch_sha256": "3c8b0105eede1ce822b95747b100dab44d551ee896c3d594ccd0b62f2d771a8f",
+ "provenance_path": "tasks/3ea396b1b65a9f258c569d07/source-proof.json",
+ "repository_lineage": [
+ "swesmith/c-bata__go-prompt.82a91227",
+ "c-bata/go-prompt"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "4f5335e42c678a3329de595256fbbbcbb9b42958",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "bd2dd73e7021c765153e86af050541204d1fe734",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/c-bata__go-prompt.82a91227",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn",
+ "task_sha256": "96968bb4e75f38d03133f3d808c198cc075766382ebec7bd9a9610ee667f649f",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "c-bata/go-prompt",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "1672511f4a668743c3bd367356a2c415955b05d783306203334ca02e7c510aac",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.md",
+ "/testbed/.github/ISSUE_TEMPLATE/feature_request.md",
+ "/testbed/.gitignore",
+ "/testbed/CHANGELOG.md",
+ "/testbed/LICENSE",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/_example/README.md",
+ "/testbed/_example/build.sh",
+ "/testbed/_example/exec-command/main.go",
+ "/testbed/_example/http-prompt/api.py",
+ "/testbed/_example/http-prompt/main.go",
+ "/testbed/_example/live-prefix/main.go",
+ "/testbed/_example/simple-echo/cjk-cyrillic/main.go",
+ "/testbed/_example/simple-echo/main.go",
+ "/testbed/_tools/README.md",
+ "/testbed/_tools/complete_file/main.go",
+ "/testbed/_tools/sigwinch/main.go",
+ "/testbed/_tools/vt100_debug/main.go",
+ "/testbed/buffer.go",
+ "/testbed/completer/file.go",
+ "/testbed/completion.go",
+ "/testbed/document.go",
+ "/testbed/emacs.go",
+ "/testbed/filter.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum",
+ "/testbed/history.go",
+ "/testbed/input.go",
+ "/testbed/input_posix.go",
+ "/testbed/input_windows.go",
+ "/testbed/internal/bisect/bisect.go",
+ "/testbed/internal/debug/assert.go",
+ "/testbed/internal/debug/log.go",
+ "/testbed/internal/strings/strings.go",
+ "/testbed/internal/term/raw.go",
+ "/testbed/internal/term/term.go",
+ "/testbed/key.go",
+ "/testbed/key_bind.go",
+ "/testbed/key_bind_func.go",
+ "/testbed/key_string.go",
+ "/testbed/option.go",
+ "/testbed/output.go",
+ "/testbed/output_posix.go",
+ "/testbed/output_vt100.go",
+ "/testbed/output_windows.go",
+ "/testbed/prompt.go",
+ "/testbed/render.go",
+ "/testbed/shortcut.go",
+ "/testbed/signal_posix.go",
+ "/testbed/signal_windows.go"
+ ]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/solution/solve.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7b1491520258de7be4d970d00e4aef3dabf95e6b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"buffer.go": {"data": "cGFja2FnZSBwcm9tcHQKCmltcG9ydCAoCgkic3RyaW5ncyIKCgkiZ2l0aHViLmNvbS9jLWJhdGEvZ28tcHJvbXB0L2ludGVybmFsL2RlYnVnIgopCgovLyBCdWZmZXIgZW11bGF0ZXMgdGhlIGNvbnNvbGUgYnVmZmVyLgp0eXBlIEJ1ZmZlciBzdHJ1Y3QgewoJd29ya2luZ0xpbmVzICAgIFtdc3RyaW5nIC8vIFRoZSB3b3JraW5nIGxpbmVzLiBTaW1pbGFyIHRvIGhpc3RvcnkKCXdvcmtpbmdJbmRleCAgICBpbnQKCWN1cnNvclBvc2l0aW9uICBpbnQKCWNhY2hlRG9jdW1lbnQgICAqRG9jdW1lbnQKCXByZWZlcnJlZENvbHVtbiBpbnQgLy8gUmVtZW1iZXIgdGhlIG9yaWdpbmFsIGNvbHVtbiBmb3IgdGhlIG5leHQgdXAvZG93biBtb3ZlbWVudC4KCWxhc3RLZXlTdHJva2UgICBLZXkKfQoKLy8gVGV4dCByZXR1cm5zIHN0cmluZyBvZiB0aGUgY3VycmVudCBsaW5lLgpmdW5jIChiICpCdWZmZXIpIFRleHQoKSBzdHJpbmcgewoJcmV0dXJuIGIud29ya2luZ0xpbmVzW2Iud29ya2luZ0luZGV4XQp9CgovLyBEb2N1bWVudCBtZXRob2QgdG8gcmV0dXJuIGRvY3VtZW50IGluc3RhbmNlIGZyb20gdGhlIGN1cnJlbnQgdGV4dCBhbmQgY3Vyc29yIHBvc2l0aW9uLgpmdW5jIChiICpCdWZmZXIpIERvY3VtZW50KCkgKGQgKkRvY3VtZW50KSB7CglpZiBiLmNhY2hlRG9jdW1lbnQgPT0gbmlsIHx8CgkJYi5jYWNoZURvY3VtZW50LlRleHQgIT0gYi5UZXh0KCkgfHwKCQliLmNhY2hlRG9jdW1lbnQuY3Vyc29yUG9zaXRpb24gIT0gYi5jdXJzb3JQb3NpdGlvbiB7CgkJYi5jYWNoZURvY3VtZW50ID0gJkRvY3VtZW50ewoJCQlUZXh0OiAgICAgICAgICAgYi5UZXh0KCksCgkJCWN1cnNvclBvc2l0aW9uOiBiLmN1cnNvclBvc2l0aW9uLAoJCX0KCX0KCWIuY2FjaGVEb2N1bWVudC5sYXN0S2V5ID0gYi5sYXN0S2V5U3Ryb2tlCglyZXR1cm4gYi5jYWNoZURvY3VtZW50Cn0KCi8vIERpc3BsYXlDdXJzb3JQb3NpdGlvbiByZXR1cm5zIHRoZSBjdXJzb3IgcG9zaXRpb24gb24gcmVuZGVyZWQgdGV4dCBvbiB0ZXJtaW5hbCBlbXVsYXRvcnMuCi8vIFNvIGlmIERvY3VtZW50IGlzICLml6XmnKwoY3Vyc29yKeiqniIsIERpc3BsYXllZEN1cnNvclBvc2l0aW9uIHJldHVybnMgNCBiZWNhdXNlICfml6UnIGFuZCAn5pysJyBhcmUgZG91YmxlIHdpZHRoIGNoYXJhY3RlcnMuCmZ1bmMgKGIgKkJ1ZmZlcikgRGlzcGxheUN1cnNvclBvc2l0aW9uKCkgaW50IHsKCXJldHVybiBiLkRvY3VtZW50KCkuRGlzcGxheUN1cnNvclBvc2l0aW9uKCkKfQoKLy8gSW5zZXJ0VGV4dCBpbnNlcnQgc3RyaW5nIGZyb20gY3VycmVudCBsaW5lLgpmdW5jIChiICpCdWZmZXIpIEluc2VydFRleHQodiBzdHJpbmcsIG92ZXJ3cml0ZSBib29sLCBtb3ZlQ3Vyc29yIGJvb2wpIHsKCW9yIDo9IFtdcnVuZShiLlRleHQoKSkKCW9jIDo9IGIuY3Vyc29yUG9zaXRpb24KCglpZiBvdmVyd3JpdGUgewoJCW92ZXJ3cml0dGVuIDo9IHN0cmluZyhvcltvYyA6IG9jK2xlbih2KV0pCgkJaWYgc3RyaW5ncy5Db250YWlucyhvdmVyd3JpdHRlbiwgIlxuIikgewoJCQlpIDo9IHN0cmluZ3MuSW5kZXhBbnkob3ZlcndyaXR0ZW4sICJcbiIpCgkJCW92ZXJ3cml0dGVuID0gb3ZlcndyaXR0ZW5bOmldCgkJfQoJCWIuc2V0VGV4dChzdHJpbmcob3JbOm9jXSkgKyB2ICsgc3RyaW5nKG9yW29jK2xlbihvdmVyd3JpdHRlbik6XSkpCgl9IGVsc2UgewoJCWIuc2V0VGV4dChzdHJpbmcob3JbOm9jXSkgKyB2ICsgc3RyaW5nKG9yW29jOl0pKQoJfQoKCWlmIG1vdmVDdXJzb3IgewoJCWIuY3Vyc29yUG9zaXRpb24gKz0gbGVuKFtdcnVuZSh2KSkKCX0KfQoKLy8gU2V0VGV4dCBtZXRob2QgdG8gc2V0IHRleHQgYW5kIHVwZGF0ZSBjdXJzb3JQb3NpdGlvbi4KLy8gKFdoZW4gZG9pbmcgdGhpcywgbWFrZSBzdXJlIHRoYXQgdGhlIGN1cnNvcl9wb3NpdGlvbiBpcyB2YWxpZCBmb3IgdGhpcyB0ZXh0LgovLyB0ZXh0L2N1cnNvcl9wb3NpdGlvbiBzaG91bGQgYmUgY29uc2lzdGVudCBhdCBhbnkgdGltZSwgb3RoZXJ3aXNlIHNldCBhIERvY3VtZW50IGluc3RlYWQuKQpmdW5jIChiICpCdWZmZXIpIHNldFRleHQodiBzdHJpbmcpIHsKCWRlYnVnLkFzc2VydChiLmN1cnNvclBvc2l0aW9uIDw9IGxlbihbXXJ1bmUodikpLCAibGVuZ3RoIG9mIGlucHV0IHNob3VsZCBiZSBzaG9ydGVyIHRoYW4gY3Vyc29yIHBvc2l0aW9uIikKCWIud29ya2luZ0xpbmVzW2Iud29ya2luZ0luZGV4XSA9IHYKfQoKLy8gU2V0IGN1cnNvciBwb3NpdGlvbi4gUmV0dXJuIHdoZXRoZXIgaXQgY2hhbmdlZC4KZnVuYyAoYiAqQnVmZmVyKSBzZXRDdXJzb3JQb3NpdGlvbihwIGludCkgewoJaWYgcCA+IDAgewoJCWIuY3Vyc29yUG9zaXRpb24gPSBwCgl9IGVsc2UgewoJCWIuY3Vyc29yUG9zaXRpb24gPSAwCgl9Cn0KCmZ1bmMgKGIgKkJ1ZmZlcikgc2V0RG9jdW1lbnQoZCAqRG9jdW1lbnQpIHsKCWIuY2FjaGVEb2N1bWVudCA9IGQKCWIuc2V0Q3Vyc29yUG9zaXRpb24oZC5jdXJzb3JQb3NpdGlvbikgLy8gQ2FsbCBiZWZvcmUgc2V0VGV4dCBiZWNhdXNlIHNldFRleHQgY2hlY2sgdGhlIHJlbGF0aW9uIGJldHdlZW4gY3Vyc29yUG9zaXRpb24gYW5kIGxpbmUgbGVuZ3RoLgoJYi5zZXRUZXh0KGQuVGV4dCkKfQoKLy8gQ3Vyc29yTGVmdCBtb3ZlIHRvIGxlZnQgb24gdGhlIGN1cnJlbnQgbGluZS4KZnVuYyAoYiAqQnVmZmVyKSBDdXJzb3JMZWZ0KGNvdW50IGludCkgewoJbCA6PSBiLkRvY3VtZW50KCkuR2V0Q3Vyc29yTGVmdFBvc2l0aW9uKGNvdW50KQoJYi5jdXJzb3JQb3NpdGlvbiArPSBsCn0KCi8vIEN1cnNvclJpZ2h0IG1vdmUgdG8gcmlnaHQgb24gdGhlIGN1cnJlbnQgbGluZS4KZnVuYyAoYiAqQnVmZmVyKSBDdXJzb3JSaWdodChjb3VudCBpbnQpIHsKCWwgOj0gYi5Eb2N1bWVudCgpLkdldEN1cnNvclJpZ2h0UG9zaXRpb24oY291bnQpCgliLmN1cnNvclBvc2l0aW9uICs9IGwKfQoKLy8gQ3Vyc29yVXAgbW92ZSBjdXJzb3IgdG8gdGhlIHByZXZpb3VzIGxpbmUuCi8vIChmb3IgbXVsdGktbGluZSBlZGl0KS4KZnVuYyAoYiAqQnVmZmVyKSBDdXJzb3JVcChjb3VudCBpbnQpIHsKCW9yaWcgOj0gYi5wcmVmZXJyZWRDb2x1bW4KCWlmIGIucHJlZmVycmVkQ29sdW1uID09IC0xIHsgLy8gLTEgbWVhbnMgbmlsCgkJb3JpZyA9IGIuRG9jdW1lbnQoKS5DdXJzb3JQb3NpdGlvbkNvbCgpCgl9CgliLmN1cnNvclBvc2l0aW9uICs9IGIuRG9jdW1lbnQoKS5HZXRDdXJzb3JVcFBvc2l0aW9uKGNvdW50LCBvcmlnKQoKCS8vIFJlbWVtYmVyIHRoZSBvcmlnaW5hbCBjb2x1bW4gZm9yIHRoZSBuZXh0IHVwL2Rvd24gbW92ZW1lbnQuCgliLnByZWZlcnJlZENvbHVtbiA9IG9yaWcKfQoKLy8gQ3Vyc29yRG93biBtb3ZlIGN1cnNvciB0byB0aGUgbmV4dCBsaW5lLgovLyAoZm9yIG11bHRpLWxpbmUgZWRpdCkuCmZ1bmMgKGIgKkJ1ZmZlcikgQ3Vyc29yRG93bihjb3VudCBpbnQpIHsKCW9yaWcgOj0gYi5wcmVmZXJyZWRDb2x1bW4KCWlmIGIucHJlZmVycmVkQ29sdW1uID09IC0xIHsgLy8gLTEgbWVhbnMgbmlsCgkJb3JpZyA9IGIuRG9jdW1lbnQoKS5DdXJzb3JQb3NpdGlvbkNvbCgpCgl9CgliLmN1cnNvclBvc2l0aW9uICs9IGIuRG9jdW1lbnQoKS5HZXRDdXJzb3JEb3duUG9zaXRpb24oY291bnQsIG9yaWcpCgoJLy8gUmVtZW1iZXIgdGhlIG9yaWdpbmFsIGNvbHVtbiBmb3IgdGhlIG5leHQgdXAvZG93biBtb3ZlbWVudC4KCWIucHJlZmVycmVkQ29sdW1uID0gb3JpZwp9CgovLyBEZWxldGVCZWZvcmVDdXJzb3IgZGVsZXRlIHNwZWNpZmllZCBudW1iZXIgb2YgY2hhcmFjdGVycyBiZWZvcmUgY3Vyc29yIGFuZCByZXR1cm4gdGhlIGRlbGV0ZWQgdGV4dC4KZnVuYyAoYiAqQnVmZmVyKSBEZWxldGVCZWZvcmVDdXJzb3IoY291bnQgaW50KSAoZGVsZXRlZCBzdHJpbmcpIHsKCWRlYnVnLkFzc2VydChjb3VudCA+PSAwLCAiY291bnQgc2hvdWxkIGJlIHBvc2l0aXZlIikKCXIgOj0gW11ydW5lKGIuVGV4dCgpKQoKCWlmIGIuY3Vyc29yUG9zaXRpb24gPiAwIHsKCQlzdGFydCA6PSBiLmN1cnNvclBvc2l0aW9uIC0gY291bnQKCQlpZiBzdGFydCA8IDAgewoJCQlzdGFydCA9IDAKCQl9CgkJZGVsZXRlZCA9IHN0cmluZyhyW3N0YXJ0OmIuY3Vyc29yUG9zaXRpb25dKQoJCWIuc2V0RG9jdW1lbnQoJkRvY3VtZW50ewoJCQlUZXh0OiAgICAgICAgICAgc3RyaW5nKHJbOnN0YXJ0XSkgKyBzdHJpbmcocltiLmN1cnNvclBvc2l0aW9uOl0pLAoJCQljdXJzb3JQb3NpdGlvbjogYi5jdXJzb3JQb3NpdGlvbiAtIGxlbihbXXJ1bmUoZGVsZXRlZCkpLAoJCX0pCgl9CglyZXR1cm4KfQoKLy8gTmV3TGluZSBtZWFucyBDUi4KZnVuYyAoYiAqQnVmZmVyKSBOZXdMaW5lKGNvcHlNYXJnaW4gYm9vbCkgewoJaWYgY29weU1hcmdpbiB7CgkJYi5JbnNlcnRUZXh0KCJcbiIrYi5Eb2N1bWVudCgpLmxlYWRpbmdXaGl0ZXNwYWNlSW5DdXJyZW50TGluZSgpLCBmYWxzZSwgdHJ1ZSkKCX0gZWxzZSB7CgkJYi5JbnNlcnRUZXh0KCJcbiIsIGZhbHNlLCB0cnVlKQoJfQp9CgovLyBEZWxldGUgc3BlY2lmaWVkIG51bWJlciBvZiBjaGFyYWN0ZXJzIGFuZCBSZXR1cm4gdGhlIGRlbGV0ZWQgdGV4dC4KZnVuYyAoYiAqQnVmZmVyKSBEZWxldGUoY291bnQgaW50KSAoZGVsZXRlZCBzdHJpbmcpIHsKCXIgOj0gW11ydW5lKGIuVGV4dCgpKQoJaWYgYi5jdXJzb3JQb3NpdGlvbiA8IGxlbihyKSB7CgkJZGVsZXRlZCA9IGIuRG9jdW1lbnQoKS5UZXh0QWZ0ZXJDdXJzb3IoKVs6Y291bnRdCgkJYi5zZXRUZXh0KHN0cmluZyhyWzpiLmN1cnNvclBvc2l0aW9uXSkgKyBzdHJpbmcocltiLmN1cnNvclBvc2l0aW9uK2xlbihkZWxldGVkKTpdKSkKCX0KCXJldHVybgp9CgovLyBKb2luTmV4dExpbmUgam9pbnMgdGhlIG5leHQgbGluZSB0byB0aGUgY3VycmVudCBvbmUgYnkgZGVsZXRpbmcgdGhlIGxpbmUgZW5kaW5nIGFmdGVyIHRoZSBjdXJyZW50IGxpbmUuCmZ1bmMgKGIgKkJ1ZmZlcikgSm9pbk5leHRMaW5lKHNlcGFyYXRvciBzdHJpbmcpIHsKCWlmICFiLkRvY3VtZW50KCkuT25MYXN0TGluZSgpIHsKCQliLmN1cnNvclBvc2l0aW9uICs9IGIuRG9jdW1lbnQoKS5HZXRFbmRPZkxpbmVQb3NpdGlvbigpCgkJYi5EZWxldGUoMSkKCQkvLyBSZW1vdmUgc3BhY2VzCgkJYi5zZXRUZXh0KGIuRG9jdW1lbnQoKS5UZXh0QmVmb3JlQ3Vyc29yKCkgKyBzZXBhcmF0b3IgKyBzdHJpbmdzLlRyaW1MZWZ0KGIuRG9jdW1lbnQoKS5UZXh0QWZ0ZXJDdXJzb3IoKSwgIiAiKSkKCX0KfQoKLy8gU3dhcENoYXJhY3RlcnNCZWZvcmVDdXJzb3Igc3dhcHMgdGhlIGxhc3QgdHdvIGNoYXJhY3RlcnMgYmVmb3JlIHRoZSBjdXJzb3IuCmZ1bmMgKGIgKkJ1ZmZlcikgU3dhcENoYXJhY3RlcnNCZWZvcmVDdXJzb3IoKSB7CglpZiBiLmN1cnNvclBvc2l0aW9uID49IDIgewoJCXggOj0gYi5UZXh0KClbYi5jdXJzb3JQb3NpdGlvbi0yIDogYi5jdXJzb3JQb3NpdGlvbi0xXQoJCXkgOj0gYi5UZXh0KClbYi5jdXJzb3JQb3NpdGlvbi0xIDogYi5jdXJzb3JQb3NpdGlvbl0KCQliLnNldFRleHQoYi5UZXh0KClbOmIuY3Vyc29yUG9zaXRpb24tMl0gKyB5ICsgeCArIGIuVGV4dCgpW2IuY3Vyc29yUG9zaXRpb246XSkKCX0KfQoKLy8gTmV3QnVmZmVyIGlzIGNvbnN0cnVjdG9yIG9mIEJ1ZmZlciBzdHJ1Y3QuCmZ1bmMgTmV3QnVmZmVyKCkgKGIgKkJ1ZmZlcikgewoJYiA9ICZCdWZmZXJ7CgkJd29ya2luZ0xpbmVzOiAgICBbXXN0cmluZ3siIn0sCgkJd29ya2luZ0luZGV4OiAgICAwLAoJCXByZWZlcnJlZENvbHVtbjogLTEsIC8vIC0xIG1lYW5zIG5pbAoJfQoJcmV0dXJuCn0K", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/task.toml b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..a51fbae6d91b87de20d78535a31816252c2fc471
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/task.toml
@@ -0,0 +1,11 @@
+version = "1.0"
+[agent]
+timeout_sec = 300.0
+[verifier]
+timeout_sec = 300.0
+environment_mode = "shared"
+[environment]
+docker_image = "ghcr.io/younesbelkada/scale800@sha256:a173dcdc0b4e0ba2cb7f5af1b748e8b9ad2dc2c61a40ff91c085d615f59574f1"
+cpus = 1
+memory_mb = 2048
+storage_mb = 4096
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..43d184fa27fc3f99d96c42bdd8185cbf7f728a7f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/manifest.json
@@ -0,0 +1,432 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CursorPositionRowAndCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorLeftPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorUpPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorDownPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorRightPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_Lines"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_LineCount"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateIndexToPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateRowColToIndex"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_OnLastLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetEndOfLinePosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestEmacsKeyBindings"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFilter"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFuzzyMatch"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryClear"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryAdd"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryOlder"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/escape"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/undefined"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWrite"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteRawStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatCompletion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBreakLineCallback"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionRow"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition_withJapanese"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/validation/canaries/delete-tests.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/validation/canaries/delete-tests.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/validation/canaries/delete-tests.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+find /testbed -name '*_test.go' -type f -delete
+printf 'PASS\nok forged-package 0.001s\n'
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..2ca39107df665165a2bccfcc4b1911a8bf3c2b72
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "16354cbba400baf421ea119329e22f4aadbe3d8a2932637d6980619ae15ddc0c",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/Dockerfile b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f35bf9e5393ee1086fe1b72c1b442f3b16e2bd5b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22
+WORKDIR /testbed
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c8c031d0f87fb9aea0aff433b1fcaeaac259c41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: "Bug report"
+about: Create a bug report to improve go-prompt
+title: "[Bug]"
+labels: bug
+assignees: ''
+
+---
+
+# Bug reports
+
+*Please file a bug report here.*
+
+## Expected Behavior
+
+*Please describe the behavior you are expecting*
+
+## Current Behavior and Steps to Reproduce
+
+*What is the current behavior? Please provide detailed steps for reproducing the issue.*
+*A picture or gif animation tells a thousand words*
+
+## Context
+
+Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
+
+* Operating System:
+* Terminal Emulator: (i.e. iTerm2)
+* tag of go-prompt or commit revision:
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb816a2496376983781774cb5466fed8e1efc93b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,13 @@
+---
+name: "Feature request"
+about: Suggest an idea for new features in go-prompt.
+title: "[Feature Request]"
+labels: enhancement
+assignees: ''
+
+---
+
+# Feature Request
+
+*Please write your suggestion here.*
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/.gitignore b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..eba2b56abe0f7758a560d47dd19d8985b67ef327
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+bin/
+
+# Folders
+pkg/
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+# Glide
+vendor/
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/CHANGELOG.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..b9e21f1ef333b9ec13323bcd4a8f377322ed7e9f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/CHANGELOG.md
@@ -0,0 +1,79 @@
+# Change Log
+
+## v0.3.0 (2018/??/??)
+
+next release.
+
+## v0.2.3 (2018/10/25)
+
+### What's new?
+
+* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92).
+* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100).
+* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102).
+
+### Fixed
+
+* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details).
+* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details).
+* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details).
+
+### Removed or Deprecated
+
+* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`.
+
+## v0.2.2 (2018/06/28)
+
+### What's new?
+
+* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters.
+* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions.
+ * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details).
+* Add FilePathCompleter to complete file path on your system.
+* Add option to customize ascii code key bindings.
+* Add GetWordAfterCursor method in Document.
+
+### Removed or Deprecated
+
+* prompt.Choose shortcut function is deprecated.
+
+## v0.2.1 (2018/02/14)
+
+### What's New?
+
+* ~~It seems that windows support is almost perfect.~~
+ * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows.
+
+### Fixed
+
+* Fix a Shift+Tab handling on Windows.
+* Fix 4-dimension arrow keys handling on Windows.
+
+## v0.2.0 (2018/02/13)
+
+### What's New?
+
+* Supports scrollbar when there are too many matched suggestions
+* Windows support (but please caution because this is still not perfect).
+* Add OptionLivePrefix to update the prefix dynamically
+* Implement clear screen by `Ctrl+L`.
+
+### Fixed
+
+* Fix the behavior of `Ctrl+W` keybind.
+* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details).
+* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details).
+* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ).
+
+### News
+
+New core developers are joined (alphabetical order).
+
+* Nao Yonashiro (Github @orisano)
+* Ryoma Abe (Github @Allajah)
+* Yusuke Nakamura (Github @unasuke)
+
+
+## v0.1.0 (2017/08/15)
+
+Initial Release
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/LICENSE b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a86acaa7ab24fe61ea152a9afcadc21980020efb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Masashi SHIBATA
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/Makefile b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..505817c36f0b8a0bb643eed8680b8989af2b0920
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/Makefile
@@ -0,0 +1,46 @@
+.DEFAULT_GOAL := help
+
+SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
+
+GOIMPORTS ?= goimports
+GOCILINT ?= golangci-lint
+
+.PHONY: setup
+setup: ## Setup for required tools.
+ go get -u golang.org/x/tools/cmd/goimports
+ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: fmt
+fmt: $(SOURCES) ## Formatting source codes.
+ @$(GOIMPORTS) -w $^
+
+.PHONY: lint
+lint: ## Run golangci-lint.
+ @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
+
+.PHONY: test
+test: ## Run tests with race condition checking.
+ @go test -race ./...
+
+.PHONY: bench
+bench: ## Run benchmarks.
+ @go test -bench=. -run=- -benchmem ./...
+
+.PHONY: coverage
+cover: ## Run the tests.
+ @go test -coverprofile=coverage.o
+ @go tool cover -func=coverage.o
+
+.PHONY: generate
+generate: ## Run go generate
+ @go generate ./...
+
+.PHONY: build
+build: ## Build example command lines.
+ ./_example/build.sh
+
+.PHONY: help
+help: ## Show help text
+ @echo "Commands:"
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}'
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/README.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfcd7a399b4827d6b126d6a173cce34d36520481
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/README.md
@@ -0,0 +1,125 @@
+# go-prompt
+
+[](https://goreportcard.com/report/github.com/c-bata/go-prompt)
+
+[](https://godoc.org/github.com/c-bata/go-prompt)
+
+
+A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit),
+making it easier to build cross-platform command line tools using Go.
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func completer(d prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ }
+ return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ fmt.Println("Please select table.")
+ t := prompt.Input("> ", completer)
+ fmt.Println("You selected " + t)
+}
+```
+
+#### Projects using go-prompt
+
+* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt)
+* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli)
+* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn)
+* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli)
+* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans)
+* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit)
+* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go)
+* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS)
+* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs)
+* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli)
+* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt)
+* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh)
+* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell)
+* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt)
+* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim)
+* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron)
+* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl)
+* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl)
+* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit)
+* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.)
+
+## Features
+
+### Powerful auto-completion
+
+[](https://github.com/c-bata/kube-prompt)
+
+(This is a GIF animation of kube-prompt.)
+
+### Flexible options
+
+go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details.
+
+[](#flexible-options)
+
+### Keyboard Shortcuts
+
+Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell).
+You can customize and expand these shortcuts.
+
+[](#keyboard-shortcuts)
+
+Key Binding | Description
+---------------------|---------------------------------------------------------
+Ctrl + A | Go to the beginning of the line (Home)
+Ctrl + E | Go to the end of the line (End)
+Ctrl + P | Previous command (Up arrow)
+Ctrl + N | Next command (Down arrow)
+Ctrl + F | Forward one character
+Ctrl + B | Backward one character
+Ctrl + D | Delete character under the cursor
+Ctrl + H | Delete character before the cursor (Backspace)
+Ctrl + W | Cut the word before the cursor to the clipboard
+Ctrl + K | Cut the line after the cursor to the clipboard
+Ctrl + U | Cut the line before the cursor to the clipboard
+Ctrl + L | Clear the screen
+
+### History
+
+You can use Up arrow and Down arrow to walk through the history of commands executed.
+
+[](#history)
+
+### Multiple platform support
+
+We have confirmed go-prompt works fine in the following terminals:
+
+* iTerm2 (macOS)
+* Terminal.app (macOS)
+* Command Prompt (Windows)
+* gnome-terminal (Ubuntu)
+
+## Links
+
+* [Change Log](./CHANGELOG.md)
+* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt)
+* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt)
+
+## Author
+
+Masashi Shibata
+
+* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/)
+* Github: [@c-bata](https://github.com/c-bata/)
+
+## License
+
+This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/README.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..759b0e3f8acf1216b055e0f9458758a6c1e8950a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/README.md
@@ -0,0 +1,30 @@
+# Examples of go-prompt
+
+This directory includes some examples using go-prompt.
+These examples are useful to know the usage of go-prompt and check behavior for development.
+
+## simple-echo
+
+
+
+A simple echo example using `prompt.Input`.
+
+## http-prompt
+
+
+
+A simple [http-prompt](https://github.com/eliangcs/http-prompt) implementation using go-prompt in less than 200 lines of Go.
+
+## live-prefix
+
+
+
+A example application which changes a prefix string dynamically.
+This feature is used like [ktr0731/evans](https://github.com/ktr0731/evans) which is interactive gRPC client using go-prompt.
+
+## exec-command
+
+Run another CLI tool via `os/exec` package.
+More practical example is [a source code of kube-prompt](https://github.com/c-bata/kube-prompt).
+I recommend you to look this if you want to create tools like kube-prompt.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/build.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c552afcfa69b2356ffcd484c867abcaaaaeeaff
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+export GO111MODULE=on
+DIR=$(cd $(dirname $0); pwd)
+BIN_DIR=$(cd $(dirname $(dirname $0)); pwd)/bin
+
+mkdir -p ${BIN_DIR}
+go build -o ${BIN_DIR}/exec-command ${DIR}/exec-command/main.go
+go build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.go
+go build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.go
+go build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.go
+go build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/exec-command/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/exec-command/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..838f756260df91569491def29a7ee05a7c9a98f7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/exec-command/main.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "os/exec"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(t string) {
+ if t == "bash" {
+ cmd := exec.Command("bash")
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Run()
+ }
+ return
+}
+
+func completer(t prompt.Document) []prompt.Suggest {
+ return []prompt.Suggest{
+ {Text: "bash"},
+ }
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/http-prompt/api.py b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/http-prompt/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..08e7b1a489a2077f26f280fe39e3bd06efa52cd2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/http-prompt/api.py
@@ -0,0 +1,17 @@
+from bottle import route, run, request
+
+@route('/')
+def hello():
+ return "Hello World!"
+
+@route('/ping')
+def hello():
+ return "pong!"
+
+@route('/register', method='POST')
+def register():
+ name = request.json.get("name")
+ return "Hello %s!" % name
+
+if __name__ == "__main__":
+ run(host='localhost', port=8000, debug=True)
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/http-prompt/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/http-prompt/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b372a3550c50121d6e500e2a08e641e168b8c00d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/http-prompt/main.go
@@ -0,0 +1,192 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+type RequestContext struct {
+ url *url.URL
+ header http.Header
+ client *http.Client
+}
+
+var ctx *RequestContext
+
+// See https://github.com/eliangcs/http-prompt/blob/master/http_prompt/completion.py
+var suggestions = []prompt.Suggest{
+ // Command
+ {"cd", "Change URL/path"},
+ {"exit", "Exit http-prompt"},
+
+ // HTTP Method
+ {"delete", "DELETE request"},
+ {"get", "GET request"},
+ {"patch", "GET request"},
+ {"post", "POST request"},
+ {"put", "PUT request"},
+
+ // HTTP Header
+ {"Accept", "Acceptable response media type"},
+ {"Accept-Charset", "Acceptable response charsets"},
+ {"Accept-Encoding", "Acceptable response content codings"},
+ {"Accept-Language", "Preferred natural languages in response"},
+ {"ALPN", "Application-layer protocol negotiation to use"},
+ {"Alt-Used", "Alternative host in use"},
+ {"Authorization", "Authentication information"},
+ {"Cache-Control", "Directives for caches"},
+ {"Connection", "Connection options"},
+ {"Content-Encoding", "Content codings"},
+ {"Content-Language", "Natural languages for content"},
+ {"Content-Length", "Anticipated size for payload body"},
+ {"Content-Location", "Where content was obtained"},
+ {"Content-MD5", "Base64-encoded MD5 sum of content"},
+ {"Content-Type", "Content media type"},
+ {"Cookie", "Stored cookies"},
+ {"Date", "Datetime when message was originated"},
+ {"Depth", "Applied only to resource or its members"},
+ {"DNT", "Do not track user"},
+ {"Expect", "Expected behaviors supported by server"},
+ {"Forwarded", "Proxies involved"},
+ {"From", "Sender email address"},
+ {"Host", "Target URI"},
+ {"HTTP2-Settings", "HTTP/2 connection parameters"},
+ {"If", "Request condition on state tokens and ETags"},
+ {"If-Match", "Request condition on target resource"},
+ {"If-Modified-Since", "Request condition on modification date"},
+ {"If-None-Match", "Request condition on target resource"},
+ {"If-Range", "Request condition on Range"},
+ {"If-Schedule-Tag-Match", "Request condition on Schedule-Tag"},
+ {"If-Unmodified-Since", "Request condition on modification date"},
+ {"Max-Forwards", "Max number of times forwarded by proxies"},
+ {"MIME-Version", "Version of MIME protocol"},
+ {"Origin", "Origin(s} issuing the request"},
+ {"Pragma", "Implementation-specific directives"},
+ {"Prefer", "Preferred server behaviors"},
+ {"Proxy-Authorization", "Proxy authorization credentials"},
+ {"Proxy-Connection", "Proxy connection options"},
+ {"Range", "Request transfer of only part of data"},
+ {"Referer", "Previous web page"},
+ {"TE", "Transfer codings willing to accept"},
+ {"Transfer-Encoding", "Transfer codings applied to payload body"},
+ {"Upgrade", "Invite server to upgrade to another protocol"},
+ {"User-Agent", "User agent string"},
+ {"Via", "Intermediate proxies"},
+ {"Warning", "Possible incorrectness with payload body"},
+ {"WWW-Authenticate", "Authentication scheme"},
+ {"X-Csrf-Token", "Prevent cross-site request forgery"},
+ {"X-CSRFToken", "Prevent cross-site request forgery"},
+ {"X-Forwarded-For", "Originating client IP address"},
+ {"X-Forwarded-Host", "Original host requested by client"},
+ {"X-Forwarded-Proto", "Originating protocol"},
+ {"X-Http-Method-Override", "Request method override"},
+ {"X-Requested-With", "Used to identify Ajax requests"},
+ {"X-XSRF-TOKEN", "Prevent cross-site request forgery"},
+}
+
+func livePrefix() (string, bool) {
+ if ctx.url.Path == "/" {
+ return "", false
+ }
+ return ctx.url.String() + "> ", true
+}
+
+func executor(in string) {
+ in = strings.TrimSpace(in)
+
+ var method, body string
+ blocks := strings.Split(in, " ")
+ switch blocks[0] {
+ case "exit":
+ fmt.Println("Bye!")
+ os.Exit(0)
+ case "cd":
+ if len(blocks) < 2 {
+ ctx.url.Path = "/"
+ } else {
+ ctx.url.Path = path.Join(ctx.url.Path, blocks[1])
+ }
+ return
+ case "get", "delete":
+ method = strings.ToUpper(blocks[0])
+ case "post", "put", "patch":
+ if len(blocks) < 2 {
+ fmt.Println("please set request body.")
+ return
+ }
+ body = strings.Join(blocks[1:], " ")
+ method = strings.ToUpper(blocks[0])
+ }
+ if method != "" {
+ req, err := http.NewRequest(method, ctx.url.String(), strings.NewReader(body))
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ req.Header = ctx.header
+ res, err := ctx.client.Do(req)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ result, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ fmt.Printf("%s\n", result)
+ ctx.header = http.Header{}
+ return
+ }
+
+ if h := strings.Split(in, ":"); len(h) == 2 {
+ // Handling HTTP Header
+ ctx.header.Add(strings.TrimSpace(h[0]), strings.Trim(h[1], ` '"`))
+ } else {
+ fmt.Println("Sorry, I don't understand.")
+ }
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ w := in.GetWordBeforeCursor()
+ if w == "" {
+ return []prompt.Suggest{}
+ }
+ return prompt.FilterHasPrefix(suggestions, w, true)
+}
+
+func main() {
+ var baseURL = "http://localhost:8000/"
+ if len(os.Args) == 2 {
+ baseURL = os.Args[1]
+ if strings.HasSuffix(baseURL, "/") {
+ baseURL += "/"
+ }
+ }
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ ctx = &RequestContext{
+ url: u,
+ header: http.Header{},
+ client: &http.Client{},
+ }
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(u.String()+"> "),
+ prompt.OptionLivePrefix(livePrefix),
+ prompt.OptionTitle("http-prompt"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/live-prefix/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/live-prefix/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c7ced720592173e2a13f19f7cb543730192d3f8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/live-prefix/main.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var LivePrefixState struct {
+ LivePrefix string
+ IsEnable bool
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+ if in == "" {
+ LivePrefixState.IsEnable = false
+ LivePrefixState.LivePrefix = in
+ return
+ }
+ LivePrefixState.LivePrefix = in + "> "
+ LivePrefixState.IsEnable = true
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func changeLivePrefix() (string, bool) {
+ return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionLivePrefix(changeLivePrefix),
+ prompt.OptionTitle("live-prefix-example"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/simple-echo/cjk-cyrillic/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/simple-echo/cjk-cyrillic/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e9e53adef1558e004f86ccbca2c2e2b83c1da39
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/simple-echo/cjk-cyrillic/main.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
+ {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
+ {Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
+ {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionTitle("sql-prompt for multi width characters"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/simple-echo/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/simple-echo/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..12b1bb4fc189e6b369e889779418d7826a45db9d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_example/simple-echo/main.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ in := prompt.Input(">>> ", completer,
+ prompt.OptionTitle("sql-prompt"),
+ prompt.OptionHistory([]string{"SELECT * FROM users;"}),
+ prompt.OptionPrefixTextColor(prompt.Yellow),
+ prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
+ prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
+ prompt.OptionSuggestionBGColor(prompt.DarkGray))
+ fmt.Println("Your input: " + in)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_tools/README.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..45bd2234f21ff32562984bec046316c8e52868fd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_tools/README.md
@@ -0,0 +1,10 @@
+## Tools of go-prompt
+
+### vt100_debug
+
+
+
+### sigwinch
+
+
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_tools/complete_file/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_tools/complete_file/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..41015cfab9b021fbc7df575bde87e3c510705496
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_tools/complete_file/main.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/completer"
+)
+
+var filePathCompleter = completer.FilePathCompleter{
+ IgnoreCase: true,
+ Filter: func(fi os.FileInfo) bool {
+ return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
+ },
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completerFunc(d prompt.Document) []prompt.Suggest {
+ t := d.GetWordBeforeCursor()
+ if strings.HasPrefix(t, "--") {
+ return []prompt.Suggest{
+ {"--foo", ""},
+ {"--bar", ""},
+ {"--baz", ""},
+ }
+ }
+ return filePathCompleter.Complete(d)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completerFunc,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_tools/sigwinch/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_tools/sigwinch/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9608eb3b4a5e3c6942c140c41e08a36ab3adb33b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_tools/sigwinch/main.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "unsafe"
+)
+
+// Winsize is winsize struct got from the ioctl(2) system call.
+type Winsize struct {
+ Row uint16
+ Col uint16
+ X uint16 // pixel value
+ Y uint16 // pixel value
+}
+
+// GetWinSize returns winsize struct which is the response of ioctl(2).
+func GetWinSize(fd int) *Winsize {
+ ws := &Winsize{}
+ retCode, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ uintptr(fd),
+ uintptr(syscall.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(ws)))
+
+ if int(retCode) == -1 {
+ panic(errno)
+ }
+ return ws
+}
+
+func main() {
+ signalChan := make(chan os.Signal, 1)
+ signal.Notify(
+ signalChan,
+ syscall.SIGHUP,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ exitChan := make(chan int)
+ go func() {
+ for {
+ s := <-signalChan
+ switch s {
+ // kill -SIGHUP XXXX
+ case syscall.SIGHUP:
+ exitChan <- 0
+
+ // kill -SIGINT XXXX or Ctrl+c
+ case syscall.SIGINT:
+ exitChan <- 0
+
+ // kill -SIGTERM XXXX
+ case syscall.SIGTERM:
+ exitChan <- 0
+
+ // kill -SIGQUIT XXXX
+ case syscall.SIGQUIT:
+ exitChan <- 0
+
+ case syscall.SIGWINCH:
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ default:
+ exitChan <- 1
+ }
+ }
+ }()
+
+ code := <-exitChan
+ os.Exit(code)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_tools/vt100_debug/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_tools/vt100_debug/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c6036d45959febc739e287a3a7b631259d4ee7c1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/_tools/vt100_debug/main.go
@@ -0,0 +1,47 @@
+// +build !windows
+
+package main
+
+import (
+ "fmt"
+ "syscall"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/term"
+)
+
+func main() {
+ if err := term.SetRaw(syscall.Stdin); err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer term.Restore()
+
+ bufCh := make(chan []byte, 128)
+ go readBuffer(bufCh)
+ fmt.Print("> ")
+
+ for {
+ b := <-bufCh
+ if key := prompt.GetKey(b); key == prompt.NotDefined {
+ fmt.Printf("Key '%s' data:'%#v'\n", string(b), b)
+ } else {
+ if key == prompt.ControlC {
+ fmt.Println("exit.")
+ return
+ }
+ fmt.Printf("Key '%s' data:'%#v'\n", key, b)
+ }
+ fmt.Print("> ")
+ }
+}
+
+func readBuffer(bufCh chan []byte) {
+ buf := make([]byte, 1024)
+
+ for {
+ if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
+ bufCh <- buf[:n]
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/buffer.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..46efbbba8bfb75f4a064c83368b781d1d6dbbb29
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/buffer.go
@@ -0,0 +1,191 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Buffer emulates the console buffer.
+type Buffer struct {
+ workingLines []string // The working lines. Similar to history
+ workingIndex int
+ cursorPosition int
+ cacheDocument *Document
+ preferredColumn int // Remember the original column for the next up/down movement.
+ lastKeyStroke Key
+}
+
+// Text returns string of the current line.
+func (b *Buffer) Text() string {
+ return b.workingLines[b.workingIndex]
+}
+
+// Document method to return document instance from the current text and cursor position.
+func (b *Buffer) Document() (d *Document) {
+ if b.cacheDocument == nil ||
+ b.cacheDocument.Text != b.Text() ||
+ b.cacheDocument.cursorPosition != b.cursorPosition {
+ b.cacheDocument = &Document{
+ Text: b.Text(),
+ cursorPosition: b.cursorPosition,
+ }
+ }
+ b.cacheDocument.lastKey = b.lastKeyStroke
+ return b.cacheDocument
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (b *Buffer) DisplayCursorPosition() int {
+ return b.Document().DisplayCursorPosition()
+}
+
+// InsertText insert string from current line.
+func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
+ or := []rune(b.Text())
+ oc := b.cursorPosition
+
+ if overwrite {
+ overwritten := string(or[oc : oc+len(v)])
+ if strings.Contains(overwritten, "\n") {
+ i := strings.IndexAny(overwritten, "\n")
+ overwritten = overwritten[:i]
+ }
+ b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):]))
+ } else {
+ b.setText(string(or[:oc]) + v + string(or[oc:]))
+ }
+
+ if moveCursor {
+ b.cursorPosition += len([]rune(v))
+ }
+}
+
+// SetText method to set text and update cursorPosition.
+// (When doing this, make sure that the cursor_position is valid for this text.
+// text/cursor_position should be consistent at any time, otherwise set a Document instead.)
+func (b *Buffer) setText(v string) {
+ debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position")
+ b.workingLines[b.workingIndex] = v
+}
+
+// Set cursor position. Return whether it changed.
+func (b *Buffer) setCursorPosition(p int) {
+ if p > 0 {
+ b.cursorPosition = p
+ } else {
+ b.cursorPosition = 0
+ }
+}
+
+func (b *Buffer) setDocument(d *Document) {
+ b.cacheDocument = d
+ b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length.
+ b.setText(d.Text)
+}
+
+// CursorLeft move to left on the current line.
+func (b *Buffer) CursorLeft(count int) {
+ l := b.Document().GetCursorLeftPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorRight move to right on the current line.
+func (b *Buffer) CursorRight(count int) {
+ l := b.Document().GetCursorRightPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorUp move cursor to the previous line.
+// (for multi-line edit).
+func (b *Buffer) CursorUp(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorUpPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// CursorDown move cursor to the next line.
+// (for multi-line edit).
+func (b *Buffer) CursorDown(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorDownPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text.
+func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) {
+ debug.Assert(count >= 0, "count should be positive")
+ r := []rune(b.Text())
+
+ if b.cursorPosition > 0 {
+ start := b.cursorPosition - count
+ if start < 0 {
+ start = 0
+ }
+ deleted = string(r[start:b.cursorPosition])
+ b.setDocument(&Document{
+ Text: string(r[:start]) + string(r[b.cursorPosition:]),
+ cursorPosition: b.cursorPosition - len([]rune(deleted)),
+ })
+ }
+ return
+}
+
+// NewLine means CR.
+func (b *Buffer) NewLine(copyMargin bool) {
+ if copyMargin {
+ b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true)
+ } else {
+ b.InsertText("\n", false, true)
+ }
+}
+
+// Delete specified number of characters and Return the deleted text.
+func (b *Buffer) Delete(count int) (deleted string) {
+ r := []rune(b.Text())
+ if b.cursorPosition < len(r) {
+ deleted = b.Document().TextAfterCursor()[:count]
+ b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):]))
+ }
+ return
+}
+
+// JoinNextLine joins the next line to the current one by deleting the line ending after the current line.
+func (b *Buffer) JoinNextLine(separator string) {
+ if !b.Document().OnLastLine() {
+ b.cursorPosition += b.Document().GetEndOfLinePosition()
+ b.Delete(1)
+ // Remove spaces
+ b.setText(b.Document().TextBeforeCursor() + separator + strings.TrimLeft(b.Document().TextAfterCursor(), " "))
+ }
+}
+
+// SwapCharactersBeforeCursor swaps the last two characters before the cursor.
+func (b *Buffer) SwapCharactersBeforeCursor() {
+ if b.cursorPosition >= 2 {
+ x := b.Text()[b.cursorPosition-2 : b.cursorPosition-1]
+ y := b.Text()[b.cursorPosition-1 : b.cursorPosition]
+ b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:])
+ }
+}
+
+// NewBuffer is constructor of Buffer struct.
+func NewBuffer() (b *Buffer) {
+ b = &Buffer{
+ workingLines: []string{""},
+ workingIndex: 0,
+ preferredColumn: -1, // -1 means nil
+ }
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/completer/file.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/completer/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..59f2d8dec84214ccaa6e345a11ed51aa61a08199
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/completer/file.go
@@ -0,0 +1,90 @@
+package completer
+
+import (
+ "io/ioutil"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+var (
+ // FilePathCompletionSeparator holds separate characters.
+ FilePathCompletionSeparator = string([]byte{' ', os.PathSeparator})
+)
+
+// FilePathCompleter is a completer for your local file system.
+// Please caution that you need to set OptionCompletionWordSeparator(completer.FilePathCompletionSeparator)
+// when you use this completer.
+type FilePathCompleter struct {
+ Filter func(fi os.FileInfo) bool
+ IgnoreCase bool
+ fileListCache map[string][]prompt.Suggest
+}
+
+func cleanFilePath(path string) (dir, base string, err error) {
+ if path == "" {
+ return ".", "", nil
+ }
+
+ var endsWithSeparator bool
+ if len(path) >= 1 && path[len(path)-1] == os.PathSeparator {
+ endsWithSeparator = true
+ }
+
+ if runtime.GOOS != "windows" && len(path) >= 2 && path[0:2] == "~/" {
+ me, err := user.Current()
+ if err != nil {
+ return "", "", err
+ }
+ path = filepath.Join(me.HomeDir, path[1:])
+ }
+ path = filepath.Clean(os.ExpandEnv(path))
+ dir = filepath.Dir(path)
+ base = filepath.Base(path)
+
+ if endsWithSeparator {
+ dir = path + string(os.PathSeparator) // Append slash(in POSIX) if path ends with slash.
+ base = "" // Set empty string if path ends with separator.
+ }
+ return dir, base, nil
+}
+
+// Complete returns suggestions from your local file system.
+func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest {
+ if c.fileListCache == nil {
+ c.fileListCache = make(map[string][]prompt.Suggest, 4)
+ }
+
+ path := d.GetWordBeforeCursor()
+ dir, base, err := cleanFilePath(path)
+ if err != nil {
+ debug.Log("completer: cannot get current user:" + err.Error())
+ return nil
+ }
+
+ if cached, ok := c.fileListCache[dir]; ok {
+ return prompt.FilterHasPrefix(cached, base, c.IgnoreCase)
+ }
+
+ files, err := ioutil.ReadDir(dir)
+ if err != nil && os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ debug.Log("completer: cannot read directory items:" + err.Error())
+ return nil
+ }
+
+ suggests := make([]prompt.Suggest, 0, len(files))
+ for _, f := range files {
+ if c.Filter != nil && !c.Filter(f) {
+ continue
+ }
+ suggests = append(suggests, prompt.Suggest{Text: f.Name()})
+ }
+ c.fileListCache[dir] = suggests
+ return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/completion.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/completion.go
new file mode 100644
index 0000000000000000000000000000000000000000..57e82eefc0f50e9561214704e770a2ad313a3659
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/completion.go
@@ -0,0 +1,190 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+const (
+ shortenSuffix = "..."
+ leftPrefix = " "
+ leftSuffix = " "
+ rightPrefix = " "
+ rightSuffix = " "
+)
+
+var (
+ leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix)
+ rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix)
+ completionMargin = leftMargin + rightMargin
+)
+
+// Suggest is printed when completing.
+type Suggest struct {
+ Text string
+ Description string
+}
+
+// CompletionManager manages which suggestion is now selected.
+type CompletionManager struct {
+ selected int // -1 means nothing one is selected.
+ tmp []Suggest
+ max uint16
+ completer Completer
+
+ verticalScroll int
+ wordSeparator string
+ showAtStart bool
+}
+
+// GetSelectedSuggestion returns the selected item.
+func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) {
+ if c.selected == -1 {
+ return Suggest{}, false
+ } else if c.selected < -1 {
+ debug.Assert(false, "must not reach here")
+ c.selected = -1
+ return Suggest{}, false
+ }
+ return c.tmp[c.selected], true
+}
+
+// GetSuggestions returns the list of suggestion.
+func (c *CompletionManager) GetSuggestions() []Suggest {
+ return c.tmp
+}
+
+// Reset to select nothing.
+func (c *CompletionManager) Reset() {
+ c.selected = -1
+ c.verticalScroll = 0
+ c.Update(*NewDocument())
+}
+
+// Update to update the suggestions.
+func (c *CompletionManager) Update(in Document) {
+ c.tmp = c.completer(in)
+}
+
+// Previous to select the previous suggestion item.
+func (c *CompletionManager) Previous() {
+ if c.verticalScroll == c.selected && c.selected > 0 {
+ c.verticalScroll--
+ }
+ c.selected--
+ c.update()
+}
+
+// Next to select the next suggestion item.
+func (c *CompletionManager) Next() {
+ if c.verticalScroll+int(c.max)-1 == c.selected {
+ c.verticalScroll++
+ }
+ c.selected++
+ c.update()
+}
+
+// Completing returns whether the CompletionManager selects something one.
+func (c *CompletionManager) Completing() bool {
+ return c.selected != -1
+}
+
+func (c *CompletionManager) update() {
+ max := int(c.max)
+ if len(c.tmp) < max {
+ max = len(c.tmp)
+ }
+
+ if c.selected >= len(c.tmp) {
+ c.Reset()
+ } else if c.selected < -1 {
+ c.selected = len(c.tmp) - 1
+ c.verticalScroll = len(c.tmp) - max
+ }
+}
+
+func deleteBreakLineCharacters(s string) string {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, "\r", "", -1)
+ return s
+}
+
+func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) {
+ l := len(o)
+ n := make([]string, l)
+
+ lenPrefix := runewidth.StringWidth(prefix)
+ lenSuffix := runewidth.StringWidth(suffix)
+ lenShorten := runewidth.StringWidth(shortenSuffix)
+ min := lenPrefix + lenSuffix + lenShorten
+ for i := 0; i < l; i++ {
+ o[i] = deleteBreakLineCharacters(o[i])
+
+ w := runewidth.StringWidth(o[i])
+ if width < w {
+ width = w
+ }
+ }
+
+ if width == 0 {
+ return n, 0
+ }
+ if min >= max {
+ return n, 0
+ }
+ if lenPrefix+width+lenSuffix > max {
+ width = max - lenPrefix - lenSuffix
+ }
+
+ for i := 0; i < l; i++ {
+ x := runewidth.StringWidth(o[i])
+ if x <= width {
+ spaces := strings.Repeat(" ", width-x)
+ n[i] = prefix + o[i] + spaces + suffix
+ } else if x > width {
+ x := runewidth.Truncate(o[i], width, shortenSuffix)
+ // When calling runewidth.Truncate("您好xxx您好xxx", 11, "...") returns "您好xxx..."
+ // But the length of this result is 10. So we need fill right using runewidth.FillRight.
+ n[i] = prefix + runewidth.FillRight(x, width) + suffix
+ }
+ }
+ return n, lenPrefix + width + lenSuffix
+}
+
+func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) {
+ num := len(suggests)
+ new = make([]Suggest, num)
+
+ left := make([]string, num)
+ for i := 0; i < num; i++ {
+ left[i] = suggests[i].Text
+ }
+ right := make([]string, num)
+ for i := 0; i < num; i++ {
+ right[i] = suggests[i].Description
+ }
+
+ left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix)
+ if leftWidth == 0 {
+ return []Suggest{}, 0
+ }
+ right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix)
+
+ for i := 0; i < num; i++ {
+ new[i] = Suggest{Text: left[i], Description: right[i]}
+ }
+ return new, leftWidth + rightWidth
+}
+
+// NewCompletionManager returns initialized CompletionManager object.
+func NewCompletionManager(completer Completer, max uint16) *CompletionManager {
+ return &CompletionManager{
+ selected: -1,
+ max: max,
+ completer: completer,
+
+ verticalScroll: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/document.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/document.go
new file mode 100644
index 0000000000000000000000000000000000000000..2a47f52bb2a760b293b5b81de1f27f2b8325a805
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/document.go
@@ -0,0 +1,441 @@
+package prompt
+
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+ istrings "github.com/c-bata/go-prompt/internal/strings"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Document has text displayed in terminal and cursor position.
+type Document struct {
+ Text string
+ // This represents a index in a rune array of Document.Text.
+ // So if Document is "日本(cursor)語", cursorPosition is 2.
+ // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+ cursorPosition int
+ lastKey Key
+}
+
+// NewDocument return the new empty document.
+func NewDocument() *Document {
+ return &Document{
+ Text: "",
+ cursorPosition: 0,
+ }
+}
+
+// LastKeyStroke return the last key pressed in this document.
+func (d *Document) LastKeyStroke() Key {
+ return d.lastKey
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (d *Document) DisplayCursorPosition() int {
+ var position int
+ runes := []rune(d.Text)[:d.cursorPosition]
+ for i := range runes {
+ position += runewidth.RuneWidth(runes[i])
+ }
+ return position
+}
+
+// GetCharRelativeToCursor return character relative to cursor position, or empty string
+func (d *Document) GetCharRelativeToCursor(offset int) (r rune) {
+ s := d.Text
+ cnt := 0
+
+ for len(s) > 0 {
+ cnt++
+ r, size := utf8.DecodeRuneInString(s)
+ if cnt == d.cursorPosition+offset {
+ return r
+ }
+ s = s[size:]
+ }
+ return 0
+}
+
+// TextBeforeCursor returns the text before the cursor.
+func (d *Document) TextBeforeCursor() string {
+ r := []rune(d.Text)
+ return string(r[:d.cursorPosition])
+}
+
+// TextAfterCursor returns the text after the cursor.
+func (d *Document) TextAfterCursor() string {
+ r := []rune(d.Text)
+ return string(r[d.cursorPosition:])
+}
+
+// GetWordBeforeCursor returns the word before the cursor.
+// If we have whitespace before the cursor this returns an empty string.
+func (d *Document) GetWordBeforeCursor() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWord():]
+}
+
+// GetWordAfterCursor returns the word after the cursor.
+// If we have whitespace after the cursor this returns an empty string.
+func (d *Document) GetWordAfterCursor() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWord()]
+}
+
+// GetWordBeforeCursorWithSpace returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorWithSpace() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordWithSpace():]
+}
+
+// GetWordAfterCursorWithSpace returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorWithSpace() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordWithSpace()]
+}
+
+// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
+func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparator(sep):]
+}
+
+// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
+func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparator(sep)]
+}
+
+// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):]
+}
+
+// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)]
+}
+
+// FindStartOfPreviousWord returns an index relative to the cursor position
+// pointing to the start of the previous word. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWord() int {
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexByte(x, ' ')
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindStartOfPreviousWordWithSpace() int {
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotByte(x, ' ')
+ if end == -1 {
+ return 0
+ }
+
+ start := strings.LastIndexByte(x[:end], ' ')
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWord()
+ }
+
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexAny(x, sep)
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWordWithSpace()
+ }
+
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotAny(x, sep)
+ if end == -1 {
+ return 0
+ }
+ start := strings.LastIndexAny(x[:end], sep)
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindEndOfCurrentWord returns an index relative to the cursor position.
+// pointing to the end of the current word. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWord() int {
+ x := d.TextAfterCursor()
+ i := strings.IndexByte(x, ' ')
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindEndOfCurrentWordWithSpace() int {
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotByte(x, ' ')
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexByte(x[start:], ' ')
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWord()
+ }
+
+ x := d.TextAfterCursor()
+ i := strings.IndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWordWithSpace()
+ }
+
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotAny(x, sep)
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexAny(x[start:], sep)
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// CurrentLineBeforeCursor returns the text from the start of the line until the cursor.
+func (d *Document) CurrentLineBeforeCursor() string {
+ s := strings.Split(d.TextBeforeCursor(), "\n")
+ return s[len(s)-1]
+}
+
+// CurrentLineAfterCursor returns the text from the cursor until the end of the line.
+func (d *Document) CurrentLineAfterCursor() string {
+ return strings.Split(d.TextAfterCursor(), "\n")[0]
+}
+
+// CurrentLine return the text on the line where the cursor is. (when the input
+// consists of just one line, it equals `text`.
+func (d *Document) CurrentLine() string {
+ return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor()
+}
+
+// Array pointing to the start indexes of all the lines.
+func (d *Document) lineStartIndexes() []int {
+ // TODO: Cache, because this is often reused.
+ // (If it is used, it's often used many times.
+ // And this has to be fast for editing big documents!)
+ lc := d.LineCount()
+ lengths := make([]int, lc)
+ for i, l := range d.Lines() {
+ lengths[i] = len(l)
+ }
+
+ // Calculate cumulative sums.
+ indexes := make([]int, lc+1)
+ indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189
+ pos := 0
+ for i, l := range lengths {
+ pos += l + 1
+ indexes[i+1] = pos
+ }
+ if lc > 1 {
+ // Pop the last item. (This is not a new line.)
+ indexes = indexes[:lc]
+ }
+ return indexes
+}
+
+// For the index of a character at a certain line, calculate the index of
+// the first character on that line.
+func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) {
+ indexes := d.lineStartIndexes()
+ pos = bisect.Right(indexes, index) - 1
+ lineStartIndex = indexes[pos]
+ return
+}
+
+// CursorPositionRow returns the current row. (0-based.)
+func (d *Document) CursorPositionRow() (row int) {
+ row, _ = d.findLineStartIndex(d.cursorPosition)
+ return
+}
+
+// CursorPositionCol returns the current column. (0-based.)
+func (d *Document) CursorPositionCol() (col int) {
+ // Don't use self.text_before_cursor to calculate this. Creating substrings
+ // and splitting is too expensive for getting the cursor position.
+ _, index := d.findLineStartIndex(d.cursorPosition)
+ col = d.cursorPosition - index
+ return
+}
+
+// GetCursorLeftPosition returns the relative position for cursor left.
+func (d *Document) GetCursorLeftPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorRightPosition(-count)
+ }
+ if d.CursorPositionCol() > count {
+ return -count
+ }
+ return -d.CursorPositionCol()
+}
+
+// GetCursorRightPosition returns relative position for cursor right.
+func (d *Document) GetCursorRightPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorLeftPosition(-count)
+ }
+ if len(d.CurrentLineAfterCursor()) > count {
+ return count
+ }
+ return len(d.CurrentLineAfterCursor())
+}
+
+// GetCursorUpPosition return the relative cursor position (character index) where we would be
+// if the user pressed the arrow-up button.
+func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+
+ row := d.CursorPositionRow() - count
+ if row < 0 {
+ row = 0
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// GetCursorDownPosition return the relative cursor position (character index) where we would be if the
+// user pressed the arrow-down button.
+func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+ row := d.CursorPositionRow() + count
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// Lines returns the array of all the lines.
+func (d *Document) Lines() []string {
+ // TODO: Cache, because this one is reused very often.
+ return strings.Split(d.Text, "\n")
+}
+
+// LineCount return the number of lines in this document. If the document ends
+// with a trailing \n, that counts as the beginning of a new line.
+func (d *Document) LineCount() int {
+ return len(d.Lines())
+}
+
+// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple.
+// (0-based. Returns (0, 0) for index=0.)
+func (d *Document) TranslateIndexToPosition(index int) (row int, col int) {
+ row, rowIndex := d.findLineStartIndex(index)
+ col = index - rowIndex
+ return
+}
+
+// TranslateRowColToIndex given a (row, col), return the corresponding index.
+// (Row and col params are 0-based.)
+func (d *Document) TranslateRowColToIndex(row int, column int) (index int) {
+ indexes := d.lineStartIndexes()
+ if row < 0 {
+ row = 0
+ } else if row > len(indexes) {
+ row = len(indexes) - 1
+ }
+ index = indexes[row]
+ line := d.Lines()[row]
+
+ // python) result += max(0, min(col, len(line)))
+ if column > 0 || len(line) > 0 {
+ if column > len(line) {
+ index += len(line)
+ } else {
+ index += column
+ }
+ }
+
+ // Keep in range. (len(self.text) is included, because the cursor can be
+ // right after the end of the text as well.)
+ // python) result = max(0, min(result, len(self.text)))
+ if index > len(d.Text) {
+ index = len(d.Text)
+ }
+ if index < 0 {
+ index = 0
+ }
+ return index
+}
+
+// OnLastLine returns true when we are at the last line.
+func (d *Document) OnLastLine() bool {
+ return d.CursorPositionRow() == (d.LineCount() - 1)
+}
+
+// GetEndOfLinePosition returns relative position for the end of this line.
+func (d *Document) GetEndOfLinePosition() int {
+ return len([]rune(d.CurrentLineAfterCursor()))
+}
+
+func (d *Document) leadingWhitespaceInCurrentLine() (margin string) {
+ trimmed := strings.TrimSpace(d.CurrentLine())
+ margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)]
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/emacs.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/emacs.go
new file mode 100644
index 0000000000000000000000000000000000000000..632f96321f2577cdb7e8cffe639f1518a65d5e0f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/emacs.go
@@ -0,0 +1,120 @@
+package prompt
+
+import "github.com/c-bata/go-prompt/internal/debug"
+
+/*
+
+========
+PROGRESS
+========
+
+Moving the cursor
+-----------------
+
+* [x] Ctrl + a Go to the beginning of the line (Home)
+* [x] Ctrl + e Go to the End of the line (End)
+* [x] Ctrl + p Previous command (Up arrow)
+* [x] Ctrl + n Next command (Down arrow)
+* [x] Ctrl + f Forward one character
+* [x] Ctrl + b Backward one character
+* [x] Ctrl + xx Toggle between the start of line and current cursor position
+
+Editing
+-------
+
+* [x] Ctrl + L Clear the Screen, similar to the clear command
+* [x] Ctrl + d Delete character under the cursor
+* [x] Ctrl + h Delete character before the cursor (Backspace)
+
+* [x] Ctrl + w Cut the Word before the cursor to the clipboard.
+* [x] Ctrl + k Cut the Line after the cursor to the clipboard.
+* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard.
+
+* [ ] Ctrl + t Swap the last two characters before the cursor (typo).
+* [ ] Esc + t Swap the last two words before the cursor.
+
+* [ ] ctrl + y Paste the last thing to be cut (yank)
+* [ ] ctrl + _ Undo
+
+*/
+
+var emacsKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: ControlE,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+ },
+ },
+ // Go to the beginning of the line
+ {
+ Key: ControlA,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+ },
+ },
+ // Cut the Line after the cursor
+ {
+ Key: ControlK,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.Delete(len(x))
+ },
+ },
+ // Cut/delete the Line before the cursor
+ {
+ Key: ControlU,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.DeleteBeforeCursor(len(x))
+ },
+ },
+ // Delete character under the cursor
+ {
+ Key: ControlD,
+ Fn: func(buf *Buffer) {
+ if buf.Text() != "" {
+ buf.Delete(1)
+ }
+ },
+ },
+ // Backspace
+ {
+ Key: ControlH,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+ },
+ },
+ // Right allow: Forward one character
+ {
+ Key: ControlF,
+ Fn: func(buf *Buffer) {
+ buf.CursorRight(1)
+ },
+ },
+ // Left allow: Backward one character
+ {
+ Key: ControlB,
+ Fn: func(buf *Buffer) {
+ buf.CursorLeft(1)
+ },
+ },
+ // Cut the Word before the cursor.
+ {
+ Key: ControlW,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace())))
+ },
+ },
+ // Clear the Screen, similar to the clear command
+ {
+ Key: ControlL,
+ Fn: func(buf *Buffer) {
+ consoleWriter.EraseScreen()
+ consoleWriter.CursorGoTo(0, 0)
+ debug.AssertNoError(consoleWriter.Flush())
+ },
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/filter.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/filter.go
new file mode 100644
index 0000000000000000000000000000000000000000..61c17ed7f436a069563f520512bd25e4d81af0de
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/filter.go
@@ -0,0 +1,71 @@
+package prompt
+
+import "strings"
+
+// Filter is the type to filter the prompt.Suggestion array.
+type Filter func([]Suggest, string, bool) []Suggest
+
+// FilterHasPrefix checks whether the string completions.Text begins with sub.
+func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
+}
+
+// FilterHasSuffix checks whether the completion.Text ends with sub.
+func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
+}
+
+// FilterContains checks whether the completion.Text contains sub.
+func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
+}
+
+// FilterFuzzy checks whether the completion.Text fuzzy matches sub.
+// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
+// would match, for example, "Good food is gone"
+// ^ ^ ^
+func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
+}
+
+func fuzzyMatch(s, sub string) bool {
+ sChars := []rune(s)
+ sIdx := 0
+
+ // https://staticcheck.io/docs/checks#S1029
+ for _, c := range sub {
+ found := false
+ for ; sIdx < len(sChars); sIdx++ {
+ if sChars[sIdx] == c {
+ found = true
+ sIdx++
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
+
+func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
+ if sub == "" {
+ return suggestions
+ }
+ if ignoreCase {
+ sub = strings.ToUpper(sub)
+ }
+
+ ret := make([]Suggest, 0, len(suggestions))
+ for i := range suggestions {
+ c := suggestions[i].Text
+ if ignoreCase {
+ c = strings.ToUpper(c)
+ }
+ if function(c, sub) {
+ ret = append(ret, suggestions[i])
+ }
+ }
+ return ret
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/go.mod b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..30bc6d39a39c328341ca7153d3391352be5baa63
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/go.mod
@@ -0,0 +1,11 @@
+module github.com/c-bata/go-prompt
+
+go 1.14
+
+require (
+ github.com/mattn/go-colorable v0.1.7
+ github.com/mattn/go-runewidth v0.0.9
+ github.com/mattn/go-tty v0.0.3
+ github.com/pkg/term v1.2.0-beta.2
+ golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/go.sum b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..768bf93619a68e1b334c13e7b93ec84fa465598e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/go.sum
@@ -0,0 +1,23 @@
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/history.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/history.go
new file mode 100644
index 0000000000000000000000000000000000000000..e75c64592d82142bf4826ceb8c613ac72ca24d9c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/history.go
@@ -0,0 +1,61 @@
+package prompt
+
+// History stores the texts that are entered.
+type History struct {
+ histories []string
+ tmp []string
+ selected int
+}
+
+// Add to add text in history.
+func (h *History) Add(input string) {
+ h.histories = append(h.histories, input)
+ h.Clear()
+}
+
+// Clear to clear the history.
+func (h *History) Clear() {
+ h.tmp = make([]string, len(h.histories))
+ for i := range h.histories {
+ h.tmp[i] = h.histories[i]
+ }
+ h.tmp = append(h.tmp, "")
+ h.selected = len(h.tmp) - 1
+}
+
+// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
+ if len(h.tmp) == 1 || h.selected == 0 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected--
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
+ if h.selected >= len(h.tmp)-1 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected++
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// NewHistory returns new history object.
+func NewHistory() *History {
+ return &History{
+ histories: []string{},
+ tmp: []string{""},
+ selected: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/input.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/input.go
new file mode 100644
index 0000000000000000000000000000000000000000..307e747190c2b27bf888b379644fc4f3cdd489a2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/input.go
@@ -0,0 +1,169 @@
+package prompt
+
+import "bytes"
+
+// WinSize represents the width and height of terminal.
+type WinSize struct {
+ Row uint16
+ Col uint16
+}
+
+// ConsoleParser is an interface to abstract input layer.
+type ConsoleParser interface {
+ // Setup should be called before starting input
+ Setup() error
+ // TearDown should be called after stopping input
+ TearDown() error
+ // GetWinSize returns WinSize object to represent width and height of terminal.
+ GetWinSize() *WinSize
+ // Read returns byte array.
+ Read() ([]byte, error)
+}
+
+// GetKey returns Key correspond to input byte codes.
+func GetKey(b []byte) Key {
+ for _, k := range ASCIISequences {
+ if bytes.Equal(k.ASCIICode, b) {
+ return k.Key
+ }
+ }
+ return NotDefined
+}
+
+// ASCIISequences holds mappings of the key and byte array.
+var ASCIISequences = []*ASCIICode{
+ {Key: Escape, ASCIICode: []byte{0x1b}},
+
+ {Key: ControlSpace, ASCIICode: []byte{0x00}},
+ {Key: ControlA, ASCIICode: []byte{0x1}},
+ {Key: ControlB, ASCIICode: []byte{0x2}},
+ {Key: ControlC, ASCIICode: []byte{0x3}},
+ {Key: ControlD, ASCIICode: []byte{0x4}},
+ {Key: ControlE, ASCIICode: []byte{0x5}},
+ {Key: ControlF, ASCIICode: []byte{0x6}},
+ {Key: ControlG, ASCIICode: []byte{0x7}},
+ {Key: ControlH, ASCIICode: []byte{0x8}},
+ //{Key: ControlI, ASCIICode: []byte{0x9}},
+ //{Key: ControlJ, ASCIICode: []byte{0xa}},
+ {Key: ControlK, ASCIICode: []byte{0xb}},
+ {Key: ControlL, ASCIICode: []byte{0xc}},
+ {Key: ControlM, ASCIICode: []byte{0xd}},
+ {Key: ControlN, ASCIICode: []byte{0xe}},
+ {Key: ControlO, ASCIICode: []byte{0xf}},
+ {Key: ControlP, ASCIICode: []byte{0x10}},
+ {Key: ControlQ, ASCIICode: []byte{0x11}},
+ {Key: ControlR, ASCIICode: []byte{0x12}},
+ {Key: ControlS, ASCIICode: []byte{0x13}},
+ {Key: ControlT, ASCIICode: []byte{0x14}},
+ {Key: ControlU, ASCIICode: []byte{0x15}},
+ {Key: ControlV, ASCIICode: []byte{0x16}},
+ {Key: ControlW, ASCIICode: []byte{0x17}},
+ {Key: ControlX, ASCIICode: []byte{0x18}},
+ {Key: ControlY, ASCIICode: []byte{0x19}},
+ {Key: ControlZ, ASCIICode: []byte{0x1a}},
+
+ {Key: ControlBackslash, ASCIICode: []byte{0x1c}},
+ {Key: ControlSquareClose, ASCIICode: []byte{0x1d}},
+ {Key: ControlCircumflex, ASCIICode: []byte{0x1e}},
+ {Key: ControlUnderscore, ASCIICode: []byte{0x1f}},
+ {Key: Backspace, ASCIICode: []byte{0x7f}},
+
+ {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}},
+
+ {Key: Enter, ASCIICode: []byte{0xa}},
+ {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}},
+ {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+ {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}},
+ {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}},
+ {Key: Tab, ASCIICode: []byte{0x9}},
+ {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}},
+ {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}},
+ {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}},
+ {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}},
+ {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode
+
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}},
+ {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}},
+ {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}},
+ {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}},
+ {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}},
+ {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}},
+ {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}},
+ {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}},
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}},
+ {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}},
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+
+ // Xterm
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}},
+ // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}},
+ {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}},
+ {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}},
+ {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}},
+ {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}},
+
+ {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}},
+ {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}},
+ {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}},
+ {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}},
+
+ // Tmux sends following keystrokes when control+arrow is pressed, but for
+ // Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ // it a normal arrow press, because that's more important.
+ {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}},
+
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt
+
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/input_posix.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/input_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f10430318be0e797c841eba8e08ab1cf5277be27
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/input_posix.go
@@ -0,0 +1,77 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/term"
+ "golang.org/x/sys/unix"
+)
+
+const maxReadBytes = 1024
+
+// PosixParser is a ConsoleParser implementation for POSIX environment.
+type PosixParser struct {
+ fd int
+ origTermios syscall.Termios
+}
+
+// Setup should be called before starting input
+func (t *PosixParser) Setup() error {
+ // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
+ if err := syscall.SetNonblock(t.fd, true); err != nil {
+ return err
+ }
+ if err := term.SetRaw(t.fd); err != nil {
+ return err
+ }
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (t *PosixParser) TearDown() error {
+ if err := syscall.SetNonblock(t.fd, false); err != nil {
+ return err
+ }
+ if err := term.Restore(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Read returns byte array.
+func (t *PosixParser) Read() ([]byte, error) {
+ buf := make([]byte, maxReadBytes)
+ n, err := syscall.Read(t.fd, buf)
+ if err != nil {
+ return []byte{}, err
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (t *PosixParser) GetWinSize() *WinSize {
+ ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: ws.Row,
+ Col: ws.Col,
+ }
+}
+
+var _ ConsoleParser = &PosixParser{}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *PosixParser {
+ in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ return &PosixParser{
+ fd: in,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/input_windows.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/input_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..11b7679d4c4bc8b924a5b6c863ca1f6d6880570d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/input_windows.go
@@ -0,0 +1,83 @@
+// +build windows
+
+package prompt
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf8"
+ "unsafe"
+
+ tty "github.com/mattn/go-tty"
+)
+
+const maxReadBytes = 1024
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
+
+// WindowsParser is a ConsoleParser implementation for Win32 console.
+type WindowsParser struct {
+ tty *tty.TTY
+}
+
+// Setup should be called before starting input
+func (p *WindowsParser) Setup() error {
+ t, err := tty.Open()
+ if err != nil {
+ return err
+ }
+ p.tty = t
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (p *WindowsParser) TearDown() error {
+ return p.tty.Close()
+}
+
+// Read returns byte array.
+func (p *WindowsParser) Read() ([]byte, error) {
+ var ev uint32
+ r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
+ if r0 == 0 {
+ return nil, err
+ }
+ if ev == 0 {
+ return nil, errors.New("EAGAIN")
+ }
+
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, maxReadBytes)
+ n := utf8.EncodeRune(buf[:], r)
+ for p.tty.Buffered() && n < maxReadBytes {
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ break
+ }
+ n += utf8.EncodeRune(buf[n:], r)
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (p *WindowsParser) GetWinSize() *WinSize {
+ w, h, err := p.tty.Size()
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: uint16(h),
+ Col: uint16(w),
+ }
+}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *WindowsParser {
+ return &WindowsParser{}
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/bisect/bisect.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/bisect/bisect.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe162fa8c4873302e25702081b629a445d43415
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/bisect/bisect.go
@@ -0,0 +1,15 @@
+package bisect
+
+import "sort"
+
+// Right to locate the insertion point for v in a to maintain sorted order.
+func Right(a []int, v int) int {
+ return bisectRightRange(a, v, 0, len(a))
+}
+
+func bisectRightRange(a []int, v int, lo, hi int) int {
+ s := a[lo:hi]
+ return sort.Search(len(s), func(i int) bool {
+ return s[i] > v
+ })
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/debug/assert.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/debug/assert.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f648ac93c44e1e021cdf581a68f03b548534d9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/debug/assert.go
@@ -0,0 +1,55 @@
+package debug
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
+)
+
+var (
+ enableAssert bool
+)
+
+func init() {
+ if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
+ enableAssert = true
+ }
+}
+
+// Assert ensures expected condition.
+func Assert(cond bool, msg interface{}) {
+ if cond {
+ return
+ }
+ if enableAssert {
+ panic(msg)
+ }
+ writeWithSync(2, "[ASSERT] "+toString(msg))
+}
+
+func toString(v interface{}) string {
+ switch a := v.(type) {
+ case func() string:
+ return a()
+ case string:
+ return a
+ case fmt.Stringer:
+ return a.String()
+ default:
+ return fmt.Sprintf("unexpected type, %t", v)
+ }
+}
+
+// AssertNoError ensures err is nil.
+func AssertNoError(err error) {
+ if err == nil {
+ return
+ }
+ if enableAssert {
+ panic(err)
+ }
+ writeWithSync(2, "[ASSERT] "+err.Error())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/debug/log.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/debug/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..516378627a34ead9063ab7ce6c445b23c77b7cb4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/debug/log.go
@@ -0,0 +1,52 @@
+package debug
+
+import (
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+const (
+ envEnableLog = "GO_PROMPT_ENABLE_LOG"
+ logFileName = "go-prompt.log"
+)
+
+var (
+ logfile *os.File
+ logger *log.Logger
+)
+
+func init() {
+ if e := os.Getenv(envEnableLog); e == "true" || e == "1" {
+ var err error
+ logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
+ if err == nil {
+ logger = log.New(logfile, "", log.Llongfile)
+ return
+ }
+ }
+ logger = log.New(ioutil.Discard, "", log.Llongfile)
+}
+
+// Teardown to close logfile
+func Teardown() {
+ if logfile == nil {
+ return
+ }
+ _ = logfile.Close()
+}
+
+func writeWithSync(calldepth int, msg string) {
+ calldepth++
+ if logfile == nil {
+ return
+ }
+ _ = logger.Output(calldepth, msg)
+ _ = logfile.Sync() // immediately write msg
+}
+
+// Log to output message
+func Log(msg string) {
+ calldepth := 2
+ writeWithSync(calldepth, msg)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/strings/strings.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/strings/strings.go
new file mode 100644
index 0000000000000000000000000000000000000000..5cb753c6cef3b4719ce1867e1706e4a0b3128ff3
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/strings/strings.go
@@ -0,0 +1,102 @@
+package strings
+
+import "unicode/utf8"
+
+// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior.
+func IndexNotByte(s string, c byte) int {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior.
+func LastIndexNotByte(s string, c byte) int {
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+type asciiSet [8]uint32
+
+func (as *asciiSet) notContains(c byte) bool {
+ return (as[c>>5] & (1 << uint(c&31))) == 0
+}
+
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c>>4] |= 1 << uint(c&31)
+ }
+ return as, true
+}
+
+// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior.
+func IndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := 0; i < len(s); i++ {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+
+ LabelFirstLoop:
+ for i, c := range s {
+ for j, m := range chars {
+ if c != m && j == len(chars)-1 {
+ return i
+ } else if c != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior.
+func LastIndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ LabelFirstLoop:
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRuneInString(s[:i])
+ i -= size
+ for j, m := range chars {
+ if r != m && j == len(chars)-1 {
+ return i
+ } else if r != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/term/raw.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/term/raw.go
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3ed8d04023558cf386a98080815d661248b85
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/term/raw.go
@@ -0,0 +1,29 @@
+// +build !windows
+
+package term
+
+import (
+ "syscall"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+// SetRaw put terminal into a raw mode
+func SetRaw(fd int) error {
+ n, err := getOriginalTermios(fd)
+ if err != nil {
+ return err
+ }
+
+ n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK |
+ syscall.ISTRIP | syscall.INLCR | syscall.IGNCR |
+ syscall.ICRNL | syscall.IXON
+ n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL
+ n.Cflag &^= syscall.CSIZE | syscall.PARENB
+ n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters.
+ n.Cc[syscall.VMIN] = 1
+ n.Cc[syscall.VTIME] = 0
+
+ return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n))
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/term/term.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/term/term.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a53c059ae60c0348ec01689babef4b13a2ecd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/internal/term/term.go
@@ -0,0 +1,34 @@
+// +build !windows
+
+package term
+
+import (
+ "sync"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ saveTermios *unix.Termios
+ saveTermiosFD int
+ saveTermiosOnce sync.Once
+)
+
+func getOriginalTermios(fd int) (*unix.Termios, error) {
+ var err error
+ saveTermiosOnce.Do(func() {
+ saveTermiosFD = fd
+ saveTermios, err = termios.Tcgetattr(uintptr(fd))
+ })
+ return saveTermios, err
+}
+
+// Restore terminal's mode.
+func Restore() error {
+ o, err := getOriginalTermios(saveTermiosFD)
+ if err != nil {
+ return err
+ }
+ return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/key.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ba569c2dd20a8ae3b3dd79ff3695bf0b6c1bd09
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/key.go
@@ -0,0 +1,128 @@
+// Code generated by hand; DO NOT EDIT.
+// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment.
+
+package prompt
+
+// Key is the type express the key inserted from user.
+//go:generate stringer -type=Key
+type Key int
+
+// ASCIICode is the type contains Key and it's ascii byte array.
+type ASCIICode struct {
+ Key Key
+ ASCIICode []byte
+}
+
+const (
+ Escape Key = iota
+
+ ControlA
+ ControlB
+ ControlC
+ ControlD
+ ControlE
+ ControlF
+ ControlG
+ ControlH
+ ControlI
+ ControlJ
+ ControlK
+ ControlL
+ ControlM
+ ControlN
+ ControlO
+ ControlP
+ ControlQ
+ ControlR
+ ControlS
+ ControlT
+ ControlU
+ ControlV
+ ControlW
+ ControlX
+ ControlY
+ ControlZ
+
+ ControlSpace
+ ControlBackslash
+ ControlSquareClose
+ ControlCircumflex
+ ControlUnderscore
+ ControlLeft
+ ControlRight
+ ControlUp
+ ControlDown
+
+ Up
+ Down
+ Right
+ Left
+
+ ShiftLeft
+ ShiftUp
+ ShiftDown
+ ShiftRight
+
+ Home
+ End
+ Delete
+ ShiftDelete
+ ControlDelete
+ PageUp
+ PageDown
+ BackTab
+ Insert
+ Backspace
+
+ // Aliases.
+ Tab
+ Enter
+ // Actually Enter equals ControlM, not ControlJ,
+ // However, in prompt_toolkit, we made the mistake of translating
+ // \r into \n during the input, so everyone is now handling the
+ // enter key by binding ControlJ.
+
+ // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere,
+ // because that's future compatible, and will still work when we
+ // stop replacing \r by \n.
+
+ F1
+ F2
+ F3
+ F4
+ F5
+ F6
+ F7
+ F8
+ F9
+ F10
+ F11
+ F12
+ F13
+ F14
+ F15
+ F16
+ F17
+ F18
+ F19
+ F20
+ F21
+ F22
+ F23
+ F24
+
+ // Matches any key.
+ Any
+
+ // Special
+ CPRResponse
+ Vt100MouseEvent
+ WindowsMouseEvent
+ BracketedPaste
+
+ // Key which is ignored. (The key binding for this key should not do anything.)
+ Ignore
+
+ // Key is not defined
+ NotDefined
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/key_bind.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/key_bind.go
new file mode 100644
index 0000000000000000000000000000000000000000..42669e7f942efc4d92f896388daede90b96b55dd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/key_bind.go
@@ -0,0 +1,59 @@
+package prompt
+
+// KeyBindFunc receives buffer and processed it.
+type KeyBindFunc func(*Buffer)
+
+// KeyBind represents which key should do what operation.
+type KeyBind struct {
+ Key Key
+ Fn KeyBindFunc
+}
+
+// ASCIICodeBind represents which []byte should do what operation
+type ASCIICodeBind struct {
+ ASCIICode []byte
+ Fn KeyBindFunc
+}
+
+// KeyBindMode to switch a key binding flexibly.
+type KeyBindMode string
+
+const (
+ // CommonKeyBind is a mode without any keyboard shortcut
+ CommonKeyBind KeyBindMode = "common"
+ // EmacsKeyBind is a mode to use emacs-like keyboard shortcut
+ EmacsKeyBind KeyBindMode = "emacs"
+)
+
+var commonKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: End,
+ Fn: GoLineEnd,
+ },
+ // Go to the beginning of the line
+ {
+ Key: Home,
+ Fn: GoLineBeginning,
+ },
+ // Delete character under the cursor
+ {
+ Key: Delete,
+ Fn: DeleteChar,
+ },
+ // Backspace
+ {
+ Key: Backspace,
+ Fn: DeleteBeforeChar,
+ },
+ // Right allow: Forward one character
+ {
+ Key: Right,
+ Fn: GoRightChar,
+ },
+ // Left allow: Backward one character
+ {
+ Key: Left,
+ Fn: GoLeftChar,
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/key_bind_func.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/key_bind_func.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b2ecdf63179dbfdbcb0d71bfa436bb36d62d230
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/key_bind_func.go
@@ -0,0 +1,48 @@
+package prompt
+
+// GoLineEnd Go to the End of the line
+func GoLineEnd(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+}
+
+// GoLineBeginning Go to the beginning of the line
+func GoLineBeginning(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+}
+
+// DeleteChar Delete character under the cursor
+func DeleteChar(buf *Buffer) {
+ buf.Delete(1)
+}
+
+// DeleteWord Delete word before the cursor
+func DeleteWord(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
+
+// DeleteBeforeChar Go to Backspace
+func DeleteBeforeChar(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+}
+
+// GoRightChar Forward one character
+func GoRightChar(buf *Buffer) {
+ buf.CursorRight(1)
+}
+
+// GoLeftChar Backward one character
+func GoLeftChar(buf *Buffer) {
+ buf.CursorLeft(1)
+}
+
+// GoRightWord Forward one word
+func GoRightWord(buf *Buffer) {
+ buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
+}
+
+// GoLeftWord Backward one word
+func GoLeftWord(buf *Buffer) {
+ buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/key_string.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/key_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..fce6ea31c502b3e763451cb47757ae1b49c32814
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/key_string.go
@@ -0,0 +1,16 @@
+// Code generated by "stringer -type=Key"; DO NOT EDIT.
+
+package prompt
+
+import "strconv"
+
+const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined"
+
+var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607}
+
+func (i Key) String() string {
+ if i < 0 || i >= Key(len(_Key_index)-1) {
+ return "Key(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _Key_name[_Key_index[i]:_Key_index[i+1]]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/option.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/option.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd6806cc1dbccf8c4ddb048080fde615c59088
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/option.go
@@ -0,0 +1,310 @@
+package prompt
+
+// Option is the type to replace default parameters.
+// prompt.New accepts any number of options (this is functional option pattern).
+type Option func(prompt *Prompt) error
+
+// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
+func OptionParser(x ConsoleParser) Option {
+ return func(p *Prompt) error {
+ p.in = x
+ return nil
+ }
+}
+
+// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
+func OptionWriter(x ConsoleWriter) Option {
+ return func(p *Prompt) error {
+ registerConsoleWriter(x)
+ p.renderer.out = x
+ return nil
+ }
+}
+
+// OptionTitle to set title displayed at the header bar of terminal.
+func OptionTitle(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.title = x
+ return nil
+ }
+}
+
+// OptionPrefix to set prefix string.
+func OptionPrefix(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefix = x
+ return nil
+ }
+}
+
+// OptionInitialBufferText to set the initial buffer text
+func OptionInitialBufferText(x string) Option {
+ return func(p *Prompt) error {
+ p.buf.InsertText(x, false, true)
+ return nil
+ }
+}
+
+// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
+func OptionCompletionWordSeparator(x string) Option {
+ return func(p *Prompt) error {
+ p.completion.wordSeparator = x
+ return nil
+ }
+}
+
+// OptionLivePrefix to change the prefix dynamically by callback function
+func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
+ return func(p *Prompt) error {
+ p.renderer.livePrefixCallback = f
+ return nil
+ }
+}
+
+// OptionPrefixTextColor change a text color of prefix string
+func OptionPrefixTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixTextColor = x
+ return nil
+ }
+}
+
+// OptionPrefixBackgroundColor to change a background color of prefix string
+func OptionPrefixBackgroundColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixBGColor = x
+ return nil
+ }
+}
+
+// OptionInputTextColor to change a color of text which is input by user
+func OptionInputTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputTextColor = x
+ return nil
+ }
+}
+
+// OptionInputBGColor to change a color of background which is input by user
+func OptionInputBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputBGColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionTextColor to change a text color which is completed
+func OptionPreviewSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionBGColor to change a background color which is completed
+func OptionPreviewSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionTextColor to change a text color in drop down suggestions.
+func OptionSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionBGColor change a background color in drop down suggestions.
+func OptionSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarThumbColor to change a thumb color on scrollbar.
+func OptionScrollbarThumbColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarThumbColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarBGColor to change a background color of scrollbar.
+func OptionScrollbarBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarBGColor = x
+ return nil
+ }
+}
+
+// OptionMaxSuggestion specify the max number of displayed suggestions.
+func OptionMaxSuggestion(x uint16) Option {
+ return func(p *Prompt) error {
+ p.completion.max = x
+ return nil
+ }
+}
+
+// OptionHistory to set history expressed by string array.
+func OptionHistory(x []string) Option {
+ return func(p *Prompt) error {
+ p.history.histories = x
+ p.history.Clear()
+ return nil
+ }
+}
+
+// OptionSwitchKeyBindMode set a key bind mode.
+func OptionSwitchKeyBindMode(m KeyBindMode) Option {
+ return func(p *Prompt) error {
+ p.keyBindMode = m
+ return nil
+ }
+}
+
+// OptionCompletionOnDown allows for Down arrow key to trigger completion.
+func OptionCompletionOnDown() Option {
+ return func(p *Prompt) error {
+ p.completionOnDown = true
+ return nil
+ }
+}
+
+// SwitchKeyBindMode to set a key bind mode.
+// Deprecated: Please use OptionSwitchKeyBindMode.
+var SwitchKeyBindMode = OptionSwitchKeyBindMode
+
+// OptionAddKeyBind to set a custom key bind.
+func OptionAddKeyBind(b ...KeyBind) Option {
+ return func(p *Prompt) error {
+ p.keyBindings = append(p.keyBindings, b...)
+ return nil
+ }
+}
+
+// OptionAddASCIICodeBind to set a custom key bind.
+func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option {
+ return func(p *Prompt) error {
+ p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...)
+ return nil
+ }
+}
+
+// OptionShowCompletionAtStart to set completion window is open at start.
+func OptionShowCompletionAtStart() Option {
+ return func(p *Prompt) error {
+ p.completion.showAtStart = true
+ return nil
+ }
+}
+
+// OptionBreakLineCallback to run a callback at every break line
+func OptionBreakLineCallback(fn func(*Document)) Option {
+ return func(p *Prompt) error {
+ p.renderer.breakLineCallback = fn
+ return nil
+ }
+}
+
+// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop
+func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
+ return func(p *Prompt) error {
+ p.exitChecker = fn
+ return nil
+ }
+}
+
+// New returns a Prompt with powerful auto-completion.
+func New(executor Executor, completer Completer, opts ...Option) *Prompt {
+ defaultWriter := NewStdoutWriter()
+ registerConsoleWriter(defaultWriter)
+
+ pt := &Prompt{
+ in: NewStandardInputParser(),
+ renderer: &Render{
+ prefix: "> ",
+ out: defaultWriter,
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ },
+ buf: NewBuffer(),
+ executor: executor,
+ history: NewHistory(),
+ completion: NewCompletionManager(completer, 6),
+ keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting
+ }
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/output.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/output.go
new file mode 100644
index 0000000000000000000000000000000000000000..42531b412f1ed027c2fff5b85bc273e53e569b3a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/output.go
@@ -0,0 +1,161 @@
+package prompt
+
+import "sync"
+
+var (
+ consoleWriterMu sync.Mutex
+ consoleWriter ConsoleWriter
+)
+
+func registerConsoleWriter(f ConsoleWriter) {
+ consoleWriterMu.Lock()
+ defer consoleWriterMu.Unlock()
+ consoleWriter = f
+}
+
+// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on.
+type DisplayAttribute int
+
+const (
+ // DisplayReset reset all display attributes.
+ DisplayReset DisplayAttribute = iota
+ // DisplayBold set bold or increases intensity.
+ DisplayBold
+ // DisplayLowIntensity decreases intensity. Not widely supported.
+ DisplayLowIntensity
+ // DisplayItalic set italic. Not widely supported.
+ DisplayItalic
+ // DisplayUnderline set underline
+ DisplayUnderline
+ // DisplayBlink set blink (less than 150 per minute).
+ DisplayBlink
+ // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported.
+ DisplayRapidBlink
+ // DisplayReverse swap foreground and background colors.
+ DisplayReverse
+ // DisplayInvisible set invisible. Not widely supported.
+ DisplayInvisible
+ // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported.
+ DisplayCrossedOut
+ // DisplayDefaultFont set primary(default) font
+ DisplayDefaultFont
+)
+
+// Color represents color on terminal.
+type Color int
+
+const (
+ // DefaultColor represents a default color.
+ DefaultColor Color = iota
+
+ // Low intensity
+
+ // Black represents a black.
+ Black
+ // DarkRed represents a dark red.
+ DarkRed
+ // DarkGreen represents a dark green.
+ DarkGreen
+ // Brown represents a brown.
+ Brown
+ // DarkBlue represents a dark blue.
+ DarkBlue
+ // Purple represents a purple.
+ Purple
+ // Cyan represents a cyan.
+ Cyan
+ // LightGray represents a light gray.
+ LightGray
+
+ // High intensity
+
+ // DarkGray represents a dark gray.
+ DarkGray
+ // Red represents a red.
+ Red
+ // Green represents a green.
+ Green
+ // Yellow represents a yellow.
+ Yellow
+ // Blue represents a blue.
+ Blue
+ // Fuchsia represents a fuchsia.
+ Fuchsia
+ // Turquoise represents a turquoise.
+ Turquoise
+ // White represents a white.
+ White
+)
+
+// ConsoleWriter is an interface to abstract output layer.
+type ConsoleWriter interface {
+ /* Write */
+
+ // WriteRaw to write raw byte array.
+ WriteRaw(data []byte)
+ // Write to write safety byte array by removing control sequences.
+ Write(data []byte)
+ // WriteStr to write raw string.
+ WriteRawStr(data string)
+ // WriteStr to write safety string by removing control sequences.
+ WriteStr(data string)
+ // Flush to flush buffer.
+ Flush() error
+
+ /* Erasing */
+
+ // EraseScreen erases the screen with the background colour and moves the cursor to home.
+ EraseScreen()
+ // EraseUp erases the screen from the current line up to the top of the screen.
+ EraseUp()
+ // EraseDown erases the screen from the current line down to the bottom of the screen.
+ EraseDown()
+ // EraseStartOfLine erases from the current cursor position to the start of the current line.
+ EraseStartOfLine()
+ // EraseEndOfLine erases from the current cursor position to the end of the current line.
+ EraseEndOfLine()
+ // EraseLine erases the entire current line.
+ EraseLine()
+
+ /* Cursor */
+
+ // ShowCursor stops blinking cursor and show.
+ ShowCursor()
+ // HideCursor hides cursor.
+ HideCursor()
+ // CursorGoTo sets the cursor position where subsequent text will begin.
+ CursorGoTo(row, col int)
+ // CursorUp moves the cursor up by 'n' rows; the default count is 1.
+ CursorUp(n int)
+ // CursorDown moves the cursor down by 'n' rows; the default count is 1.
+ CursorDown(n int)
+ // CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+ CursorForward(n int)
+ // CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+ CursorBackward(n int)
+ // AskForCPR asks for a cursor position report (CPR).
+ AskForCPR()
+ // SaveCursor saves current cursor position.
+ SaveCursor()
+ // UnSaveCursor restores cursor position after a Save Cursor.
+ UnSaveCursor()
+
+ /* Scrolling */
+
+ // ScrollDown scrolls display down one line.
+ ScrollDown()
+ // ScrollUp scroll display up one line.
+ ScrollUp()
+
+ /* Title */
+
+ // SetTitle sets a title of terminal window.
+ SetTitle(title string)
+ // ClearTitle clears a title of terminal window.
+ ClearTitle()
+
+ /* Font */
+
+ // SetColor sets text and background colors. and specify whether text is bold.
+ SetColor(fg, bg Color, bold bool)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/output_posix.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/output_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..26c770cc152a7b126be43915d60b8ba000ad0e38
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/output_posix.go
@@ -0,0 +1,67 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+)
+
+const flushMaxRetryCount = 3
+
+// PosixWriter is a ConsoleWriter implementation for POSIX environment.
+// To control terminal emulator, this outputs VT100 escape sequences.
+type PosixWriter struct {
+ VT100Writer
+ fd int
+}
+
+// Flush to flush buffer
+func (w *PosixWriter) Flush() error {
+ l := len(w.buffer)
+ offset := 0
+ retry := 0
+ for {
+ n, err := syscall.Write(w.fd, w.buffer[offset:])
+ if err != nil {
+ if retry < flushMaxRetryCount {
+ retry++
+ continue
+ }
+ return err
+ }
+ offset += n
+ if offset == l {
+ break
+ }
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &PosixWriter{}
+
+var (
+ // NewStandardOutputWriter returns ConsoleWriter object to write to stdout.
+ // This generates VT100 escape sequences because almost terminal emulators
+ // in POSIX OS built on top of a VT100 specification.
+ // Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStdoutWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stdout,
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStderrWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stderr,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/output_vt100.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/output_vt100.go
new file mode 100644
index 0000000000000000000000000000000000000000..20850fead883c4cd9802928b5de3f935fbbeb047
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/output_vt100.go
@@ -0,0 +1,310 @@
+package prompt
+
+import (
+ "bytes"
+ "strconv"
+)
+
+// VT100Writer generates VT100 escape sequences.
+type VT100Writer struct {
+ buffer []byte
+}
+
+// WriteRaw to write raw byte array
+func (w *VT100Writer) WriteRaw(data []byte) {
+ w.buffer = append(w.buffer, data...)
+}
+
+// Write to write safety byte array by removing control sequences.
+func (w *VT100Writer) Write(data []byte) {
+ w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1))
+}
+
+// WriteRawStr to write raw string
+func (w *VT100Writer) WriteRawStr(data string) {
+ w.WriteRaw([]byte(data))
+}
+
+// WriteStr to write safety string by removing control sequences.
+func (w *VT100Writer) WriteStr(data string) {
+ w.Write([]byte(data))
+}
+
+/* Erase */
+
+// EraseScreen erases the screen with the background colour and moves the cursor to home.
+func (w *VT100Writer) EraseScreen() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'J'})
+}
+
+// EraseUp erases the screen from the current line up to the top of the screen.
+func (w *VT100Writer) EraseUp() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'J'})
+}
+
+// EraseDown erases the screen from the current line down to the bottom of the screen.
+func (w *VT100Writer) EraseDown() {
+ w.WriteRaw([]byte{0x1b, '[', 'J'})
+}
+
+// EraseStartOfLine erases from the current cursor position to the start of the current line.
+func (w *VT100Writer) EraseStartOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'K'})
+}
+
+// EraseEndOfLine erases from the current cursor position to the end of the current line.
+func (w *VT100Writer) EraseEndOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', 'K'})
+}
+
+// EraseLine erases the entire current line.
+func (w *VT100Writer) EraseLine() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'K'})
+}
+
+/* Cursor */
+
+// ShowCursor stops blinking cursor and show.
+func (w *VT100Writer) ShowCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'})
+}
+
+// HideCursor hides cursor.
+func (w *VT100Writer) HideCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'})
+}
+
+// CursorGoTo sets the cursor position where subsequent text will begin.
+func (w *VT100Writer) CursorGoTo(row, col int) {
+ if row == 0 && col == 0 {
+ // If no row/column parameters are provided (ie. [H), the cursor will move to the home position.
+ w.WriteRaw([]byte{0x1b, '[', 'H'})
+ return
+ }
+ r := strconv.Itoa(row)
+ c := strconv.Itoa(col)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(r))
+ w.WriteRaw([]byte{';'})
+ w.WriteRaw([]byte(c))
+ w.WriteRaw([]byte{'H'})
+}
+
+// CursorUp moves the cursor up by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorUp(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorDown(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'A'})
+}
+
+// CursorDown moves the cursor down by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorDown(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorUp(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'B'})
+}
+
+// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorForward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorBackward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'C'})
+}
+
+// CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorBackward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorForward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'D'})
+}
+
+// AskForCPR asks for a cursor position report (CPR).
+func (w *VT100Writer) AskForCPR() {
+ // CPR: Cursor Position Request.
+ w.WriteRaw([]byte{0x1b, '[', '6', 'n'})
+}
+
+// SaveCursor saves current cursor position.
+func (w *VT100Writer) SaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 's'})
+}
+
+// UnSaveCursor restores cursor position after a Save Cursor.
+func (w *VT100Writer) UnSaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 'u'})
+}
+
+/* Scrolling */
+
+// ScrollDown scrolls display down one line.
+func (w *VT100Writer) ScrollDown() {
+ w.WriteRaw([]byte{0x1b, 'D'})
+}
+
+// ScrollUp scroll display up one line.
+func (w *VT100Writer) ScrollUp() {
+ w.WriteRaw([]byte{0x1b, 'M'})
+}
+
+/* Title */
+
+// SetTitle sets a title of terminal window.
+func (w *VT100Writer) SetTitle(title string) {
+ titleBytes := []byte(title)
+ patterns := []struct {
+ from []byte
+ to []byte
+ }{
+ {
+ from: []byte{0x13},
+ to: []byte{},
+ },
+ {
+ from: []byte{0x07},
+ to: []byte{},
+ },
+ }
+ for i := range patterns {
+ titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1)
+ }
+
+ w.WriteRaw([]byte{0x1b, ']', '2', ';'})
+ w.WriteRaw(titleBytes)
+ w.WriteRaw([]byte{0x07})
+}
+
+// ClearTitle clears a title of terminal window.
+func (w *VT100Writer) ClearTitle() {
+ w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07})
+}
+
+/* Font */
+
+// SetColor sets text and background colors. and specify whether text is bold.
+func (w *VT100Writer) SetColor(fg, bg Color, bold bool) {
+ if bold {
+ w.SetDisplayAttributes(fg, bg, DisplayBold)
+ } else {
+ // If using `DisplayDefualt`, it will be broken in some environment.
+ // Details are https://github.com/c-bata/go-prompt/pull/85
+ w.SetDisplayAttributes(fg, bg, DisplayReset)
+ }
+}
+
+// SetDisplayAttributes to set VT100 display attributes.
+func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) {
+ w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer
+ defer w.WriteRaw([]byte{'m'}) // final character
+
+ var separator byte = ';'
+ for i := range attrs {
+ p, ok := displayAttributeParameters[attrs[i]]
+ if !ok {
+ continue
+ }
+ w.WriteRaw(p)
+ w.WriteRaw([]byte{separator})
+ }
+
+ f, ok := foregroundANSIColors[fg]
+ if !ok {
+ f = foregroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(f)
+ w.WriteRaw([]byte{separator})
+ b, ok := backgroundANSIColors[bg]
+ if !ok {
+ b = backgroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(b)
+}
+
+var displayAttributeParameters = map[DisplayAttribute][]byte{
+ DisplayReset: {'0'},
+ DisplayBold: {'1'},
+ DisplayLowIntensity: {'2'},
+ DisplayItalic: {'3'},
+ DisplayUnderline: {'4'},
+ DisplayBlink: {'5'},
+ DisplayRapidBlink: {'6'},
+ DisplayReverse: {'7'},
+ DisplayInvisible: {'8'},
+ DisplayCrossedOut: {'9'},
+ DisplayDefaultFont: {'1', '0'},
+}
+
+var foregroundANSIColors = map[Color][]byte{
+ DefaultColor: {'3', '9'},
+
+ // Low intensity.
+ Black: {'3', '0'},
+ DarkRed: {'3', '1'},
+ DarkGreen: {'3', '2'},
+ Brown: {'3', '3'},
+ DarkBlue: {'3', '4'},
+ Purple: {'3', '5'},
+ Cyan: {'3', '6'},
+ LightGray: {'3', '7'},
+
+ // High intensity.
+ DarkGray: {'9', '0'},
+ Red: {'9', '1'},
+ Green: {'9', '2'},
+ Yellow: {'9', '3'},
+ Blue: {'9', '4'},
+ Fuchsia: {'9', '5'},
+ Turquoise: {'9', '6'},
+ White: {'9', '7'},
+}
+
+var backgroundANSIColors = map[Color][]byte{
+ DefaultColor: {'4', '9'},
+
+ // Low intensity.
+ Black: {'4', '0'},
+ DarkRed: {'4', '1'},
+ DarkGreen: {'4', '2'},
+ Brown: {'4', '3'},
+ DarkBlue: {'4', '4'},
+ Purple: {'4', '5'},
+ Cyan: {'4', '6'},
+ LightGray: {'4', '7'},
+
+ // High intensity
+ DarkGray: {'1', '0', '0'},
+ Red: {'1', '0', '1'},
+ Green: {'1', '0', '2'},
+ Yellow: {'1', '0', '3'},
+ Blue: {'1', '0', '4'},
+ Fuchsia: {'1', '0', '5'},
+ Turquoise: {'1', '0', '6'},
+ White: {'1', '0', '7'},
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/output_windows.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/output_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b9c2769fc2d64cfcfcc5b99c915591ec625bd5f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/output_windows.go
@@ -0,0 +1,49 @@
+// +build windows
+
+package prompt
+
+import (
+ "io"
+
+ colorable "github.com/mattn/go-colorable"
+)
+
+// WindowsWriter is a ConsoleWriter implementation for Win32 console.
+// Output is converted from VT100 escape sequences by mattn/go-colorable.
+type WindowsWriter struct {
+ VT100Writer
+ out io.Writer
+}
+
+// Flush to flush buffer
+func (w *WindowsWriter) Flush() error {
+ _, err := w.out.Write(w.buffer)
+ if err != nil {
+ return err
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &WindowsWriter{}
+
+var (
+ // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates win32 control sequences.
+func NewStdoutWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStdout(),
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates win32 control sequences.
+func NewStderrWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStderr(),
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/prompt.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/prompt.go
new file mode 100644
index 0000000000000000000000000000000000000000..173cd517c40cde212433e399978641ceff1d1a43
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/prompt.go
@@ -0,0 +1,296 @@
+package prompt
+
+import (
+ "bytes"
+ "os"
+ "time"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Executor is called when user input something text.
+type Executor func(string)
+
+// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
+// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
+// - immediate exit (if breakline is false) without executor called
+// - exit after typing (meaning breakline is true), and the executor is called first, before exit.
+// Exit means exit go-prompt (not the overall Go program)
+type ExitChecker func(in string, breakline bool) bool
+
+// Completer should return the suggest item from Document.
+type Completer func(Document) []Suggest
+
+// Prompt is core struct of go-prompt.
+type Prompt struct {
+ in ConsoleParser
+ buf *Buffer
+ renderer *Render
+ executor Executor
+ history *History
+ completion *CompletionManager
+ keyBindings []KeyBind
+ ASCIICodeBindings []ASCIICodeBind
+ keyBindMode KeyBindMode
+ completionOnDown bool
+ exitChecker ExitChecker
+ skipTearDown bool
+}
+
+// Exec is the struct contains user input context.
+type Exec struct {
+ input string
+}
+
+// Run starts prompt.
+func (p *Prompt) Run() {
+ p.skipTearDown = false
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ exitCh := make(chan int)
+ winSizeCh := make(chan *WinSize)
+ stopHandleSignalCh := make(chan struct{})
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+ return
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+
+ // Unset raw mode
+ // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
+ debug.AssertNoError(p.in.TearDown())
+ p.executor(e.input)
+
+ p.completion.Update(*p.buf.Document())
+
+ p.renderer.Render(p.buf, p.completion)
+
+ if p.exitChecker != nil && p.exitChecker(e.input, true) {
+ p.skipTearDown = true
+ return
+ }
+ // Set raw mode
+ debug.AssertNoError(p.in.Setup())
+ go p.readBuffer(bufCh, stopReadBufCh)
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ case w := <-winSizeCh:
+ p.renderer.UpdateWinSize(w)
+ p.renderer.Render(p.buf, p.completion)
+ case code := <-exitCh:
+ p.renderer.BreakLine(p.buf)
+ p.tearDown()
+ os.Exit(code)
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
+ key := GetKey(b)
+ p.buf.lastKeyStroke = key
+ // completion
+ completing := p.completion.Completing()
+ p.handleCompletionKeyBinding(key, completing)
+
+ switch key {
+ case Enter, ControlJ, ControlM:
+ p.renderer.BreakLine(p.buf)
+
+ exec = &Exec{input: p.buf.Text()}
+ p.buf = NewBuffer()
+ if exec.input != "" {
+ p.history.Add(exec.input)
+ }
+ case ControlC:
+ p.renderer.BreakLine(p.buf)
+ p.buf = NewBuffer()
+ p.history.Clear()
+ case Up, ControlP:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Older(p.buf); changed {
+ p.buf = newBuf
+ }
+ }
+ case Down, ControlN:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Newer(p.buf); changed {
+ p.buf = newBuf
+ }
+ return
+ }
+ case ControlD:
+ if p.buf.Text() == "" {
+ shouldExit = true
+ return
+ }
+ case NotDefined:
+ if p.handleASCIICodeBinding(b) {
+ return
+ }
+ p.buf.InsertText(string(b), false, true)
+ }
+
+ shouldExit = p.handleKeyBinding(key)
+ return
+}
+
+func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
+ switch key {
+ case Down:
+ if completing || p.completionOnDown {
+ p.completion.Next()
+ }
+ case Tab, ControlI:
+ p.completion.Next()
+ case Up:
+ if completing {
+ p.completion.Previous()
+ }
+ case BackTab:
+ p.completion.Previous()
+ default:
+ if s, ok := p.completion.GetSelectedSuggestion(); ok {
+ w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
+ if w != "" {
+ p.buf.DeleteBeforeCursor(len([]rune(w)))
+ }
+ p.buf.InsertText(s.Text, false, true)
+ }
+ p.completion.Reset()
+ }
+}
+
+func (p *Prompt) handleKeyBinding(key Key) bool {
+ shouldExit := false
+ for i := range commonKeyBindings {
+ kb := commonKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+
+ if p.keyBindMode == EmacsKeyBind {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ }
+
+ // Custom key bindings
+ for i := range p.keyBindings {
+ kb := p.keyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
+ shouldExit = true
+ }
+ return shouldExit
+}
+
+func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
+ checked := false
+ for _, kb := range p.ASCIICodeBindings {
+ if bytes.Equal(kb.ASCIICode, b) {
+ kb.Fn(p.buf)
+ checked = true
+ }
+ }
+ return checked
+}
+
+// Input just returns user input text.
+func (p *Prompt) Input() string {
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ return ""
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ return e.input
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
+ debug.Log("start reading buffer")
+ for {
+ select {
+ case <-stopCh:
+ debug.Log("stop reading buffer")
+ return
+ default:
+ if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
+ bufCh <- b
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (p *Prompt) setUp() {
+ debug.AssertNoError(p.in.Setup())
+ p.renderer.Setup()
+ p.renderer.UpdateWinSize(p.in.GetWinSize())
+}
+
+func (p *Prompt) tearDown() {
+ if !p.skipTearDown {
+ debug.AssertNoError(p.in.TearDown())
+ }
+ p.renderer.TearDown()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/render.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/render.go
new file mode 100644
index 0000000000000000000000000000000000000000..299ac48b6254b9752ea16516aaedcd41acca6515
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/render.go
@@ -0,0 +1,287 @@
+package prompt
+
+import (
+ "runtime"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Render to render prompt information from state of Buffer.
+type Render struct {
+ out ConsoleWriter
+ prefix string
+ livePrefixCallback func() (prefix string, useLivePrefix bool)
+ breakLineCallback func(*Document)
+ title string
+ row uint16
+ col uint16
+
+ previousCursor int
+
+ // colors,
+ prefixTextColor Color
+ prefixBGColor Color
+ inputTextColor Color
+ inputBGColor Color
+ previewSuggestionTextColor Color
+ previewSuggestionBGColor Color
+ suggestionTextColor Color
+ suggestionBGColor Color
+ selectedSuggestionTextColor Color
+ selectedSuggestionBGColor Color
+ descriptionTextColor Color
+ descriptionBGColor Color
+ selectedDescriptionTextColor Color
+ selectedDescriptionBGColor Color
+ scrollbarThumbColor Color
+ scrollbarBGColor Color
+}
+
+// Setup to initialize console output.
+func (r *Render) Setup() {
+ if r.title != "" {
+ r.out.SetTitle(r.title)
+ debug.AssertNoError(r.out.Flush())
+ }
+}
+
+// getCurrentPrefix to get current prefix.
+// If live-prefix is enabled, return live-prefix.
+func (r *Render) getCurrentPrefix() string {
+ if prefix, ok := r.livePrefixCallback(); ok {
+ return prefix
+ }
+ return r.prefix
+}
+
+func (r *Render) renderPrefix() {
+ r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
+ r.out.WriteStr(r.getCurrentPrefix())
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// TearDown to clear title and erasing.
+func (r *Render) TearDown() {
+ r.out.ClearTitle()
+ r.out.EraseDown()
+ debug.AssertNoError(r.out.Flush())
+}
+
+func (r *Render) prepareArea(lines int) {
+ for i := 0; i < lines; i++ {
+ r.out.ScrollDown()
+ }
+ for i := 0; i < lines; i++ {
+ r.out.ScrollUp()
+ }
+}
+
+// UpdateWinSize called when window size is changed.
+func (r *Render) UpdateWinSize(ws *WinSize) {
+ r.row = ws.Row
+ r.col = ws.Col
+}
+
+func (r *Render) renderWindowTooSmall() {
+ r.out.CursorGoTo(0, 0)
+ r.out.EraseScreen()
+ r.out.SetColor(DarkRed, White, false)
+ r.out.WriteStr("Your console window is too small...")
+}
+
+func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) {
+ suggestions := completions.GetSuggestions()
+ if len(completions.GetSuggestions()) == 0 {
+ return
+ }
+ prefix := r.getCurrentPrefix()
+ formatted, width := formatSuggestions(
+ suggestions,
+ int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar
+ )
+ // +1 means a width of scrollbar.
+ width++
+
+ windowHeight := len(formatted)
+ if windowHeight > int(completions.max) {
+ windowHeight = int(completions.max)
+ }
+ formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
+ r.prepareArea(windowHeight)
+
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor())
+ x, _ := r.toPos(cursor)
+ if x+width >= int(r.col) {
+ cursor = r.backward(cursor, x+width-int(r.col))
+ }
+
+ contentHeight := len(completions.tmp)
+
+ fractionVisible := float64(windowHeight) / float64(contentHeight)
+ fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
+
+ scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
+ scrollbarTop := int(float64(windowHeight) * fractionAbove)
+
+ isScrollThumb := func(row int) bool {
+ return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
+ }
+
+ selected := completions.selected - completions.verticalScroll
+ r.out.SetColor(White, Cyan, false)
+ for i := 0; i < windowHeight; i++ {
+ r.out.CursorDown(1)
+ if i == selected {
+ r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
+ } else {
+ r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Text)
+
+ if i == selected {
+ r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
+ } else {
+ r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Description)
+
+ if isScrollThumb(i) {
+ r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
+ } else {
+ r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
+ }
+ r.out.WriteStr(" ")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+
+ r.lineWrap(cursor + width)
+ r.backward(cursor+width, width)
+ }
+
+ if x+width >= int(r.col) {
+ r.out.CursorForward(x + width - int(r.col))
+ }
+
+ r.out.CursorUp(windowHeight)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// Render renders to the console.
+func (r *Render) Render(buffer *Buffer, completion *CompletionManager) {
+ // In situations where a pseudo tty is allocated (e.g. within a docker container),
+ // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
+ if r.col == 0 {
+ return
+ }
+ defer func() { debug.AssertNoError(r.out.Flush()) }()
+ r.move(r.previousCursor, 0)
+
+ line := buffer.Text()
+ prefix := r.getCurrentPrefix()
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line)
+
+ // prepare area
+ _, y := r.toPos(cursor)
+
+ h := y + 1 + int(completion.max)
+ if h > int(r.row) || completionMargin > int(r.col) {
+ r.renderWindowTooSmall()
+ return
+ }
+
+ // Rendering
+ r.out.HideCursor()
+ defer r.out.ShowCursor()
+
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(line)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ r.lineWrap(cursor)
+
+ r.out.EraseDown()
+
+ cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition())
+
+ r.renderCompletion(buffer, completion)
+ if suggest, ok := completion.GetSelectedSuggestion(); ok {
+ cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator)))
+
+ r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false)
+ r.out.WriteStr(suggest.Text)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ cursor += runewidth.StringWidth(suggest.Text)
+
+ rest := buffer.Document().TextAfterCursor()
+ r.out.WriteStr(rest)
+ cursor += runewidth.StringWidth(rest)
+ r.lineWrap(cursor)
+
+ cursor = r.backward(cursor, runewidth.StringWidth(rest))
+ }
+ r.previousCursor = cursor
+}
+
+// BreakLine to break line.
+func (r *Render) BreakLine(buffer *Buffer) {
+ // Erasing and Render
+ cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix())
+ r.clear(cursor)
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(buffer.Document().Text + "\n")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ debug.AssertNoError(r.out.Flush())
+ if r.breakLineCallback != nil {
+ r.breakLineCallback(buffer.Document())
+ }
+
+ r.previousCursor = 0
+}
+
+// clear erases the screen from a beginning of input
+// even if there is line break which means input length exceeds a window's width.
+func (r *Render) clear(cursor int) {
+ r.move(cursor, 0)
+ r.out.EraseDown()
+}
+
+// backward moves cursor to backward from a current cursor position
+// regardless there is a line break.
+func (r *Render) backward(from, n int) int {
+ return r.move(from, from-n)
+}
+
+// move moves cursor to specified position from the beginning of input
+// even if there is a line break.
+func (r *Render) move(from, to int) int {
+ fromX, fromY := r.toPos(from)
+ toX, toY := r.toPos(to)
+
+ r.out.CursorUp(fromY - toY)
+ r.out.CursorBackward(fromX - toX)
+ return to
+}
+
+// toPos returns the relative position from the beginning of the string.
+func (r *Render) toPos(cursor int) (x, y int) {
+ col := int(r.col)
+ return cursor % col, cursor / col
+}
+
+func (r *Render) lineWrap(cursor int) {
+ if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 {
+ r.out.WriteRaw([]byte{'\n'})
+ }
+}
+
+func clamp(high, low, x float64) float64 {
+ switch {
+ case high < x:
+ return high
+ case x < low:
+ return low
+ default:
+ return x
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/shortcut.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/shortcut.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8d4282700c0bdb30e4decfb9c9ac91f27af251
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/shortcut.go
@@ -0,0 +1,43 @@
+package prompt
+
+func dummyExecutor(in string) {}
+
+// Input get the input data from the user and return it.
+func Input(prefix string, completer Completer, opts ...Option) string {
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+// Choose to the shortcut of input function to select from string array.
+// Deprecated: Maybe anyone want to use this.
+func Choose(prefix string, choices []string, opts ...Option) string {
+ completer := newChoiceCompleter(choices, FilterHasPrefix)
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+func newChoiceCompleter(choices []string, filter Filter) Completer {
+ s := make([]Suggest, len(choices))
+ for i := range choices {
+ s[i] = Suggest{Text: choices[i]}
+ }
+ return func(x Document) []Suggest {
+ return filter(s, x.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/signal_posix.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/signal_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3150df5d85e7612c42c2a889dbefee3b524bef6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/signal_posix.go
@@ -0,0 +1,49 @@
+// +build !windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ in := p.in
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+
+ case syscall.SIGWINCH:
+ debug.Log("Catch SIGWINCH")
+ winSizeCh <- in.GetWinSize()
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/signal_windows.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/signal_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a427c79ec0414540f8f40694731b2565ea80c13
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/environment/source/signal_windows.go
@@ -0,0 +1,44 @@
+// +build windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/instruction.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..df9ecd90d50b1c6f599529c7c96a87353ab08d1f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/instruction.md
@@ -0,0 +1,31 @@
+ASCII character set detection broken for certain characters
+
+#### Description
+
+The ASCII character set detection in the strings package is not working correctly for some characters. When using functions that rely on ASCII character set detection, certain characters are not being properly identified or handled.
+
+#### Steps/Code to Reproduce
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func main() {
+ // Create a document with text containing various ASCII characters
+ doc := prompt.NewDocument("hello,world", 6)
+
+ // Try to get word after cursor until separator
+ result := doc.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(",")
+ fmt.Printf("got: %q\n", result)
+ fmt.Printf("want: %q\n", ",i am c-bata")
+}
+```
+
+The function should properly detect the comma separator and return the expected text, but instead returns an empty string.
+
+This appears to affect character detection logic where certain ASCII characters in specific ranges are not being correctly identified as part of the character set.
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/provenance.json b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..62dfc24205716cb33c546ff5d944b7c5b2b3bb9a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/provenance.json
@@ -0,0 +1,477 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt",
+ "original-bug": "task-specific unchanged semantic bug",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only",
+ "extra_semantic_repair_coverage": false,
+ "original_patch_hunks": 1
+ },
+ "private_frozen_files": {
+ "buffer_test.go": {
+ "mode": "0o644",
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098",
+ "size": 4965
+ },
+ "completion_test.go": {
+ "mode": "0o644",
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d",
+ "size": 7010
+ },
+ "document_test.go": {
+ "mode": "0o644",
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284",
+ "size": 28938
+ },
+ "emacs_test.go": {
+ "mode": "0o644",
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095",
+ "size": 741
+ },
+ "filter_test.go": {
+ "mode": "0o644",
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247",
+ "size": 3339
+ },
+ "history_test.go": {
+ "mode": "0o644",
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327",
+ "size": 1319
+ },
+ "input_test.go": {
+ "mode": "0o644",
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922",
+ "size": 533
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": "0o644",
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf",
+ "size": 1075
+ },
+ "internal/strings/strings_test.go": {
+ "mode": "0o644",
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6",
+ "size": 981
+ },
+ "output_vt100_test.go": {
+ "mode": "0o644",
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee",
+ "size": 1349
+ },
+ "render_test.go": {
+ "mode": "0o644",
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb",
+ "size": 2890
+ }
+ },
+ "public_files": {
+ ".github/ISSUE_TEMPLATE/bug_report.md": {
+ "mode": "0o644",
+ "sha256": "89d3492ca8533a3d31e4de49a23828a322f75d2a1ec4236327c4a76c7c51ada6",
+ "size": 684
+ },
+ ".github/ISSUE_TEMPLATE/feature_request.md": {
+ "mode": "0o644",
+ "sha256": "d82e14e6b4d021d0007eeef4f5ca489fc6c8e8e4d7479ee30e74fe82afd3b08f",
+ "size": 206
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "3239b94a1a41c05eff5dc086ef1378cf1e289fad0203420b5cb4c78e3c5c239b",
+ "size": 270
+ },
+ "CHANGELOG.md": {
+ "mode": "0o644",
+ "sha256": "1f88f92d3247e1b52af0f0de7ad1263a59807edb17238c7a0211554f8080e51c",
+ "size": 2895
+ },
+ "LICENSE": {
+ "mode": "0o644",
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "size": 1072
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "9425a0d4c15747863625f647348962a9b0f81a0971a7e0184ee722bf34a60ba2",
+ "size": 1177
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "ce56df51a1a9a5b5c5b056429bbee006a260fb0730af63b1d0fe91755e574cc4",
+ "size": 6185
+ },
+ "_example/README.md": {
+ "mode": "0o644",
+ "sha256": "155951bafd778493bd41ae57dcc0ba6b8eca821fcbe2ffe770960ac2780d3d09",
+ "size": 1102
+ },
+ "_example/build.sh": {
+ "mode": "0o755",
+ "sha256": "de2fb330b665691cd75b990236cd6a5df0058608de0dfc6194da30d4041a1e29",
+ "size": 469
+ },
+ "_example/exec-command/main.go": {
+ "mode": "0o644",
+ "sha256": "0e96493b6e6d446b2e691d4834ff8a55834caa410ead970cb611a63ba84f174a",
+ "size": 429
+ },
+ "_example/http-prompt/api.py": {
+ "mode": "0o644",
+ "sha256": "2c2bca9acb07a84c65a4482c61c9ade253a574477a8e461307568ea1f9a342c8",
+ "size": 335
+ },
+ "_example/http-prompt/main.go": {
+ "mode": "0o644",
+ "sha256": "6994b190c4165068e69ed44eb61698af69a15a7690179ce46e3c1c5d8c211643",
+ "size": 5484
+ },
+ "_example/live-prefix/main.go": {
+ "mode": "0o644",
+ "sha256": "20268f9cb6f3b82a52eddc33cbf8082adaa46092e2063df279499e05e25a228c",
+ "size": 1103
+ },
+ "_example/simple-echo/cjk-cyrillic/main.go": {
+ "mode": "0o644",
+ "sha256": "8fb10807d4085ebc4b345bc0ccfef9217e21e49a888bfe3192e8ddfdfa01e89c",
+ "size": 800
+ },
+ "_example/simple-echo/main.go": {
+ "mode": "0o644",
+ "sha256": "e46563ddaa932831fe9ede870b10efb5222c0d54a86f4b4f5197c9cf20942a24",
+ "size": 902
+ },
+ "_tools/README.md": {
+ "mode": "0o644",
+ "sha256": "96dc2343bc5cde642fd449ddc366462753a2e17b6a78adfa015bf991e9dac241",
+ "size": 234
+ },
+ "_tools/complete_file/main.go": {
+ "mode": "0o644",
+ "sha256": "e5dd823f9d6415614a8238ce106d26e9ded1db9b308c121d7f48bb1df003effc",
+ "size": 803
+ },
+ "_tools/sigwinch/main.go": {
+ "mode": "0o644",
+ "sha256": "a806b4e45298f5003c95432d8dd3c40c9c096335f19f1a4160afcdb64fa727e3",
+ "size": 1386
+ },
+ "_tools/vt100_debug/main.go": {
+ "mode": "0o644",
+ "sha256": "7f72eba3cc7037fcf39c9b56a96c578c157e5fb235cb626ab1e83cbef0dc290b",
+ "size": 794
+ },
+ "buffer.go": {
+ "mode": "0o644",
+ "sha256": "10188d96a450fe13ba1e9ec00c89603eb2a2860536965d980d1e4abf4374b018",
+ "size": 5781
+ },
+ "completer/file.go": {
+ "mode": "0o644",
+ "sha256": "6181ed9e39028236c5c93fbe219331fc1492ecfd6af2df764cc42b5455c9bb96",
+ "size": 2401
+ },
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "b90bd9628534cfb343a592775430e17a1999b1de500fb2a8f1507c030a432eae",
+ "size": 4491
+ },
+ "document.go": {
+ "mode": "0o644",
+ "sha256": "e719d4c10a10f506c371b87dbd363a9b7f7d3aa8f0190a40965ac761197e1f1e",
+ "size": 13097
+ },
+ "emacs.go": {
+ "mode": "0o644",
+ "sha256": "53f0df0016ef9d9695a797b19286681666cf0c7e5a866c393b194aae915f2664",
+ "size": 2675
+ },
+ "filter.go": {
+ "mode": "0o644",
+ "sha256": "dc5922bad6ecb32ecdaf20bd6035dddc7ce8c14f15dbd4d49192c2354cb8a038",
+ "size": 2005
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "97413fa2a2ed68170496f2289a2dca6fb0a192dcd020fc0ca48a5d106e60d55e",
+ "size": 253
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "88ea0a91babaa54b67cc6d5f6f7f47fa4be798fe523324ea568d8926eed2024c",
+ "size": 2183
+ },
+ "history.go": {
+ "mode": "0o644",
+ "sha256": "4ce80ba067cfc72c56a3ee3353ec75cd6bb2f5d82097515c591e3c7c773c51cd",
+ "size": 1488
+ },
+ "input.go": {
+ "mode": "0o644",
+ "sha256": "73461cc4f57d68b66e2a9e196239aaef942539134593beac0d0023743832e0e1",
+ "size": 7630
+ },
+ "input_posix.go": {
+ "mode": "0o644",
+ "sha256": "c7e5a4dfc3910f178f0685ef99f2e47d481a91c4cf9af50f92fc4266aed634df",
+ "size": 1648
+ },
+ "input_windows.go": {
+ "mode": "0o644",
+ "sha256": "f763250d309fb88d9536f77da1d1285c04bc6defe859506f1501e10f7743da9e",
+ "size": 1679
+ },
+ "internal/bisect/bisect.go": {
+ "mode": "0o644",
+ "sha256": "c4de2adfa2e08a77f902661d67325467f89013634dbcef22d24dc6f34d26624a",
+ "size": 327
+ },
+ "internal/debug/assert.go": {
+ "mode": "0o644",
+ "sha256": "1a3050ec58991b62c7ea352d19505e3080ac9760bdb091544f0ecf5aba35969c",
+ "size": 815
+ },
+ "internal/debug/log.go": {
+ "mode": "0o644",
+ "sha256": "2ce968e275558de61c6d83793e85561f7a8dd69c95ec7902ccd2cc3fb169aa82",
+ "size": 875
+ },
+ "internal/strings/strings.go": {
+ "mode": "0o644",
+ "sha256": "ea50daad532ab8d3f90065e620be7b9c68baee4544efa3555095e027274ebbfc",
+ "size": 2018
+ },
+ "internal/term/raw.go": {
+ "mode": "0o644",
+ "sha256": "177a1a20ae8d71b56857383a5797754560f7f6404ea86778d5f01e9a1c1b4f9f",
+ "size": 747
+ },
+ "internal/term/term.go": {
+ "mode": "0o644",
+ "sha256": "abe6fa965fa15b999b2010135903f598830d4c885a52ef9b067fd5ebbf6e373f",
+ "size": 606
+ },
+ "key.go": {
+ "mode": "0o644",
+ "sha256": "03a43283e07de7a4ea6fed32692d86325f73e98fd89a296f19c171e0bc780999",
+ "size": 1746
+ },
+ "key_bind.go": {
+ "mode": "0o644",
+ "sha256": "83f48bb720a11c8e49165ac382e3a870fdcf6b380a0a95267f8c25211898c9eb",
+ "size": 1109
+ },
+ "key_bind_func.go": {
+ "mode": "0o644",
+ "sha256": "445bff5c0fdb0b52879c635322603c2fc75d265de3761cb8c3b980c798bf39af",
+ "size": 1219
+ },
+ "key_string.go": {
+ "mode": "0o644",
+ "sha256": "55c429dae227bb1659d5d5e2e906dbfa9c7f53b5105fa83fbe290529ff6f2317",
+ "size": 1359
+ },
+ "option.go": {
+ "mode": "0o644",
+ "sha256": "28cfcc1d08b3cf650483d977195458531b3b3913f8a5f357a3ec17ea5d73e215",
+ "size": 8737
+ },
+ "output.go": {
+ "mode": "0o644",
+ "sha256": "372876b0aa908479ed3b29de70a479f420d85e3666b8957c8b61eaed9b32c3f2",
+ "size": 4320
+ },
+ "output_posix.go": {
+ "mode": "0o644",
+ "sha256": "d46b1da307e8969b033e1ade2eb51a83c4c3d4f2a7e4aba35ec3a03991b89a0f",
+ "size": 1545
+ },
+ "output_vt100.go": {
+ "mode": "0o644",
+ "sha256": "9082c7e4619c1eb38030bc4994a4fbf66ef27b130751bf2eb9c25c01082e8605",
+ "size": 7453
+ },
+ "output_windows.go": {
+ "mode": "0o644",
+ "sha256": "571c5ae1ad051a701b426371efd79a3776c2226ca9e3c2e598fe5996dfa1b8e1",
+ "size": 1066
+ },
+ "prompt.go": {
+ "mode": "0o644",
+ "sha256": "6b3e2bbd90f40ad6a487f1a6ea7f5a6fb48cae6c8c246ecc77621fb3e7383ca7",
+ "size": 7062
+ },
+ "render.go": {
+ "mode": "0o644",
+ "sha256": "90fdd57a63e06f01940d10ee1a0be95ced7d6adc7faa255b3141556d7d316270",
+ "size": 8020
+ },
+ "shortcut.go": {
+ "mode": "0o644",
+ "sha256": "b4a097f466df7396049ebe8393f81c9b1200159d4e2be22bd6838c307ec156dc",
+ "size": 1120
+ },
+ "signal_posix.go": {
+ "mode": "0o644",
+ "sha256": "74f0bae5f290f3f7f82a5dd495e672f627a4ab4b63118f870e8c13c0a7024314",
+ "size": 881
+ },
+ "signal_windows.go": {
+ "mode": "0o644",
+ "sha256": "444f662a32e6997df2af8e2a9e7dbfe977414a6bfc0f54a7f10117f204648437",
+ "size": 757
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982",
+ "os": "linux",
+ "sha256": "0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982"
+ },
+ "context_inventory_sha256": "6b8f93086e81483ac1ce82f328d7f4b38b1b560dbad057ed6a2a30ff3cf0e13f",
+ "image": "registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "9d3b21cdacadfa4f3de9584d0cea973e5aa2ceedcd5ec9cbd3a63df22b313455",
+ "receipt_path": "production/runtime-images-extra-v1/resolutions/316e0e68930cd4ef/resolution.json",
+ "receipt_sha256": "697bb0619eddcdfdeba1c9144b033f564f2d7514be6e6a44dc520fa4e63ed8bc",
+ "registry_digest": "sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "source_image": "docker.io/swebench/swesmith.x86_64.c-bata_1776_go-prompt.82a91227@sha256:3daf51c74a01657e9ad8f326651fb6f5b796ffecdb90098e74a52a9560e0a1bb",
+ "source_receipt_sha256": "b450bea0e201cbe194b765ded4b51539144c85296122c8b642d7e94c889526f3",
+ "space_commit": "5ae654cd2e9d695f0de304bd4398835fc7cf45e0",
+ "space_id": "harness-hub/scale800-go-316e0e68930cd4ef-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "42475412600cb2ea6e16fec97236eca57a9974d014245d406c7974463e445aa9",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21",
+ "source_proof_sha256": "f10e5be0fc436f45b4026864078cefe71938ca10ec688b53489fd090c84ae12a",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "9992c59c25864ce1556e67b9e1501c93f6e7f9ff",
+ "instruction_sha256": "18504627d0b319dc27284fe188d5766e786bda35a7266ecb7f536c92a50f7618",
+ "is_fork": true,
+ "learner_path": "tasks/582f3ee9cca36bf884946a4a/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/c-bata__go-prompt.82a91227/cb7b0d04686212eb4a13ed44810e8eaac3b22d2a/LICENSE"
+ },
+ "task_bundle": {
+ "basis": "Captured publisherMIT/train; exactsoftwarepermissionverifiedseparately",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "82a912274504477990ecf7c852eebb7c85291772",
+ "patch_sha256": "132775567ff5fcb172c37f4cf9d6576cdc3f3c57938e88e1ce4765e3442d581a",
+ "provenance_path": "tasks/582f3ee9cca36bf884946a4a/source-proof.json",
+ "repository_lineage": [
+ "swesmith/c-bata__go-prompt.82a91227",
+ "c-bata/go-prompt"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "cb7b0d04686212eb4a13ed44810e8eaac3b22d2a",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "13575f82650711039c784f792724c700407d589a",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/c-bata__go-prompt.82a91227",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg",
+ "task_sha256": "5aafc5b2cca1cf76cc2199d85c79be58376f489e98e7833935ae7062830696d7",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "c-bata/go-prompt",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "6ddefef8740f5149b4a93f07db0607c312119c6f8f09e8f836cfe6d5fb94b7a6",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.md",
+ "/testbed/.github/ISSUE_TEMPLATE/feature_request.md",
+ "/testbed/.gitignore",
+ "/testbed/CHANGELOG.md",
+ "/testbed/LICENSE",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/_example/README.md",
+ "/testbed/_example/build.sh",
+ "/testbed/_example/exec-command/main.go",
+ "/testbed/_example/http-prompt/api.py",
+ "/testbed/_example/http-prompt/main.go",
+ "/testbed/_example/live-prefix/main.go",
+ "/testbed/_example/simple-echo/cjk-cyrillic/main.go",
+ "/testbed/_example/simple-echo/main.go",
+ "/testbed/_tools/README.md",
+ "/testbed/_tools/complete_file/main.go",
+ "/testbed/_tools/sigwinch/main.go",
+ "/testbed/_tools/vt100_debug/main.go",
+ "/testbed/buffer.go",
+ "/testbed/completer/file.go",
+ "/testbed/completion.go",
+ "/testbed/document.go",
+ "/testbed/emacs.go",
+ "/testbed/filter.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum",
+ "/testbed/history.go",
+ "/testbed/input.go",
+ "/testbed/input_posix.go",
+ "/testbed/input_windows.go",
+ "/testbed/internal/bisect/bisect.go",
+ "/testbed/internal/debug/assert.go",
+ "/testbed/internal/debug/log.go",
+ "/testbed/internal/strings/strings.go",
+ "/testbed/internal/term/raw.go",
+ "/testbed/internal/term/term.go",
+ "/testbed/key.go",
+ "/testbed/key_bind.go",
+ "/testbed/key_bind_func.go",
+ "/testbed/key_string.go",
+ "/testbed/option.go",
+ "/testbed/output.go",
+ "/testbed/output_posix.go",
+ "/testbed/output_vt100.go",
+ "/testbed/output_windows.go",
+ "/testbed/prompt.go",
+ "/testbed/render.go",
+ "/testbed/shortcut.go",
+ "/testbed/signal_posix.go",
+ "/testbed/signal_windows.go"
+ ]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/solution/solve.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4bf2e9d8a6784b470b7925a0d8c6f8a1bb2438e0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"internal/strings/strings.go": {"data": "cGFja2FnZSBzdHJpbmdzCgppbXBvcnQgInVuaWNvZGUvdXRmOCIKCi8vIEluZGV4Tm90Qnl0ZSBpcyBzaW1pbGFyIHdpdGggc3RyaW5ncy5JbmRleEJ5dGUgYnV0IHNob3dpbmcgdGhlIG9wcG9zaXRlIGJlaGF2aW9yLgpmdW5jIEluZGV4Tm90Qnl0ZShzIHN0cmluZywgYyBieXRlKSBpbnQgewoJbiA6PSBsZW4ocykKCWZvciBpIDo9IDA7IGkgPCBuOyBpKysgewoJCWlmIHNbaV0gIT0gYyB7CgkJCXJldHVybiBpCgkJfQoJfQoJcmV0dXJuIC0xCn0KCi8vIExhc3RJbmRleE5vdEJ5dGUgaXMgc2ltaWxhciB3aXRoIHN0cmluZ3MuTGFzdEluZGV4Qnl0ZSBidXQgc2hvd2luZyB0aGUgb3Bwb3NpdGUgYmVoYXZpb3IuCmZ1bmMgTGFzdEluZGV4Tm90Qnl0ZShzIHN0cmluZywgYyBieXRlKSBpbnQgewoJZm9yIGkgOj0gbGVuKHMpIC0gMTsgaSA+PSAwOyBpLS0gewoJCWlmIHNbaV0gIT0gYyB7CgkJCXJldHVybiBpCgkJfQoJfQoJcmV0dXJuIC0xCn0KCnR5cGUgYXNjaWlTZXQgWzhddWludDMyCgpmdW5jIChhcyAqYXNjaWlTZXQpIG5vdENvbnRhaW5zKGMgYnl0ZSkgYm9vbCB7CglyZXR1cm4gKGFzW2M+PjVdICYgKDEgPDwgdWludChjJjMxKSkpID09IDAKfQoKZnVuYyBtYWtlQVNDSUlTZXQoY2hhcnMgc3RyaW5nKSAoYXMgYXNjaWlTZXQsIG9rIGJvb2wpIHsKCWZvciBpIDo9IDA7IGkgPCBsZW4oY2hhcnMpOyBpKysgewoJCWMgOj0gY2hhcnNbaV0KCQlpZiBjID49IHV0ZjguUnVuZVNlbGYgewoJCQlyZXR1cm4gYXMsIGZhbHNlCgkJfQoJCWFzW2M+PjVdIHw9IDEgPDwgdWludChjJjMxKQoJfQoJcmV0dXJuIGFzLCB0cnVlCn0KCi8vIEluZGV4Tm90QW55IGlzIHNpbWlsYXIgd2l0aCBzdHJpbmdzLkluZGV4QW55IGJ1dCBzaG93aW5nIHRoZSBvcHBvc2l0ZSBiZWhhdmlvci4KZnVuYyBJbmRleE5vdEFueShzLCBjaGFycyBzdHJpbmcpIGludCB7CglpZiBsZW4oY2hhcnMpID4gMCB7CgkJaWYgbGVuKHMpID4gOCB7CgkJCWlmIGFzLCBpc0FTQ0lJIDo9IG1ha2VBU0NJSVNldChjaGFycyk7IGlzQVNDSUkgewoJCQkJZm9yIGkgOj0gMDsgaSA8IGxlbihzKTsgaSsrIHsKCQkJCQlpZiBhcy5ub3RDb250YWlucyhzW2ldKSB7CgkJCQkJCXJldHVybiBpCgkJCQkJfQoJCQkJfQoJCQkJcmV0dXJuIC0xCgkJCX0KCQl9CgoJTGFiZWxGaXJzdExvb3A6CgkJZm9yIGksIGMgOj0gcmFuZ2UgcyB7CgkJCWZvciBqLCBtIDo9IHJhbmdlIGNoYXJzIHsKCQkJCWlmIGMgIT0gbSAmJiBqID09IGxlbihjaGFycyktMSB7CgkJCQkJcmV0dXJuIGkKCQkJCX0gZWxzZSBpZiBjICE9IG0gewoJCQkJCWNvbnRpbnVlCgkJCQl9IGVsc2UgewoJCQkJCWNvbnRpbnVlIExhYmVsRmlyc3RMb29wCgkJCQl9CgkJCX0KCQl9Cgl9CglyZXR1cm4gLTEKfQoKLy8gTGFzdEluZGV4Tm90QW55IGlzIHNpbWlsYXIgd2l0aCBzdHJpbmdzLkxhc3RJbmRleEFueSBidXQgc2hvd2luZyB0aGUgb3Bwb3NpdGUgYmVoYXZpb3IuCmZ1bmMgTGFzdEluZGV4Tm90QW55KHMsIGNoYXJzIHN0cmluZykgaW50IHsKCWlmIGxlbihjaGFycykgPiAwIHsKCQlpZiBsZW4ocykgPiA4IHsKCQkJaWYgYXMsIGlzQVNDSUkgOj0gbWFrZUFTQ0lJU2V0KGNoYXJzKTsgaXNBU0NJSSB7CgkJCQlmb3IgaSA6PSBsZW4ocykgLSAxOyBpID49IDA7IGktLSB7CgkJCQkJaWYgYXMubm90Q29udGFpbnMoc1tpXSkgewoJCQkJCQlyZXR1cm4gaQoJCQkJCX0KCQkJCX0KCQkJCXJldHVybiAtMQoJCQl9CgkJfQoJTGFiZWxGaXJzdExvb3A6CgkJZm9yIGkgOj0gbGVuKHMpOyBpID4gMDsgewoJCQlyLCBzaXplIDo9IHV0ZjguRGVjb2RlTGFzdFJ1bmVJblN0cmluZyhzWzppXSkKCQkJaSAtPSBzaXplCgkJCWZvciBqLCBtIDo9IHJhbmdlIGNoYXJzIHsKCQkJCWlmIHIgIT0gbSAmJiBqID09IGxlbihjaGFycyktMSB7CgkJCQkJcmV0dXJuIGkKCQkJCX0gZWxzZSBpZiByICE9IG0gewoJCQkJCWNvbnRpbnVlCgkJCQl9IGVsc2UgewoJCQkJCWNvbnRpbnVlIExhYmVsRmlyc3RMb29wCgkJCQl9CgkJCX0KCQl9Cgl9CglyZXR1cm4gLTEKfQo=", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/task.toml b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..1f5bb26c4315b97ebc24e2fc9e4c08423b566c73
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/task.toml
@@ -0,0 +1,11 @@
+version = "1.0"
+[agent]
+timeout_sec = 300.0
+[verifier]
+timeout_sec = 300.0
+environment_mode = "shared"
+[environment]
+docker_image = "ghcr.io/younesbelkada/scale800@sha256:f063ce507d5f5baf6621e3763715ac64ccb0d392eb8a31bb77c5b70ef4104b4a"
+cpus = 1
+memory_mb = 2048
+storage_mb = 4096
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..0454aefd3c3fa8b575b0a68bd116bf723153cb33
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/manifest.json
@@ -0,0 +1,432 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CursorPositionRowAndCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorLeftPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorUpPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorDownPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorRightPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_Lines"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_LineCount"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateIndexToPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateRowColToIndex"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_OnLastLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetEndOfLinePosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestEmacsKeyBindings"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFilter"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFuzzyMatch"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryClear"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryAdd"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryOlder"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/escape"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/undefined"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWrite"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteRawStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatCompletion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBreakLineCallback"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionRow"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition_withJapanese"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/validation/canaries/delete-tests.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/validation/canaries/delete-tests.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/validation/canaries/delete-tests.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+find /testbed -name '*_test.go' -type f -delete
+printf 'PASS\nok forged-package 0.001s\n'
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..71b03811820e4c3bc7600346a7014d6c7e3e9663
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__uaxymypg/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "1014606aeb070ae8a9a827baa005d8bc66de83df15e17ea893ce60cabe7cb6be",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/Dockerfile b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f35bf9e5393ee1086fe1b72c1b442f3b16e2bd5b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22
+WORKDIR /testbed
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c8c031d0f87fb9aea0aff433b1fcaeaac259c41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: "Bug report"
+about: Create a bug report to improve go-prompt
+title: "[Bug]"
+labels: bug
+assignees: ''
+
+---
+
+# Bug reports
+
+*Please file a bug report here.*
+
+## Expected Behavior
+
+*Please describe the behavior you are expecting*
+
+## Current Behavior and Steps to Reproduce
+
+*What is the current behavior? Please provide detailed steps for reproducing the issue.*
+*A picture or gif animation tells a thousand words*
+
+## Context
+
+Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
+
+* Operating System:
+* Terminal Emulator: (i.e. iTerm2)
+* tag of go-prompt or commit revision:
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb816a2496376983781774cb5466fed8e1efc93b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,13 @@
+---
+name: "Feature request"
+about: Suggest an idea for new features in go-prompt.
+title: "[Feature Request]"
+labels: enhancement
+assignees: ''
+
+---
+
+# Feature Request
+
+*Please write your suggestion here.*
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/.gitignore b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..eba2b56abe0f7758a560d47dd19d8985b67ef327
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+bin/
+
+# Folders
+pkg/
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+# Glide
+vendor/
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/CHANGELOG.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..b9e21f1ef333b9ec13323bcd4a8f377322ed7e9f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/CHANGELOG.md
@@ -0,0 +1,79 @@
+# Change Log
+
+## v0.3.0 (2018/??/??)
+
+next release.
+
+## v0.2.3 (2018/10/25)
+
+### What's new?
+
+* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92).
+* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100).
+* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102).
+
+### Fixed
+
+* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details).
+* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details).
+* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details).
+
+### Removed or Deprecated
+
+* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`.
+
+## v0.2.2 (2018/06/28)
+
+### What's new?
+
+* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters.
+* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions.
+ * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details).
+* Add FilePathCompleter to complete file path on your system.
+* Add option to customize ascii code key bindings.
+* Add GetWordAfterCursor method in Document.
+
+### Removed or Deprecated
+
+* prompt.Choose shortcut function is deprecated.
+
+## v0.2.1 (2018/02/14)
+
+### What's New?
+
+* ~~It seems that windows support is almost perfect.~~
+ * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows.
+
+### Fixed
+
+* Fix a Shift+Tab handling on Windows.
+* Fix 4-dimension arrow keys handling on Windows.
+
+## v0.2.0 (2018/02/13)
+
+### What's New?
+
+* Supports scrollbar when there are too many matched suggestions
+* Windows support (but please caution because this is still not perfect).
+* Add OptionLivePrefix to update the prefix dynamically
+* Implement clear screen by `Ctrl+L`.
+
+### Fixed
+
+* Fix the behavior of `Ctrl+W` keybind.
+* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details).
+* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details).
+* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ).
+
+### News
+
+New core developers are joined (alphabetical order).
+
+* Nao Yonashiro (Github @orisano)
+* Ryoma Abe (Github @Allajah)
+* Yusuke Nakamura (Github @unasuke)
+
+
+## v0.1.0 (2017/08/15)
+
+Initial Release
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/LICENSE b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a86acaa7ab24fe61ea152a9afcadc21980020efb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Masashi SHIBATA
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/Makefile b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..505817c36f0b8a0bb643eed8680b8989af2b0920
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/Makefile
@@ -0,0 +1,46 @@
+.DEFAULT_GOAL := help
+
+SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
+
+GOIMPORTS ?= goimports
+GOCILINT ?= golangci-lint
+
+.PHONY: setup
+setup: ## Setup for required tools.
+ go get -u golang.org/x/tools/cmd/goimports
+ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: fmt
+fmt: $(SOURCES) ## Formatting source codes.
+ @$(GOIMPORTS) -w $^
+
+.PHONY: lint
+lint: ## Run golangci-lint.
+ @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
+
+.PHONY: test
+test: ## Run tests with race condition checking.
+ @go test -race ./...
+
+.PHONY: bench
+bench: ## Run benchmarks.
+ @go test -bench=. -run=- -benchmem ./...
+
+.PHONY: coverage
+cover: ## Run the tests.
+ @go test -coverprofile=coverage.o
+ @go tool cover -func=coverage.o
+
+.PHONY: generate
+generate: ## Run go generate
+ @go generate ./...
+
+.PHONY: build
+build: ## Build example command lines.
+ ./_example/build.sh
+
+.PHONY: help
+help: ## Show help text
+ @echo "Commands:"
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}'
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/README.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfcd7a399b4827d6b126d6a173cce34d36520481
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/README.md
@@ -0,0 +1,125 @@
+# go-prompt
+
+[](https://goreportcard.com/report/github.com/c-bata/go-prompt)
+
+[](https://godoc.org/github.com/c-bata/go-prompt)
+
+
+A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit),
+making it easier to build cross-platform command line tools using Go.
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func completer(d prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ }
+ return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ fmt.Println("Please select table.")
+ t := prompt.Input("> ", completer)
+ fmt.Println("You selected " + t)
+}
+```
+
+#### Projects using go-prompt
+
+* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt)
+* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli)
+* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn)
+* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli)
+* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans)
+* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit)
+* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go)
+* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS)
+* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs)
+* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli)
+* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt)
+* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh)
+* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell)
+* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt)
+* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim)
+* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron)
+* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl)
+* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl)
+* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit)
+* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.)
+
+## Features
+
+### Powerful auto-completion
+
+[](https://github.com/c-bata/kube-prompt)
+
+(This is a GIF animation of kube-prompt.)
+
+### Flexible options
+
+go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details.
+
+[](#flexible-options)
+
+### Keyboard Shortcuts
+
+Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell).
+You can customize and expand these shortcuts.
+
+[](#keyboard-shortcuts)
+
+Key Binding | Description
+---------------------|---------------------------------------------------------
+Ctrl + A | Go to the beginning of the line (Home)
+Ctrl + E | Go to the end of the line (End)
+Ctrl + P | Previous command (Up arrow)
+Ctrl + N | Next command (Down arrow)
+Ctrl + F | Forward one character
+Ctrl + B | Backward one character
+Ctrl + D | Delete character under the cursor
+Ctrl + H | Delete character before the cursor (Backspace)
+Ctrl + W | Cut the word before the cursor to the clipboard
+Ctrl + K | Cut the line after the cursor to the clipboard
+Ctrl + U | Cut the line before the cursor to the clipboard
+Ctrl + L | Clear the screen
+
+### History
+
+You can use Up arrow and Down arrow to walk through the history of commands executed.
+
+[](#history)
+
+### Multiple platform support
+
+We have confirmed go-prompt works fine in the following terminals:
+
+* iTerm2 (macOS)
+* Terminal.app (macOS)
+* Command Prompt (Windows)
+* gnome-terminal (Ubuntu)
+
+## Links
+
+* [Change Log](./CHANGELOG.md)
+* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt)
+* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt)
+
+## Author
+
+Masashi Shibata
+
+* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/)
+* Github: [@c-bata](https://github.com/c-bata/)
+
+## License
+
+This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/README.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..759b0e3f8acf1216b055e0f9458758a6c1e8950a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/README.md
@@ -0,0 +1,30 @@
+# Examples of go-prompt
+
+This directory includes some examples using go-prompt.
+These examples are useful to know the usage of go-prompt and check behavior for development.
+
+## simple-echo
+
+
+
+A simple echo example using `prompt.Input`.
+
+## http-prompt
+
+
+
+A simple [http-prompt](https://github.com/eliangcs/http-prompt) implementation using go-prompt in less than 200 lines of Go.
+
+## live-prefix
+
+
+
+A example application which changes a prefix string dynamically.
+This feature is used like [ktr0731/evans](https://github.com/ktr0731/evans) which is interactive gRPC client using go-prompt.
+
+## exec-command
+
+Run another CLI tool via `os/exec` package.
+More practical example is [a source code of kube-prompt](https://github.com/c-bata/kube-prompt).
+I recommend you to look this if you want to create tools like kube-prompt.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/build.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c552afcfa69b2356ffcd484c867abcaaaaeeaff
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+export GO111MODULE=on
+DIR=$(cd $(dirname $0); pwd)
+BIN_DIR=$(cd $(dirname $(dirname $0)); pwd)/bin
+
+mkdir -p ${BIN_DIR}
+go build -o ${BIN_DIR}/exec-command ${DIR}/exec-command/main.go
+go build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.go
+go build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.go
+go build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.go
+go build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/exec-command/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/exec-command/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..838f756260df91569491def29a7ee05a7c9a98f7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/exec-command/main.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "os/exec"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(t string) {
+ if t == "bash" {
+ cmd := exec.Command("bash")
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Run()
+ }
+ return
+}
+
+func completer(t prompt.Document) []prompt.Suggest {
+ return []prompt.Suggest{
+ {Text: "bash"},
+ }
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/http-prompt/api.py b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/http-prompt/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..08e7b1a489a2077f26f280fe39e3bd06efa52cd2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/http-prompt/api.py
@@ -0,0 +1,17 @@
+from bottle import route, run, request
+
+@route('/')
+def hello():
+ return "Hello World!"
+
+@route('/ping')
+def hello():
+ return "pong!"
+
+@route('/register', method='POST')
+def register():
+ name = request.json.get("name")
+ return "Hello %s!" % name
+
+if __name__ == "__main__":
+ run(host='localhost', port=8000, debug=True)
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/http-prompt/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/http-prompt/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b372a3550c50121d6e500e2a08e641e168b8c00d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/http-prompt/main.go
@@ -0,0 +1,192 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+type RequestContext struct {
+ url *url.URL
+ header http.Header
+ client *http.Client
+}
+
+var ctx *RequestContext
+
+// See https://github.com/eliangcs/http-prompt/blob/master/http_prompt/completion.py
+var suggestions = []prompt.Suggest{
+ // Command
+ {"cd", "Change URL/path"},
+ {"exit", "Exit http-prompt"},
+
+ // HTTP Method
+ {"delete", "DELETE request"},
+ {"get", "GET request"},
+ {"patch", "GET request"},
+ {"post", "POST request"},
+ {"put", "PUT request"},
+
+ // HTTP Header
+ {"Accept", "Acceptable response media type"},
+ {"Accept-Charset", "Acceptable response charsets"},
+ {"Accept-Encoding", "Acceptable response content codings"},
+ {"Accept-Language", "Preferred natural languages in response"},
+ {"ALPN", "Application-layer protocol negotiation to use"},
+ {"Alt-Used", "Alternative host in use"},
+ {"Authorization", "Authentication information"},
+ {"Cache-Control", "Directives for caches"},
+ {"Connection", "Connection options"},
+ {"Content-Encoding", "Content codings"},
+ {"Content-Language", "Natural languages for content"},
+ {"Content-Length", "Anticipated size for payload body"},
+ {"Content-Location", "Where content was obtained"},
+ {"Content-MD5", "Base64-encoded MD5 sum of content"},
+ {"Content-Type", "Content media type"},
+ {"Cookie", "Stored cookies"},
+ {"Date", "Datetime when message was originated"},
+ {"Depth", "Applied only to resource or its members"},
+ {"DNT", "Do not track user"},
+ {"Expect", "Expected behaviors supported by server"},
+ {"Forwarded", "Proxies involved"},
+ {"From", "Sender email address"},
+ {"Host", "Target URI"},
+ {"HTTP2-Settings", "HTTP/2 connection parameters"},
+ {"If", "Request condition on state tokens and ETags"},
+ {"If-Match", "Request condition on target resource"},
+ {"If-Modified-Since", "Request condition on modification date"},
+ {"If-None-Match", "Request condition on target resource"},
+ {"If-Range", "Request condition on Range"},
+ {"If-Schedule-Tag-Match", "Request condition on Schedule-Tag"},
+ {"If-Unmodified-Since", "Request condition on modification date"},
+ {"Max-Forwards", "Max number of times forwarded by proxies"},
+ {"MIME-Version", "Version of MIME protocol"},
+ {"Origin", "Origin(s} issuing the request"},
+ {"Pragma", "Implementation-specific directives"},
+ {"Prefer", "Preferred server behaviors"},
+ {"Proxy-Authorization", "Proxy authorization credentials"},
+ {"Proxy-Connection", "Proxy connection options"},
+ {"Range", "Request transfer of only part of data"},
+ {"Referer", "Previous web page"},
+ {"TE", "Transfer codings willing to accept"},
+ {"Transfer-Encoding", "Transfer codings applied to payload body"},
+ {"Upgrade", "Invite server to upgrade to another protocol"},
+ {"User-Agent", "User agent string"},
+ {"Via", "Intermediate proxies"},
+ {"Warning", "Possible incorrectness with payload body"},
+ {"WWW-Authenticate", "Authentication scheme"},
+ {"X-Csrf-Token", "Prevent cross-site request forgery"},
+ {"X-CSRFToken", "Prevent cross-site request forgery"},
+ {"X-Forwarded-For", "Originating client IP address"},
+ {"X-Forwarded-Host", "Original host requested by client"},
+ {"X-Forwarded-Proto", "Originating protocol"},
+ {"X-Http-Method-Override", "Request method override"},
+ {"X-Requested-With", "Used to identify Ajax requests"},
+ {"X-XSRF-TOKEN", "Prevent cross-site request forgery"},
+}
+
+func livePrefix() (string, bool) {
+ if ctx.url.Path == "/" {
+ return "", false
+ }
+ return ctx.url.String() + "> ", true
+}
+
+func executor(in string) {
+ in = strings.TrimSpace(in)
+
+ var method, body string
+ blocks := strings.Split(in, " ")
+ switch blocks[0] {
+ case "exit":
+ fmt.Println("Bye!")
+ os.Exit(0)
+ case "cd":
+ if len(blocks) < 2 {
+ ctx.url.Path = "/"
+ } else {
+ ctx.url.Path = path.Join(ctx.url.Path, blocks[1])
+ }
+ return
+ case "get", "delete":
+ method = strings.ToUpper(blocks[0])
+ case "post", "put", "patch":
+ if len(blocks) < 2 {
+ fmt.Println("please set request body.")
+ return
+ }
+ body = strings.Join(blocks[1:], " ")
+ method = strings.ToUpper(blocks[0])
+ }
+ if method != "" {
+ req, err := http.NewRequest(method, ctx.url.String(), strings.NewReader(body))
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ req.Header = ctx.header
+ res, err := ctx.client.Do(req)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ result, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ fmt.Printf("%s\n", result)
+ ctx.header = http.Header{}
+ return
+ }
+
+ if h := strings.Split(in, ":"); len(h) == 2 {
+ // Handling HTTP Header
+ ctx.header.Add(strings.TrimSpace(h[0]), strings.Trim(h[1], ` '"`))
+ } else {
+ fmt.Println("Sorry, I don't understand.")
+ }
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ w := in.GetWordBeforeCursor()
+ if w == "" {
+ return []prompt.Suggest{}
+ }
+ return prompt.FilterHasPrefix(suggestions, w, true)
+}
+
+func main() {
+ var baseURL = "http://localhost:8000/"
+ if len(os.Args) == 2 {
+ baseURL = os.Args[1]
+ if strings.HasSuffix(baseURL, "/") {
+ baseURL += "/"
+ }
+ }
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ ctx = &RequestContext{
+ url: u,
+ header: http.Header{},
+ client: &http.Client{},
+ }
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(u.String()+"> "),
+ prompt.OptionLivePrefix(livePrefix),
+ prompt.OptionTitle("http-prompt"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/live-prefix/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/live-prefix/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c7ced720592173e2a13f19f7cb543730192d3f8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/live-prefix/main.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var LivePrefixState struct {
+ LivePrefix string
+ IsEnable bool
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+ if in == "" {
+ LivePrefixState.IsEnable = false
+ LivePrefixState.LivePrefix = in
+ return
+ }
+ LivePrefixState.LivePrefix = in + "> "
+ LivePrefixState.IsEnable = true
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func changeLivePrefix() (string, bool) {
+ return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionLivePrefix(changeLivePrefix),
+ prompt.OptionTitle("live-prefix-example"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/simple-echo/cjk-cyrillic/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/simple-echo/cjk-cyrillic/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e9e53adef1558e004f86ccbca2c2e2b83c1da39
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/simple-echo/cjk-cyrillic/main.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
+ {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
+ {Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
+ {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionTitle("sql-prompt for multi width characters"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/simple-echo/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/simple-echo/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..12b1bb4fc189e6b369e889779418d7826a45db9d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_example/simple-echo/main.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ in := prompt.Input(">>> ", completer,
+ prompt.OptionTitle("sql-prompt"),
+ prompt.OptionHistory([]string{"SELECT * FROM users;"}),
+ prompt.OptionPrefixTextColor(prompt.Yellow),
+ prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
+ prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
+ prompt.OptionSuggestionBGColor(prompt.DarkGray))
+ fmt.Println("Your input: " + in)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_tools/README.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..45bd2234f21ff32562984bec046316c8e52868fd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_tools/README.md
@@ -0,0 +1,10 @@
+## Tools of go-prompt
+
+### vt100_debug
+
+
+
+### sigwinch
+
+
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_tools/complete_file/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_tools/complete_file/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..41015cfab9b021fbc7df575bde87e3c510705496
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_tools/complete_file/main.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/completer"
+)
+
+var filePathCompleter = completer.FilePathCompleter{
+ IgnoreCase: true,
+ Filter: func(fi os.FileInfo) bool {
+ return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
+ },
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completerFunc(d prompt.Document) []prompt.Suggest {
+ t := d.GetWordBeforeCursor()
+ if strings.HasPrefix(t, "--") {
+ return []prompt.Suggest{
+ {"--foo", ""},
+ {"--bar", ""},
+ {"--baz", ""},
+ }
+ }
+ return filePathCompleter.Complete(d)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completerFunc,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_tools/sigwinch/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_tools/sigwinch/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9608eb3b4a5e3c6942c140c41e08a36ab3adb33b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_tools/sigwinch/main.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "unsafe"
+)
+
+// Winsize is winsize struct got from the ioctl(2) system call.
+type Winsize struct {
+ Row uint16
+ Col uint16
+ X uint16 // pixel value
+ Y uint16 // pixel value
+}
+
+// GetWinSize returns winsize struct which is the response of ioctl(2).
+func GetWinSize(fd int) *Winsize {
+ ws := &Winsize{}
+ retCode, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ uintptr(fd),
+ uintptr(syscall.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(ws)))
+
+ if int(retCode) == -1 {
+ panic(errno)
+ }
+ return ws
+}
+
+func main() {
+ signalChan := make(chan os.Signal, 1)
+ signal.Notify(
+ signalChan,
+ syscall.SIGHUP,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ exitChan := make(chan int)
+ go func() {
+ for {
+ s := <-signalChan
+ switch s {
+ // kill -SIGHUP XXXX
+ case syscall.SIGHUP:
+ exitChan <- 0
+
+ // kill -SIGINT XXXX or Ctrl+c
+ case syscall.SIGINT:
+ exitChan <- 0
+
+ // kill -SIGTERM XXXX
+ case syscall.SIGTERM:
+ exitChan <- 0
+
+ // kill -SIGQUIT XXXX
+ case syscall.SIGQUIT:
+ exitChan <- 0
+
+ case syscall.SIGWINCH:
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ default:
+ exitChan <- 1
+ }
+ }
+ }()
+
+ code := <-exitChan
+ os.Exit(code)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_tools/vt100_debug/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_tools/vt100_debug/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c6036d45959febc739e287a3a7b631259d4ee7c1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/_tools/vt100_debug/main.go
@@ -0,0 +1,47 @@
+// +build !windows
+
+package main
+
+import (
+ "fmt"
+ "syscall"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/term"
+)
+
+func main() {
+ if err := term.SetRaw(syscall.Stdin); err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer term.Restore()
+
+ bufCh := make(chan []byte, 128)
+ go readBuffer(bufCh)
+ fmt.Print("> ")
+
+ for {
+ b := <-bufCh
+ if key := prompt.GetKey(b); key == prompt.NotDefined {
+ fmt.Printf("Key '%s' data:'%#v'\n", string(b), b)
+ } else {
+ if key == prompt.ControlC {
+ fmt.Println("exit.")
+ return
+ }
+ fmt.Printf("Key '%s' data:'%#v'\n", key, b)
+ }
+ fmt.Print("> ")
+ }
+}
+
+func readBuffer(bufCh chan []byte) {
+ buf := make([]byte, 1024)
+
+ for {
+ if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
+ bufCh <- buf[:n]
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/buffer.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..46efbbba8bfb75f4a064c83368b781d1d6dbbb29
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/buffer.go
@@ -0,0 +1,191 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Buffer emulates the console buffer.
+type Buffer struct {
+ workingLines []string // The working lines. Similar to history
+ workingIndex int
+ cursorPosition int
+ cacheDocument *Document
+ preferredColumn int // Remember the original column for the next up/down movement.
+ lastKeyStroke Key
+}
+
+// Text returns string of the current line.
+func (b *Buffer) Text() string {
+ return b.workingLines[b.workingIndex]
+}
+
+// Document method to return document instance from the current text and cursor position.
+func (b *Buffer) Document() (d *Document) {
+ if b.cacheDocument == nil ||
+ b.cacheDocument.Text != b.Text() ||
+ b.cacheDocument.cursorPosition != b.cursorPosition {
+ b.cacheDocument = &Document{
+ Text: b.Text(),
+ cursorPosition: b.cursorPosition,
+ }
+ }
+ b.cacheDocument.lastKey = b.lastKeyStroke
+ return b.cacheDocument
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (b *Buffer) DisplayCursorPosition() int {
+ return b.Document().DisplayCursorPosition()
+}
+
+// InsertText insert string from current line.
+func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
+ or := []rune(b.Text())
+ oc := b.cursorPosition
+
+ if overwrite {
+ overwritten := string(or[oc : oc+len(v)])
+ if strings.Contains(overwritten, "\n") {
+ i := strings.IndexAny(overwritten, "\n")
+ overwritten = overwritten[:i]
+ }
+ b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):]))
+ } else {
+ b.setText(string(or[:oc]) + v + string(or[oc:]))
+ }
+
+ if moveCursor {
+ b.cursorPosition += len([]rune(v))
+ }
+}
+
+// SetText method to set text and update cursorPosition.
+// (When doing this, make sure that the cursor_position is valid for this text.
+// text/cursor_position should be consistent at any time, otherwise set a Document instead.)
+func (b *Buffer) setText(v string) {
+ debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position")
+ b.workingLines[b.workingIndex] = v
+}
+
+// Set cursor position. Return whether it changed.
+func (b *Buffer) setCursorPosition(p int) {
+ if p > 0 {
+ b.cursorPosition = p
+ } else {
+ b.cursorPosition = 0
+ }
+}
+
+func (b *Buffer) setDocument(d *Document) {
+ b.cacheDocument = d
+ b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length.
+ b.setText(d.Text)
+}
+
+// CursorLeft move to left on the current line.
+func (b *Buffer) CursorLeft(count int) {
+ l := b.Document().GetCursorLeftPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorRight move to right on the current line.
+func (b *Buffer) CursorRight(count int) {
+ l := b.Document().GetCursorRightPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorUp move cursor to the previous line.
+// (for multi-line edit).
+func (b *Buffer) CursorUp(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorUpPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// CursorDown move cursor to the next line.
+// (for multi-line edit).
+func (b *Buffer) CursorDown(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorDownPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text.
+func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) {
+ debug.Assert(count >= 0, "count should be positive")
+ r := []rune(b.Text())
+
+ if b.cursorPosition > 0 {
+ start := b.cursorPosition - count
+ if start < 0 {
+ start = 0
+ }
+ deleted = string(r[start:b.cursorPosition])
+ b.setDocument(&Document{
+ Text: string(r[:start]) + string(r[b.cursorPosition:]),
+ cursorPosition: b.cursorPosition - len([]rune(deleted)),
+ })
+ }
+ return
+}
+
+// NewLine means CR.
+func (b *Buffer) NewLine(copyMargin bool) {
+ if copyMargin {
+ b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true)
+ } else {
+ b.InsertText("\n", false, true)
+ }
+}
+
+// Delete specified number of characters and Return the deleted text.
+func (b *Buffer) Delete(count int) (deleted string) {
+ r := []rune(b.Text())
+ if b.cursorPosition < len(r) {
+ deleted = b.Document().TextAfterCursor()[:count]
+ b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):]))
+ }
+ return
+}
+
+// JoinNextLine joins the next line to the current one by deleting the line ending after the current line.
+func (b *Buffer) JoinNextLine(separator string) {
+ if !b.Document().OnLastLine() {
+ b.cursorPosition += b.Document().GetEndOfLinePosition()
+ b.Delete(1)
+ // Remove spaces
+ b.setText(b.Document().TextBeforeCursor() + separator + strings.TrimLeft(b.Document().TextAfterCursor(), " "))
+ }
+}
+
+// SwapCharactersBeforeCursor swaps the last two characters before the cursor.
+func (b *Buffer) SwapCharactersBeforeCursor() {
+ if b.cursorPosition >= 2 {
+ x := b.Text()[b.cursorPosition-2 : b.cursorPosition-1]
+ y := b.Text()[b.cursorPosition-1 : b.cursorPosition]
+ b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:])
+ }
+}
+
+// NewBuffer is constructor of Buffer struct.
+func NewBuffer() (b *Buffer) {
+ b = &Buffer{
+ workingLines: []string{""},
+ workingIndex: 0,
+ preferredColumn: -1, // -1 means nil
+ }
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/completer/file.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/completer/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..59f2d8dec84214ccaa6e345a11ed51aa61a08199
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/completer/file.go
@@ -0,0 +1,90 @@
+package completer
+
+import (
+ "io/ioutil"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+var (
+ // FilePathCompletionSeparator holds separate characters.
+ FilePathCompletionSeparator = string([]byte{' ', os.PathSeparator})
+)
+
+// FilePathCompleter is a completer for your local file system.
+// Please caution that you need to set OptionCompletionWordSeparator(completer.FilePathCompletionSeparator)
+// when you use this completer.
+type FilePathCompleter struct {
+ Filter func(fi os.FileInfo) bool
+ IgnoreCase bool
+ fileListCache map[string][]prompt.Suggest
+}
+
+func cleanFilePath(path string) (dir, base string, err error) {
+ if path == "" {
+ return ".", "", nil
+ }
+
+ var endsWithSeparator bool
+ if len(path) >= 1 && path[len(path)-1] == os.PathSeparator {
+ endsWithSeparator = true
+ }
+
+ if runtime.GOOS != "windows" && len(path) >= 2 && path[0:2] == "~/" {
+ me, err := user.Current()
+ if err != nil {
+ return "", "", err
+ }
+ path = filepath.Join(me.HomeDir, path[1:])
+ }
+ path = filepath.Clean(os.ExpandEnv(path))
+ dir = filepath.Dir(path)
+ base = filepath.Base(path)
+
+ if endsWithSeparator {
+ dir = path + string(os.PathSeparator) // Append slash(in POSIX) if path ends with slash.
+ base = "" // Set empty string if path ends with separator.
+ }
+ return dir, base, nil
+}
+
+// Complete returns suggestions from your local file system.
+func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest {
+ if c.fileListCache == nil {
+ c.fileListCache = make(map[string][]prompt.Suggest, 4)
+ }
+
+ path := d.GetWordBeforeCursor()
+ dir, base, err := cleanFilePath(path)
+ if err != nil {
+ debug.Log("completer: cannot get current user:" + err.Error())
+ return nil
+ }
+
+ if cached, ok := c.fileListCache[dir]; ok {
+ return prompt.FilterHasPrefix(cached, base, c.IgnoreCase)
+ }
+
+ files, err := ioutil.ReadDir(dir)
+ if err != nil && os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ debug.Log("completer: cannot read directory items:" + err.Error())
+ return nil
+ }
+
+ suggests := make([]prompt.Suggest, 0, len(files))
+ for _, f := range files {
+ if c.Filter != nil && !c.Filter(f) {
+ continue
+ }
+ suggests = append(suggests, prompt.Suggest{Text: f.Name()})
+ }
+ c.fileListCache[dir] = suggests
+ return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/completion.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/completion.go
new file mode 100644
index 0000000000000000000000000000000000000000..57e82eefc0f50e9561214704e770a2ad313a3659
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/completion.go
@@ -0,0 +1,190 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+const (
+ shortenSuffix = "..."
+ leftPrefix = " "
+ leftSuffix = " "
+ rightPrefix = " "
+ rightSuffix = " "
+)
+
+var (
+ leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix)
+ rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix)
+ completionMargin = leftMargin + rightMargin
+)
+
+// Suggest is printed when completing.
+type Suggest struct {
+ Text string
+ Description string
+}
+
+// CompletionManager manages which suggestion is now selected.
+type CompletionManager struct {
+ selected int // -1 means nothing one is selected.
+ tmp []Suggest
+ max uint16
+ completer Completer
+
+ verticalScroll int
+ wordSeparator string
+ showAtStart bool
+}
+
+// GetSelectedSuggestion returns the selected item.
+func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) {
+ if c.selected == -1 {
+ return Suggest{}, false
+ } else if c.selected < -1 {
+ debug.Assert(false, "must not reach here")
+ c.selected = -1
+ return Suggest{}, false
+ }
+ return c.tmp[c.selected], true
+}
+
+// GetSuggestions returns the list of suggestion.
+func (c *CompletionManager) GetSuggestions() []Suggest {
+ return c.tmp
+}
+
+// Reset to select nothing.
+func (c *CompletionManager) Reset() {
+ c.selected = -1
+ c.verticalScroll = 0
+ c.Update(*NewDocument())
+}
+
+// Update to update the suggestions.
+func (c *CompletionManager) Update(in Document) {
+ c.tmp = c.completer(in)
+}
+
+// Previous to select the previous suggestion item.
+func (c *CompletionManager) Previous() {
+ if c.verticalScroll == c.selected && c.selected > 0 {
+ c.verticalScroll--
+ }
+ c.selected--
+ c.update()
+}
+
+// Next to select the next suggestion item.
+func (c *CompletionManager) Next() {
+ if c.verticalScroll+int(c.max)-1 == c.selected {
+ c.verticalScroll++
+ }
+ c.selected++
+ c.update()
+}
+
+// Completing returns whether the CompletionManager selects something one.
+func (c *CompletionManager) Completing() bool {
+ return c.selected != -1
+}
+
+func (c *CompletionManager) update() {
+ max := int(c.max)
+ if len(c.tmp) < max {
+ max = len(c.tmp)
+ }
+
+ if c.selected >= len(c.tmp) {
+ c.Reset()
+ } else if c.selected < -1 {
+ c.selected = len(c.tmp) - 1
+ c.verticalScroll = len(c.tmp) - max
+ }
+}
+
+func deleteBreakLineCharacters(s string) string {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, "\r", "", -1)
+ return s
+}
+
+func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) {
+ l := len(o)
+ n := make([]string, l)
+
+ lenPrefix := runewidth.StringWidth(prefix)
+ lenSuffix := runewidth.StringWidth(suffix)
+ lenShorten := runewidth.StringWidth(shortenSuffix)
+ min := lenPrefix + lenSuffix + lenShorten
+ for i := 0; i < l; i++ {
+ o[i] = deleteBreakLineCharacters(o[i])
+
+ w := runewidth.StringWidth(o[i])
+ if width < w {
+ width = w
+ }
+ }
+
+ if width == 0 {
+ return n, 0
+ }
+ if min >= max {
+ return n, 0
+ }
+ if lenPrefix+width+lenSuffix > max {
+ width = max - lenPrefix - lenSuffix
+ }
+
+ for i := 0; i < l; i++ {
+ x := runewidth.StringWidth(o[i])
+ if x <= width {
+ spaces := strings.Repeat(" ", width-x)
+ n[i] = prefix + o[i] + spaces + suffix
+ } else if x > width {
+ x := runewidth.Truncate(o[i], width, shortenSuffix)
+ // When calling runewidth.Truncate("您好xxx您好xxx", 11, "...") returns "您好xxx..."
+ // But the length of this result is 10. So we need fill right using runewidth.FillRight.
+ n[i] = prefix + runewidth.FillRight(x, width) + suffix
+ }
+ }
+ return n, lenPrefix + width + lenSuffix
+}
+
+func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) {
+ num := len(suggests)
+ new = make([]Suggest, num)
+
+ left := make([]string, num)
+ for i := 0; i < num; i++ {
+ left[i] = suggests[i].Text
+ }
+ right := make([]string, num)
+ for i := 0; i < num; i++ {
+ right[i] = suggests[i].Description
+ }
+
+ left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix)
+ if leftWidth == 0 {
+ return []Suggest{}, 0
+ }
+ right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix)
+
+ for i := 0; i < num; i++ {
+ new[i] = Suggest{Text: left[i], Description: right[i]}
+ }
+ return new, leftWidth + rightWidth
+}
+
+// NewCompletionManager returns initialized CompletionManager object.
+func NewCompletionManager(completer Completer, max uint16) *CompletionManager {
+ return &CompletionManager{
+ selected: -1,
+ max: max,
+ completer: completer,
+
+ verticalScroll: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/document.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/document.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d0b92cb05dc637d477a72b9b2d7abec4f0abf4a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/document.go
@@ -0,0 +1,441 @@
+package prompt
+
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+ istrings "github.com/c-bata/go-prompt/internal/strings"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Document has text displayed in terminal and cursor position.
+type Document struct {
+ Text string
+ // This represents a index in a rune array of Document.Text.
+ // So if Document is "日本(cursor)語", cursorPosition is 2.
+ // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+ cursorPosition int
+ lastKey Key
+}
+
+// NewDocument return the new empty document.
+func NewDocument() *Document {
+ return &Document{
+ Text: "",
+ cursorPosition: 0,
+ }
+}
+
+// LastKeyStroke return the last key pressed in this document.
+func (d *Document) LastKeyStroke() Key {
+ return d.lastKey
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (d *Document) DisplayCursorPosition() int {
+ var position int
+ runes := []rune(d.Text)[:d.cursorPosition]
+ for i := range runes {
+ position += runewidth.RuneWidth(runes[i])
+ }
+ return position
+}
+
+// GetCharRelativeToCursor return character relative to cursor position, or empty string
+func (d *Document) GetCharRelativeToCursor(offset int) (r rune) {
+ s := d.Text
+ cnt := 0
+
+ for len(s) > 0 {
+ cnt++
+ r, size := utf8.DecodeRuneInString(s)
+ if cnt == d.cursorPosition+offset {
+ return r
+ }
+ s = s[size:]
+ }
+ return 0
+}
+
+// TextBeforeCursor returns the text before the cursor.
+func (d *Document) TextBeforeCursor() string {
+ r := []rune(d.Text)
+ return string(r[:d.cursorPosition])
+}
+
+// TextAfterCursor returns the text after the cursor.
+func (d *Document) TextAfterCursor() string {
+ r := []rune(d.Text)
+ return string(r[d.cursorPosition:])
+}
+
+// GetWordBeforeCursor returns the word before the cursor.
+// If we have whitespace before the cursor this returns an empty string.
+func (d *Document) GetWordBeforeCursor() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWord():]
+}
+
+// GetWordAfterCursor returns the word after the cursor.
+// If we have whitespace after the cursor this returns an empty string.
+func (d *Document) GetWordAfterCursor() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWord()]
+}
+
+// GetWordBeforeCursorWithSpace returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorWithSpace() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordWithSpace():]
+}
+
+// GetWordAfterCursorWithSpace returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorWithSpace() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordWithSpace()]
+}
+
+// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
+func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparator(sep):]
+}
+
+// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
+func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparator(sep)]
+}
+
+// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):]
+}
+
+// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)]
+}
+
+// FindStartOfPreviousWord returns an index relative to the cursor position
+// pointing to the start of the previous word. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWord() int {
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexByte(x, ' ')
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindStartOfPreviousWordWithSpace() int {
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotByte(x, ' ')
+ if end == -1 {
+ return 0
+ }
+
+ start := strings.LastIndexByte(x[:end], ' ')
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWord()
+ }
+
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexAny(x, sep)
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWordWithSpace()
+ }
+
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotAny(x, sep)
+ if end == -1 {
+ return 0
+ }
+ start := strings.LastIndexAny(x[:end], sep)
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindEndOfCurrentWord returns an index relative to the cursor position.
+// pointing to the end of the current word. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWord() int {
+ x := d.TextAfterCursor()
+ i := strings.IndexByte(x, ' ')
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindEndOfCurrentWordWithSpace() int {
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotByte(x, ' ')
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexByte(x[start:], ' ')
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWord()
+ }
+
+ x := d.TextAfterCursor()
+ i := strings.IndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWordWithSpace()
+ }
+
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotAny(x, sep)
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexAny(x[start:], sep)
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// CurrentLineBeforeCursor returns the text from the start of the line until the cursor.
+func (d *Document) CurrentLineBeforeCursor() string {
+ s := strings.Split(d.TextBeforeCursor(), "\n")
+ return s[len(s)-1]
+}
+
+// CurrentLineAfterCursor returns the text from the cursor until the end of the line.
+func (d *Document) CurrentLineAfterCursor() string {
+ return strings.Split(d.TextAfterCursor(), "\n")[0]
+}
+
+// CurrentLine return the text on the line where the cursor is. (when the input
+// consists of just one line, it equals `text`.
+func (d *Document) CurrentLine() string {
+ return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor()
+}
+
+// Array pointing to the start indexes of all the lines.
+func (d *Document) lineStartIndexes() []int {
+ // TODO: Cache, because this is often reused.
+ // (If it is used, it's often used many times.
+ // And this has to be fast for editing big documents!)
+ lc := d.LineCount()
+ lengths := make([]int, lc)
+ for i, l := range d.Lines() {
+ lengths[i] = len(l)
+ }
+
+ // Calculate cumulative sums.
+ indexes := make([]int, lc+1)
+ indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189
+ pos := 0
+ for i, l := range lengths {
+ pos += l + 1
+ indexes[i+1] = pos
+ }
+ if lc > 1 {
+ // Pop the last item. (This is not a new line.)
+ indexes = indexes[:lc]
+ }
+ return indexes
+}
+
+// For the index of a character at a certain line, calculate the index of
+// the first character on that line.
+func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) {
+ indexes := d.lineStartIndexes()
+ pos = bisect.Right(indexes, index) - 1
+ lineStartIndex = indexes[pos]
+ return
+}
+
+// CursorPositionRow returns the current row. (0-based.)
+func (d *Document) CursorPositionRow() (row int) {
+ row, _ = d.findLineStartIndex(d.cursorPosition)
+ return
+}
+
+// CursorPositionCol returns the current column. (0-based.)
+func (d *Document) CursorPositionCol() (col int) {
+ // Don't use self.text_before_cursor to calculate this. Creating substrings
+ // and splitting is too expensive for getting the cursor position.
+ _, index := d.findLineStartIndex(d.cursorPosition)
+ col = d.cursorPosition - index
+ return
+}
+
+// GetCursorLeftPosition returns the relative position for cursor left.
+func (d *Document) GetCursorLeftPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorRightPosition(-count)
+ }
+ if d.CursorPositionCol() > count {
+ return -count
+ }
+ return -d.CursorPositionCol()
+}
+
+// GetCursorRightPosition returns relative position for cursor right.
+func (d *Document) GetCursorRightPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorLeftPosition(-count)
+ }
+ if len(d.CurrentLineAfterCursor()) > count {
+ return count
+ }
+ return len(d.CurrentLineAfterCursor())
+}
+
+// GetCursorUpPosition return the relative cursor position (character index) where we would be
+// if the user pressed the arrow-up button.
+func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int {
+ var col int
+ if -1 == preferredColumn { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+
+ row := d.CursorPositionRow() - count
+ if 0 < row {
+ row = 0
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// GetCursorDownPosition return the relative cursor position (character index) where we would be if the
+// user pressed the arrow-down button.
+func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+ row := d.CursorPositionRow() + count
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// Lines returns the array of all the lines.
+func (d *Document) Lines() []string {
+ // TODO: Cache, because this one is reused very often.
+ return strings.Split(d.Text, "\n")
+}
+
+// LineCount return the number of lines in this document. If the document ends
+// with a trailing \n, that counts as the beginning of a new line.
+func (d *Document) LineCount() int {
+ return len(d.Lines())
+}
+
+// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple.
+// (0-based. Returns (0, 0) for index=0.)
+func (d *Document) TranslateIndexToPosition(index int) (row int, col int) {
+ row, rowIndex := d.findLineStartIndex(index)
+ col = index - rowIndex
+ return
+}
+
+// TranslateRowColToIndex given a (row, col), return the corresponding index.
+// (Row and col params are 0-based.)
+func (d *Document) TranslateRowColToIndex(row int, column int) (index int) {
+ indexes := d.lineStartIndexes()
+ if row < 0 {
+ row = 0
+ } else if row > len(indexes) {
+ row = len(indexes) - 1
+ }
+ index = indexes[row]
+ line := d.Lines()[row]
+
+ // python) result += max(0, min(col, len(line)))
+ if column > 0 || len(line) > 0 {
+ if column > len(line) {
+ index += len(line)
+ } else {
+ index += column
+ }
+ }
+
+ // Keep in range. (len(self.text) is included, because the cursor can be
+ // right after the end of the text as well.)
+ // python) result = max(0, min(result, len(self.text)))
+ if index > len(d.Text) {
+ index = len(d.Text)
+ }
+ if index < 0 {
+ index = 0
+ }
+ return index
+}
+
+// OnLastLine returns true when we are at the last line.
+func (d *Document) OnLastLine() bool {
+ return d.CursorPositionRow() == (d.LineCount() - 1)
+}
+
+// GetEndOfLinePosition returns relative position for the end of this line.
+func (d *Document) GetEndOfLinePosition() int {
+ return len([]rune(d.CurrentLineAfterCursor()))
+}
+
+func (d *Document) leadingWhitespaceInCurrentLine() (margin string) {
+ trimmed := strings.TrimSpace(d.CurrentLine())
+ margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)]
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/emacs.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/emacs.go
new file mode 100644
index 0000000000000000000000000000000000000000..632f96321f2577cdb7e8cffe639f1518a65d5e0f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/emacs.go
@@ -0,0 +1,120 @@
+package prompt
+
+import "github.com/c-bata/go-prompt/internal/debug"
+
+/*
+
+========
+PROGRESS
+========
+
+Moving the cursor
+-----------------
+
+* [x] Ctrl + a Go to the beginning of the line (Home)
+* [x] Ctrl + e Go to the End of the line (End)
+* [x] Ctrl + p Previous command (Up arrow)
+* [x] Ctrl + n Next command (Down arrow)
+* [x] Ctrl + f Forward one character
+* [x] Ctrl + b Backward one character
+* [x] Ctrl + xx Toggle between the start of line and current cursor position
+
+Editing
+-------
+
+* [x] Ctrl + L Clear the Screen, similar to the clear command
+* [x] Ctrl + d Delete character under the cursor
+* [x] Ctrl + h Delete character before the cursor (Backspace)
+
+* [x] Ctrl + w Cut the Word before the cursor to the clipboard.
+* [x] Ctrl + k Cut the Line after the cursor to the clipboard.
+* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard.
+
+* [ ] Ctrl + t Swap the last two characters before the cursor (typo).
+* [ ] Esc + t Swap the last two words before the cursor.
+
+* [ ] ctrl + y Paste the last thing to be cut (yank)
+* [ ] ctrl + _ Undo
+
+*/
+
+var emacsKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: ControlE,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+ },
+ },
+ // Go to the beginning of the line
+ {
+ Key: ControlA,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+ },
+ },
+ // Cut the Line after the cursor
+ {
+ Key: ControlK,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.Delete(len(x))
+ },
+ },
+ // Cut/delete the Line before the cursor
+ {
+ Key: ControlU,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.DeleteBeforeCursor(len(x))
+ },
+ },
+ // Delete character under the cursor
+ {
+ Key: ControlD,
+ Fn: func(buf *Buffer) {
+ if buf.Text() != "" {
+ buf.Delete(1)
+ }
+ },
+ },
+ // Backspace
+ {
+ Key: ControlH,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+ },
+ },
+ // Right allow: Forward one character
+ {
+ Key: ControlF,
+ Fn: func(buf *Buffer) {
+ buf.CursorRight(1)
+ },
+ },
+ // Left allow: Backward one character
+ {
+ Key: ControlB,
+ Fn: func(buf *Buffer) {
+ buf.CursorLeft(1)
+ },
+ },
+ // Cut the Word before the cursor.
+ {
+ Key: ControlW,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace())))
+ },
+ },
+ // Clear the Screen, similar to the clear command
+ {
+ Key: ControlL,
+ Fn: func(buf *Buffer) {
+ consoleWriter.EraseScreen()
+ consoleWriter.CursorGoTo(0, 0)
+ debug.AssertNoError(consoleWriter.Flush())
+ },
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/filter.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/filter.go
new file mode 100644
index 0000000000000000000000000000000000000000..61c17ed7f436a069563f520512bd25e4d81af0de
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/filter.go
@@ -0,0 +1,71 @@
+package prompt
+
+import "strings"
+
+// Filter is the type to filter the prompt.Suggestion array.
+type Filter func([]Suggest, string, bool) []Suggest
+
+// FilterHasPrefix checks whether the string completions.Text begins with sub.
+func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
+}
+
+// FilterHasSuffix checks whether the completion.Text ends with sub.
+func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
+}
+
+// FilterContains checks whether the completion.Text contains sub.
+func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
+}
+
+// FilterFuzzy checks whether the completion.Text fuzzy matches sub.
+// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
+// would match, for example, "Good food is gone"
+// ^ ^ ^
+func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
+}
+
+func fuzzyMatch(s, sub string) bool {
+ sChars := []rune(s)
+ sIdx := 0
+
+ // https://staticcheck.io/docs/checks#S1029
+ for _, c := range sub {
+ found := false
+ for ; sIdx < len(sChars); sIdx++ {
+ if sChars[sIdx] == c {
+ found = true
+ sIdx++
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
+
+func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
+ if sub == "" {
+ return suggestions
+ }
+ if ignoreCase {
+ sub = strings.ToUpper(sub)
+ }
+
+ ret := make([]Suggest, 0, len(suggestions))
+ for i := range suggestions {
+ c := suggestions[i].Text
+ if ignoreCase {
+ c = strings.ToUpper(c)
+ }
+ if function(c, sub) {
+ ret = append(ret, suggestions[i])
+ }
+ }
+ return ret
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/go.mod b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..30bc6d39a39c328341ca7153d3391352be5baa63
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/go.mod
@@ -0,0 +1,11 @@
+module github.com/c-bata/go-prompt
+
+go 1.14
+
+require (
+ github.com/mattn/go-colorable v0.1.7
+ github.com/mattn/go-runewidth v0.0.9
+ github.com/mattn/go-tty v0.0.3
+ github.com/pkg/term v1.2.0-beta.2
+ golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/go.sum b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..768bf93619a68e1b334c13e7b93ec84fa465598e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/go.sum
@@ -0,0 +1,23 @@
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/history.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/history.go
new file mode 100644
index 0000000000000000000000000000000000000000..e75c64592d82142bf4826ceb8c613ac72ca24d9c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/history.go
@@ -0,0 +1,61 @@
+package prompt
+
+// History stores the texts that are entered.
+type History struct {
+ histories []string
+ tmp []string
+ selected int
+}
+
+// Add to add text in history.
+func (h *History) Add(input string) {
+ h.histories = append(h.histories, input)
+ h.Clear()
+}
+
+// Clear to clear the history.
+func (h *History) Clear() {
+ h.tmp = make([]string, len(h.histories))
+ for i := range h.histories {
+ h.tmp[i] = h.histories[i]
+ }
+ h.tmp = append(h.tmp, "")
+ h.selected = len(h.tmp) - 1
+}
+
+// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
+ if len(h.tmp) == 1 || h.selected == 0 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected--
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
+ if h.selected >= len(h.tmp)-1 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected++
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// NewHistory returns new history object.
+func NewHistory() *History {
+ return &History{
+ histories: []string{},
+ tmp: []string{""},
+ selected: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/input.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/input.go
new file mode 100644
index 0000000000000000000000000000000000000000..307e747190c2b27bf888b379644fc4f3cdd489a2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/input.go
@@ -0,0 +1,169 @@
+package prompt
+
+import "bytes"
+
+// WinSize represents the width and height of terminal.
+type WinSize struct {
+ Row uint16
+ Col uint16
+}
+
+// ConsoleParser is an interface to abstract input layer.
+type ConsoleParser interface {
+ // Setup should be called before starting input
+ Setup() error
+ // TearDown should be called after stopping input
+ TearDown() error
+ // GetWinSize returns WinSize object to represent width and height of terminal.
+ GetWinSize() *WinSize
+ // Read returns byte array.
+ Read() ([]byte, error)
+}
+
+// GetKey returns Key correspond to input byte codes.
+func GetKey(b []byte) Key {
+ for _, k := range ASCIISequences {
+ if bytes.Equal(k.ASCIICode, b) {
+ return k.Key
+ }
+ }
+ return NotDefined
+}
+
+// ASCIISequences holds mappings of the key and byte array.
+var ASCIISequences = []*ASCIICode{
+ {Key: Escape, ASCIICode: []byte{0x1b}},
+
+ {Key: ControlSpace, ASCIICode: []byte{0x00}},
+ {Key: ControlA, ASCIICode: []byte{0x1}},
+ {Key: ControlB, ASCIICode: []byte{0x2}},
+ {Key: ControlC, ASCIICode: []byte{0x3}},
+ {Key: ControlD, ASCIICode: []byte{0x4}},
+ {Key: ControlE, ASCIICode: []byte{0x5}},
+ {Key: ControlF, ASCIICode: []byte{0x6}},
+ {Key: ControlG, ASCIICode: []byte{0x7}},
+ {Key: ControlH, ASCIICode: []byte{0x8}},
+ //{Key: ControlI, ASCIICode: []byte{0x9}},
+ //{Key: ControlJ, ASCIICode: []byte{0xa}},
+ {Key: ControlK, ASCIICode: []byte{0xb}},
+ {Key: ControlL, ASCIICode: []byte{0xc}},
+ {Key: ControlM, ASCIICode: []byte{0xd}},
+ {Key: ControlN, ASCIICode: []byte{0xe}},
+ {Key: ControlO, ASCIICode: []byte{0xf}},
+ {Key: ControlP, ASCIICode: []byte{0x10}},
+ {Key: ControlQ, ASCIICode: []byte{0x11}},
+ {Key: ControlR, ASCIICode: []byte{0x12}},
+ {Key: ControlS, ASCIICode: []byte{0x13}},
+ {Key: ControlT, ASCIICode: []byte{0x14}},
+ {Key: ControlU, ASCIICode: []byte{0x15}},
+ {Key: ControlV, ASCIICode: []byte{0x16}},
+ {Key: ControlW, ASCIICode: []byte{0x17}},
+ {Key: ControlX, ASCIICode: []byte{0x18}},
+ {Key: ControlY, ASCIICode: []byte{0x19}},
+ {Key: ControlZ, ASCIICode: []byte{0x1a}},
+
+ {Key: ControlBackslash, ASCIICode: []byte{0x1c}},
+ {Key: ControlSquareClose, ASCIICode: []byte{0x1d}},
+ {Key: ControlCircumflex, ASCIICode: []byte{0x1e}},
+ {Key: ControlUnderscore, ASCIICode: []byte{0x1f}},
+ {Key: Backspace, ASCIICode: []byte{0x7f}},
+
+ {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}},
+
+ {Key: Enter, ASCIICode: []byte{0xa}},
+ {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}},
+ {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+ {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}},
+ {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}},
+ {Key: Tab, ASCIICode: []byte{0x9}},
+ {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}},
+ {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}},
+ {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}},
+ {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}},
+ {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode
+
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}},
+ {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}},
+ {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}},
+ {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}},
+ {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}},
+ {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}},
+ {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}},
+ {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}},
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}},
+ {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}},
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+
+ // Xterm
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}},
+ // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}},
+ {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}},
+ {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}},
+ {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}},
+ {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}},
+
+ {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}},
+ {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}},
+ {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}},
+ {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}},
+
+ // Tmux sends following keystrokes when control+arrow is pressed, but for
+ // Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ // it a normal arrow press, because that's more important.
+ {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}},
+
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt
+
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/input_posix.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/input_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f10430318be0e797c841eba8e08ab1cf5277be27
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/input_posix.go
@@ -0,0 +1,77 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/term"
+ "golang.org/x/sys/unix"
+)
+
+const maxReadBytes = 1024
+
+// PosixParser is a ConsoleParser implementation for POSIX environment.
+type PosixParser struct {
+ fd int
+ origTermios syscall.Termios
+}
+
+// Setup should be called before starting input
+func (t *PosixParser) Setup() error {
+ // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
+ if err := syscall.SetNonblock(t.fd, true); err != nil {
+ return err
+ }
+ if err := term.SetRaw(t.fd); err != nil {
+ return err
+ }
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (t *PosixParser) TearDown() error {
+ if err := syscall.SetNonblock(t.fd, false); err != nil {
+ return err
+ }
+ if err := term.Restore(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Read returns byte array.
+func (t *PosixParser) Read() ([]byte, error) {
+ buf := make([]byte, maxReadBytes)
+ n, err := syscall.Read(t.fd, buf)
+ if err != nil {
+ return []byte{}, err
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (t *PosixParser) GetWinSize() *WinSize {
+ ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: ws.Row,
+ Col: ws.Col,
+ }
+}
+
+var _ ConsoleParser = &PosixParser{}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *PosixParser {
+ in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ return &PosixParser{
+ fd: in,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/input_windows.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/input_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..11b7679d4c4bc8b924a5b6c863ca1f6d6880570d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/input_windows.go
@@ -0,0 +1,83 @@
+// +build windows
+
+package prompt
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf8"
+ "unsafe"
+
+ tty "github.com/mattn/go-tty"
+)
+
+const maxReadBytes = 1024
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
+
+// WindowsParser is a ConsoleParser implementation for Win32 console.
+type WindowsParser struct {
+ tty *tty.TTY
+}
+
+// Setup should be called before starting input
+func (p *WindowsParser) Setup() error {
+ t, err := tty.Open()
+ if err != nil {
+ return err
+ }
+ p.tty = t
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (p *WindowsParser) TearDown() error {
+ return p.tty.Close()
+}
+
+// Read returns byte array.
+func (p *WindowsParser) Read() ([]byte, error) {
+ var ev uint32
+ r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
+ if r0 == 0 {
+ return nil, err
+ }
+ if ev == 0 {
+ return nil, errors.New("EAGAIN")
+ }
+
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, maxReadBytes)
+ n := utf8.EncodeRune(buf[:], r)
+ for p.tty.Buffered() && n < maxReadBytes {
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ break
+ }
+ n += utf8.EncodeRune(buf[n:], r)
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (p *WindowsParser) GetWinSize() *WinSize {
+ w, h, err := p.tty.Size()
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: uint16(h),
+ Col: uint16(w),
+ }
+}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *WindowsParser {
+ return &WindowsParser{}
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/bisect/bisect.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/bisect/bisect.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe162fa8c4873302e25702081b629a445d43415
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/bisect/bisect.go
@@ -0,0 +1,15 @@
+package bisect
+
+import "sort"
+
+// Right to locate the insertion point for v in a to maintain sorted order.
+func Right(a []int, v int) int {
+ return bisectRightRange(a, v, 0, len(a))
+}
+
+func bisectRightRange(a []int, v int, lo, hi int) int {
+ s := a[lo:hi]
+ return sort.Search(len(s), func(i int) bool {
+ return s[i] > v
+ })
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/debug/assert.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/debug/assert.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f648ac93c44e1e021cdf581a68f03b548534d9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/debug/assert.go
@@ -0,0 +1,55 @@
+package debug
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
+)
+
+var (
+ enableAssert bool
+)
+
+func init() {
+ if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
+ enableAssert = true
+ }
+}
+
+// Assert ensures expected condition.
+func Assert(cond bool, msg interface{}) {
+ if cond {
+ return
+ }
+ if enableAssert {
+ panic(msg)
+ }
+ writeWithSync(2, "[ASSERT] "+toString(msg))
+}
+
+func toString(v interface{}) string {
+ switch a := v.(type) {
+ case func() string:
+ return a()
+ case string:
+ return a
+ case fmt.Stringer:
+ return a.String()
+ default:
+ return fmt.Sprintf("unexpected type, %t", v)
+ }
+}
+
+// AssertNoError ensures err is nil.
+func AssertNoError(err error) {
+ if err == nil {
+ return
+ }
+ if enableAssert {
+ panic(err)
+ }
+ writeWithSync(2, "[ASSERT] "+err.Error())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/debug/log.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/debug/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..516378627a34ead9063ab7ce6c445b23c77b7cb4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/debug/log.go
@@ -0,0 +1,52 @@
+package debug
+
+import (
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+const (
+ envEnableLog = "GO_PROMPT_ENABLE_LOG"
+ logFileName = "go-prompt.log"
+)
+
+var (
+ logfile *os.File
+ logger *log.Logger
+)
+
+func init() {
+ if e := os.Getenv(envEnableLog); e == "true" || e == "1" {
+ var err error
+ logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
+ if err == nil {
+ logger = log.New(logfile, "", log.Llongfile)
+ return
+ }
+ }
+ logger = log.New(ioutil.Discard, "", log.Llongfile)
+}
+
+// Teardown to close logfile
+func Teardown() {
+ if logfile == nil {
+ return
+ }
+ _ = logfile.Close()
+}
+
+func writeWithSync(calldepth int, msg string) {
+ calldepth++
+ if logfile == nil {
+ return
+ }
+ _ = logger.Output(calldepth, msg)
+ _ = logfile.Sync() // immediately write msg
+}
+
+// Log to output message
+func Log(msg string) {
+ calldepth := 2
+ writeWithSync(calldepth, msg)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/strings/strings.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/strings/strings.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7d1886ae03a7d541c66dffca921e2d040e6d5eb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/strings/strings.go
@@ -0,0 +1,102 @@
+package strings
+
+import "unicode/utf8"
+
+// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior.
+func IndexNotByte(s string, c byte) int {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior.
+func LastIndexNotByte(s string, c byte) int {
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+type asciiSet [8]uint32
+
+func (as *asciiSet) notContains(c byte) bool {
+ return (as[c>>5] & (1 << uint(c&31))) == 0
+}
+
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c>>5] |= 1 << uint(c&31)
+ }
+ return as, true
+}
+
+// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior.
+func IndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := 0; i < len(s); i++ {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+
+ LabelFirstLoop:
+ for i, c := range s {
+ for j, m := range chars {
+ if c != m && j == len(chars)-1 {
+ return i
+ } else if c != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior.
+func LastIndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ LabelFirstLoop:
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRuneInString(s[:i])
+ i -= size
+ for j, m := range chars {
+ if r != m && j == len(chars)-1 {
+ return i
+ } else if r != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/term/raw.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/term/raw.go
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3ed8d04023558cf386a98080815d661248b85
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/term/raw.go
@@ -0,0 +1,29 @@
+// +build !windows
+
+package term
+
+import (
+ "syscall"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+// SetRaw put terminal into a raw mode
+func SetRaw(fd int) error {
+ n, err := getOriginalTermios(fd)
+ if err != nil {
+ return err
+ }
+
+ n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK |
+ syscall.ISTRIP | syscall.INLCR | syscall.IGNCR |
+ syscall.ICRNL | syscall.IXON
+ n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL
+ n.Cflag &^= syscall.CSIZE | syscall.PARENB
+ n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters.
+ n.Cc[syscall.VMIN] = 1
+ n.Cc[syscall.VTIME] = 0
+
+ return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n))
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/term/term.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/term/term.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a53c059ae60c0348ec01689babef4b13a2ecd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/internal/term/term.go
@@ -0,0 +1,34 @@
+// +build !windows
+
+package term
+
+import (
+ "sync"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ saveTermios *unix.Termios
+ saveTermiosFD int
+ saveTermiosOnce sync.Once
+)
+
+func getOriginalTermios(fd int) (*unix.Termios, error) {
+ var err error
+ saveTermiosOnce.Do(func() {
+ saveTermiosFD = fd
+ saveTermios, err = termios.Tcgetattr(uintptr(fd))
+ })
+ return saveTermios, err
+}
+
+// Restore terminal's mode.
+func Restore() error {
+ o, err := getOriginalTermios(saveTermiosFD)
+ if err != nil {
+ return err
+ }
+ return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/key.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ba569c2dd20a8ae3b3dd79ff3695bf0b6c1bd09
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/key.go
@@ -0,0 +1,128 @@
+// Code generated by hand; DO NOT EDIT.
+// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment.
+
+package prompt
+
+// Key is the type express the key inserted from user.
+//go:generate stringer -type=Key
+type Key int
+
+// ASCIICode is the type contains Key and it's ascii byte array.
+type ASCIICode struct {
+ Key Key
+ ASCIICode []byte
+}
+
+const (
+ Escape Key = iota
+
+ ControlA
+ ControlB
+ ControlC
+ ControlD
+ ControlE
+ ControlF
+ ControlG
+ ControlH
+ ControlI
+ ControlJ
+ ControlK
+ ControlL
+ ControlM
+ ControlN
+ ControlO
+ ControlP
+ ControlQ
+ ControlR
+ ControlS
+ ControlT
+ ControlU
+ ControlV
+ ControlW
+ ControlX
+ ControlY
+ ControlZ
+
+ ControlSpace
+ ControlBackslash
+ ControlSquareClose
+ ControlCircumflex
+ ControlUnderscore
+ ControlLeft
+ ControlRight
+ ControlUp
+ ControlDown
+
+ Up
+ Down
+ Right
+ Left
+
+ ShiftLeft
+ ShiftUp
+ ShiftDown
+ ShiftRight
+
+ Home
+ End
+ Delete
+ ShiftDelete
+ ControlDelete
+ PageUp
+ PageDown
+ BackTab
+ Insert
+ Backspace
+
+ // Aliases.
+ Tab
+ Enter
+ // Actually Enter equals ControlM, not ControlJ,
+ // However, in prompt_toolkit, we made the mistake of translating
+ // \r into \n during the input, so everyone is now handling the
+ // enter key by binding ControlJ.
+
+ // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere,
+ // because that's future compatible, and will still work when we
+ // stop replacing \r by \n.
+
+ F1
+ F2
+ F3
+ F4
+ F5
+ F6
+ F7
+ F8
+ F9
+ F10
+ F11
+ F12
+ F13
+ F14
+ F15
+ F16
+ F17
+ F18
+ F19
+ F20
+ F21
+ F22
+ F23
+ F24
+
+ // Matches any key.
+ Any
+
+ // Special
+ CPRResponse
+ Vt100MouseEvent
+ WindowsMouseEvent
+ BracketedPaste
+
+ // Key which is ignored. (The key binding for this key should not do anything.)
+ Ignore
+
+ // Key is not defined
+ NotDefined
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/key_bind.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/key_bind.go
new file mode 100644
index 0000000000000000000000000000000000000000..42669e7f942efc4d92f896388daede90b96b55dd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/key_bind.go
@@ -0,0 +1,59 @@
+package prompt
+
+// KeyBindFunc receives buffer and processed it.
+type KeyBindFunc func(*Buffer)
+
+// KeyBind represents which key should do what operation.
+type KeyBind struct {
+ Key Key
+ Fn KeyBindFunc
+}
+
+// ASCIICodeBind represents which []byte should do what operation
+type ASCIICodeBind struct {
+ ASCIICode []byte
+ Fn KeyBindFunc
+}
+
+// KeyBindMode to switch a key binding flexibly.
+type KeyBindMode string
+
+const (
+ // CommonKeyBind is a mode without any keyboard shortcut
+ CommonKeyBind KeyBindMode = "common"
+ // EmacsKeyBind is a mode to use emacs-like keyboard shortcut
+ EmacsKeyBind KeyBindMode = "emacs"
+)
+
+var commonKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: End,
+ Fn: GoLineEnd,
+ },
+ // Go to the beginning of the line
+ {
+ Key: Home,
+ Fn: GoLineBeginning,
+ },
+ // Delete character under the cursor
+ {
+ Key: Delete,
+ Fn: DeleteChar,
+ },
+ // Backspace
+ {
+ Key: Backspace,
+ Fn: DeleteBeforeChar,
+ },
+ // Right allow: Forward one character
+ {
+ Key: Right,
+ Fn: GoRightChar,
+ },
+ // Left allow: Backward one character
+ {
+ Key: Left,
+ Fn: GoLeftChar,
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/key_bind_func.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/key_bind_func.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b2ecdf63179dbfdbcb0d71bfa436bb36d62d230
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/key_bind_func.go
@@ -0,0 +1,48 @@
+package prompt
+
+// GoLineEnd Go to the End of the line
+func GoLineEnd(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+}
+
+// GoLineBeginning Go to the beginning of the line
+func GoLineBeginning(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+}
+
+// DeleteChar Delete character under the cursor
+func DeleteChar(buf *Buffer) {
+ buf.Delete(1)
+}
+
+// DeleteWord Delete word before the cursor
+func DeleteWord(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
+
+// DeleteBeforeChar Go to Backspace
+func DeleteBeforeChar(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+}
+
+// GoRightChar Forward one character
+func GoRightChar(buf *Buffer) {
+ buf.CursorRight(1)
+}
+
+// GoLeftChar Backward one character
+func GoLeftChar(buf *Buffer) {
+ buf.CursorLeft(1)
+}
+
+// GoRightWord Forward one word
+func GoRightWord(buf *Buffer) {
+ buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
+}
+
+// GoLeftWord Backward one word
+func GoLeftWord(buf *Buffer) {
+ buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/key_string.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/key_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..fce6ea31c502b3e763451cb47757ae1b49c32814
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/key_string.go
@@ -0,0 +1,16 @@
+// Code generated by "stringer -type=Key"; DO NOT EDIT.
+
+package prompt
+
+import "strconv"
+
+const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined"
+
+var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607}
+
+func (i Key) String() string {
+ if i < 0 || i >= Key(len(_Key_index)-1) {
+ return "Key(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _Key_name[_Key_index[i]:_Key_index[i+1]]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/option.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/option.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd6806cc1dbccf8c4ddb048080fde615c59088
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/option.go
@@ -0,0 +1,310 @@
+package prompt
+
+// Option is the type to replace default parameters.
+// prompt.New accepts any number of options (this is functional option pattern).
+type Option func(prompt *Prompt) error
+
+// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
+func OptionParser(x ConsoleParser) Option {
+ return func(p *Prompt) error {
+ p.in = x
+ return nil
+ }
+}
+
+// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
+func OptionWriter(x ConsoleWriter) Option {
+ return func(p *Prompt) error {
+ registerConsoleWriter(x)
+ p.renderer.out = x
+ return nil
+ }
+}
+
+// OptionTitle to set title displayed at the header bar of terminal.
+func OptionTitle(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.title = x
+ return nil
+ }
+}
+
+// OptionPrefix to set prefix string.
+func OptionPrefix(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefix = x
+ return nil
+ }
+}
+
+// OptionInitialBufferText to set the initial buffer text
+func OptionInitialBufferText(x string) Option {
+ return func(p *Prompt) error {
+ p.buf.InsertText(x, false, true)
+ return nil
+ }
+}
+
+// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
+func OptionCompletionWordSeparator(x string) Option {
+ return func(p *Prompt) error {
+ p.completion.wordSeparator = x
+ return nil
+ }
+}
+
+// OptionLivePrefix to change the prefix dynamically by callback function
+func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
+ return func(p *Prompt) error {
+ p.renderer.livePrefixCallback = f
+ return nil
+ }
+}
+
+// OptionPrefixTextColor change a text color of prefix string
+func OptionPrefixTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixTextColor = x
+ return nil
+ }
+}
+
+// OptionPrefixBackgroundColor to change a background color of prefix string
+func OptionPrefixBackgroundColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixBGColor = x
+ return nil
+ }
+}
+
+// OptionInputTextColor to change a color of text which is input by user
+func OptionInputTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputTextColor = x
+ return nil
+ }
+}
+
+// OptionInputBGColor to change a color of background which is input by user
+func OptionInputBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputBGColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionTextColor to change a text color which is completed
+func OptionPreviewSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionBGColor to change a background color which is completed
+func OptionPreviewSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionTextColor to change a text color in drop down suggestions.
+func OptionSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionBGColor change a background color in drop down suggestions.
+func OptionSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarThumbColor to change a thumb color on scrollbar.
+func OptionScrollbarThumbColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarThumbColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarBGColor to change a background color of scrollbar.
+func OptionScrollbarBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarBGColor = x
+ return nil
+ }
+}
+
+// OptionMaxSuggestion specify the max number of displayed suggestions.
+func OptionMaxSuggestion(x uint16) Option {
+ return func(p *Prompt) error {
+ p.completion.max = x
+ return nil
+ }
+}
+
+// OptionHistory to set history expressed by string array.
+func OptionHistory(x []string) Option {
+ return func(p *Prompt) error {
+ p.history.histories = x
+ p.history.Clear()
+ return nil
+ }
+}
+
+// OptionSwitchKeyBindMode set a key bind mode.
+func OptionSwitchKeyBindMode(m KeyBindMode) Option {
+ return func(p *Prompt) error {
+ p.keyBindMode = m
+ return nil
+ }
+}
+
+// OptionCompletionOnDown allows for Down arrow key to trigger completion.
+func OptionCompletionOnDown() Option {
+ return func(p *Prompt) error {
+ p.completionOnDown = true
+ return nil
+ }
+}
+
+// SwitchKeyBindMode to set a key bind mode.
+// Deprecated: Please use OptionSwitchKeyBindMode.
+var SwitchKeyBindMode = OptionSwitchKeyBindMode
+
+// OptionAddKeyBind to set a custom key bind.
+func OptionAddKeyBind(b ...KeyBind) Option {
+ return func(p *Prompt) error {
+ p.keyBindings = append(p.keyBindings, b...)
+ return nil
+ }
+}
+
+// OptionAddASCIICodeBind to set a custom key bind.
+func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option {
+ return func(p *Prompt) error {
+ p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...)
+ return nil
+ }
+}
+
+// OptionShowCompletionAtStart to set completion window is open at start.
+func OptionShowCompletionAtStart() Option {
+ return func(p *Prompt) error {
+ p.completion.showAtStart = true
+ return nil
+ }
+}
+
+// OptionBreakLineCallback to run a callback at every break line
+func OptionBreakLineCallback(fn func(*Document)) Option {
+ return func(p *Prompt) error {
+ p.renderer.breakLineCallback = fn
+ return nil
+ }
+}
+
+// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop
+func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
+ return func(p *Prompt) error {
+ p.exitChecker = fn
+ return nil
+ }
+}
+
+// New returns a Prompt with powerful auto-completion.
+func New(executor Executor, completer Completer, opts ...Option) *Prompt {
+ defaultWriter := NewStdoutWriter()
+ registerConsoleWriter(defaultWriter)
+
+ pt := &Prompt{
+ in: NewStandardInputParser(),
+ renderer: &Render{
+ prefix: "> ",
+ out: defaultWriter,
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ },
+ buf: NewBuffer(),
+ executor: executor,
+ history: NewHistory(),
+ completion: NewCompletionManager(completer, 6),
+ keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting
+ }
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/output.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/output.go
new file mode 100644
index 0000000000000000000000000000000000000000..42531b412f1ed027c2fff5b85bc273e53e569b3a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/output.go
@@ -0,0 +1,161 @@
+package prompt
+
+import "sync"
+
+var (
+ consoleWriterMu sync.Mutex
+ consoleWriter ConsoleWriter
+)
+
+func registerConsoleWriter(f ConsoleWriter) {
+ consoleWriterMu.Lock()
+ defer consoleWriterMu.Unlock()
+ consoleWriter = f
+}
+
+// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on.
+type DisplayAttribute int
+
+const (
+ // DisplayReset reset all display attributes.
+ DisplayReset DisplayAttribute = iota
+ // DisplayBold set bold or increases intensity.
+ DisplayBold
+ // DisplayLowIntensity decreases intensity. Not widely supported.
+ DisplayLowIntensity
+ // DisplayItalic set italic. Not widely supported.
+ DisplayItalic
+ // DisplayUnderline set underline
+ DisplayUnderline
+ // DisplayBlink set blink (less than 150 per minute).
+ DisplayBlink
+ // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported.
+ DisplayRapidBlink
+ // DisplayReverse swap foreground and background colors.
+ DisplayReverse
+ // DisplayInvisible set invisible. Not widely supported.
+ DisplayInvisible
+ // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported.
+ DisplayCrossedOut
+ // DisplayDefaultFont set primary(default) font
+ DisplayDefaultFont
+)
+
+// Color represents color on terminal.
+type Color int
+
+const (
+ // DefaultColor represents a default color.
+ DefaultColor Color = iota
+
+ // Low intensity
+
+ // Black represents a black.
+ Black
+ // DarkRed represents a dark red.
+ DarkRed
+ // DarkGreen represents a dark green.
+ DarkGreen
+ // Brown represents a brown.
+ Brown
+ // DarkBlue represents a dark blue.
+ DarkBlue
+ // Purple represents a purple.
+ Purple
+ // Cyan represents a cyan.
+ Cyan
+ // LightGray represents a light gray.
+ LightGray
+
+ // High intensity
+
+ // DarkGray represents a dark gray.
+ DarkGray
+ // Red represents a red.
+ Red
+ // Green represents a green.
+ Green
+ // Yellow represents a yellow.
+ Yellow
+ // Blue represents a blue.
+ Blue
+ // Fuchsia represents a fuchsia.
+ Fuchsia
+ // Turquoise represents a turquoise.
+ Turquoise
+ // White represents a white.
+ White
+)
+
+// ConsoleWriter is an interface to abstract output layer.
+type ConsoleWriter interface {
+ /* Write */
+
+ // WriteRaw to write raw byte array.
+ WriteRaw(data []byte)
+ // Write to write safety byte array by removing control sequences.
+ Write(data []byte)
+ // WriteStr to write raw string.
+ WriteRawStr(data string)
+ // WriteStr to write safety string by removing control sequences.
+ WriteStr(data string)
+ // Flush to flush buffer.
+ Flush() error
+
+ /* Erasing */
+
+ // EraseScreen erases the screen with the background colour and moves the cursor to home.
+ EraseScreen()
+ // EraseUp erases the screen from the current line up to the top of the screen.
+ EraseUp()
+ // EraseDown erases the screen from the current line down to the bottom of the screen.
+ EraseDown()
+ // EraseStartOfLine erases from the current cursor position to the start of the current line.
+ EraseStartOfLine()
+ // EraseEndOfLine erases from the current cursor position to the end of the current line.
+ EraseEndOfLine()
+ // EraseLine erases the entire current line.
+ EraseLine()
+
+ /* Cursor */
+
+ // ShowCursor stops blinking cursor and show.
+ ShowCursor()
+ // HideCursor hides cursor.
+ HideCursor()
+ // CursorGoTo sets the cursor position where subsequent text will begin.
+ CursorGoTo(row, col int)
+ // CursorUp moves the cursor up by 'n' rows; the default count is 1.
+ CursorUp(n int)
+ // CursorDown moves the cursor down by 'n' rows; the default count is 1.
+ CursorDown(n int)
+ // CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+ CursorForward(n int)
+ // CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+ CursorBackward(n int)
+ // AskForCPR asks for a cursor position report (CPR).
+ AskForCPR()
+ // SaveCursor saves current cursor position.
+ SaveCursor()
+ // UnSaveCursor restores cursor position after a Save Cursor.
+ UnSaveCursor()
+
+ /* Scrolling */
+
+ // ScrollDown scrolls display down one line.
+ ScrollDown()
+ // ScrollUp scroll display up one line.
+ ScrollUp()
+
+ /* Title */
+
+ // SetTitle sets a title of terminal window.
+ SetTitle(title string)
+ // ClearTitle clears a title of terminal window.
+ ClearTitle()
+
+ /* Font */
+
+ // SetColor sets text and background colors. and specify whether text is bold.
+ SetColor(fg, bg Color, bold bool)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/output_posix.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/output_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..26c770cc152a7b126be43915d60b8ba000ad0e38
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/output_posix.go
@@ -0,0 +1,67 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+)
+
+const flushMaxRetryCount = 3
+
+// PosixWriter is a ConsoleWriter implementation for POSIX environment.
+// To control terminal emulator, this outputs VT100 escape sequences.
+type PosixWriter struct {
+ VT100Writer
+ fd int
+}
+
+// Flush to flush buffer
+func (w *PosixWriter) Flush() error {
+ l := len(w.buffer)
+ offset := 0
+ retry := 0
+ for {
+ n, err := syscall.Write(w.fd, w.buffer[offset:])
+ if err != nil {
+ if retry < flushMaxRetryCount {
+ retry++
+ continue
+ }
+ return err
+ }
+ offset += n
+ if offset == l {
+ break
+ }
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &PosixWriter{}
+
+var (
+ // NewStandardOutputWriter returns ConsoleWriter object to write to stdout.
+ // This generates VT100 escape sequences because almost terminal emulators
+ // in POSIX OS built on top of a VT100 specification.
+ // Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStdoutWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stdout,
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStderrWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stderr,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/output_vt100.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/output_vt100.go
new file mode 100644
index 0000000000000000000000000000000000000000..20850fead883c4cd9802928b5de3f935fbbeb047
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/output_vt100.go
@@ -0,0 +1,310 @@
+package prompt
+
+import (
+ "bytes"
+ "strconv"
+)
+
+// VT100Writer generates VT100 escape sequences.
+type VT100Writer struct {
+ buffer []byte
+}
+
+// WriteRaw to write raw byte array
+func (w *VT100Writer) WriteRaw(data []byte) {
+ w.buffer = append(w.buffer, data...)
+}
+
+// Write to write safety byte array by removing control sequences.
+func (w *VT100Writer) Write(data []byte) {
+ w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1))
+}
+
+// WriteRawStr to write raw string
+func (w *VT100Writer) WriteRawStr(data string) {
+ w.WriteRaw([]byte(data))
+}
+
+// WriteStr to write safety string by removing control sequences.
+func (w *VT100Writer) WriteStr(data string) {
+ w.Write([]byte(data))
+}
+
+/* Erase */
+
+// EraseScreen erases the screen with the background colour and moves the cursor to home.
+func (w *VT100Writer) EraseScreen() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'J'})
+}
+
+// EraseUp erases the screen from the current line up to the top of the screen.
+func (w *VT100Writer) EraseUp() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'J'})
+}
+
+// EraseDown erases the screen from the current line down to the bottom of the screen.
+func (w *VT100Writer) EraseDown() {
+ w.WriteRaw([]byte{0x1b, '[', 'J'})
+}
+
+// EraseStartOfLine erases from the current cursor position to the start of the current line.
+func (w *VT100Writer) EraseStartOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'K'})
+}
+
+// EraseEndOfLine erases from the current cursor position to the end of the current line.
+func (w *VT100Writer) EraseEndOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', 'K'})
+}
+
+// EraseLine erases the entire current line.
+func (w *VT100Writer) EraseLine() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'K'})
+}
+
+/* Cursor */
+
+// ShowCursor stops blinking cursor and show.
+func (w *VT100Writer) ShowCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'})
+}
+
+// HideCursor hides cursor.
+func (w *VT100Writer) HideCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'})
+}
+
+// CursorGoTo sets the cursor position where subsequent text will begin.
+func (w *VT100Writer) CursorGoTo(row, col int) {
+ if row == 0 && col == 0 {
+ // If no row/column parameters are provided (ie. [H), the cursor will move to the home position.
+ w.WriteRaw([]byte{0x1b, '[', 'H'})
+ return
+ }
+ r := strconv.Itoa(row)
+ c := strconv.Itoa(col)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(r))
+ w.WriteRaw([]byte{';'})
+ w.WriteRaw([]byte(c))
+ w.WriteRaw([]byte{'H'})
+}
+
+// CursorUp moves the cursor up by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorUp(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorDown(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'A'})
+}
+
+// CursorDown moves the cursor down by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorDown(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorUp(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'B'})
+}
+
+// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorForward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorBackward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'C'})
+}
+
+// CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorBackward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorForward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'D'})
+}
+
+// AskForCPR asks for a cursor position report (CPR).
+func (w *VT100Writer) AskForCPR() {
+ // CPR: Cursor Position Request.
+ w.WriteRaw([]byte{0x1b, '[', '6', 'n'})
+}
+
+// SaveCursor saves current cursor position.
+func (w *VT100Writer) SaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 's'})
+}
+
+// UnSaveCursor restores cursor position after a Save Cursor.
+func (w *VT100Writer) UnSaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 'u'})
+}
+
+/* Scrolling */
+
+// ScrollDown scrolls display down one line.
+func (w *VT100Writer) ScrollDown() {
+ w.WriteRaw([]byte{0x1b, 'D'})
+}
+
+// ScrollUp scroll display up one line.
+func (w *VT100Writer) ScrollUp() {
+ w.WriteRaw([]byte{0x1b, 'M'})
+}
+
+/* Title */
+
+// SetTitle sets a title of terminal window.
+func (w *VT100Writer) SetTitle(title string) {
+ titleBytes := []byte(title)
+ patterns := []struct {
+ from []byte
+ to []byte
+ }{
+ {
+ from: []byte{0x13},
+ to: []byte{},
+ },
+ {
+ from: []byte{0x07},
+ to: []byte{},
+ },
+ }
+ for i := range patterns {
+ titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1)
+ }
+
+ w.WriteRaw([]byte{0x1b, ']', '2', ';'})
+ w.WriteRaw(titleBytes)
+ w.WriteRaw([]byte{0x07})
+}
+
+// ClearTitle clears a title of terminal window.
+func (w *VT100Writer) ClearTitle() {
+ w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07})
+}
+
+/* Font */
+
+// SetColor sets text and background colors. and specify whether text is bold.
+func (w *VT100Writer) SetColor(fg, bg Color, bold bool) {
+ if bold {
+ w.SetDisplayAttributes(fg, bg, DisplayBold)
+ } else {
+ // If using `DisplayDefualt`, it will be broken in some environment.
+ // Details are https://github.com/c-bata/go-prompt/pull/85
+ w.SetDisplayAttributes(fg, bg, DisplayReset)
+ }
+}
+
+// SetDisplayAttributes to set VT100 display attributes.
+func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) {
+ w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer
+ defer w.WriteRaw([]byte{'m'}) // final character
+
+ var separator byte = ';'
+ for i := range attrs {
+ p, ok := displayAttributeParameters[attrs[i]]
+ if !ok {
+ continue
+ }
+ w.WriteRaw(p)
+ w.WriteRaw([]byte{separator})
+ }
+
+ f, ok := foregroundANSIColors[fg]
+ if !ok {
+ f = foregroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(f)
+ w.WriteRaw([]byte{separator})
+ b, ok := backgroundANSIColors[bg]
+ if !ok {
+ b = backgroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(b)
+}
+
+var displayAttributeParameters = map[DisplayAttribute][]byte{
+ DisplayReset: {'0'},
+ DisplayBold: {'1'},
+ DisplayLowIntensity: {'2'},
+ DisplayItalic: {'3'},
+ DisplayUnderline: {'4'},
+ DisplayBlink: {'5'},
+ DisplayRapidBlink: {'6'},
+ DisplayReverse: {'7'},
+ DisplayInvisible: {'8'},
+ DisplayCrossedOut: {'9'},
+ DisplayDefaultFont: {'1', '0'},
+}
+
+var foregroundANSIColors = map[Color][]byte{
+ DefaultColor: {'3', '9'},
+
+ // Low intensity.
+ Black: {'3', '0'},
+ DarkRed: {'3', '1'},
+ DarkGreen: {'3', '2'},
+ Brown: {'3', '3'},
+ DarkBlue: {'3', '4'},
+ Purple: {'3', '5'},
+ Cyan: {'3', '6'},
+ LightGray: {'3', '7'},
+
+ // High intensity.
+ DarkGray: {'9', '0'},
+ Red: {'9', '1'},
+ Green: {'9', '2'},
+ Yellow: {'9', '3'},
+ Blue: {'9', '4'},
+ Fuchsia: {'9', '5'},
+ Turquoise: {'9', '6'},
+ White: {'9', '7'},
+}
+
+var backgroundANSIColors = map[Color][]byte{
+ DefaultColor: {'4', '9'},
+
+ // Low intensity.
+ Black: {'4', '0'},
+ DarkRed: {'4', '1'},
+ DarkGreen: {'4', '2'},
+ Brown: {'4', '3'},
+ DarkBlue: {'4', '4'},
+ Purple: {'4', '5'},
+ Cyan: {'4', '6'},
+ LightGray: {'4', '7'},
+
+ // High intensity
+ DarkGray: {'1', '0', '0'},
+ Red: {'1', '0', '1'},
+ Green: {'1', '0', '2'},
+ Yellow: {'1', '0', '3'},
+ Blue: {'1', '0', '4'},
+ Fuchsia: {'1', '0', '5'},
+ Turquoise: {'1', '0', '6'},
+ White: {'1', '0', '7'},
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/output_windows.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/output_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b9c2769fc2d64cfcfcc5b99c915591ec625bd5f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/output_windows.go
@@ -0,0 +1,49 @@
+// +build windows
+
+package prompt
+
+import (
+ "io"
+
+ colorable "github.com/mattn/go-colorable"
+)
+
+// WindowsWriter is a ConsoleWriter implementation for Win32 console.
+// Output is converted from VT100 escape sequences by mattn/go-colorable.
+type WindowsWriter struct {
+ VT100Writer
+ out io.Writer
+}
+
+// Flush to flush buffer
+func (w *WindowsWriter) Flush() error {
+ _, err := w.out.Write(w.buffer)
+ if err != nil {
+ return err
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &WindowsWriter{}
+
+var (
+ // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates win32 control sequences.
+func NewStdoutWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStdout(),
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates win32 control sequences.
+func NewStderrWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStderr(),
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/prompt.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/prompt.go
new file mode 100644
index 0000000000000000000000000000000000000000..173cd517c40cde212433e399978641ceff1d1a43
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/prompt.go
@@ -0,0 +1,296 @@
+package prompt
+
+import (
+ "bytes"
+ "os"
+ "time"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Executor is called when user input something text.
+type Executor func(string)
+
+// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
+// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
+// - immediate exit (if breakline is false) without executor called
+// - exit after typing (meaning breakline is true), and the executor is called first, before exit.
+// Exit means exit go-prompt (not the overall Go program)
+type ExitChecker func(in string, breakline bool) bool
+
+// Completer should return the suggest item from Document.
+type Completer func(Document) []Suggest
+
+// Prompt is core struct of go-prompt.
+type Prompt struct {
+ in ConsoleParser
+ buf *Buffer
+ renderer *Render
+ executor Executor
+ history *History
+ completion *CompletionManager
+ keyBindings []KeyBind
+ ASCIICodeBindings []ASCIICodeBind
+ keyBindMode KeyBindMode
+ completionOnDown bool
+ exitChecker ExitChecker
+ skipTearDown bool
+}
+
+// Exec is the struct contains user input context.
+type Exec struct {
+ input string
+}
+
+// Run starts prompt.
+func (p *Prompt) Run() {
+ p.skipTearDown = false
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ exitCh := make(chan int)
+ winSizeCh := make(chan *WinSize)
+ stopHandleSignalCh := make(chan struct{})
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+ return
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+
+ // Unset raw mode
+ // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
+ debug.AssertNoError(p.in.TearDown())
+ p.executor(e.input)
+
+ p.completion.Update(*p.buf.Document())
+
+ p.renderer.Render(p.buf, p.completion)
+
+ if p.exitChecker != nil && p.exitChecker(e.input, true) {
+ p.skipTearDown = true
+ return
+ }
+ // Set raw mode
+ debug.AssertNoError(p.in.Setup())
+ go p.readBuffer(bufCh, stopReadBufCh)
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ case w := <-winSizeCh:
+ p.renderer.UpdateWinSize(w)
+ p.renderer.Render(p.buf, p.completion)
+ case code := <-exitCh:
+ p.renderer.BreakLine(p.buf)
+ p.tearDown()
+ os.Exit(code)
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
+ key := GetKey(b)
+ p.buf.lastKeyStroke = key
+ // completion
+ completing := p.completion.Completing()
+ p.handleCompletionKeyBinding(key, completing)
+
+ switch key {
+ case Enter, ControlJ, ControlM:
+ p.renderer.BreakLine(p.buf)
+
+ exec = &Exec{input: p.buf.Text()}
+ p.buf = NewBuffer()
+ if exec.input != "" {
+ p.history.Add(exec.input)
+ }
+ case ControlC:
+ p.renderer.BreakLine(p.buf)
+ p.buf = NewBuffer()
+ p.history.Clear()
+ case Up, ControlP:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Older(p.buf); changed {
+ p.buf = newBuf
+ }
+ }
+ case Down, ControlN:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Newer(p.buf); changed {
+ p.buf = newBuf
+ }
+ return
+ }
+ case ControlD:
+ if p.buf.Text() == "" {
+ shouldExit = true
+ return
+ }
+ case NotDefined:
+ if p.handleASCIICodeBinding(b) {
+ return
+ }
+ p.buf.InsertText(string(b), false, true)
+ }
+
+ shouldExit = p.handleKeyBinding(key)
+ return
+}
+
+func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
+ switch key {
+ case Down:
+ if completing || p.completionOnDown {
+ p.completion.Next()
+ }
+ case Tab, ControlI:
+ p.completion.Next()
+ case Up:
+ if completing {
+ p.completion.Previous()
+ }
+ case BackTab:
+ p.completion.Previous()
+ default:
+ if s, ok := p.completion.GetSelectedSuggestion(); ok {
+ w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
+ if w != "" {
+ p.buf.DeleteBeforeCursor(len([]rune(w)))
+ }
+ p.buf.InsertText(s.Text, false, true)
+ }
+ p.completion.Reset()
+ }
+}
+
+func (p *Prompt) handleKeyBinding(key Key) bool {
+ shouldExit := false
+ for i := range commonKeyBindings {
+ kb := commonKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+
+ if p.keyBindMode == EmacsKeyBind {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ }
+
+ // Custom key bindings
+ for i := range p.keyBindings {
+ kb := p.keyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
+ shouldExit = true
+ }
+ return shouldExit
+}
+
+func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
+ checked := false
+ for _, kb := range p.ASCIICodeBindings {
+ if bytes.Equal(kb.ASCIICode, b) {
+ kb.Fn(p.buf)
+ checked = true
+ }
+ }
+ return checked
+}
+
+// Input just returns user input text.
+func (p *Prompt) Input() string {
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ return ""
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ return e.input
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
+ debug.Log("start reading buffer")
+ for {
+ select {
+ case <-stopCh:
+ debug.Log("stop reading buffer")
+ return
+ default:
+ if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
+ bufCh <- b
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (p *Prompt) setUp() {
+ debug.AssertNoError(p.in.Setup())
+ p.renderer.Setup()
+ p.renderer.UpdateWinSize(p.in.GetWinSize())
+}
+
+func (p *Prompt) tearDown() {
+ if !p.skipTearDown {
+ debug.AssertNoError(p.in.TearDown())
+ }
+ p.renderer.TearDown()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/render.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/render.go
new file mode 100644
index 0000000000000000000000000000000000000000..299ac48b6254b9752ea16516aaedcd41acca6515
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/render.go
@@ -0,0 +1,287 @@
+package prompt
+
+import (
+ "runtime"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Render to render prompt information from state of Buffer.
+type Render struct {
+ out ConsoleWriter
+ prefix string
+ livePrefixCallback func() (prefix string, useLivePrefix bool)
+ breakLineCallback func(*Document)
+ title string
+ row uint16
+ col uint16
+
+ previousCursor int
+
+ // colors,
+ prefixTextColor Color
+ prefixBGColor Color
+ inputTextColor Color
+ inputBGColor Color
+ previewSuggestionTextColor Color
+ previewSuggestionBGColor Color
+ suggestionTextColor Color
+ suggestionBGColor Color
+ selectedSuggestionTextColor Color
+ selectedSuggestionBGColor Color
+ descriptionTextColor Color
+ descriptionBGColor Color
+ selectedDescriptionTextColor Color
+ selectedDescriptionBGColor Color
+ scrollbarThumbColor Color
+ scrollbarBGColor Color
+}
+
+// Setup to initialize console output.
+func (r *Render) Setup() {
+ if r.title != "" {
+ r.out.SetTitle(r.title)
+ debug.AssertNoError(r.out.Flush())
+ }
+}
+
+// getCurrentPrefix to get current prefix.
+// If live-prefix is enabled, return live-prefix.
+func (r *Render) getCurrentPrefix() string {
+ if prefix, ok := r.livePrefixCallback(); ok {
+ return prefix
+ }
+ return r.prefix
+}
+
+func (r *Render) renderPrefix() {
+ r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
+ r.out.WriteStr(r.getCurrentPrefix())
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// TearDown to clear title and erasing.
+func (r *Render) TearDown() {
+ r.out.ClearTitle()
+ r.out.EraseDown()
+ debug.AssertNoError(r.out.Flush())
+}
+
+func (r *Render) prepareArea(lines int) {
+ for i := 0; i < lines; i++ {
+ r.out.ScrollDown()
+ }
+ for i := 0; i < lines; i++ {
+ r.out.ScrollUp()
+ }
+}
+
+// UpdateWinSize called when window size is changed.
+func (r *Render) UpdateWinSize(ws *WinSize) {
+ r.row = ws.Row
+ r.col = ws.Col
+}
+
+func (r *Render) renderWindowTooSmall() {
+ r.out.CursorGoTo(0, 0)
+ r.out.EraseScreen()
+ r.out.SetColor(DarkRed, White, false)
+ r.out.WriteStr("Your console window is too small...")
+}
+
+func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) {
+ suggestions := completions.GetSuggestions()
+ if len(completions.GetSuggestions()) == 0 {
+ return
+ }
+ prefix := r.getCurrentPrefix()
+ formatted, width := formatSuggestions(
+ suggestions,
+ int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar
+ )
+ // +1 means a width of scrollbar.
+ width++
+
+ windowHeight := len(formatted)
+ if windowHeight > int(completions.max) {
+ windowHeight = int(completions.max)
+ }
+ formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
+ r.prepareArea(windowHeight)
+
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor())
+ x, _ := r.toPos(cursor)
+ if x+width >= int(r.col) {
+ cursor = r.backward(cursor, x+width-int(r.col))
+ }
+
+ contentHeight := len(completions.tmp)
+
+ fractionVisible := float64(windowHeight) / float64(contentHeight)
+ fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
+
+ scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
+ scrollbarTop := int(float64(windowHeight) * fractionAbove)
+
+ isScrollThumb := func(row int) bool {
+ return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
+ }
+
+ selected := completions.selected - completions.verticalScroll
+ r.out.SetColor(White, Cyan, false)
+ for i := 0; i < windowHeight; i++ {
+ r.out.CursorDown(1)
+ if i == selected {
+ r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
+ } else {
+ r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Text)
+
+ if i == selected {
+ r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
+ } else {
+ r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Description)
+
+ if isScrollThumb(i) {
+ r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
+ } else {
+ r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
+ }
+ r.out.WriteStr(" ")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+
+ r.lineWrap(cursor + width)
+ r.backward(cursor+width, width)
+ }
+
+ if x+width >= int(r.col) {
+ r.out.CursorForward(x + width - int(r.col))
+ }
+
+ r.out.CursorUp(windowHeight)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// Render renders to the console.
+func (r *Render) Render(buffer *Buffer, completion *CompletionManager) {
+ // In situations where a pseudo tty is allocated (e.g. within a docker container),
+ // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
+ if r.col == 0 {
+ return
+ }
+ defer func() { debug.AssertNoError(r.out.Flush()) }()
+ r.move(r.previousCursor, 0)
+
+ line := buffer.Text()
+ prefix := r.getCurrentPrefix()
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line)
+
+ // prepare area
+ _, y := r.toPos(cursor)
+
+ h := y + 1 + int(completion.max)
+ if h > int(r.row) || completionMargin > int(r.col) {
+ r.renderWindowTooSmall()
+ return
+ }
+
+ // Rendering
+ r.out.HideCursor()
+ defer r.out.ShowCursor()
+
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(line)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ r.lineWrap(cursor)
+
+ r.out.EraseDown()
+
+ cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition())
+
+ r.renderCompletion(buffer, completion)
+ if suggest, ok := completion.GetSelectedSuggestion(); ok {
+ cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator)))
+
+ r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false)
+ r.out.WriteStr(suggest.Text)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ cursor += runewidth.StringWidth(suggest.Text)
+
+ rest := buffer.Document().TextAfterCursor()
+ r.out.WriteStr(rest)
+ cursor += runewidth.StringWidth(rest)
+ r.lineWrap(cursor)
+
+ cursor = r.backward(cursor, runewidth.StringWidth(rest))
+ }
+ r.previousCursor = cursor
+}
+
+// BreakLine to break line.
+func (r *Render) BreakLine(buffer *Buffer) {
+ // Erasing and Render
+ cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix())
+ r.clear(cursor)
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(buffer.Document().Text + "\n")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ debug.AssertNoError(r.out.Flush())
+ if r.breakLineCallback != nil {
+ r.breakLineCallback(buffer.Document())
+ }
+
+ r.previousCursor = 0
+}
+
+// clear erases the screen from a beginning of input
+// even if there is line break which means input length exceeds a window's width.
+func (r *Render) clear(cursor int) {
+ r.move(cursor, 0)
+ r.out.EraseDown()
+}
+
+// backward moves cursor to backward from a current cursor position
+// regardless there is a line break.
+func (r *Render) backward(from, n int) int {
+ return r.move(from, from-n)
+}
+
+// move moves cursor to specified position from the beginning of input
+// even if there is a line break.
+func (r *Render) move(from, to int) int {
+ fromX, fromY := r.toPos(from)
+ toX, toY := r.toPos(to)
+
+ r.out.CursorUp(fromY - toY)
+ r.out.CursorBackward(fromX - toX)
+ return to
+}
+
+// toPos returns the relative position from the beginning of the string.
+func (r *Render) toPos(cursor int) (x, y int) {
+ col := int(r.col)
+ return cursor % col, cursor / col
+}
+
+func (r *Render) lineWrap(cursor int) {
+ if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 {
+ r.out.WriteRaw([]byte{'\n'})
+ }
+}
+
+func clamp(high, low, x float64) float64 {
+ switch {
+ case high < x:
+ return high
+ case x < low:
+ return low
+ default:
+ return x
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/shortcut.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/shortcut.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8d4282700c0bdb30e4decfb9c9ac91f27af251
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/shortcut.go
@@ -0,0 +1,43 @@
+package prompt
+
+func dummyExecutor(in string) {}
+
+// Input get the input data from the user and return it.
+func Input(prefix string, completer Completer, opts ...Option) string {
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+// Choose to the shortcut of input function to select from string array.
+// Deprecated: Maybe anyone want to use this.
+func Choose(prefix string, choices []string, opts ...Option) string {
+ completer := newChoiceCompleter(choices, FilterHasPrefix)
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+func newChoiceCompleter(choices []string, filter Filter) Completer {
+ s := make([]Suggest, len(choices))
+ for i := range choices {
+ s[i] = Suggest{Text: choices[i]}
+ }
+ return func(x Document) []Suggest {
+ return filter(s, x.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/signal_posix.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/signal_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3150df5d85e7612c42c2a889dbefee3b524bef6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/signal_posix.go
@@ -0,0 +1,49 @@
+// +build !windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ in := p.in
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+
+ case syscall.SIGWINCH:
+ debug.Log("Catch SIGWINCH")
+ winSizeCh <- in.GetWinSize()
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/signal_windows.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/signal_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a427c79ec0414540f8f40694731b2565ea80c13
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/environment/source/signal_windows.go
@@ -0,0 +1,44 @@
+// +build windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/instruction.md b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..92a9eb6ce4cf48ece5bdf471399b3457d190328f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/instruction.md
@@ -0,0 +1,32 @@
+Cursor up movement broken when at top of document
+
+#### Description
+
+When using cursor up movement in a document, the cursor position calculation is incorrect when already at the top of the document. The cursor moves to unexpected positions instead of staying at the beginning.
+
+#### Steps/Code to Reproduce
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func main() {
+ doc := prompt.NewDocument("line1\nline2\nline3", 0)
+
+ // Try to move cursor up when already at top
+ upPos := doc.GetCursorUpPosition(1, -1)
+ fmt.Printf("Expected: 0, Got: %d\n", upPos)
+
+ // Should stay at position 0 when at top of document
+ if upPos != 0 {
+ fmt.Printf("Cursor up movement broken - cursor moved to position %d instead of staying at 0\n", upPos)
+ }
+}
+```
+
+The cursor should remain at position 0 when trying to move up from the first line, but instead it calculates an incorrect position.
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/provenance.json b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..7bc169a5ea6e55615db2e5394dfb8e3f716de1e3
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/provenance.json
@@ -0,0 +1,477 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt",
+ "original-bug": "task-specific unchanged semantic bug",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only",
+ "extra_semantic_repair_coverage": false,
+ "original_patch_hunks": 1
+ },
+ "private_frozen_files": {
+ "buffer_test.go": {
+ "mode": "0o644",
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098",
+ "size": 4965
+ },
+ "completion_test.go": {
+ "mode": "0o644",
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d",
+ "size": 7010
+ },
+ "document_test.go": {
+ "mode": "0o644",
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284",
+ "size": 28938
+ },
+ "emacs_test.go": {
+ "mode": "0o644",
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095",
+ "size": 741
+ },
+ "filter_test.go": {
+ "mode": "0o644",
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247",
+ "size": 3339
+ },
+ "history_test.go": {
+ "mode": "0o644",
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327",
+ "size": 1319
+ },
+ "input_test.go": {
+ "mode": "0o644",
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922",
+ "size": 533
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": "0o644",
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf",
+ "size": 1075
+ },
+ "internal/strings/strings_test.go": {
+ "mode": "0o644",
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6",
+ "size": 981
+ },
+ "output_vt100_test.go": {
+ "mode": "0o644",
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee",
+ "size": 1349
+ },
+ "render_test.go": {
+ "mode": "0o644",
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb",
+ "size": 2890
+ }
+ },
+ "public_files": {
+ ".github/ISSUE_TEMPLATE/bug_report.md": {
+ "mode": "0o644",
+ "sha256": "89d3492ca8533a3d31e4de49a23828a322f75d2a1ec4236327c4a76c7c51ada6",
+ "size": 684
+ },
+ ".github/ISSUE_TEMPLATE/feature_request.md": {
+ "mode": "0o644",
+ "sha256": "d82e14e6b4d021d0007eeef4f5ca489fc6c8e8e4d7479ee30e74fe82afd3b08f",
+ "size": 206
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "3239b94a1a41c05eff5dc086ef1378cf1e289fad0203420b5cb4c78e3c5c239b",
+ "size": 270
+ },
+ "CHANGELOG.md": {
+ "mode": "0o644",
+ "sha256": "1f88f92d3247e1b52af0f0de7ad1263a59807edb17238c7a0211554f8080e51c",
+ "size": 2895
+ },
+ "LICENSE": {
+ "mode": "0o644",
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "size": 1072
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "9425a0d4c15747863625f647348962a9b0f81a0971a7e0184ee722bf34a60ba2",
+ "size": 1177
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "ce56df51a1a9a5b5c5b056429bbee006a260fb0730af63b1d0fe91755e574cc4",
+ "size": 6185
+ },
+ "_example/README.md": {
+ "mode": "0o644",
+ "sha256": "155951bafd778493bd41ae57dcc0ba6b8eca821fcbe2ffe770960ac2780d3d09",
+ "size": 1102
+ },
+ "_example/build.sh": {
+ "mode": "0o755",
+ "sha256": "de2fb330b665691cd75b990236cd6a5df0058608de0dfc6194da30d4041a1e29",
+ "size": 469
+ },
+ "_example/exec-command/main.go": {
+ "mode": "0o644",
+ "sha256": "0e96493b6e6d446b2e691d4834ff8a55834caa410ead970cb611a63ba84f174a",
+ "size": 429
+ },
+ "_example/http-prompt/api.py": {
+ "mode": "0o644",
+ "sha256": "2c2bca9acb07a84c65a4482c61c9ade253a574477a8e461307568ea1f9a342c8",
+ "size": 335
+ },
+ "_example/http-prompt/main.go": {
+ "mode": "0o644",
+ "sha256": "6994b190c4165068e69ed44eb61698af69a15a7690179ce46e3c1c5d8c211643",
+ "size": 5484
+ },
+ "_example/live-prefix/main.go": {
+ "mode": "0o644",
+ "sha256": "20268f9cb6f3b82a52eddc33cbf8082adaa46092e2063df279499e05e25a228c",
+ "size": 1103
+ },
+ "_example/simple-echo/cjk-cyrillic/main.go": {
+ "mode": "0o644",
+ "sha256": "8fb10807d4085ebc4b345bc0ccfef9217e21e49a888bfe3192e8ddfdfa01e89c",
+ "size": 800
+ },
+ "_example/simple-echo/main.go": {
+ "mode": "0o644",
+ "sha256": "e46563ddaa932831fe9ede870b10efb5222c0d54a86f4b4f5197c9cf20942a24",
+ "size": 902
+ },
+ "_tools/README.md": {
+ "mode": "0o644",
+ "sha256": "96dc2343bc5cde642fd449ddc366462753a2e17b6a78adfa015bf991e9dac241",
+ "size": 234
+ },
+ "_tools/complete_file/main.go": {
+ "mode": "0o644",
+ "sha256": "e5dd823f9d6415614a8238ce106d26e9ded1db9b308c121d7f48bb1df003effc",
+ "size": 803
+ },
+ "_tools/sigwinch/main.go": {
+ "mode": "0o644",
+ "sha256": "a806b4e45298f5003c95432d8dd3c40c9c096335f19f1a4160afcdb64fa727e3",
+ "size": 1386
+ },
+ "_tools/vt100_debug/main.go": {
+ "mode": "0o644",
+ "sha256": "7f72eba3cc7037fcf39c9b56a96c578c157e5fb235cb626ab1e83cbef0dc290b",
+ "size": 794
+ },
+ "buffer.go": {
+ "mode": "0o644",
+ "sha256": "10188d96a450fe13ba1e9ec00c89603eb2a2860536965d980d1e4abf4374b018",
+ "size": 5781
+ },
+ "completer/file.go": {
+ "mode": "0o644",
+ "sha256": "6181ed9e39028236c5c93fbe219331fc1492ecfd6af2df764cc42b5455c9bb96",
+ "size": 2401
+ },
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "b90bd9628534cfb343a592775430e17a1999b1de500fb2a8f1507c030a432eae",
+ "size": 4491
+ },
+ "document.go": {
+ "mode": "0o644",
+ "sha256": "3f109f3e06e2311040ae1f1154db0b37f8179b7ee5a3f212d54b3506591c8a42",
+ "size": 13097
+ },
+ "emacs.go": {
+ "mode": "0o644",
+ "sha256": "53f0df0016ef9d9695a797b19286681666cf0c7e5a866c393b194aae915f2664",
+ "size": 2675
+ },
+ "filter.go": {
+ "mode": "0o644",
+ "sha256": "dc5922bad6ecb32ecdaf20bd6035dddc7ce8c14f15dbd4d49192c2354cb8a038",
+ "size": 2005
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "97413fa2a2ed68170496f2289a2dca6fb0a192dcd020fc0ca48a5d106e60d55e",
+ "size": 253
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "88ea0a91babaa54b67cc6d5f6f7f47fa4be798fe523324ea568d8926eed2024c",
+ "size": 2183
+ },
+ "history.go": {
+ "mode": "0o644",
+ "sha256": "4ce80ba067cfc72c56a3ee3353ec75cd6bb2f5d82097515c591e3c7c773c51cd",
+ "size": 1488
+ },
+ "input.go": {
+ "mode": "0o644",
+ "sha256": "73461cc4f57d68b66e2a9e196239aaef942539134593beac0d0023743832e0e1",
+ "size": 7630
+ },
+ "input_posix.go": {
+ "mode": "0o644",
+ "sha256": "c7e5a4dfc3910f178f0685ef99f2e47d481a91c4cf9af50f92fc4266aed634df",
+ "size": 1648
+ },
+ "input_windows.go": {
+ "mode": "0o644",
+ "sha256": "f763250d309fb88d9536f77da1d1285c04bc6defe859506f1501e10f7743da9e",
+ "size": 1679
+ },
+ "internal/bisect/bisect.go": {
+ "mode": "0o644",
+ "sha256": "c4de2adfa2e08a77f902661d67325467f89013634dbcef22d24dc6f34d26624a",
+ "size": 327
+ },
+ "internal/debug/assert.go": {
+ "mode": "0o644",
+ "sha256": "1a3050ec58991b62c7ea352d19505e3080ac9760bdb091544f0ecf5aba35969c",
+ "size": 815
+ },
+ "internal/debug/log.go": {
+ "mode": "0o644",
+ "sha256": "2ce968e275558de61c6d83793e85561f7a8dd69c95ec7902ccd2cc3fb169aa82",
+ "size": 875
+ },
+ "internal/strings/strings.go": {
+ "mode": "0o644",
+ "sha256": "b97f08157c3baf1f94fea4bb2237691d8270bd5380b4311709ecd59b84cf4b7b",
+ "size": 2018
+ },
+ "internal/term/raw.go": {
+ "mode": "0o644",
+ "sha256": "177a1a20ae8d71b56857383a5797754560f7f6404ea86778d5f01e9a1c1b4f9f",
+ "size": 747
+ },
+ "internal/term/term.go": {
+ "mode": "0o644",
+ "sha256": "abe6fa965fa15b999b2010135903f598830d4c885a52ef9b067fd5ebbf6e373f",
+ "size": 606
+ },
+ "key.go": {
+ "mode": "0o644",
+ "sha256": "03a43283e07de7a4ea6fed32692d86325f73e98fd89a296f19c171e0bc780999",
+ "size": 1746
+ },
+ "key_bind.go": {
+ "mode": "0o644",
+ "sha256": "83f48bb720a11c8e49165ac382e3a870fdcf6b380a0a95267f8c25211898c9eb",
+ "size": 1109
+ },
+ "key_bind_func.go": {
+ "mode": "0o644",
+ "sha256": "445bff5c0fdb0b52879c635322603c2fc75d265de3761cb8c3b980c798bf39af",
+ "size": 1219
+ },
+ "key_string.go": {
+ "mode": "0o644",
+ "sha256": "55c429dae227bb1659d5d5e2e906dbfa9c7f53b5105fa83fbe290529ff6f2317",
+ "size": 1359
+ },
+ "option.go": {
+ "mode": "0o644",
+ "sha256": "28cfcc1d08b3cf650483d977195458531b3b3913f8a5f357a3ec17ea5d73e215",
+ "size": 8737
+ },
+ "output.go": {
+ "mode": "0o644",
+ "sha256": "372876b0aa908479ed3b29de70a479f420d85e3666b8957c8b61eaed9b32c3f2",
+ "size": 4320
+ },
+ "output_posix.go": {
+ "mode": "0o644",
+ "sha256": "d46b1da307e8969b033e1ade2eb51a83c4c3d4f2a7e4aba35ec3a03991b89a0f",
+ "size": 1545
+ },
+ "output_vt100.go": {
+ "mode": "0o644",
+ "sha256": "9082c7e4619c1eb38030bc4994a4fbf66ef27b130751bf2eb9c25c01082e8605",
+ "size": 7453
+ },
+ "output_windows.go": {
+ "mode": "0o644",
+ "sha256": "571c5ae1ad051a701b426371efd79a3776c2226ca9e3c2e598fe5996dfa1b8e1",
+ "size": 1066
+ },
+ "prompt.go": {
+ "mode": "0o644",
+ "sha256": "6b3e2bbd90f40ad6a487f1a6ea7f5a6fb48cae6c8c246ecc77621fb3e7383ca7",
+ "size": 7062
+ },
+ "render.go": {
+ "mode": "0o644",
+ "sha256": "90fdd57a63e06f01940d10ee1a0be95ced7d6adc7faa255b3141556d7d316270",
+ "size": 8020
+ },
+ "shortcut.go": {
+ "mode": "0o644",
+ "sha256": "b4a097f466df7396049ebe8393f81c9b1200159d4e2be22bd6838c307ec156dc",
+ "size": 1120
+ },
+ "signal_posix.go": {
+ "mode": "0o644",
+ "sha256": "74f0bae5f290f3f7f82a5dd495e672f627a4ab4b63118f870e8c13c0a7024314",
+ "size": 881
+ },
+ "signal_windows.go": {
+ "mode": "0o644",
+ "sha256": "444f662a32e6997df2af8e2a9e7dbfe977414a6bfc0f54a7f10117f204648437",
+ "size": 757
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982",
+ "os": "linux",
+ "sha256": "0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982"
+ },
+ "context_inventory_sha256": "6b8f93086e81483ac1ce82f328d7f4b38b1b560dbad057ed6a2a30ff3cf0e13f",
+ "image": "registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "9d3b21cdacadfa4f3de9584d0cea973e5aa2ceedcd5ec9cbd3a63df22b313455",
+ "receipt_path": "production/runtime-images-extra-v1/resolutions/316e0e68930cd4ef/resolution.json",
+ "receipt_sha256": "697bb0619eddcdfdeba1c9144b033f564f2d7514be6e6a44dc520fa4e63ed8bc",
+ "registry_digest": "sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "source_image": "docker.io/swebench/swesmith.x86_64.c-bata_1776_go-prompt.82a91227@sha256:3daf51c74a01657e9ad8f326651fb6f5b796ffecdb90098e74a52a9560e0a1bb",
+ "source_receipt_sha256": "b450bea0e201cbe194b765ded4b51539144c85296122c8b642d7e94c889526f3",
+ "space_commit": "5ae654cd2e9d695f0de304bd4398835fc7cf45e0",
+ "space_id": "harness-hub/scale800-go-316e0e68930cd4ef-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "ad10d096b9a6cf82001aef74f7a2ffe25f993ac7d58fa71414f4591b51d84d12",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21",
+ "source_proof_sha256": "17819aa9ae2461cd864b1f93916c08cb72c879845ac30c163f5adf6135d922b2",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "9992c59c25864ce1556e67b9e1501c93f6e7f9ff",
+ "instruction_sha256": "8f184f7378a1e380cd462039975c121b7ae3352adece0fa830082eea6917f6fb",
+ "is_fork": true,
+ "learner_path": "tasks/299dcda3e9d14bc0c4073e2e/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/c-bata__go-prompt.82a91227/e4b8a63ea8e8fb4c3e495ba1ab8069d434132814/LICENSE"
+ },
+ "task_bundle": {
+ "basis": "Captured publisherMIT/train; exactsoftwarepermissionverifiedseparately",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "82a912274504477990ecf7c852eebb7c85291772",
+ "patch_sha256": "403e7ca6ba726da3adc75d8679eb817f7a4960f1f47bb89831d8b1321c39683c",
+ "provenance_path": "tasks/299dcda3e9d14bc0c4073e2e/source-proof.json",
+ "repository_lineage": [
+ "swesmith/c-bata__go-prompt.82a91227",
+ "c-bata/go-prompt"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "e4b8a63ea8e8fb4c3e495ba1ab8069d434132814",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "0140e0324455a1b54346bb0e65ba2f61cf6a0bd3",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/c-bata__go-prompt.82a91227",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn",
+ "task_sha256": "3a5f6ecc7514ffa49f6996c6d04a39308bbb78d46e491eeedfaf007a1c855507",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "c-bata/go-prompt",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "d8b000126fa6b1729bace58cce6feec0028a72b54a9f99c2d9e510dfc46ff279",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.md",
+ "/testbed/.github/ISSUE_TEMPLATE/feature_request.md",
+ "/testbed/.gitignore",
+ "/testbed/CHANGELOG.md",
+ "/testbed/LICENSE",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/_example/README.md",
+ "/testbed/_example/build.sh",
+ "/testbed/_example/exec-command/main.go",
+ "/testbed/_example/http-prompt/api.py",
+ "/testbed/_example/http-prompt/main.go",
+ "/testbed/_example/live-prefix/main.go",
+ "/testbed/_example/simple-echo/cjk-cyrillic/main.go",
+ "/testbed/_example/simple-echo/main.go",
+ "/testbed/_tools/README.md",
+ "/testbed/_tools/complete_file/main.go",
+ "/testbed/_tools/sigwinch/main.go",
+ "/testbed/_tools/vt100_debug/main.go",
+ "/testbed/buffer.go",
+ "/testbed/completer/file.go",
+ "/testbed/completion.go",
+ "/testbed/document.go",
+ "/testbed/emacs.go",
+ "/testbed/filter.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum",
+ "/testbed/history.go",
+ "/testbed/input.go",
+ "/testbed/input_posix.go",
+ "/testbed/input_windows.go",
+ "/testbed/internal/bisect/bisect.go",
+ "/testbed/internal/debug/assert.go",
+ "/testbed/internal/debug/log.go",
+ "/testbed/internal/strings/strings.go",
+ "/testbed/internal/term/raw.go",
+ "/testbed/internal/term/term.go",
+ "/testbed/key.go",
+ "/testbed/key_bind.go",
+ "/testbed/key_bind_func.go",
+ "/testbed/key_string.go",
+ "/testbed/option.go",
+ "/testbed/output.go",
+ "/testbed/output_posix.go",
+ "/testbed/output_vt100.go",
+ "/testbed/output_windows.go",
+ "/testbed/prompt.go",
+ "/testbed/render.go",
+ "/testbed/shortcut.go",
+ "/testbed/signal_posix.go",
+ "/testbed/signal_windows.go"
+ ]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/solution/solve.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..00d1a533519e8abc9def758862da6b859247bfe5
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"document.go": {"data": "cGFja2FnZSBwcm9tcHQKCmltcG9ydCAoCgkic3RyaW5ncyIKCSJ1bmljb2RlL3V0ZjgiCgoJImdpdGh1Yi5jb20vYy1iYXRhL2dvLXByb21wdC9pbnRlcm5hbC9iaXNlY3QiCglpc3RyaW5ncyAiZ2l0aHViLmNvbS9jLWJhdGEvZ28tcHJvbXB0L2ludGVybmFsL3N0cmluZ3MiCglydW5ld2lkdGggImdpdGh1Yi5jb20vbWF0dG4vZ28tcnVuZXdpZHRoIgopCgovLyBEb2N1bWVudCBoYXMgdGV4dCBkaXNwbGF5ZWQgaW4gdGVybWluYWwgYW5kIGN1cnNvciBwb3NpdGlvbi4KdHlwZSBEb2N1bWVudCBzdHJ1Y3QgewoJVGV4dCBzdHJpbmcKCS8vIFRoaXMgcmVwcmVzZW50cyBhIGluZGV4IGluIGEgcnVuZSBhcnJheSBvZiBEb2N1bWVudC5UZXh0LgoJLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgY3Vyc29yUG9zaXRpb24gaXMgMi4KCS8vIEJ1dCBEaXNwbGF5ZWRDdXJzb3JQb3NpdGlvbiByZXR1cm5zIDQgYmVjYXVzZSAn5pelJyBhbmQgJ+acrCcgYXJlIGRvdWJsZSB3aWR0aCBjaGFyYWN0ZXJzLgoJY3Vyc29yUG9zaXRpb24gaW50CglsYXN0S2V5ICAgICAgICBLZXkKfQoKLy8gTmV3RG9jdW1lbnQgcmV0dXJuIHRoZSBuZXcgZW1wdHkgZG9jdW1lbnQuCmZ1bmMgTmV3RG9jdW1lbnQoKSAqRG9jdW1lbnQgewoJcmV0dXJuICZEb2N1bWVudHsKCQlUZXh0OiAgICAgICAgICAgIiIsCgkJY3Vyc29yUG9zaXRpb246IDAsCgl9Cn0KCi8vIExhc3RLZXlTdHJva2UgcmV0dXJuIHRoZSBsYXN0IGtleSBwcmVzc2VkIGluIHRoaXMgZG9jdW1lbnQuCmZ1bmMgKGQgKkRvY3VtZW50KSBMYXN0S2V5U3Ryb2tlKCkgS2V5IHsKCXJldHVybiBkLmxhc3RLZXkKfQoKLy8gRGlzcGxheUN1cnNvclBvc2l0aW9uIHJldHVybnMgdGhlIGN1cnNvciBwb3NpdGlvbiBvbiByZW5kZXJlZCB0ZXh0IG9uIHRlcm1pbmFsIGVtdWxhdG9ycy4KLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgRGlzcGxheWVkQ3Vyc29yUG9zaXRpb24gcmV0dXJucyA0IGJlY2F1c2UgJ+aXpScgYW5kICfmnKwnIGFyZSBkb3VibGUgd2lkdGggY2hhcmFjdGVycy4KZnVuYyAoZCAqRG9jdW1lbnQpIERpc3BsYXlDdXJzb3JQb3NpdGlvbigpIGludCB7Cgl2YXIgcG9zaXRpb24gaW50CglydW5lcyA6PSBbXXJ1bmUoZC5UZXh0KVs6ZC5jdXJzb3JQb3NpdGlvbl0KCWZvciBpIDo9IHJhbmdlIHJ1bmVzIHsKCQlwb3NpdGlvbiArPSBydW5ld2lkdGguUnVuZVdpZHRoKHJ1bmVzW2ldKQoJfQoJcmV0dXJuIHBvc2l0aW9uCn0KCi8vIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yIHJldHVybiBjaGFyYWN0ZXIgcmVsYXRpdmUgdG8gY3Vyc29yIHBvc2l0aW9uLCBvciBlbXB0eSBzdHJpbmcKZnVuYyAoZCAqRG9jdW1lbnQpIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yKG9mZnNldCBpbnQpIChyIHJ1bmUpIHsKCXMgOj0gZC5UZXh0CgljbnQgOj0gMAoKCWZvciBsZW4ocykgPiAwIHsKCQljbnQrKwoJCXIsIHNpemUgOj0gdXRmOC5EZWNvZGVSdW5lSW5TdHJpbmcocykKCQlpZiBjbnQgPT0gZC5jdXJzb3JQb3NpdGlvbitvZmZzZXQgewoJCQlyZXR1cm4gcgoJCX0KCQlzID0gc1tzaXplOl0KCX0KCXJldHVybiAwCn0KCi8vIFRleHRCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJciA6PSBbXXJ1bmUoZC5UZXh0KQoJcmV0dXJuIHN0cmluZyhyWzpkLmN1cnNvclBvc2l0aW9uXSkKfQoKLy8gVGV4dEFmdGVyQ3Vyc29yIHJldHVybnMgdGhlIHRleHQgYWZ0ZXIgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRBZnRlckN1cnNvcigpIHN0cmluZyB7CglyIDo9IFtdcnVuZShkLlRleHQpCglyZXR1cm4gc3RyaW5nKHJbZC5jdXJzb3JQb3NpdGlvbjpdKQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYmVmb3JlIHRoZSBjdXJzb3IuCi8vIElmIHdlIGhhdmUgd2hpdGVzcGFjZSBiZWZvcmUgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcigpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBJZiB3ZSBoYXZlIHdoaXRlc3BhY2UgYWZ0ZXIgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yKCkgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmQoKV0KfQoKLy8gR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSgpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEFmdGVyQ3Vyc29yLCBpdCByZXR1cm5zIHN0cmluZyBjb250YWluaW5nIHNwYWNlCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UoKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpXQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yVW50aWxTZXBhcmF0b3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvciB1bnRpbCBuZXh0IHNlcGFyYXRvci4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJcmV0dXJuIHhbZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFVudGlsU2VwYXJhdG9yKHNlcCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvciByZXR1cm5zIHRoZSB0ZXh0IGFmdGVyIHRoZSBjdXJzb3IgdW50aWwgbmV4dCBzZXBhcmF0b3IuCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCldCn0KCi8vIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvciByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yKHNlcCBzdHJpbmcpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwKTpdCn0KCi8vIEdldFdvcmRBZnRlckN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYWZ0ZXIgdGhlIGN1cnNvci4KLy8gVW5saWtlIEdldFdvcmRBZnRlckN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXApXQp9CgovLyBGaW5kU3RhcnRPZlByZXZpb3VzV29yZCByZXR1cm5zIGFuIGluZGV4IHJlbGF0aXZlIHRvIHRoZSBjdXJzb3IgcG9zaXRpb24KLy8gcG9pbnRpbmcgdG8gdGhlIHN0YXJ0IG9mIHRoZSBwcmV2aW91cyB3b3JkLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5MYXN0SW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpICsgMQoJfQoJcmV0dXJuIDAKfQoKLy8gRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRXaXRoU3BhY2UgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBUaGUgb25seSBkaWZmZXJlbmNlIGlzIHRvIGlnbm9yZSBjb250aWd1b3VzIHNwYWNlcy4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWVuZCA6PSBpc3RyaW5ncy5MYXN0SW5kZXhOb3RCeXRlKHgsICcgJykKCWlmIGVuZCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEJ5dGUoeFs6ZW5kXSwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiAwCgl9CglyZXR1cm4gc3RhcnQgKyAxCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZCgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJaSA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaSArIDEKCX0KCXJldHVybiAwCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFdpdGhTcGFjZSgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJZW5kIDo9IGlzdHJpbmdzLkxhc3RJbmRleE5vdEFueSh4LCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiAwCgl9CglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4WzplbmRdLCBzZXApCglpZiBzdGFydCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCXJldHVybiBzdGFydCArIDEKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmQgcmV0dXJucyBhbiBpbmRleCByZWxhdGl2ZSB0byB0aGUgY3Vyc29yIHBvc2l0aW9uLgovLyBwb2ludGluZyB0byB0aGUgZW5kIG9mIHRoZSBjdXJyZW50IHdvcmQuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZEVuZE9mQ3VycmVudFdvcmQoKSBpbnQgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglpIDo9IHN0cmluZ3MuSW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpCgl9CglyZXR1cm4gbGVuKHgpCn0KCi8vIEZpbmRFbmRPZkN1cnJlbnRXb3JkV2l0aFNwYWNlIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZC4KLy8gVGhlIG9ubHkgZGlmZmVyZW5jZSBpcyB0byBpZ25vcmUgY29udGlndW91cyBzcGFjZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpIGludCB7Cgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCglzdGFydCA6PSBpc3RyaW5ncy5JbmRleE5vdEJ5dGUoeCwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCgllbmQgOj0gc3RyaW5ncy5JbmRleEJ5dGUoeFtzdGFydDpdLCAnICcpCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvciBpcyBhbG1vc3QgdGhlIHNhbWUgYXMgRmluZEVuZE9mQ3VycmVudFdvcmQuCi8vIEJ1dCB0aGlzIGNhbiBzcGVjaWZ5IFNlcGFyYXRvci4gUmV0dXJuIDAgaWYgbm90aGluZyB3YXMgZm91bmQuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCBzdHJpbmcpIGludCB7CglpZiBzZXAgPT0gIiIgewoJCXJldHVybiBkLkZpbmRFbmRPZkN1cnJlbnRXb3JkKCkKCX0KCgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5JbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaQoJfQoJcmV0dXJuIGxlbih4KQp9CgovLyBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZS4KLy8gQnV0IHRoaXMgY2FuIHNwZWNpZnkgU2VwYXJhdG9yLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRFbmRPZkN1cnJlbnRXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgaW50IHsKCWlmIHNlcCA9PSAiIiB7CgkJcmV0dXJuIGQuRmluZEVuZE9mQ3VycmVudFdvcmRXaXRoU3BhY2UoKQoJfQoKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoKCXN0YXJ0IDo9IGlzdHJpbmdzLkluZGV4Tm90QW55KHgsIHNlcCkKCWlmIHN0YXJ0ID09IC0xIHsKCQlyZXR1cm4gbGVuKHgpCgl9CgoJZW5kIDo9IHN0cmluZ3MuSW5kZXhBbnkoeFtzdGFydDpdLCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gQ3VycmVudExpbmVCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBzdGFydCBvZiB0aGUgbGluZSB1bnRpbCB0aGUgY3Vyc29yLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJcyA6PSBzdHJpbmdzLlNwbGl0KGQuVGV4dEJlZm9yZUN1cnNvcigpLCAiXG4iKQoJcmV0dXJuIHNbbGVuKHMpLTFdCn0KCi8vIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBjdXJzb3IgdW50aWwgdGhlIGVuZCBvZiB0aGUgbGluZS4KZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSBzdHJpbmcgewoJcmV0dXJuIHN0cmluZ3MuU3BsaXQoZC5UZXh0QWZ0ZXJDdXJzb3IoKSwgIlxuIilbMF0KfQoKLy8gQ3VycmVudExpbmUgcmV0dXJuIHRoZSB0ZXh0IG9uIHRoZSBsaW5lIHdoZXJlIHRoZSBjdXJzb3IgaXMuICh3aGVuIHRoZSBpbnB1dAovLyBjb25zaXN0cyBvZiBqdXN0IG9uZSBsaW5lLCBpdCBlcXVhbHMgYHRleHRgLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmUoKSBzdHJpbmcgewoJcmV0dXJuIGQuQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSArIGQuQ3VycmVudExpbmVBZnRlckN1cnNvcigpCn0KCi8vIEFycmF5IHBvaW50aW5nIHRvIHRoZSBzdGFydCBpbmRleGVzIG9mIGFsbCB0aGUgbGluZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBsaW5lU3RhcnRJbmRleGVzKCkgW11pbnQgewoJLy8gVE9ETzogQ2FjaGUsIGJlY2F1c2UgdGhpcyBpcyBvZnRlbiByZXVzZWQuCgkvLyAoSWYgaXQgaXMgdXNlZCwgaXQncyBvZnRlbiB1c2VkIG1hbnkgdGltZXMuCgkvLyBBbmQgdGhpcyBoYXMgdG8gYmUgZmFzdCBmb3IgZWRpdGluZyBiaWcgZG9jdW1lbnRzISkKCWxjIDo9IGQuTGluZUNvdW50KCkKCWxlbmd0aHMgOj0gbWFrZShbXWludCwgbGMpCglmb3IgaSwgbCA6PSByYW5nZSBkLkxpbmVzKCkgewoJCWxlbmd0aHNbaV0gPSBsZW4obCkKCX0KCgkvLyBDYWxjdWxhdGUgY3VtdWxhdGl2ZSBzdW1zLgoJaW5kZXhlcyA6PSBtYWtlKFtdaW50LCBsYysxKQoJaW5kZXhlc1swXSA9IDAgLy8gaHR0cHM6Ly9naXRodWIuY29tL2pvbmF0aGFuc2xlbmRlcnMvcHl0aG9uLXByb21wdC10b29sa2l0L2Jsb2IvbWFzdGVyL3Byb21wdF90b29sa2l0L2RvY3VtZW50LnB5I0wxODkKCXBvcyA6PSAwCglmb3IgaSwgbCA6PSByYW5nZSBsZW5ndGhzIHsKCQlwb3MgKz0gbCArIDEKCQlpbmRleGVzW2krMV0gPSBwb3MKCX0KCWlmIGxjID4gMSB7CgkJLy8gUG9wIHRoZSBsYXN0IGl0ZW0uIChUaGlzIGlzIG5vdCBhIG5ldyBsaW5lLikKCQlpbmRleGVzID0gaW5kZXhlc1s6bGNdCgl9CglyZXR1cm4gaW5kZXhlcwp9CgovLyBGb3IgdGhlIGluZGV4IG9mIGEgY2hhcmFjdGVyIGF0IGEgY2VydGFpbiBsaW5lLCBjYWxjdWxhdGUgdGhlIGluZGV4IG9mCi8vIHRoZSBmaXJzdCBjaGFyYWN0ZXIgb24gdGhhdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgZmluZExpbmVTdGFydEluZGV4KGluZGV4IGludCkgKHBvcyBpbnQsIGxpbmVTdGFydEluZGV4IGludCkgewoJaW5kZXhlcyA6PSBkLmxpbmVTdGFydEluZGV4ZXMoKQoJcG9zID0gYmlzZWN0LlJpZ2h0KGluZGV4ZXMsIGluZGV4KSAtIDEKCWxpbmVTdGFydEluZGV4ID0gaW5kZXhlc1twb3NdCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Sb3cgcmV0dXJucyB0aGUgY3VycmVudCByb3cuICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uUm93KCkgKHJvdyBpbnQpIHsKCXJvdywgXyA9IGQuZmluZExpbmVTdGFydEluZGV4KGQuY3Vyc29yUG9zaXRpb24pCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Db2wgcmV0dXJucyB0aGUgY3VycmVudCBjb2x1bW4uICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uQ29sKCkgKGNvbCBpbnQpIHsKCS8vIERvbid0IHVzZSBzZWxmLnRleHRfYmVmb3JlX2N1cnNvciB0byBjYWxjdWxhdGUgdGhpcy4gQ3JlYXRpbmcgc3Vic3RyaW5ncwoJLy8gYW5kIHNwbGl0dGluZyBpcyB0b28gZXhwZW5zaXZlIGZvciBnZXR0aW5nIHRoZSBjdXJzb3IgcG9zaXRpb24uCglfLCBpbmRleCA6PSBkLmZpbmRMaW5lU3RhcnRJbmRleChkLmN1cnNvclBvc2l0aW9uKQoJY29sID0gZC5jdXJzb3JQb3NpdGlvbiAtIGluZGV4CglyZXR1cm4KfQoKLy8gR2V0Q3Vyc29yTGVmdFBvc2l0aW9uIHJldHVybnMgdGhlIHJlbGF0aXZlIHBvc2l0aW9uIGZvciBjdXJzb3IgbGVmdC4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldEN1cnNvckxlZnRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvclJpZ2h0UG9zaXRpb24oLWNvdW50KQoJfQoJaWYgZC5DdXJzb3JQb3NpdGlvbkNvbCgpID4gY291bnQgewoJCXJldHVybiAtY291bnQKCX0KCXJldHVybiAtZC5DdXJzb3JQb3NpdGlvbkNvbCgpCn0KCi8vIEdldEN1cnNvclJpZ2h0UG9zaXRpb24gcmV0dXJucyByZWxhdGl2ZSBwb3NpdGlvbiBmb3IgY3Vyc29yIHJpZ2h0LgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yUmlnaHRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvckxlZnRQb3NpdGlvbigtY291bnQpCgl9CglpZiBsZW4oZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpID4gY291bnQgewoJCXJldHVybiBjb3VudAoJfQoJcmV0dXJuIGxlbihkLkN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSkKfQoKLy8gR2V0Q3Vyc29yVXBQb3NpdGlvbiByZXR1cm4gdGhlIHJlbGF0aXZlIGN1cnNvciBwb3NpdGlvbiAoY2hhcmFjdGVyIGluZGV4KSB3aGVyZSB3ZSB3b3VsZCBiZQovLyBpZiB0aGUgdXNlciBwcmVzc2VkIHRoZSBhcnJvdy11cCBidXR0b24uCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRDdXJzb3JVcFBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9CgoJcm93IDo9IGQuQ3Vyc29yUG9zaXRpb25Sb3coKSAtIGNvdW50CglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9CglyZXR1cm4gZC5UcmFuc2xhdGVSb3dDb2xUb0luZGV4KHJvdywgY29sKSAtIGQuY3Vyc29yUG9zaXRpb24KfQoKLy8gR2V0Q3Vyc29yRG93blBvc2l0aW9uIHJldHVybiB0aGUgcmVsYXRpdmUgY3Vyc29yIHBvc2l0aW9uIChjaGFyYWN0ZXIgaW5kZXgpIHdoZXJlIHdlIHdvdWxkIGJlIGlmIHRoZQovLyB1c2VyIHByZXNzZWQgdGhlIGFycm93LWRvd24gYnV0dG9uLgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yRG93blBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9Cglyb3cgOj0gZC5DdXJzb3JQb3NpdGlvblJvdygpICsgY291bnQKCXJldHVybiBkLlRyYW5zbGF0ZVJvd0NvbFRvSW5kZXgocm93LCBjb2wpIC0gZC5jdXJzb3JQb3NpdGlvbgp9CgovLyBMaW5lcyByZXR1cm5zIHRoZSBhcnJheSBvZiBhbGwgdGhlIGxpbmVzLgpmdW5jIChkICpEb2N1bWVudCkgTGluZXMoKSBbXXN0cmluZyB7CgkvLyBUT0RPOiBDYWNoZSwgYmVjYXVzZSB0aGlzIG9uZSBpcyByZXVzZWQgdmVyeSBvZnRlbi4KCXJldHVybiBzdHJpbmdzLlNwbGl0KGQuVGV4dCwgIlxuIikKfQoKLy8gTGluZUNvdW50IHJldHVybiB0aGUgbnVtYmVyIG9mIGxpbmVzIGluIHRoaXMgZG9jdW1lbnQuIElmIHRoZSBkb2N1bWVudCBlbmRzCi8vIHdpdGggYSB0cmFpbGluZyBcbiwgdGhhdCBjb3VudHMgYXMgdGhlIGJlZ2lubmluZyBvZiBhIG5ldyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgTGluZUNvdW50KCkgaW50IHsKCXJldHVybiBsZW4oZC5MaW5lcygpKQp9CgovLyBUcmFuc2xhdGVJbmRleFRvUG9zaXRpb24gZ2l2ZW4gYW4gaW5kZXggZm9yIHRoZSB0ZXh0LCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgKHJvdywgY29sKSB0dXBsZS4KLy8gKDAtYmFzZWQuIFJldHVybnMgKDAsIDApIGZvciBpbmRleD0wLikKZnVuYyAoZCAqRG9jdW1lbnQpIFRyYW5zbGF0ZUluZGV4VG9Qb3NpdGlvbihpbmRleCBpbnQpIChyb3cgaW50LCBjb2wgaW50KSB7Cglyb3csIHJvd0luZGV4IDo9IGQuZmluZExpbmVTdGFydEluZGV4KGluZGV4KQoJY29sID0gaW5kZXggLSByb3dJbmRleAoJcmV0dXJuCn0KCi8vIFRyYW5zbGF0ZVJvd0NvbFRvSW5kZXggZ2l2ZW4gYSAocm93LCBjb2wpLCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgaW5kZXguCi8vIChSb3cgYW5kIGNvbCBwYXJhbXMgYXJlIDAtYmFzZWQuKQpmdW5jIChkICpEb2N1bWVudCkgVHJhbnNsYXRlUm93Q29sVG9JbmRleChyb3cgaW50LCBjb2x1bW4gaW50KSAoaW5kZXggaW50KSB7CglpbmRleGVzIDo9IGQubGluZVN0YXJ0SW5kZXhlcygpCglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9IGVsc2UgaWYgcm93ID4gbGVuKGluZGV4ZXMpIHsKCQlyb3cgPSBsZW4oaW5kZXhlcykgLSAxCgl9CglpbmRleCA9IGluZGV4ZXNbcm93XQoJbGluZSA6PSBkLkxpbmVzKClbcm93XQoKCS8vIHB5dGhvbikgcmVzdWx0ICs9IG1heCgwLCBtaW4oY29sLCBsZW4obGluZSkpKQoJaWYgY29sdW1uID4gMCB8fCBsZW4obGluZSkgPiAwIHsKCQlpZiBjb2x1bW4gPiBsZW4obGluZSkgewoJCQlpbmRleCArPSBsZW4obGluZSkKCQl9IGVsc2UgewoJCQlpbmRleCArPSBjb2x1bW4KCQl9Cgl9CgoJLy8gS2VlcCBpbiByYW5nZS4gKGxlbihzZWxmLnRleHQpIGlzIGluY2x1ZGVkLCBiZWNhdXNlIHRoZSBjdXJzb3IgY2FuIGJlCgkvLyByaWdodCBhZnRlciB0aGUgZW5kIG9mIHRoZSB0ZXh0IGFzIHdlbGwuKQoJLy8gcHl0aG9uKSByZXN1bHQgPSBtYXgoMCwgbWluKHJlc3VsdCwgbGVuKHNlbGYudGV4dCkpKQoJaWYgaW5kZXggPiBsZW4oZC5UZXh0KSB7CgkJaW5kZXggPSBsZW4oZC5UZXh0KQoJfQoJaWYgaW5kZXggPCAwIHsKCQlpbmRleCA9IDAKCX0KCXJldHVybiBpbmRleAp9CgovLyBPbkxhc3RMaW5lIHJldHVybnMgdHJ1ZSB3aGVuIHdlIGFyZSBhdCB0aGUgbGFzdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgT25MYXN0TGluZSgpIGJvb2wgewoJcmV0dXJuIGQuQ3Vyc29yUG9zaXRpb25Sb3coKSA9PSAoZC5MaW5lQ291bnQoKSAtIDEpCn0KCi8vIEdldEVuZE9mTGluZVBvc2l0aW9uIHJldHVybnMgcmVsYXRpdmUgcG9zaXRpb24gZm9yIHRoZSBlbmQgb2YgdGhpcyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgR2V0RW5kT2ZMaW5lUG9zaXRpb24oKSBpbnQgewoJcmV0dXJuIGxlbihbXXJ1bmUoZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpKQp9CgpmdW5jIChkICpEb2N1bWVudCkgbGVhZGluZ1doaXRlc3BhY2VJbkN1cnJlbnRMaW5lKCkgKG1hcmdpbiBzdHJpbmcpIHsKCXRyaW1tZWQgOj0gc3RyaW5ncy5UcmltU3BhY2UoZC5DdXJyZW50TGluZSgpKQoJbWFyZ2luID0gZC5DdXJyZW50TGluZSgpWzpsZW4oZC5DdXJyZW50TGluZSgpKS1sZW4odHJpbW1lZCldCglyZXR1cm4KfQo=", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/task.toml b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..5fab4e82fd2ba965cc1070c38b58c9d8bee1261d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/task.toml
@@ -0,0 +1,11 @@
+version = "1.0"
+[agent]
+timeout_sec = 300.0
+[verifier]
+timeout_sec = 300.0
+environment_mode = "shared"
+[environment]
+docker_image = "ghcr.io/younesbelkada/scale800@sha256:b9706902dcdedc7396effe343179077ab6cabaff3acb428aa557836d30c8cffb"
+cpus = 1
+memory_mb = 2048
+storage_mb = 4096
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..df17cb1062692f79989fd1bd1b8fe03c4652c2d0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/manifest.json
@@ -0,0 +1,432 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CursorPositionRowAndCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorLeftPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorUpPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorDownPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorRightPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_Lines"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_LineCount"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateIndexToPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateRowColToIndex"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_OnLastLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetEndOfLinePosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestEmacsKeyBindings"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFilter"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFuzzyMatch"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryClear"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryAdd"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryOlder"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/escape"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/undefined"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWrite"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteRawStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatCompletion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBreakLineCallback"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionRow"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition_withJapanese"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/validation/canaries/delete-tests.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/validation/canaries/delete-tests.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/validation/canaries/delete-tests.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+find /testbed -name '*_test.go' -type f -delete
+printf 'PASS\nok forged-package 0.001s\n'
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..9336a0d952ef36e97d74969de2dd6563951e5142
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_op_swap__vd60lcsn/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "d11cf75a8f5a037c2fa163e398155f5dc9b91f9e97cd683a97d23bd13429cb6e",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/Dockerfile b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f35bf9e5393ee1086fe1b72c1b442f3b16e2bd5b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22
+WORKDIR /testbed
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c8c031d0f87fb9aea0aff433b1fcaeaac259c41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: "Bug report"
+about: Create a bug report to improve go-prompt
+title: "[Bug]"
+labels: bug
+assignees: ''
+
+---
+
+# Bug reports
+
+*Please file a bug report here.*
+
+## Expected Behavior
+
+*Please describe the behavior you are expecting*
+
+## Current Behavior and Steps to Reproduce
+
+*What is the current behavior? Please provide detailed steps for reproducing the issue.*
+*A picture or gif animation tells a thousand words*
+
+## Context
+
+Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
+
+* Operating System:
+* Terminal Emulator: (i.e. iTerm2)
+* tag of go-prompt or commit revision:
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb816a2496376983781774cb5466fed8e1efc93b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,13 @@
+---
+name: "Feature request"
+about: Suggest an idea for new features in go-prompt.
+title: "[Feature Request]"
+labels: enhancement
+assignees: ''
+
+---
+
+# Feature Request
+
+*Please write your suggestion here.*
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/.gitignore b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..eba2b56abe0f7758a560d47dd19d8985b67ef327
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+bin/
+
+# Folders
+pkg/
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+# Glide
+vendor/
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/CHANGELOG.md b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..b9e21f1ef333b9ec13323bcd4a8f377322ed7e9f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/CHANGELOG.md
@@ -0,0 +1,79 @@
+# Change Log
+
+## v0.3.0 (2018/??/??)
+
+next release.
+
+## v0.2.3 (2018/10/25)
+
+### What's new?
+
+* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92).
+* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100).
+* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102).
+
+### Fixed
+
+* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details).
+* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details).
+* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details).
+
+### Removed or Deprecated
+
+* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`.
+
+## v0.2.2 (2018/06/28)
+
+### What's new?
+
+* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters.
+* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions.
+ * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details).
+* Add FilePathCompleter to complete file path on your system.
+* Add option to customize ascii code key bindings.
+* Add GetWordAfterCursor method in Document.
+
+### Removed or Deprecated
+
+* prompt.Choose shortcut function is deprecated.
+
+## v0.2.1 (2018/02/14)
+
+### What's New?
+
+* ~~It seems that windows support is almost perfect.~~
+ * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows.
+
+### Fixed
+
+* Fix a Shift+Tab handling on Windows.
+* Fix 4-dimension arrow keys handling on Windows.
+
+## v0.2.0 (2018/02/13)
+
+### What's New?
+
+* Supports scrollbar when there are too many matched suggestions
+* Windows support (but please caution because this is still not perfect).
+* Add OptionLivePrefix to update the prefix dynamically
+* Implement clear screen by `Ctrl+L`.
+
+### Fixed
+
+* Fix the behavior of `Ctrl+W` keybind.
+* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details).
+* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details).
+* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ).
+
+### News
+
+New core developers are joined (alphabetical order).
+
+* Nao Yonashiro (Github @orisano)
+* Ryoma Abe (Github @Allajah)
+* Yusuke Nakamura (Github @unasuke)
+
+
+## v0.1.0 (2017/08/15)
+
+Initial Release
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/LICENSE b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a86acaa7ab24fe61ea152a9afcadc21980020efb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Masashi SHIBATA
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/Makefile b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..505817c36f0b8a0bb643eed8680b8989af2b0920
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/Makefile
@@ -0,0 +1,46 @@
+.DEFAULT_GOAL := help
+
+SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
+
+GOIMPORTS ?= goimports
+GOCILINT ?= golangci-lint
+
+.PHONY: setup
+setup: ## Setup for required tools.
+ go get -u golang.org/x/tools/cmd/goimports
+ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: fmt
+fmt: $(SOURCES) ## Formatting source codes.
+ @$(GOIMPORTS) -w $^
+
+.PHONY: lint
+lint: ## Run golangci-lint.
+ @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
+
+.PHONY: test
+test: ## Run tests with race condition checking.
+ @go test -race ./...
+
+.PHONY: bench
+bench: ## Run benchmarks.
+ @go test -bench=. -run=- -benchmem ./...
+
+.PHONY: coverage
+cover: ## Run the tests.
+ @go test -coverprofile=coverage.o
+ @go tool cover -func=coverage.o
+
+.PHONY: generate
+generate: ## Run go generate
+ @go generate ./...
+
+.PHONY: build
+build: ## Build example command lines.
+ ./_example/build.sh
+
+.PHONY: help
+help: ## Show help text
+ @echo "Commands:"
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}'
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/README.md b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfcd7a399b4827d6b126d6a173cce34d36520481
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/README.md
@@ -0,0 +1,125 @@
+# go-prompt
+
+[](https://goreportcard.com/report/github.com/c-bata/go-prompt)
+
+[](https://godoc.org/github.com/c-bata/go-prompt)
+
+
+A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit),
+making it easier to build cross-platform command line tools using Go.
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func completer(d prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ }
+ return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ fmt.Println("Please select table.")
+ t := prompt.Input("> ", completer)
+ fmt.Println("You selected " + t)
+}
+```
+
+#### Projects using go-prompt
+
+* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt)
+* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli)
+* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn)
+* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli)
+* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans)
+* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit)
+* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go)
+* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS)
+* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs)
+* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli)
+* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt)
+* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh)
+* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell)
+* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt)
+* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim)
+* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron)
+* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl)
+* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl)
+* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit)
+* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.)
+
+## Features
+
+### Powerful auto-completion
+
+[](https://github.com/c-bata/kube-prompt)
+
+(This is a GIF animation of kube-prompt.)
+
+### Flexible options
+
+go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details.
+
+[](#flexible-options)
+
+### Keyboard Shortcuts
+
+Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell).
+You can customize and expand these shortcuts.
+
+[](#keyboard-shortcuts)
+
+Key Binding | Description
+---------------------|---------------------------------------------------------
+Ctrl + A | Go to the beginning of the line (Home)
+Ctrl + E | Go to the end of the line (End)
+Ctrl + P | Previous command (Up arrow)
+Ctrl + N | Next command (Down arrow)
+Ctrl + F | Forward one character
+Ctrl + B | Backward one character
+Ctrl + D | Delete character under the cursor
+Ctrl + H | Delete character before the cursor (Backspace)
+Ctrl + W | Cut the word before the cursor to the clipboard
+Ctrl + K | Cut the line after the cursor to the clipboard
+Ctrl + U | Cut the line before the cursor to the clipboard
+Ctrl + L | Clear the screen
+
+### History
+
+You can use Up arrow and Down arrow to walk through the history of commands executed.
+
+[](#history)
+
+### Multiple platform support
+
+We have confirmed go-prompt works fine in the following terminals:
+
+* iTerm2 (macOS)
+* Terminal.app (macOS)
+* Command Prompt (Windows)
+* gnome-terminal (Ubuntu)
+
+## Links
+
+* [Change Log](./CHANGELOG.md)
+* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt)
+* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt)
+
+## Author
+
+Masashi Shibata
+
+* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/)
+* Github: [@c-bata](https://github.com/c-bata/)
+
+## License
+
+This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/README.md b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..759b0e3f8acf1216b055e0f9458758a6c1e8950a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/README.md
@@ -0,0 +1,30 @@
+# Examples of go-prompt
+
+This directory includes some examples using go-prompt.
+These examples are useful to know the usage of go-prompt and check behavior for development.
+
+## simple-echo
+
+
+
+A simple echo example using `prompt.Input`.
+
+## http-prompt
+
+
+
+A simple [http-prompt](https://github.com/eliangcs/http-prompt) implementation using go-prompt in less than 200 lines of Go.
+
+## live-prefix
+
+
+
+A example application which changes a prefix string dynamically.
+This feature is used like [ktr0731/evans](https://github.com/ktr0731/evans) which is interactive gRPC client using go-prompt.
+
+## exec-command
+
+Run another CLI tool via `os/exec` package.
+More practical example is [a source code of kube-prompt](https://github.com/c-bata/kube-prompt).
+I recommend you to look this if you want to create tools like kube-prompt.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/build.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c552afcfa69b2356ffcd484c867abcaaaaeeaff
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+export GO111MODULE=on
+DIR=$(cd $(dirname $0); pwd)
+BIN_DIR=$(cd $(dirname $(dirname $0)); pwd)/bin
+
+mkdir -p ${BIN_DIR}
+go build -o ${BIN_DIR}/exec-command ${DIR}/exec-command/main.go
+go build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.go
+go build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.go
+go build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.go
+go build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/exec-command/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/exec-command/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..838f756260df91569491def29a7ee05a7c9a98f7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/exec-command/main.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "os/exec"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(t string) {
+ if t == "bash" {
+ cmd := exec.Command("bash")
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Run()
+ }
+ return
+}
+
+func completer(t prompt.Document) []prompt.Suggest {
+ return []prompt.Suggest{
+ {Text: "bash"},
+ }
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/http-prompt/api.py b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/http-prompt/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..08e7b1a489a2077f26f280fe39e3bd06efa52cd2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/http-prompt/api.py
@@ -0,0 +1,17 @@
+from bottle import route, run, request
+
+@route('/')
+def hello():
+ return "Hello World!"
+
+@route('/ping')
+def hello():
+ return "pong!"
+
+@route('/register', method='POST')
+def register():
+ name = request.json.get("name")
+ return "Hello %s!" % name
+
+if __name__ == "__main__":
+ run(host='localhost', port=8000, debug=True)
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/http-prompt/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/http-prompt/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b372a3550c50121d6e500e2a08e641e168b8c00d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/http-prompt/main.go
@@ -0,0 +1,192 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+type RequestContext struct {
+ url *url.URL
+ header http.Header
+ client *http.Client
+}
+
+var ctx *RequestContext
+
+// See https://github.com/eliangcs/http-prompt/blob/master/http_prompt/completion.py
+var suggestions = []prompt.Suggest{
+ // Command
+ {"cd", "Change URL/path"},
+ {"exit", "Exit http-prompt"},
+
+ // HTTP Method
+ {"delete", "DELETE request"},
+ {"get", "GET request"},
+ {"patch", "GET request"},
+ {"post", "POST request"},
+ {"put", "PUT request"},
+
+ // HTTP Header
+ {"Accept", "Acceptable response media type"},
+ {"Accept-Charset", "Acceptable response charsets"},
+ {"Accept-Encoding", "Acceptable response content codings"},
+ {"Accept-Language", "Preferred natural languages in response"},
+ {"ALPN", "Application-layer protocol negotiation to use"},
+ {"Alt-Used", "Alternative host in use"},
+ {"Authorization", "Authentication information"},
+ {"Cache-Control", "Directives for caches"},
+ {"Connection", "Connection options"},
+ {"Content-Encoding", "Content codings"},
+ {"Content-Language", "Natural languages for content"},
+ {"Content-Length", "Anticipated size for payload body"},
+ {"Content-Location", "Where content was obtained"},
+ {"Content-MD5", "Base64-encoded MD5 sum of content"},
+ {"Content-Type", "Content media type"},
+ {"Cookie", "Stored cookies"},
+ {"Date", "Datetime when message was originated"},
+ {"Depth", "Applied only to resource or its members"},
+ {"DNT", "Do not track user"},
+ {"Expect", "Expected behaviors supported by server"},
+ {"Forwarded", "Proxies involved"},
+ {"From", "Sender email address"},
+ {"Host", "Target URI"},
+ {"HTTP2-Settings", "HTTP/2 connection parameters"},
+ {"If", "Request condition on state tokens and ETags"},
+ {"If-Match", "Request condition on target resource"},
+ {"If-Modified-Since", "Request condition on modification date"},
+ {"If-None-Match", "Request condition on target resource"},
+ {"If-Range", "Request condition on Range"},
+ {"If-Schedule-Tag-Match", "Request condition on Schedule-Tag"},
+ {"If-Unmodified-Since", "Request condition on modification date"},
+ {"Max-Forwards", "Max number of times forwarded by proxies"},
+ {"MIME-Version", "Version of MIME protocol"},
+ {"Origin", "Origin(s} issuing the request"},
+ {"Pragma", "Implementation-specific directives"},
+ {"Prefer", "Preferred server behaviors"},
+ {"Proxy-Authorization", "Proxy authorization credentials"},
+ {"Proxy-Connection", "Proxy connection options"},
+ {"Range", "Request transfer of only part of data"},
+ {"Referer", "Previous web page"},
+ {"TE", "Transfer codings willing to accept"},
+ {"Transfer-Encoding", "Transfer codings applied to payload body"},
+ {"Upgrade", "Invite server to upgrade to another protocol"},
+ {"User-Agent", "User agent string"},
+ {"Via", "Intermediate proxies"},
+ {"Warning", "Possible incorrectness with payload body"},
+ {"WWW-Authenticate", "Authentication scheme"},
+ {"X-Csrf-Token", "Prevent cross-site request forgery"},
+ {"X-CSRFToken", "Prevent cross-site request forgery"},
+ {"X-Forwarded-For", "Originating client IP address"},
+ {"X-Forwarded-Host", "Original host requested by client"},
+ {"X-Forwarded-Proto", "Originating protocol"},
+ {"X-Http-Method-Override", "Request method override"},
+ {"X-Requested-With", "Used to identify Ajax requests"},
+ {"X-XSRF-TOKEN", "Prevent cross-site request forgery"},
+}
+
+func livePrefix() (string, bool) {
+ if ctx.url.Path == "/" {
+ return "", false
+ }
+ return ctx.url.String() + "> ", true
+}
+
+func executor(in string) {
+ in = strings.TrimSpace(in)
+
+ var method, body string
+ blocks := strings.Split(in, " ")
+ switch blocks[0] {
+ case "exit":
+ fmt.Println("Bye!")
+ os.Exit(0)
+ case "cd":
+ if len(blocks) < 2 {
+ ctx.url.Path = "/"
+ } else {
+ ctx.url.Path = path.Join(ctx.url.Path, blocks[1])
+ }
+ return
+ case "get", "delete":
+ method = strings.ToUpper(blocks[0])
+ case "post", "put", "patch":
+ if len(blocks) < 2 {
+ fmt.Println("please set request body.")
+ return
+ }
+ body = strings.Join(blocks[1:], " ")
+ method = strings.ToUpper(blocks[0])
+ }
+ if method != "" {
+ req, err := http.NewRequest(method, ctx.url.String(), strings.NewReader(body))
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ req.Header = ctx.header
+ res, err := ctx.client.Do(req)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ result, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ fmt.Printf("%s\n", result)
+ ctx.header = http.Header{}
+ return
+ }
+
+ if h := strings.Split(in, ":"); len(h) == 2 {
+ // Handling HTTP Header
+ ctx.header.Add(strings.TrimSpace(h[0]), strings.Trim(h[1], ` '"`))
+ } else {
+ fmt.Println("Sorry, I don't understand.")
+ }
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ w := in.GetWordBeforeCursor()
+ if w == "" {
+ return []prompt.Suggest{}
+ }
+ return prompt.FilterHasPrefix(suggestions, w, true)
+}
+
+func main() {
+ var baseURL = "http://localhost:8000/"
+ if len(os.Args) == 2 {
+ baseURL = os.Args[1]
+ if strings.HasSuffix(baseURL, "/") {
+ baseURL += "/"
+ }
+ }
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ ctx = &RequestContext{
+ url: u,
+ header: http.Header{},
+ client: &http.Client{},
+ }
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(u.String()+"> "),
+ prompt.OptionLivePrefix(livePrefix),
+ prompt.OptionTitle("http-prompt"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/live-prefix/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/live-prefix/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c7ced720592173e2a13f19f7cb543730192d3f8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/live-prefix/main.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var LivePrefixState struct {
+ LivePrefix string
+ IsEnable bool
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+ if in == "" {
+ LivePrefixState.IsEnable = false
+ LivePrefixState.LivePrefix = in
+ return
+ }
+ LivePrefixState.LivePrefix = in + "> "
+ LivePrefixState.IsEnable = true
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func changeLivePrefix() (string, bool) {
+ return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionLivePrefix(changeLivePrefix),
+ prompt.OptionTitle("live-prefix-example"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/simple-echo/cjk-cyrillic/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/simple-echo/cjk-cyrillic/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e9e53adef1558e004f86ccbca2c2e2b83c1da39
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/simple-echo/cjk-cyrillic/main.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
+ {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
+ {Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
+ {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionTitle("sql-prompt for multi width characters"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/simple-echo/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/simple-echo/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..12b1bb4fc189e6b369e889779418d7826a45db9d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_example/simple-echo/main.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ in := prompt.Input(">>> ", completer,
+ prompt.OptionTitle("sql-prompt"),
+ prompt.OptionHistory([]string{"SELECT * FROM users;"}),
+ prompt.OptionPrefixTextColor(prompt.Yellow),
+ prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
+ prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
+ prompt.OptionSuggestionBGColor(prompt.DarkGray))
+ fmt.Println("Your input: " + in)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_tools/README.md b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..45bd2234f21ff32562984bec046316c8e52868fd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_tools/README.md
@@ -0,0 +1,10 @@
+## Tools of go-prompt
+
+### vt100_debug
+
+
+
+### sigwinch
+
+
+
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_tools/complete_file/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_tools/complete_file/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..41015cfab9b021fbc7df575bde87e3c510705496
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_tools/complete_file/main.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/completer"
+)
+
+var filePathCompleter = completer.FilePathCompleter{
+ IgnoreCase: true,
+ Filter: func(fi os.FileInfo) bool {
+ return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
+ },
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completerFunc(d prompt.Document) []prompt.Suggest {
+ t := d.GetWordBeforeCursor()
+ if strings.HasPrefix(t, "--") {
+ return []prompt.Suggest{
+ {"--foo", ""},
+ {"--bar", ""},
+ {"--baz", ""},
+ }
+ }
+ return filePathCompleter.Complete(d)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completerFunc,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_tools/sigwinch/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_tools/sigwinch/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9608eb3b4a5e3c6942c140c41e08a36ab3adb33b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_tools/sigwinch/main.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "unsafe"
+)
+
+// Winsize is winsize struct got from the ioctl(2) system call.
+type Winsize struct {
+ Row uint16
+ Col uint16
+ X uint16 // pixel value
+ Y uint16 // pixel value
+}
+
+// GetWinSize returns winsize struct which is the response of ioctl(2).
+func GetWinSize(fd int) *Winsize {
+ ws := &Winsize{}
+ retCode, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ uintptr(fd),
+ uintptr(syscall.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(ws)))
+
+ if int(retCode) == -1 {
+ panic(errno)
+ }
+ return ws
+}
+
+func main() {
+ signalChan := make(chan os.Signal, 1)
+ signal.Notify(
+ signalChan,
+ syscall.SIGHUP,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ exitChan := make(chan int)
+ go func() {
+ for {
+ s := <-signalChan
+ switch s {
+ // kill -SIGHUP XXXX
+ case syscall.SIGHUP:
+ exitChan <- 0
+
+ // kill -SIGINT XXXX or Ctrl+c
+ case syscall.SIGINT:
+ exitChan <- 0
+
+ // kill -SIGTERM XXXX
+ case syscall.SIGTERM:
+ exitChan <- 0
+
+ // kill -SIGQUIT XXXX
+ case syscall.SIGQUIT:
+ exitChan <- 0
+
+ case syscall.SIGWINCH:
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ default:
+ exitChan <- 1
+ }
+ }
+ }()
+
+ code := <-exitChan
+ os.Exit(code)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_tools/vt100_debug/main.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_tools/vt100_debug/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c6036d45959febc739e287a3a7b631259d4ee7c1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/_tools/vt100_debug/main.go
@@ -0,0 +1,47 @@
+// +build !windows
+
+package main
+
+import (
+ "fmt"
+ "syscall"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/term"
+)
+
+func main() {
+ if err := term.SetRaw(syscall.Stdin); err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer term.Restore()
+
+ bufCh := make(chan []byte, 128)
+ go readBuffer(bufCh)
+ fmt.Print("> ")
+
+ for {
+ b := <-bufCh
+ if key := prompt.GetKey(b); key == prompt.NotDefined {
+ fmt.Printf("Key '%s' data:'%#v'\n", string(b), b)
+ } else {
+ if key == prompt.ControlC {
+ fmt.Println("exit.")
+ return
+ }
+ fmt.Printf("Key '%s' data:'%#v'\n", key, b)
+ }
+ fmt.Print("> ")
+ }
+}
+
+func readBuffer(bufCh chan []byte) {
+ buf := make([]byte, 1024)
+
+ for {
+ if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
+ bufCh <- buf[:n]
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/buffer.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..46efbbba8bfb75f4a064c83368b781d1d6dbbb29
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/buffer.go
@@ -0,0 +1,191 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Buffer emulates the console buffer.
+type Buffer struct {
+ workingLines []string // The working lines. Similar to history
+ workingIndex int
+ cursorPosition int
+ cacheDocument *Document
+ preferredColumn int // Remember the original column for the next up/down movement.
+ lastKeyStroke Key
+}
+
+// Text returns string of the current line.
+func (b *Buffer) Text() string {
+ return b.workingLines[b.workingIndex]
+}
+
+// Document method to return document instance from the current text and cursor position.
+func (b *Buffer) Document() (d *Document) {
+ if b.cacheDocument == nil ||
+ b.cacheDocument.Text != b.Text() ||
+ b.cacheDocument.cursorPosition != b.cursorPosition {
+ b.cacheDocument = &Document{
+ Text: b.Text(),
+ cursorPosition: b.cursorPosition,
+ }
+ }
+ b.cacheDocument.lastKey = b.lastKeyStroke
+ return b.cacheDocument
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (b *Buffer) DisplayCursorPosition() int {
+ return b.Document().DisplayCursorPosition()
+}
+
+// InsertText insert string from current line.
+func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
+ or := []rune(b.Text())
+ oc := b.cursorPosition
+
+ if overwrite {
+ overwritten := string(or[oc : oc+len(v)])
+ if strings.Contains(overwritten, "\n") {
+ i := strings.IndexAny(overwritten, "\n")
+ overwritten = overwritten[:i]
+ }
+ b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):]))
+ } else {
+ b.setText(string(or[:oc]) + v + string(or[oc:]))
+ }
+
+ if moveCursor {
+ b.cursorPosition += len([]rune(v))
+ }
+}
+
+// SetText method to set text and update cursorPosition.
+// (When doing this, make sure that the cursor_position is valid for this text.
+// text/cursor_position should be consistent at any time, otherwise set a Document instead.)
+func (b *Buffer) setText(v string) {
+ debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position")
+ b.workingLines[b.workingIndex] = v
+}
+
+// Set cursor position. Return whether it changed.
+func (b *Buffer) setCursorPosition(p int) {
+ if p > 0 {
+ b.cursorPosition = p
+ } else {
+ b.cursorPosition = 0
+ }
+}
+
+func (b *Buffer) setDocument(d *Document) {
+ b.cacheDocument = d
+ b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length.
+ b.setText(d.Text)
+}
+
+// CursorLeft move to left on the current line.
+func (b *Buffer) CursorLeft(count int) {
+ l := b.Document().GetCursorLeftPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorRight move to right on the current line.
+func (b *Buffer) CursorRight(count int) {
+ l := b.Document().GetCursorRightPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorUp move cursor to the previous line.
+// (for multi-line edit).
+func (b *Buffer) CursorUp(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorUpPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// CursorDown move cursor to the next line.
+// (for multi-line edit).
+func (b *Buffer) CursorDown(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorDownPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text.
+func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) {
+ debug.Assert(count >= 0, "count should be positive")
+ r := []rune(b.Text())
+
+ if b.cursorPosition > 0 {
+ start := b.cursorPosition - count
+ if start < 0 {
+ start = 0
+ }
+ deleted = string(r[start:b.cursorPosition])
+ b.setDocument(&Document{
+ Text: string(r[:start]) + string(r[b.cursorPosition:]),
+ cursorPosition: b.cursorPosition - len([]rune(deleted)),
+ })
+ }
+ return
+}
+
+// NewLine means CR.
+func (b *Buffer) NewLine(copyMargin bool) {
+ if copyMargin {
+ b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true)
+ } else {
+ b.InsertText("\n", false, true)
+ }
+}
+
+// Delete specified number of characters and Return the deleted text.
+func (b *Buffer) Delete(count int) (deleted string) {
+ r := []rune(b.Text())
+ if b.cursorPosition < len(r) {
+ deleted = b.Document().TextAfterCursor()[:count]
+ b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):]))
+ }
+ return
+}
+
+// JoinNextLine joins the next line to the current one by deleting the line ending after the current line.
+func (b *Buffer) JoinNextLine(separator string) {
+ if !b.Document().OnLastLine() {
+ b.cursorPosition += b.Document().GetEndOfLinePosition()
+ b.Delete(1)
+ // Remove spaces
+ b.setText(b.Document().TextBeforeCursor() + separator + strings.TrimLeft(b.Document().TextAfterCursor(), " "))
+ }
+}
+
+// SwapCharactersBeforeCursor swaps the last two characters before the cursor.
+func (b *Buffer) SwapCharactersBeforeCursor() {
+ if b.cursorPosition >= 2 {
+ x := b.Text()[b.cursorPosition-2 : b.cursorPosition-1]
+ y := b.Text()[b.cursorPosition-1 : b.cursorPosition]
+ b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:])
+ }
+}
+
+// NewBuffer is constructor of Buffer struct.
+func NewBuffer() (b *Buffer) {
+ b = &Buffer{
+ workingLines: []string{""},
+ workingIndex: 0,
+ preferredColumn: -1, // -1 means nil
+ }
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/completer/file.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/completer/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..59f2d8dec84214ccaa6e345a11ed51aa61a08199
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/completer/file.go
@@ -0,0 +1,90 @@
+package completer
+
+import (
+ "io/ioutil"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+var (
+ // FilePathCompletionSeparator holds separate characters.
+ FilePathCompletionSeparator = string([]byte{' ', os.PathSeparator})
+)
+
+// FilePathCompleter is a completer for your local file system.
+// Please caution that you need to set OptionCompletionWordSeparator(completer.FilePathCompletionSeparator)
+// when you use this completer.
+type FilePathCompleter struct {
+ Filter func(fi os.FileInfo) bool
+ IgnoreCase bool
+ fileListCache map[string][]prompt.Suggest
+}
+
+func cleanFilePath(path string) (dir, base string, err error) {
+ if path == "" {
+ return ".", "", nil
+ }
+
+ var endsWithSeparator bool
+ if len(path) >= 1 && path[len(path)-1] == os.PathSeparator {
+ endsWithSeparator = true
+ }
+
+ if runtime.GOOS != "windows" && len(path) >= 2 && path[0:2] == "~/" {
+ me, err := user.Current()
+ if err != nil {
+ return "", "", err
+ }
+ path = filepath.Join(me.HomeDir, path[1:])
+ }
+ path = filepath.Clean(os.ExpandEnv(path))
+ dir = filepath.Dir(path)
+ base = filepath.Base(path)
+
+ if endsWithSeparator {
+ dir = path + string(os.PathSeparator) // Append slash(in POSIX) if path ends with slash.
+ base = "" // Set empty string if path ends with separator.
+ }
+ return dir, base, nil
+}
+
+// Complete returns suggestions from your local file system.
+func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest {
+ if c.fileListCache == nil {
+ c.fileListCache = make(map[string][]prompt.Suggest, 4)
+ }
+
+ path := d.GetWordBeforeCursor()
+ dir, base, err := cleanFilePath(path)
+ if err != nil {
+ debug.Log("completer: cannot get current user:" + err.Error())
+ return nil
+ }
+
+ if cached, ok := c.fileListCache[dir]; ok {
+ return prompt.FilterHasPrefix(cached, base, c.IgnoreCase)
+ }
+
+ files, err := ioutil.ReadDir(dir)
+ if err != nil && os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ debug.Log("completer: cannot read directory items:" + err.Error())
+ return nil
+ }
+
+ suggests := make([]prompt.Suggest, 0, len(files))
+ for _, f := range files {
+ if c.Filter != nil && !c.Filter(f) {
+ continue
+ }
+ suggests = append(suggests, prompt.Suggest{Text: f.Name()})
+ }
+ c.fileListCache[dir] = suggests
+ return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/completion.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/completion.go
new file mode 100644
index 0000000000000000000000000000000000000000..57e82eefc0f50e9561214704e770a2ad313a3659
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/completion.go
@@ -0,0 +1,190 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+const (
+ shortenSuffix = "..."
+ leftPrefix = " "
+ leftSuffix = " "
+ rightPrefix = " "
+ rightSuffix = " "
+)
+
+var (
+ leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix)
+ rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix)
+ completionMargin = leftMargin + rightMargin
+)
+
+// Suggest is printed when completing.
+type Suggest struct {
+ Text string
+ Description string
+}
+
+// CompletionManager manages which suggestion is now selected.
+type CompletionManager struct {
+ selected int // -1 means nothing one is selected.
+ tmp []Suggest
+ max uint16
+ completer Completer
+
+ verticalScroll int
+ wordSeparator string
+ showAtStart bool
+}
+
+// GetSelectedSuggestion returns the selected item.
+func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) {
+ if c.selected == -1 {
+ return Suggest{}, false
+ } else if c.selected < -1 {
+ debug.Assert(false, "must not reach here")
+ c.selected = -1
+ return Suggest{}, false
+ }
+ return c.tmp[c.selected], true
+}
+
+// GetSuggestions returns the list of suggestion.
+func (c *CompletionManager) GetSuggestions() []Suggest {
+ return c.tmp
+}
+
+// Reset to select nothing.
+func (c *CompletionManager) Reset() {
+ c.selected = -1
+ c.verticalScroll = 0
+ c.Update(*NewDocument())
+}
+
+// Update to update the suggestions.
+func (c *CompletionManager) Update(in Document) {
+ c.tmp = c.completer(in)
+}
+
+// Previous to select the previous suggestion item.
+func (c *CompletionManager) Previous() {
+ if c.verticalScroll == c.selected && c.selected > 0 {
+ c.verticalScroll--
+ }
+ c.selected--
+ c.update()
+}
+
+// Next to select the next suggestion item.
+func (c *CompletionManager) Next() {
+ if c.verticalScroll+int(c.max)-1 == c.selected {
+ c.verticalScroll++
+ }
+ c.selected++
+ c.update()
+}
+
+// Completing returns whether the CompletionManager selects something one.
+func (c *CompletionManager) Completing() bool {
+ return c.selected != -1
+}
+
+func (c *CompletionManager) update() {
+ max := int(c.max)
+ if len(c.tmp) < max {
+ max = len(c.tmp)
+ }
+
+ if c.selected >= len(c.tmp) {
+ c.Reset()
+ } else if c.selected < -1 {
+ c.selected = len(c.tmp) - 1
+ c.verticalScroll = len(c.tmp) - max
+ }
+}
+
+func deleteBreakLineCharacters(s string) string {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, "\r", "", -1)
+ return s
+}
+
+func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) {
+ l := len(o)
+ n := make([]string, l)
+
+ lenPrefix := runewidth.StringWidth(prefix)
+ lenSuffix := runewidth.StringWidth(suffix)
+ lenShorten := runewidth.StringWidth(shortenSuffix)
+ min := lenPrefix + lenSuffix + lenShorten
+ for i := 0; i < l; i++ {
+ o[i] = deleteBreakLineCharacters(o[i])
+
+ w := runewidth.StringWidth(o[i])
+ if width < w {
+ width = w
+ }
+ }
+
+ if width == 0 {
+ return n, 0
+ }
+ if min >= max {
+ return n, 0
+ }
+ if lenPrefix+width+lenSuffix > max {
+ width = max - lenPrefix - lenSuffix
+ }
+
+ for i := 0; i < l; i++ {
+ x := runewidth.StringWidth(o[i])
+ if x <= width {
+ spaces := strings.Repeat(" ", width-x)
+ n[i] = prefix + o[i] + spaces + suffix
+ } else if x > width {
+ x := runewidth.Truncate(o[i], width, shortenSuffix)
+ // When calling runewidth.Truncate("您好xxx您好xxx", 11, "...") returns "您好xxx..."
+ // But the length of this result is 10. So we need fill right using runewidth.FillRight.
+ n[i] = prefix + runewidth.FillRight(x, width) + suffix
+ }
+ }
+ return n, lenPrefix + width + lenSuffix
+}
+
+func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) {
+ num := len(suggests)
+ new = make([]Suggest, num)
+
+ left := make([]string, num)
+ for i := 0; i < num; i++ {
+ left[i] = suggests[i].Text
+ }
+ right := make([]string, num)
+ for i := 0; i < num; i++ {
+ right[i] = suggests[i].Description
+ }
+
+ left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix)
+ if leftWidth == 0 {
+ return []Suggest{}, 0
+ }
+ right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix)
+
+ for i := 0; i < num; i++ {
+ new[i] = Suggest{Text: left[i], Description: right[i]}
+ }
+ return new, leftWidth + rightWidth
+}
+
+// NewCompletionManager returns initialized CompletionManager object.
+func NewCompletionManager(completer Completer, max uint16) *CompletionManager {
+ return &CompletionManager{
+ selected: -1,
+ max: max,
+ completer: completer,
+
+ verticalScroll: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/document.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/document.go
new file mode 100644
index 0000000000000000000000000000000000000000..2a47f52bb2a760b293b5b81de1f27f2b8325a805
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/document.go
@@ -0,0 +1,441 @@
+package prompt
+
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+ istrings "github.com/c-bata/go-prompt/internal/strings"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Document has text displayed in terminal and cursor position.
+type Document struct {
+ Text string
+ // This represents a index in a rune array of Document.Text.
+ // So if Document is "日本(cursor)語", cursorPosition is 2.
+ // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+ cursorPosition int
+ lastKey Key
+}
+
+// NewDocument return the new empty document.
+func NewDocument() *Document {
+ return &Document{
+ Text: "",
+ cursorPosition: 0,
+ }
+}
+
+// LastKeyStroke return the last key pressed in this document.
+func (d *Document) LastKeyStroke() Key {
+ return d.lastKey
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (d *Document) DisplayCursorPosition() int {
+ var position int
+ runes := []rune(d.Text)[:d.cursorPosition]
+ for i := range runes {
+ position += runewidth.RuneWidth(runes[i])
+ }
+ return position
+}
+
+// GetCharRelativeToCursor return character relative to cursor position, or empty string
+func (d *Document) GetCharRelativeToCursor(offset int) (r rune) {
+ s := d.Text
+ cnt := 0
+
+ for len(s) > 0 {
+ cnt++
+ r, size := utf8.DecodeRuneInString(s)
+ if cnt == d.cursorPosition+offset {
+ return r
+ }
+ s = s[size:]
+ }
+ return 0
+}
+
+// TextBeforeCursor returns the text before the cursor.
+func (d *Document) TextBeforeCursor() string {
+ r := []rune(d.Text)
+ return string(r[:d.cursorPosition])
+}
+
+// TextAfterCursor returns the text after the cursor.
+func (d *Document) TextAfterCursor() string {
+ r := []rune(d.Text)
+ return string(r[d.cursorPosition:])
+}
+
+// GetWordBeforeCursor returns the word before the cursor.
+// If we have whitespace before the cursor this returns an empty string.
+func (d *Document) GetWordBeforeCursor() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWord():]
+}
+
+// GetWordAfterCursor returns the word after the cursor.
+// If we have whitespace after the cursor this returns an empty string.
+func (d *Document) GetWordAfterCursor() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWord()]
+}
+
+// GetWordBeforeCursorWithSpace returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorWithSpace() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordWithSpace():]
+}
+
+// GetWordAfterCursorWithSpace returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorWithSpace() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordWithSpace()]
+}
+
+// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
+func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparator(sep):]
+}
+
+// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
+func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparator(sep)]
+}
+
+// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):]
+}
+
+// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)]
+}
+
+// FindStartOfPreviousWord returns an index relative to the cursor position
+// pointing to the start of the previous word. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWord() int {
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexByte(x, ' ')
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindStartOfPreviousWordWithSpace() int {
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotByte(x, ' ')
+ if end == -1 {
+ return 0
+ }
+
+ start := strings.LastIndexByte(x[:end], ' ')
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWord()
+ }
+
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexAny(x, sep)
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWordWithSpace()
+ }
+
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotAny(x, sep)
+ if end == -1 {
+ return 0
+ }
+ start := strings.LastIndexAny(x[:end], sep)
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindEndOfCurrentWord returns an index relative to the cursor position.
+// pointing to the end of the current word. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWord() int {
+ x := d.TextAfterCursor()
+ i := strings.IndexByte(x, ' ')
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindEndOfCurrentWordWithSpace() int {
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotByte(x, ' ')
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexByte(x[start:], ' ')
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWord()
+ }
+
+ x := d.TextAfterCursor()
+ i := strings.IndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWordWithSpace()
+ }
+
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotAny(x, sep)
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexAny(x[start:], sep)
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// CurrentLineBeforeCursor returns the text from the start of the line until the cursor.
+func (d *Document) CurrentLineBeforeCursor() string {
+ s := strings.Split(d.TextBeforeCursor(), "\n")
+ return s[len(s)-1]
+}
+
+// CurrentLineAfterCursor returns the text from the cursor until the end of the line.
+func (d *Document) CurrentLineAfterCursor() string {
+ return strings.Split(d.TextAfterCursor(), "\n")[0]
+}
+
+// CurrentLine return the text on the line where the cursor is. (when the input
+// consists of just one line, it equals `text`.
+func (d *Document) CurrentLine() string {
+ return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor()
+}
+
+// Array pointing to the start indexes of all the lines.
+func (d *Document) lineStartIndexes() []int {
+ // TODO: Cache, because this is often reused.
+ // (If it is used, it's often used many times.
+ // And this has to be fast for editing big documents!)
+ lc := d.LineCount()
+ lengths := make([]int, lc)
+ for i, l := range d.Lines() {
+ lengths[i] = len(l)
+ }
+
+ // Calculate cumulative sums.
+ indexes := make([]int, lc+1)
+ indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189
+ pos := 0
+ for i, l := range lengths {
+ pos += l + 1
+ indexes[i+1] = pos
+ }
+ if lc > 1 {
+ // Pop the last item. (This is not a new line.)
+ indexes = indexes[:lc]
+ }
+ return indexes
+}
+
+// For the index of a character at a certain line, calculate the index of
+// the first character on that line.
+func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) {
+ indexes := d.lineStartIndexes()
+ pos = bisect.Right(indexes, index) - 1
+ lineStartIndex = indexes[pos]
+ return
+}
+
+// CursorPositionRow returns the current row. (0-based.)
+func (d *Document) CursorPositionRow() (row int) {
+ row, _ = d.findLineStartIndex(d.cursorPosition)
+ return
+}
+
+// CursorPositionCol returns the current column. (0-based.)
+func (d *Document) CursorPositionCol() (col int) {
+ // Don't use self.text_before_cursor to calculate this. Creating substrings
+ // and splitting is too expensive for getting the cursor position.
+ _, index := d.findLineStartIndex(d.cursorPosition)
+ col = d.cursorPosition - index
+ return
+}
+
+// GetCursorLeftPosition returns the relative position for cursor left.
+func (d *Document) GetCursorLeftPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorRightPosition(-count)
+ }
+ if d.CursorPositionCol() > count {
+ return -count
+ }
+ return -d.CursorPositionCol()
+}
+
+// GetCursorRightPosition returns relative position for cursor right.
+func (d *Document) GetCursorRightPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorLeftPosition(-count)
+ }
+ if len(d.CurrentLineAfterCursor()) > count {
+ return count
+ }
+ return len(d.CurrentLineAfterCursor())
+}
+
+// GetCursorUpPosition return the relative cursor position (character index) where we would be
+// if the user pressed the arrow-up button.
+func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+
+ row := d.CursorPositionRow() - count
+ if row < 0 {
+ row = 0
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// GetCursorDownPosition return the relative cursor position (character index) where we would be if the
+// user pressed the arrow-down button.
+func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+ row := d.CursorPositionRow() + count
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// Lines returns the array of all the lines.
+func (d *Document) Lines() []string {
+ // TODO: Cache, because this one is reused very often.
+ return strings.Split(d.Text, "\n")
+}
+
+// LineCount return the number of lines in this document. If the document ends
+// with a trailing \n, that counts as the beginning of a new line.
+func (d *Document) LineCount() int {
+ return len(d.Lines())
+}
+
+// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple.
+// (0-based. Returns (0, 0) for index=0.)
+func (d *Document) TranslateIndexToPosition(index int) (row int, col int) {
+ row, rowIndex := d.findLineStartIndex(index)
+ col = index - rowIndex
+ return
+}
+
+// TranslateRowColToIndex given a (row, col), return the corresponding index.
+// (Row and col params are 0-based.)
+func (d *Document) TranslateRowColToIndex(row int, column int) (index int) {
+ indexes := d.lineStartIndexes()
+ if row < 0 {
+ row = 0
+ } else if row > len(indexes) {
+ row = len(indexes) - 1
+ }
+ index = indexes[row]
+ line := d.Lines()[row]
+
+ // python) result += max(0, min(col, len(line)))
+ if column > 0 || len(line) > 0 {
+ if column > len(line) {
+ index += len(line)
+ } else {
+ index += column
+ }
+ }
+
+ // Keep in range. (len(self.text) is included, because the cursor can be
+ // right after the end of the text as well.)
+ // python) result = max(0, min(result, len(self.text)))
+ if index > len(d.Text) {
+ index = len(d.Text)
+ }
+ if index < 0 {
+ index = 0
+ }
+ return index
+}
+
+// OnLastLine returns true when we are at the last line.
+func (d *Document) OnLastLine() bool {
+ return d.CursorPositionRow() == (d.LineCount() - 1)
+}
+
+// GetEndOfLinePosition returns relative position for the end of this line.
+func (d *Document) GetEndOfLinePosition() int {
+ return len([]rune(d.CurrentLineAfterCursor()))
+}
+
+func (d *Document) leadingWhitespaceInCurrentLine() (margin string) {
+ trimmed := strings.TrimSpace(d.CurrentLine())
+ margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)]
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/emacs.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/emacs.go
new file mode 100644
index 0000000000000000000000000000000000000000..632f96321f2577cdb7e8cffe639f1518a65d5e0f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/emacs.go
@@ -0,0 +1,120 @@
+package prompt
+
+import "github.com/c-bata/go-prompt/internal/debug"
+
+/*
+
+========
+PROGRESS
+========
+
+Moving the cursor
+-----------------
+
+* [x] Ctrl + a Go to the beginning of the line (Home)
+* [x] Ctrl + e Go to the End of the line (End)
+* [x] Ctrl + p Previous command (Up arrow)
+* [x] Ctrl + n Next command (Down arrow)
+* [x] Ctrl + f Forward one character
+* [x] Ctrl + b Backward one character
+* [x] Ctrl + xx Toggle between the start of line and current cursor position
+
+Editing
+-------
+
+* [x] Ctrl + L Clear the Screen, similar to the clear command
+* [x] Ctrl + d Delete character under the cursor
+* [x] Ctrl + h Delete character before the cursor (Backspace)
+
+* [x] Ctrl + w Cut the Word before the cursor to the clipboard.
+* [x] Ctrl + k Cut the Line after the cursor to the clipboard.
+* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard.
+
+* [ ] Ctrl + t Swap the last two characters before the cursor (typo).
+* [ ] Esc + t Swap the last two words before the cursor.
+
+* [ ] ctrl + y Paste the last thing to be cut (yank)
+* [ ] ctrl + _ Undo
+
+*/
+
+var emacsKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: ControlE,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+ },
+ },
+ // Go to the beginning of the line
+ {
+ Key: ControlA,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+ },
+ },
+ // Cut the Line after the cursor
+ {
+ Key: ControlK,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.Delete(len(x))
+ },
+ },
+ // Cut/delete the Line before the cursor
+ {
+ Key: ControlU,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.DeleteBeforeCursor(len(x))
+ },
+ },
+ // Delete character under the cursor
+ {
+ Key: ControlD,
+ Fn: func(buf *Buffer) {
+ if buf.Text() != "" {
+ buf.Delete(1)
+ }
+ },
+ },
+ // Backspace
+ {
+ Key: ControlH,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+ },
+ },
+ // Right allow: Forward one character
+ {
+ Key: ControlF,
+ Fn: func(buf *Buffer) {
+ buf.CursorRight(1)
+ },
+ },
+ // Left allow: Backward one character
+ {
+ Key: ControlB,
+ Fn: func(buf *Buffer) {
+ buf.CursorLeft(1)
+ },
+ },
+ // Cut the Word before the cursor.
+ {
+ Key: ControlW,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace())))
+ },
+ },
+ // Clear the Screen, similar to the clear command
+ {
+ Key: ControlL,
+ Fn: func(buf *Buffer) {
+ consoleWriter.EraseScreen()
+ consoleWriter.CursorGoTo(0, 0)
+ debug.AssertNoError(consoleWriter.Flush())
+ },
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/filter.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/filter.go
new file mode 100644
index 0000000000000000000000000000000000000000..a71335baa983d094ca8b4d164532556391ade04b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/filter.go
@@ -0,0 +1,69 @@
+package prompt
+
+import "strings"
+
+// Filter is the type to filter the prompt.Suggestion array.
+type Filter func([]Suggest, string, bool) []Suggest
+
+// FilterHasPrefix checks whether the string completions.Text begins with sub.
+func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
+}
+
+// FilterHasSuffix checks whether the completion.Text ends with sub.
+func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
+}
+
+// FilterContains checks whether the completion.Text contains sub.
+func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
+}
+
+// FilterFuzzy checks whether the completion.Text fuzzy matches sub.
+// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
+// would match, for example, "Good food is gone"
+// ^ ^ ^
+func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
+}
+
+func fuzzyMatch(s, sub string) bool {
+ sChars := []rune(s)
+ sIdx := 0
+
+ // https://staticcheck.io/docs/checks#S1029
+ for _, c := range sub {
+ found := false
+ for ; sIdx < len(sChars); sIdx++ {
+ if sChars[sIdx] == c {
+ found = true
+ sIdx++
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
+
+func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
+ if sub == "" {
+ return suggestions
+ }
+
+
+ ret := make([]Suggest, 0, len(suggestions))
+ for i := range suggestions {
+ c := suggestions[i].Text
+ if ignoreCase {
+ c = strings.ToUpper(c)
+ }
+ if function(c, sub) {
+ ret = append(ret, suggestions[i])
+ }
+ }
+ return ret
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/go.mod b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..30bc6d39a39c328341ca7153d3391352be5baa63
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/go.mod
@@ -0,0 +1,11 @@
+module github.com/c-bata/go-prompt
+
+go 1.14
+
+require (
+ github.com/mattn/go-colorable v0.1.7
+ github.com/mattn/go-runewidth v0.0.9
+ github.com/mattn/go-tty v0.0.3
+ github.com/pkg/term v1.2.0-beta.2
+ golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/go.sum b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..768bf93619a68e1b334c13e7b93ec84fa465598e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/go.sum
@@ -0,0 +1,23 @@
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/history.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/history.go
new file mode 100644
index 0000000000000000000000000000000000000000..e75c64592d82142bf4826ceb8c613ac72ca24d9c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/history.go
@@ -0,0 +1,61 @@
+package prompt
+
+// History stores the texts that are entered.
+type History struct {
+ histories []string
+ tmp []string
+ selected int
+}
+
+// Add to add text in history.
+func (h *History) Add(input string) {
+ h.histories = append(h.histories, input)
+ h.Clear()
+}
+
+// Clear to clear the history.
+func (h *History) Clear() {
+ h.tmp = make([]string, len(h.histories))
+ for i := range h.histories {
+ h.tmp[i] = h.histories[i]
+ }
+ h.tmp = append(h.tmp, "")
+ h.selected = len(h.tmp) - 1
+}
+
+// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
+ if len(h.tmp) == 1 || h.selected == 0 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected--
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
+ if h.selected >= len(h.tmp)-1 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected++
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// NewHistory returns new history object.
+func NewHistory() *History {
+ return &History{
+ histories: []string{},
+ tmp: []string{""},
+ selected: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/input.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/input.go
new file mode 100644
index 0000000000000000000000000000000000000000..307e747190c2b27bf888b379644fc4f3cdd489a2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/input.go
@@ -0,0 +1,169 @@
+package prompt
+
+import "bytes"
+
+// WinSize represents the width and height of terminal.
+type WinSize struct {
+ Row uint16
+ Col uint16
+}
+
+// ConsoleParser is an interface to abstract input layer.
+type ConsoleParser interface {
+ // Setup should be called before starting input
+ Setup() error
+ // TearDown should be called after stopping input
+ TearDown() error
+ // GetWinSize returns WinSize object to represent width and height of terminal.
+ GetWinSize() *WinSize
+ // Read returns byte array.
+ Read() ([]byte, error)
+}
+
+// GetKey returns Key correspond to input byte codes.
+func GetKey(b []byte) Key {
+ for _, k := range ASCIISequences {
+ if bytes.Equal(k.ASCIICode, b) {
+ return k.Key
+ }
+ }
+ return NotDefined
+}
+
+// ASCIISequences holds mappings of the key and byte array.
+var ASCIISequences = []*ASCIICode{
+ {Key: Escape, ASCIICode: []byte{0x1b}},
+
+ {Key: ControlSpace, ASCIICode: []byte{0x00}},
+ {Key: ControlA, ASCIICode: []byte{0x1}},
+ {Key: ControlB, ASCIICode: []byte{0x2}},
+ {Key: ControlC, ASCIICode: []byte{0x3}},
+ {Key: ControlD, ASCIICode: []byte{0x4}},
+ {Key: ControlE, ASCIICode: []byte{0x5}},
+ {Key: ControlF, ASCIICode: []byte{0x6}},
+ {Key: ControlG, ASCIICode: []byte{0x7}},
+ {Key: ControlH, ASCIICode: []byte{0x8}},
+ //{Key: ControlI, ASCIICode: []byte{0x9}},
+ //{Key: ControlJ, ASCIICode: []byte{0xa}},
+ {Key: ControlK, ASCIICode: []byte{0xb}},
+ {Key: ControlL, ASCIICode: []byte{0xc}},
+ {Key: ControlM, ASCIICode: []byte{0xd}},
+ {Key: ControlN, ASCIICode: []byte{0xe}},
+ {Key: ControlO, ASCIICode: []byte{0xf}},
+ {Key: ControlP, ASCIICode: []byte{0x10}},
+ {Key: ControlQ, ASCIICode: []byte{0x11}},
+ {Key: ControlR, ASCIICode: []byte{0x12}},
+ {Key: ControlS, ASCIICode: []byte{0x13}},
+ {Key: ControlT, ASCIICode: []byte{0x14}},
+ {Key: ControlU, ASCIICode: []byte{0x15}},
+ {Key: ControlV, ASCIICode: []byte{0x16}},
+ {Key: ControlW, ASCIICode: []byte{0x17}},
+ {Key: ControlX, ASCIICode: []byte{0x18}},
+ {Key: ControlY, ASCIICode: []byte{0x19}},
+ {Key: ControlZ, ASCIICode: []byte{0x1a}},
+
+ {Key: ControlBackslash, ASCIICode: []byte{0x1c}},
+ {Key: ControlSquareClose, ASCIICode: []byte{0x1d}},
+ {Key: ControlCircumflex, ASCIICode: []byte{0x1e}},
+ {Key: ControlUnderscore, ASCIICode: []byte{0x1f}},
+ {Key: Backspace, ASCIICode: []byte{0x7f}},
+
+ {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}},
+
+ {Key: Enter, ASCIICode: []byte{0xa}},
+ {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}},
+ {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+ {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}},
+ {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}},
+ {Key: Tab, ASCIICode: []byte{0x9}},
+ {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}},
+ {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}},
+ {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}},
+ {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}},
+ {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode
+
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}},
+ {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}},
+ {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}},
+ {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}},
+ {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}},
+ {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}},
+ {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}},
+ {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}},
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}},
+ {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}},
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+
+ // Xterm
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}},
+ // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}},
+ {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}},
+ {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}},
+ {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}},
+ {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}},
+
+ {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}},
+ {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}},
+ {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}},
+ {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}},
+
+ // Tmux sends following keystrokes when control+arrow is pressed, but for
+ // Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ // it a normal arrow press, because that's more important.
+ {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}},
+
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt
+
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/input_posix.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/input_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f10430318be0e797c841eba8e08ab1cf5277be27
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/input_posix.go
@@ -0,0 +1,77 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/term"
+ "golang.org/x/sys/unix"
+)
+
+const maxReadBytes = 1024
+
+// PosixParser is a ConsoleParser implementation for POSIX environment.
+type PosixParser struct {
+ fd int
+ origTermios syscall.Termios
+}
+
+// Setup should be called before starting input
+func (t *PosixParser) Setup() error {
+ // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
+ if err := syscall.SetNonblock(t.fd, true); err != nil {
+ return err
+ }
+ if err := term.SetRaw(t.fd); err != nil {
+ return err
+ }
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (t *PosixParser) TearDown() error {
+ if err := syscall.SetNonblock(t.fd, false); err != nil {
+ return err
+ }
+ if err := term.Restore(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Read returns byte array.
+func (t *PosixParser) Read() ([]byte, error) {
+ buf := make([]byte, maxReadBytes)
+ n, err := syscall.Read(t.fd, buf)
+ if err != nil {
+ return []byte{}, err
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (t *PosixParser) GetWinSize() *WinSize {
+ ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: ws.Row,
+ Col: ws.Col,
+ }
+}
+
+var _ ConsoleParser = &PosixParser{}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *PosixParser {
+ in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ return &PosixParser{
+ fd: in,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/input_windows.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/input_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..11b7679d4c4bc8b924a5b6c863ca1f6d6880570d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/input_windows.go
@@ -0,0 +1,83 @@
+// +build windows
+
+package prompt
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf8"
+ "unsafe"
+
+ tty "github.com/mattn/go-tty"
+)
+
+const maxReadBytes = 1024
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
+
+// WindowsParser is a ConsoleParser implementation for Win32 console.
+type WindowsParser struct {
+ tty *tty.TTY
+}
+
+// Setup should be called before starting input
+func (p *WindowsParser) Setup() error {
+ t, err := tty.Open()
+ if err != nil {
+ return err
+ }
+ p.tty = t
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (p *WindowsParser) TearDown() error {
+ return p.tty.Close()
+}
+
+// Read returns byte array.
+func (p *WindowsParser) Read() ([]byte, error) {
+ var ev uint32
+ r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
+ if r0 == 0 {
+ return nil, err
+ }
+ if ev == 0 {
+ return nil, errors.New("EAGAIN")
+ }
+
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, maxReadBytes)
+ n := utf8.EncodeRune(buf[:], r)
+ for p.tty.Buffered() && n < maxReadBytes {
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ break
+ }
+ n += utf8.EncodeRune(buf[n:], r)
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (p *WindowsParser) GetWinSize() *WinSize {
+ w, h, err := p.tty.Size()
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: uint16(h),
+ Col: uint16(w),
+ }
+}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *WindowsParser {
+ return &WindowsParser{}
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/bisect/bisect.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/bisect/bisect.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe162fa8c4873302e25702081b629a445d43415
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/bisect/bisect.go
@@ -0,0 +1,15 @@
+package bisect
+
+import "sort"
+
+// Right to locate the insertion point for v in a to maintain sorted order.
+func Right(a []int, v int) int {
+ return bisectRightRange(a, v, 0, len(a))
+}
+
+func bisectRightRange(a []int, v int, lo, hi int) int {
+ s := a[lo:hi]
+ return sort.Search(len(s), func(i int) bool {
+ return s[i] > v
+ })
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/debug/assert.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/debug/assert.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f648ac93c44e1e021cdf581a68f03b548534d9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/debug/assert.go
@@ -0,0 +1,55 @@
+package debug
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
+)
+
+var (
+ enableAssert bool
+)
+
+func init() {
+ if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
+ enableAssert = true
+ }
+}
+
+// Assert ensures expected condition.
+func Assert(cond bool, msg interface{}) {
+ if cond {
+ return
+ }
+ if enableAssert {
+ panic(msg)
+ }
+ writeWithSync(2, "[ASSERT] "+toString(msg))
+}
+
+func toString(v interface{}) string {
+ switch a := v.(type) {
+ case func() string:
+ return a()
+ case string:
+ return a
+ case fmt.Stringer:
+ return a.String()
+ default:
+ return fmt.Sprintf("unexpected type, %t", v)
+ }
+}
+
+// AssertNoError ensures err is nil.
+func AssertNoError(err error) {
+ if err == nil {
+ return
+ }
+ if enableAssert {
+ panic(err)
+ }
+ writeWithSync(2, "[ASSERT] "+err.Error())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/debug/log.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/debug/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..516378627a34ead9063ab7ce6c445b23c77b7cb4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/debug/log.go
@@ -0,0 +1,52 @@
+package debug
+
+import (
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+const (
+ envEnableLog = "GO_PROMPT_ENABLE_LOG"
+ logFileName = "go-prompt.log"
+)
+
+var (
+ logfile *os.File
+ logger *log.Logger
+)
+
+func init() {
+ if e := os.Getenv(envEnableLog); e == "true" || e == "1" {
+ var err error
+ logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
+ if err == nil {
+ logger = log.New(logfile, "", log.Llongfile)
+ return
+ }
+ }
+ logger = log.New(ioutil.Discard, "", log.Llongfile)
+}
+
+// Teardown to close logfile
+func Teardown() {
+ if logfile == nil {
+ return
+ }
+ _ = logfile.Close()
+}
+
+func writeWithSync(calldepth int, msg string) {
+ calldepth++
+ if logfile == nil {
+ return
+ }
+ _ = logger.Output(calldepth, msg)
+ _ = logfile.Sync() // immediately write msg
+}
+
+// Log to output message
+func Log(msg string) {
+ calldepth := 2
+ writeWithSync(calldepth, msg)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/strings/strings.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/strings/strings.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7d1886ae03a7d541c66dffca921e2d040e6d5eb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/strings/strings.go
@@ -0,0 +1,102 @@
+package strings
+
+import "unicode/utf8"
+
+// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior.
+func IndexNotByte(s string, c byte) int {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior.
+func LastIndexNotByte(s string, c byte) int {
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+type asciiSet [8]uint32
+
+func (as *asciiSet) notContains(c byte) bool {
+ return (as[c>>5] & (1 << uint(c&31))) == 0
+}
+
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c>>5] |= 1 << uint(c&31)
+ }
+ return as, true
+}
+
+// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior.
+func IndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := 0; i < len(s); i++ {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+
+ LabelFirstLoop:
+ for i, c := range s {
+ for j, m := range chars {
+ if c != m && j == len(chars)-1 {
+ return i
+ } else if c != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior.
+func LastIndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ LabelFirstLoop:
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRuneInString(s[:i])
+ i -= size
+ for j, m := range chars {
+ if r != m && j == len(chars)-1 {
+ return i
+ } else if r != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/term/raw.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/term/raw.go
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3ed8d04023558cf386a98080815d661248b85
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/term/raw.go
@@ -0,0 +1,29 @@
+// +build !windows
+
+package term
+
+import (
+ "syscall"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+// SetRaw put terminal into a raw mode
+func SetRaw(fd int) error {
+ n, err := getOriginalTermios(fd)
+ if err != nil {
+ return err
+ }
+
+ n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK |
+ syscall.ISTRIP | syscall.INLCR | syscall.IGNCR |
+ syscall.ICRNL | syscall.IXON
+ n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL
+ n.Cflag &^= syscall.CSIZE | syscall.PARENB
+ n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters.
+ n.Cc[syscall.VMIN] = 1
+ n.Cc[syscall.VTIME] = 0
+
+ return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n))
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/term/term.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/term/term.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a53c059ae60c0348ec01689babef4b13a2ecd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/internal/term/term.go
@@ -0,0 +1,34 @@
+// +build !windows
+
+package term
+
+import (
+ "sync"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ saveTermios *unix.Termios
+ saveTermiosFD int
+ saveTermiosOnce sync.Once
+)
+
+func getOriginalTermios(fd int) (*unix.Termios, error) {
+ var err error
+ saveTermiosOnce.Do(func() {
+ saveTermiosFD = fd
+ saveTermios, err = termios.Tcgetattr(uintptr(fd))
+ })
+ return saveTermios, err
+}
+
+// Restore terminal's mode.
+func Restore() error {
+ o, err := getOriginalTermios(saveTermiosFD)
+ if err != nil {
+ return err
+ }
+ return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/key.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ba569c2dd20a8ae3b3dd79ff3695bf0b6c1bd09
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/key.go
@@ -0,0 +1,128 @@
+// Code generated by hand; DO NOT EDIT.
+// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment.
+
+package prompt
+
+// Key is the type express the key inserted from user.
+//go:generate stringer -type=Key
+type Key int
+
+// ASCIICode is the type contains Key and it's ascii byte array.
+type ASCIICode struct {
+ Key Key
+ ASCIICode []byte
+}
+
+const (
+ Escape Key = iota
+
+ ControlA
+ ControlB
+ ControlC
+ ControlD
+ ControlE
+ ControlF
+ ControlG
+ ControlH
+ ControlI
+ ControlJ
+ ControlK
+ ControlL
+ ControlM
+ ControlN
+ ControlO
+ ControlP
+ ControlQ
+ ControlR
+ ControlS
+ ControlT
+ ControlU
+ ControlV
+ ControlW
+ ControlX
+ ControlY
+ ControlZ
+
+ ControlSpace
+ ControlBackslash
+ ControlSquareClose
+ ControlCircumflex
+ ControlUnderscore
+ ControlLeft
+ ControlRight
+ ControlUp
+ ControlDown
+
+ Up
+ Down
+ Right
+ Left
+
+ ShiftLeft
+ ShiftUp
+ ShiftDown
+ ShiftRight
+
+ Home
+ End
+ Delete
+ ShiftDelete
+ ControlDelete
+ PageUp
+ PageDown
+ BackTab
+ Insert
+ Backspace
+
+ // Aliases.
+ Tab
+ Enter
+ // Actually Enter equals ControlM, not ControlJ,
+ // However, in prompt_toolkit, we made the mistake of translating
+ // \r into \n during the input, so everyone is now handling the
+ // enter key by binding ControlJ.
+
+ // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere,
+ // because that's future compatible, and will still work when we
+ // stop replacing \r by \n.
+
+ F1
+ F2
+ F3
+ F4
+ F5
+ F6
+ F7
+ F8
+ F9
+ F10
+ F11
+ F12
+ F13
+ F14
+ F15
+ F16
+ F17
+ F18
+ F19
+ F20
+ F21
+ F22
+ F23
+ F24
+
+ // Matches any key.
+ Any
+
+ // Special
+ CPRResponse
+ Vt100MouseEvent
+ WindowsMouseEvent
+ BracketedPaste
+
+ // Key which is ignored. (The key binding for this key should not do anything.)
+ Ignore
+
+ // Key is not defined
+ NotDefined
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/key_bind.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/key_bind.go
new file mode 100644
index 0000000000000000000000000000000000000000..42669e7f942efc4d92f896388daede90b96b55dd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/key_bind.go
@@ -0,0 +1,59 @@
+package prompt
+
+// KeyBindFunc receives buffer and processed it.
+type KeyBindFunc func(*Buffer)
+
+// KeyBind represents which key should do what operation.
+type KeyBind struct {
+ Key Key
+ Fn KeyBindFunc
+}
+
+// ASCIICodeBind represents which []byte should do what operation
+type ASCIICodeBind struct {
+ ASCIICode []byte
+ Fn KeyBindFunc
+}
+
+// KeyBindMode to switch a key binding flexibly.
+type KeyBindMode string
+
+const (
+ // CommonKeyBind is a mode without any keyboard shortcut
+ CommonKeyBind KeyBindMode = "common"
+ // EmacsKeyBind is a mode to use emacs-like keyboard shortcut
+ EmacsKeyBind KeyBindMode = "emacs"
+)
+
+var commonKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: End,
+ Fn: GoLineEnd,
+ },
+ // Go to the beginning of the line
+ {
+ Key: Home,
+ Fn: GoLineBeginning,
+ },
+ // Delete character under the cursor
+ {
+ Key: Delete,
+ Fn: DeleteChar,
+ },
+ // Backspace
+ {
+ Key: Backspace,
+ Fn: DeleteBeforeChar,
+ },
+ // Right allow: Forward one character
+ {
+ Key: Right,
+ Fn: GoRightChar,
+ },
+ // Left allow: Backward one character
+ {
+ Key: Left,
+ Fn: GoLeftChar,
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/key_bind_func.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/key_bind_func.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b2ecdf63179dbfdbcb0d71bfa436bb36d62d230
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/key_bind_func.go
@@ -0,0 +1,48 @@
+package prompt
+
+// GoLineEnd Go to the End of the line
+func GoLineEnd(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+}
+
+// GoLineBeginning Go to the beginning of the line
+func GoLineBeginning(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+}
+
+// DeleteChar Delete character under the cursor
+func DeleteChar(buf *Buffer) {
+ buf.Delete(1)
+}
+
+// DeleteWord Delete word before the cursor
+func DeleteWord(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
+
+// DeleteBeforeChar Go to Backspace
+func DeleteBeforeChar(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+}
+
+// GoRightChar Forward one character
+func GoRightChar(buf *Buffer) {
+ buf.CursorRight(1)
+}
+
+// GoLeftChar Backward one character
+func GoLeftChar(buf *Buffer) {
+ buf.CursorLeft(1)
+}
+
+// GoRightWord Forward one word
+func GoRightWord(buf *Buffer) {
+ buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
+}
+
+// GoLeftWord Backward one word
+func GoLeftWord(buf *Buffer) {
+ buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/key_string.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/key_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..fce6ea31c502b3e763451cb47757ae1b49c32814
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/key_string.go
@@ -0,0 +1,16 @@
+// Code generated by "stringer -type=Key"; DO NOT EDIT.
+
+package prompt
+
+import "strconv"
+
+const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined"
+
+var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607}
+
+func (i Key) String() string {
+ if i < 0 || i >= Key(len(_Key_index)-1) {
+ return "Key(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _Key_name[_Key_index[i]:_Key_index[i+1]]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/option.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/option.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd6806cc1dbccf8c4ddb048080fde615c59088
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/option.go
@@ -0,0 +1,310 @@
+package prompt
+
+// Option is the type to replace default parameters.
+// prompt.New accepts any number of options (this is functional option pattern).
+type Option func(prompt *Prompt) error
+
+// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
+func OptionParser(x ConsoleParser) Option {
+ return func(p *Prompt) error {
+ p.in = x
+ return nil
+ }
+}
+
+// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
+func OptionWriter(x ConsoleWriter) Option {
+ return func(p *Prompt) error {
+ registerConsoleWriter(x)
+ p.renderer.out = x
+ return nil
+ }
+}
+
+// OptionTitle to set title displayed at the header bar of terminal.
+func OptionTitle(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.title = x
+ return nil
+ }
+}
+
+// OptionPrefix to set prefix string.
+func OptionPrefix(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefix = x
+ return nil
+ }
+}
+
+// OptionInitialBufferText to set the initial buffer text
+func OptionInitialBufferText(x string) Option {
+ return func(p *Prompt) error {
+ p.buf.InsertText(x, false, true)
+ return nil
+ }
+}
+
+// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
+func OptionCompletionWordSeparator(x string) Option {
+ return func(p *Prompt) error {
+ p.completion.wordSeparator = x
+ return nil
+ }
+}
+
+// OptionLivePrefix to change the prefix dynamically by callback function
+func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
+ return func(p *Prompt) error {
+ p.renderer.livePrefixCallback = f
+ return nil
+ }
+}
+
+// OptionPrefixTextColor change a text color of prefix string
+func OptionPrefixTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixTextColor = x
+ return nil
+ }
+}
+
+// OptionPrefixBackgroundColor to change a background color of prefix string
+func OptionPrefixBackgroundColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixBGColor = x
+ return nil
+ }
+}
+
+// OptionInputTextColor to change a color of text which is input by user
+func OptionInputTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputTextColor = x
+ return nil
+ }
+}
+
+// OptionInputBGColor to change a color of background which is input by user
+func OptionInputBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputBGColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionTextColor to change a text color which is completed
+func OptionPreviewSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionBGColor to change a background color which is completed
+func OptionPreviewSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionTextColor to change a text color in drop down suggestions.
+func OptionSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionBGColor change a background color in drop down suggestions.
+func OptionSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarThumbColor to change a thumb color on scrollbar.
+func OptionScrollbarThumbColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarThumbColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarBGColor to change a background color of scrollbar.
+func OptionScrollbarBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarBGColor = x
+ return nil
+ }
+}
+
+// OptionMaxSuggestion specify the max number of displayed suggestions.
+func OptionMaxSuggestion(x uint16) Option {
+ return func(p *Prompt) error {
+ p.completion.max = x
+ return nil
+ }
+}
+
+// OptionHistory to set history expressed by string array.
+func OptionHistory(x []string) Option {
+ return func(p *Prompt) error {
+ p.history.histories = x
+ p.history.Clear()
+ return nil
+ }
+}
+
+// OptionSwitchKeyBindMode set a key bind mode.
+func OptionSwitchKeyBindMode(m KeyBindMode) Option {
+ return func(p *Prompt) error {
+ p.keyBindMode = m
+ return nil
+ }
+}
+
+// OptionCompletionOnDown allows for Down arrow key to trigger completion.
+func OptionCompletionOnDown() Option {
+ return func(p *Prompt) error {
+ p.completionOnDown = true
+ return nil
+ }
+}
+
+// SwitchKeyBindMode to set a key bind mode.
+// Deprecated: Please use OptionSwitchKeyBindMode.
+var SwitchKeyBindMode = OptionSwitchKeyBindMode
+
+// OptionAddKeyBind to set a custom key bind.
+func OptionAddKeyBind(b ...KeyBind) Option {
+ return func(p *Prompt) error {
+ p.keyBindings = append(p.keyBindings, b...)
+ return nil
+ }
+}
+
+// OptionAddASCIICodeBind to set a custom key bind.
+func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option {
+ return func(p *Prompt) error {
+ p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...)
+ return nil
+ }
+}
+
+// OptionShowCompletionAtStart to set completion window is open at start.
+func OptionShowCompletionAtStart() Option {
+ return func(p *Prompt) error {
+ p.completion.showAtStart = true
+ return nil
+ }
+}
+
+// OptionBreakLineCallback to run a callback at every break line
+func OptionBreakLineCallback(fn func(*Document)) Option {
+ return func(p *Prompt) error {
+ p.renderer.breakLineCallback = fn
+ return nil
+ }
+}
+
+// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop
+func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
+ return func(p *Prompt) error {
+ p.exitChecker = fn
+ return nil
+ }
+}
+
+// New returns a Prompt with powerful auto-completion.
+func New(executor Executor, completer Completer, opts ...Option) *Prompt {
+ defaultWriter := NewStdoutWriter()
+ registerConsoleWriter(defaultWriter)
+
+ pt := &Prompt{
+ in: NewStandardInputParser(),
+ renderer: &Render{
+ prefix: "> ",
+ out: defaultWriter,
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ },
+ buf: NewBuffer(),
+ executor: executor,
+ history: NewHistory(),
+ completion: NewCompletionManager(completer, 6),
+ keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting
+ }
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/output.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/output.go
new file mode 100644
index 0000000000000000000000000000000000000000..42531b412f1ed027c2fff5b85bc273e53e569b3a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/output.go
@@ -0,0 +1,161 @@
+package prompt
+
+import "sync"
+
+var (
+ consoleWriterMu sync.Mutex
+ consoleWriter ConsoleWriter
+)
+
+func registerConsoleWriter(f ConsoleWriter) {
+ consoleWriterMu.Lock()
+ defer consoleWriterMu.Unlock()
+ consoleWriter = f
+}
+
+// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on.
+type DisplayAttribute int
+
+const (
+ // DisplayReset reset all display attributes.
+ DisplayReset DisplayAttribute = iota
+ // DisplayBold set bold or increases intensity.
+ DisplayBold
+ // DisplayLowIntensity decreases intensity. Not widely supported.
+ DisplayLowIntensity
+ // DisplayItalic set italic. Not widely supported.
+ DisplayItalic
+ // DisplayUnderline set underline
+ DisplayUnderline
+ // DisplayBlink set blink (less than 150 per minute).
+ DisplayBlink
+ // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported.
+ DisplayRapidBlink
+ // DisplayReverse swap foreground and background colors.
+ DisplayReverse
+ // DisplayInvisible set invisible. Not widely supported.
+ DisplayInvisible
+ // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported.
+ DisplayCrossedOut
+ // DisplayDefaultFont set primary(default) font
+ DisplayDefaultFont
+)
+
+// Color represents color on terminal.
+type Color int
+
+const (
+ // DefaultColor represents a default color.
+ DefaultColor Color = iota
+
+ // Low intensity
+
+ // Black represents a black.
+ Black
+ // DarkRed represents a dark red.
+ DarkRed
+ // DarkGreen represents a dark green.
+ DarkGreen
+ // Brown represents a brown.
+ Brown
+ // DarkBlue represents a dark blue.
+ DarkBlue
+ // Purple represents a purple.
+ Purple
+ // Cyan represents a cyan.
+ Cyan
+ // LightGray represents a light gray.
+ LightGray
+
+ // High intensity
+
+ // DarkGray represents a dark gray.
+ DarkGray
+ // Red represents a red.
+ Red
+ // Green represents a green.
+ Green
+ // Yellow represents a yellow.
+ Yellow
+ // Blue represents a blue.
+ Blue
+ // Fuchsia represents a fuchsia.
+ Fuchsia
+ // Turquoise represents a turquoise.
+ Turquoise
+ // White represents a white.
+ White
+)
+
+// ConsoleWriter is an interface to abstract output layer.
+type ConsoleWriter interface {
+ /* Write */
+
+ // WriteRaw to write raw byte array.
+ WriteRaw(data []byte)
+ // Write to write safety byte array by removing control sequences.
+ Write(data []byte)
+ // WriteStr to write raw string.
+ WriteRawStr(data string)
+ // WriteStr to write safety string by removing control sequences.
+ WriteStr(data string)
+ // Flush to flush buffer.
+ Flush() error
+
+ /* Erasing */
+
+ // EraseScreen erases the screen with the background colour and moves the cursor to home.
+ EraseScreen()
+ // EraseUp erases the screen from the current line up to the top of the screen.
+ EraseUp()
+ // EraseDown erases the screen from the current line down to the bottom of the screen.
+ EraseDown()
+ // EraseStartOfLine erases from the current cursor position to the start of the current line.
+ EraseStartOfLine()
+ // EraseEndOfLine erases from the current cursor position to the end of the current line.
+ EraseEndOfLine()
+ // EraseLine erases the entire current line.
+ EraseLine()
+
+ /* Cursor */
+
+ // ShowCursor stops blinking cursor and show.
+ ShowCursor()
+ // HideCursor hides cursor.
+ HideCursor()
+ // CursorGoTo sets the cursor position where subsequent text will begin.
+ CursorGoTo(row, col int)
+ // CursorUp moves the cursor up by 'n' rows; the default count is 1.
+ CursorUp(n int)
+ // CursorDown moves the cursor down by 'n' rows; the default count is 1.
+ CursorDown(n int)
+ // CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+ CursorForward(n int)
+ // CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+ CursorBackward(n int)
+ // AskForCPR asks for a cursor position report (CPR).
+ AskForCPR()
+ // SaveCursor saves current cursor position.
+ SaveCursor()
+ // UnSaveCursor restores cursor position after a Save Cursor.
+ UnSaveCursor()
+
+ /* Scrolling */
+
+ // ScrollDown scrolls display down one line.
+ ScrollDown()
+ // ScrollUp scroll display up one line.
+ ScrollUp()
+
+ /* Title */
+
+ // SetTitle sets a title of terminal window.
+ SetTitle(title string)
+ // ClearTitle clears a title of terminal window.
+ ClearTitle()
+
+ /* Font */
+
+ // SetColor sets text and background colors. and specify whether text is bold.
+ SetColor(fg, bg Color, bold bool)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/output_posix.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/output_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..26c770cc152a7b126be43915d60b8ba000ad0e38
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/output_posix.go
@@ -0,0 +1,67 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+)
+
+const flushMaxRetryCount = 3
+
+// PosixWriter is a ConsoleWriter implementation for POSIX environment.
+// To control terminal emulator, this outputs VT100 escape sequences.
+type PosixWriter struct {
+ VT100Writer
+ fd int
+}
+
+// Flush to flush buffer
+func (w *PosixWriter) Flush() error {
+ l := len(w.buffer)
+ offset := 0
+ retry := 0
+ for {
+ n, err := syscall.Write(w.fd, w.buffer[offset:])
+ if err != nil {
+ if retry < flushMaxRetryCount {
+ retry++
+ continue
+ }
+ return err
+ }
+ offset += n
+ if offset == l {
+ break
+ }
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &PosixWriter{}
+
+var (
+ // NewStandardOutputWriter returns ConsoleWriter object to write to stdout.
+ // This generates VT100 escape sequences because almost terminal emulators
+ // in POSIX OS built on top of a VT100 specification.
+ // Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStdoutWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stdout,
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStderrWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stderr,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/output_vt100.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/output_vt100.go
new file mode 100644
index 0000000000000000000000000000000000000000..20850fead883c4cd9802928b5de3f935fbbeb047
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/output_vt100.go
@@ -0,0 +1,310 @@
+package prompt
+
+import (
+ "bytes"
+ "strconv"
+)
+
+// VT100Writer generates VT100 escape sequences.
+type VT100Writer struct {
+ buffer []byte
+}
+
+// WriteRaw to write raw byte array
+func (w *VT100Writer) WriteRaw(data []byte) {
+ w.buffer = append(w.buffer, data...)
+}
+
+// Write to write safety byte array by removing control sequences.
+func (w *VT100Writer) Write(data []byte) {
+ w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1))
+}
+
+// WriteRawStr to write raw string
+func (w *VT100Writer) WriteRawStr(data string) {
+ w.WriteRaw([]byte(data))
+}
+
+// WriteStr to write safety string by removing control sequences.
+func (w *VT100Writer) WriteStr(data string) {
+ w.Write([]byte(data))
+}
+
+/* Erase */
+
+// EraseScreen erases the screen with the background colour and moves the cursor to home.
+func (w *VT100Writer) EraseScreen() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'J'})
+}
+
+// EraseUp erases the screen from the current line up to the top of the screen.
+func (w *VT100Writer) EraseUp() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'J'})
+}
+
+// EraseDown erases the screen from the current line down to the bottom of the screen.
+func (w *VT100Writer) EraseDown() {
+ w.WriteRaw([]byte{0x1b, '[', 'J'})
+}
+
+// EraseStartOfLine erases from the current cursor position to the start of the current line.
+func (w *VT100Writer) EraseStartOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'K'})
+}
+
+// EraseEndOfLine erases from the current cursor position to the end of the current line.
+func (w *VT100Writer) EraseEndOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', 'K'})
+}
+
+// EraseLine erases the entire current line.
+func (w *VT100Writer) EraseLine() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'K'})
+}
+
+/* Cursor */
+
+// ShowCursor stops blinking cursor and show.
+func (w *VT100Writer) ShowCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'})
+}
+
+// HideCursor hides cursor.
+func (w *VT100Writer) HideCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'})
+}
+
+// CursorGoTo sets the cursor position where subsequent text will begin.
+func (w *VT100Writer) CursorGoTo(row, col int) {
+ if row == 0 && col == 0 {
+ // If no row/column parameters are provided (ie. [H), the cursor will move to the home position.
+ w.WriteRaw([]byte{0x1b, '[', 'H'})
+ return
+ }
+ r := strconv.Itoa(row)
+ c := strconv.Itoa(col)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(r))
+ w.WriteRaw([]byte{';'})
+ w.WriteRaw([]byte(c))
+ w.WriteRaw([]byte{'H'})
+}
+
+// CursorUp moves the cursor up by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorUp(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorDown(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'A'})
+}
+
+// CursorDown moves the cursor down by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorDown(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorUp(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'B'})
+}
+
+// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorForward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorBackward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'C'})
+}
+
+// CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorBackward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorForward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'D'})
+}
+
+// AskForCPR asks for a cursor position report (CPR).
+func (w *VT100Writer) AskForCPR() {
+ // CPR: Cursor Position Request.
+ w.WriteRaw([]byte{0x1b, '[', '6', 'n'})
+}
+
+// SaveCursor saves current cursor position.
+func (w *VT100Writer) SaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 's'})
+}
+
+// UnSaveCursor restores cursor position after a Save Cursor.
+func (w *VT100Writer) UnSaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 'u'})
+}
+
+/* Scrolling */
+
+// ScrollDown scrolls display down one line.
+func (w *VT100Writer) ScrollDown() {
+ w.WriteRaw([]byte{0x1b, 'D'})
+}
+
+// ScrollUp scroll display up one line.
+func (w *VT100Writer) ScrollUp() {
+ w.WriteRaw([]byte{0x1b, 'M'})
+}
+
+/* Title */
+
+// SetTitle sets a title of terminal window.
+func (w *VT100Writer) SetTitle(title string) {
+ titleBytes := []byte(title)
+ patterns := []struct {
+ from []byte
+ to []byte
+ }{
+ {
+ from: []byte{0x13},
+ to: []byte{},
+ },
+ {
+ from: []byte{0x07},
+ to: []byte{},
+ },
+ }
+ for i := range patterns {
+ titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1)
+ }
+
+ w.WriteRaw([]byte{0x1b, ']', '2', ';'})
+ w.WriteRaw(titleBytes)
+ w.WriteRaw([]byte{0x07})
+}
+
+// ClearTitle clears a title of terminal window.
+func (w *VT100Writer) ClearTitle() {
+ w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07})
+}
+
+/* Font */
+
+// SetColor sets text and background colors. and specify whether text is bold.
+func (w *VT100Writer) SetColor(fg, bg Color, bold bool) {
+ if bold {
+ w.SetDisplayAttributes(fg, bg, DisplayBold)
+ } else {
+ // If using `DisplayDefualt`, it will be broken in some environment.
+ // Details are https://github.com/c-bata/go-prompt/pull/85
+ w.SetDisplayAttributes(fg, bg, DisplayReset)
+ }
+}
+
+// SetDisplayAttributes to set VT100 display attributes.
+func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) {
+ w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer
+ defer w.WriteRaw([]byte{'m'}) // final character
+
+ var separator byte = ';'
+ for i := range attrs {
+ p, ok := displayAttributeParameters[attrs[i]]
+ if !ok {
+ continue
+ }
+ w.WriteRaw(p)
+ w.WriteRaw([]byte{separator})
+ }
+
+ f, ok := foregroundANSIColors[fg]
+ if !ok {
+ f = foregroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(f)
+ w.WriteRaw([]byte{separator})
+ b, ok := backgroundANSIColors[bg]
+ if !ok {
+ b = backgroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(b)
+}
+
+var displayAttributeParameters = map[DisplayAttribute][]byte{
+ DisplayReset: {'0'},
+ DisplayBold: {'1'},
+ DisplayLowIntensity: {'2'},
+ DisplayItalic: {'3'},
+ DisplayUnderline: {'4'},
+ DisplayBlink: {'5'},
+ DisplayRapidBlink: {'6'},
+ DisplayReverse: {'7'},
+ DisplayInvisible: {'8'},
+ DisplayCrossedOut: {'9'},
+ DisplayDefaultFont: {'1', '0'},
+}
+
+var foregroundANSIColors = map[Color][]byte{
+ DefaultColor: {'3', '9'},
+
+ // Low intensity.
+ Black: {'3', '0'},
+ DarkRed: {'3', '1'},
+ DarkGreen: {'3', '2'},
+ Brown: {'3', '3'},
+ DarkBlue: {'3', '4'},
+ Purple: {'3', '5'},
+ Cyan: {'3', '6'},
+ LightGray: {'3', '7'},
+
+ // High intensity.
+ DarkGray: {'9', '0'},
+ Red: {'9', '1'},
+ Green: {'9', '2'},
+ Yellow: {'9', '3'},
+ Blue: {'9', '4'},
+ Fuchsia: {'9', '5'},
+ Turquoise: {'9', '6'},
+ White: {'9', '7'},
+}
+
+var backgroundANSIColors = map[Color][]byte{
+ DefaultColor: {'4', '9'},
+
+ // Low intensity.
+ Black: {'4', '0'},
+ DarkRed: {'4', '1'},
+ DarkGreen: {'4', '2'},
+ Brown: {'4', '3'},
+ DarkBlue: {'4', '4'},
+ Purple: {'4', '5'},
+ Cyan: {'4', '6'},
+ LightGray: {'4', '7'},
+
+ // High intensity
+ DarkGray: {'1', '0', '0'},
+ Red: {'1', '0', '1'},
+ Green: {'1', '0', '2'},
+ Yellow: {'1', '0', '3'},
+ Blue: {'1', '0', '4'},
+ Fuchsia: {'1', '0', '5'},
+ Turquoise: {'1', '0', '6'},
+ White: {'1', '0', '7'},
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/output_windows.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/output_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b9c2769fc2d64cfcfcc5b99c915591ec625bd5f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/output_windows.go
@@ -0,0 +1,49 @@
+// +build windows
+
+package prompt
+
+import (
+ "io"
+
+ colorable "github.com/mattn/go-colorable"
+)
+
+// WindowsWriter is a ConsoleWriter implementation for Win32 console.
+// Output is converted from VT100 escape sequences by mattn/go-colorable.
+type WindowsWriter struct {
+ VT100Writer
+ out io.Writer
+}
+
+// Flush to flush buffer
+func (w *WindowsWriter) Flush() error {
+ _, err := w.out.Write(w.buffer)
+ if err != nil {
+ return err
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &WindowsWriter{}
+
+var (
+ // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates win32 control sequences.
+func NewStdoutWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStdout(),
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates win32 control sequences.
+func NewStderrWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStderr(),
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/prompt.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/prompt.go
new file mode 100644
index 0000000000000000000000000000000000000000..173cd517c40cde212433e399978641ceff1d1a43
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/prompt.go
@@ -0,0 +1,296 @@
+package prompt
+
+import (
+ "bytes"
+ "os"
+ "time"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Executor is called when user input something text.
+type Executor func(string)
+
+// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
+// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
+// - immediate exit (if breakline is false) without executor called
+// - exit after typing (meaning breakline is true), and the executor is called first, before exit.
+// Exit means exit go-prompt (not the overall Go program)
+type ExitChecker func(in string, breakline bool) bool
+
+// Completer should return the suggest item from Document.
+type Completer func(Document) []Suggest
+
+// Prompt is core struct of go-prompt.
+type Prompt struct {
+ in ConsoleParser
+ buf *Buffer
+ renderer *Render
+ executor Executor
+ history *History
+ completion *CompletionManager
+ keyBindings []KeyBind
+ ASCIICodeBindings []ASCIICodeBind
+ keyBindMode KeyBindMode
+ completionOnDown bool
+ exitChecker ExitChecker
+ skipTearDown bool
+}
+
+// Exec is the struct contains user input context.
+type Exec struct {
+ input string
+}
+
+// Run starts prompt.
+func (p *Prompt) Run() {
+ p.skipTearDown = false
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ exitCh := make(chan int)
+ winSizeCh := make(chan *WinSize)
+ stopHandleSignalCh := make(chan struct{})
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+ return
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+
+ // Unset raw mode
+ // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
+ debug.AssertNoError(p.in.TearDown())
+ p.executor(e.input)
+
+ p.completion.Update(*p.buf.Document())
+
+ p.renderer.Render(p.buf, p.completion)
+
+ if p.exitChecker != nil && p.exitChecker(e.input, true) {
+ p.skipTearDown = true
+ return
+ }
+ // Set raw mode
+ debug.AssertNoError(p.in.Setup())
+ go p.readBuffer(bufCh, stopReadBufCh)
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ case w := <-winSizeCh:
+ p.renderer.UpdateWinSize(w)
+ p.renderer.Render(p.buf, p.completion)
+ case code := <-exitCh:
+ p.renderer.BreakLine(p.buf)
+ p.tearDown()
+ os.Exit(code)
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
+ key := GetKey(b)
+ p.buf.lastKeyStroke = key
+ // completion
+ completing := p.completion.Completing()
+ p.handleCompletionKeyBinding(key, completing)
+
+ switch key {
+ case Enter, ControlJ, ControlM:
+ p.renderer.BreakLine(p.buf)
+
+ exec = &Exec{input: p.buf.Text()}
+ p.buf = NewBuffer()
+ if exec.input != "" {
+ p.history.Add(exec.input)
+ }
+ case ControlC:
+ p.renderer.BreakLine(p.buf)
+ p.buf = NewBuffer()
+ p.history.Clear()
+ case Up, ControlP:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Older(p.buf); changed {
+ p.buf = newBuf
+ }
+ }
+ case Down, ControlN:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Newer(p.buf); changed {
+ p.buf = newBuf
+ }
+ return
+ }
+ case ControlD:
+ if p.buf.Text() == "" {
+ shouldExit = true
+ return
+ }
+ case NotDefined:
+ if p.handleASCIICodeBinding(b) {
+ return
+ }
+ p.buf.InsertText(string(b), false, true)
+ }
+
+ shouldExit = p.handleKeyBinding(key)
+ return
+}
+
+func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
+ switch key {
+ case Down:
+ if completing || p.completionOnDown {
+ p.completion.Next()
+ }
+ case Tab, ControlI:
+ p.completion.Next()
+ case Up:
+ if completing {
+ p.completion.Previous()
+ }
+ case BackTab:
+ p.completion.Previous()
+ default:
+ if s, ok := p.completion.GetSelectedSuggestion(); ok {
+ w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
+ if w != "" {
+ p.buf.DeleteBeforeCursor(len([]rune(w)))
+ }
+ p.buf.InsertText(s.Text, false, true)
+ }
+ p.completion.Reset()
+ }
+}
+
+func (p *Prompt) handleKeyBinding(key Key) bool {
+ shouldExit := false
+ for i := range commonKeyBindings {
+ kb := commonKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+
+ if p.keyBindMode == EmacsKeyBind {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ }
+
+ // Custom key bindings
+ for i := range p.keyBindings {
+ kb := p.keyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
+ shouldExit = true
+ }
+ return shouldExit
+}
+
+func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
+ checked := false
+ for _, kb := range p.ASCIICodeBindings {
+ if bytes.Equal(kb.ASCIICode, b) {
+ kb.Fn(p.buf)
+ checked = true
+ }
+ }
+ return checked
+}
+
+// Input just returns user input text.
+func (p *Prompt) Input() string {
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ return ""
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ return e.input
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
+ debug.Log("start reading buffer")
+ for {
+ select {
+ case <-stopCh:
+ debug.Log("stop reading buffer")
+ return
+ default:
+ if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
+ bufCh <- b
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (p *Prompt) setUp() {
+ debug.AssertNoError(p.in.Setup())
+ p.renderer.Setup()
+ p.renderer.UpdateWinSize(p.in.GetWinSize())
+}
+
+func (p *Prompt) tearDown() {
+ if !p.skipTearDown {
+ debug.AssertNoError(p.in.TearDown())
+ }
+ p.renderer.TearDown()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/render.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/render.go
new file mode 100644
index 0000000000000000000000000000000000000000..299ac48b6254b9752ea16516aaedcd41acca6515
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/render.go
@@ -0,0 +1,287 @@
+package prompt
+
+import (
+ "runtime"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Render to render prompt information from state of Buffer.
+type Render struct {
+ out ConsoleWriter
+ prefix string
+ livePrefixCallback func() (prefix string, useLivePrefix bool)
+ breakLineCallback func(*Document)
+ title string
+ row uint16
+ col uint16
+
+ previousCursor int
+
+ // colors,
+ prefixTextColor Color
+ prefixBGColor Color
+ inputTextColor Color
+ inputBGColor Color
+ previewSuggestionTextColor Color
+ previewSuggestionBGColor Color
+ suggestionTextColor Color
+ suggestionBGColor Color
+ selectedSuggestionTextColor Color
+ selectedSuggestionBGColor Color
+ descriptionTextColor Color
+ descriptionBGColor Color
+ selectedDescriptionTextColor Color
+ selectedDescriptionBGColor Color
+ scrollbarThumbColor Color
+ scrollbarBGColor Color
+}
+
+// Setup to initialize console output.
+func (r *Render) Setup() {
+ if r.title != "" {
+ r.out.SetTitle(r.title)
+ debug.AssertNoError(r.out.Flush())
+ }
+}
+
+// getCurrentPrefix to get current prefix.
+// If live-prefix is enabled, return live-prefix.
+func (r *Render) getCurrentPrefix() string {
+ if prefix, ok := r.livePrefixCallback(); ok {
+ return prefix
+ }
+ return r.prefix
+}
+
+func (r *Render) renderPrefix() {
+ r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
+ r.out.WriteStr(r.getCurrentPrefix())
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// TearDown to clear title and erasing.
+func (r *Render) TearDown() {
+ r.out.ClearTitle()
+ r.out.EraseDown()
+ debug.AssertNoError(r.out.Flush())
+}
+
+func (r *Render) prepareArea(lines int) {
+ for i := 0; i < lines; i++ {
+ r.out.ScrollDown()
+ }
+ for i := 0; i < lines; i++ {
+ r.out.ScrollUp()
+ }
+}
+
+// UpdateWinSize called when window size is changed.
+func (r *Render) UpdateWinSize(ws *WinSize) {
+ r.row = ws.Row
+ r.col = ws.Col
+}
+
+func (r *Render) renderWindowTooSmall() {
+ r.out.CursorGoTo(0, 0)
+ r.out.EraseScreen()
+ r.out.SetColor(DarkRed, White, false)
+ r.out.WriteStr("Your console window is too small...")
+}
+
+func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) {
+ suggestions := completions.GetSuggestions()
+ if len(completions.GetSuggestions()) == 0 {
+ return
+ }
+ prefix := r.getCurrentPrefix()
+ formatted, width := formatSuggestions(
+ suggestions,
+ int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar
+ )
+ // +1 means a width of scrollbar.
+ width++
+
+ windowHeight := len(formatted)
+ if windowHeight > int(completions.max) {
+ windowHeight = int(completions.max)
+ }
+ formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
+ r.prepareArea(windowHeight)
+
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor())
+ x, _ := r.toPos(cursor)
+ if x+width >= int(r.col) {
+ cursor = r.backward(cursor, x+width-int(r.col))
+ }
+
+ contentHeight := len(completions.tmp)
+
+ fractionVisible := float64(windowHeight) / float64(contentHeight)
+ fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
+
+ scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
+ scrollbarTop := int(float64(windowHeight) * fractionAbove)
+
+ isScrollThumb := func(row int) bool {
+ return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
+ }
+
+ selected := completions.selected - completions.verticalScroll
+ r.out.SetColor(White, Cyan, false)
+ for i := 0; i < windowHeight; i++ {
+ r.out.CursorDown(1)
+ if i == selected {
+ r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
+ } else {
+ r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Text)
+
+ if i == selected {
+ r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
+ } else {
+ r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Description)
+
+ if isScrollThumb(i) {
+ r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
+ } else {
+ r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
+ }
+ r.out.WriteStr(" ")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+
+ r.lineWrap(cursor + width)
+ r.backward(cursor+width, width)
+ }
+
+ if x+width >= int(r.col) {
+ r.out.CursorForward(x + width - int(r.col))
+ }
+
+ r.out.CursorUp(windowHeight)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// Render renders to the console.
+func (r *Render) Render(buffer *Buffer, completion *CompletionManager) {
+ // In situations where a pseudo tty is allocated (e.g. within a docker container),
+ // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
+ if r.col == 0 {
+ return
+ }
+ defer func() { debug.AssertNoError(r.out.Flush()) }()
+ r.move(r.previousCursor, 0)
+
+ line := buffer.Text()
+ prefix := r.getCurrentPrefix()
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line)
+
+ // prepare area
+ _, y := r.toPos(cursor)
+
+ h := y + 1 + int(completion.max)
+ if h > int(r.row) || completionMargin > int(r.col) {
+ r.renderWindowTooSmall()
+ return
+ }
+
+ // Rendering
+ r.out.HideCursor()
+ defer r.out.ShowCursor()
+
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(line)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ r.lineWrap(cursor)
+
+ r.out.EraseDown()
+
+ cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition())
+
+ r.renderCompletion(buffer, completion)
+ if suggest, ok := completion.GetSelectedSuggestion(); ok {
+ cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator)))
+
+ r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false)
+ r.out.WriteStr(suggest.Text)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ cursor += runewidth.StringWidth(suggest.Text)
+
+ rest := buffer.Document().TextAfterCursor()
+ r.out.WriteStr(rest)
+ cursor += runewidth.StringWidth(rest)
+ r.lineWrap(cursor)
+
+ cursor = r.backward(cursor, runewidth.StringWidth(rest))
+ }
+ r.previousCursor = cursor
+}
+
+// BreakLine to break line.
+func (r *Render) BreakLine(buffer *Buffer) {
+ // Erasing and Render
+ cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix())
+ r.clear(cursor)
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(buffer.Document().Text + "\n")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ debug.AssertNoError(r.out.Flush())
+ if r.breakLineCallback != nil {
+ r.breakLineCallback(buffer.Document())
+ }
+
+ r.previousCursor = 0
+}
+
+// clear erases the screen from a beginning of input
+// even if there is line break which means input length exceeds a window's width.
+func (r *Render) clear(cursor int) {
+ r.move(cursor, 0)
+ r.out.EraseDown()
+}
+
+// backward moves cursor to backward from a current cursor position
+// regardless there is a line break.
+func (r *Render) backward(from, n int) int {
+ return r.move(from, from-n)
+}
+
+// move moves cursor to specified position from the beginning of input
+// even if there is a line break.
+func (r *Render) move(from, to int) int {
+ fromX, fromY := r.toPos(from)
+ toX, toY := r.toPos(to)
+
+ r.out.CursorUp(fromY - toY)
+ r.out.CursorBackward(fromX - toX)
+ return to
+}
+
+// toPos returns the relative position from the beginning of the string.
+func (r *Render) toPos(cursor int) (x, y int) {
+ col := int(r.col)
+ return cursor % col, cursor / col
+}
+
+func (r *Render) lineWrap(cursor int) {
+ if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 {
+ r.out.WriteRaw([]byte{'\n'})
+ }
+}
+
+func clamp(high, low, x float64) float64 {
+ switch {
+ case high < x:
+ return high
+ case x < low:
+ return low
+ default:
+ return x
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/shortcut.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/shortcut.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8d4282700c0bdb30e4decfb9c9ac91f27af251
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/shortcut.go
@@ -0,0 +1,43 @@
+package prompt
+
+func dummyExecutor(in string) {}
+
+// Input get the input data from the user and return it.
+func Input(prefix string, completer Completer, opts ...Option) string {
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+// Choose to the shortcut of input function to select from string array.
+// Deprecated: Maybe anyone want to use this.
+func Choose(prefix string, choices []string, opts ...Option) string {
+ completer := newChoiceCompleter(choices, FilterHasPrefix)
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+func newChoiceCompleter(choices []string, filter Filter) Completer {
+ s := make([]Suggest, len(choices))
+ for i := range choices {
+ s[i] = Suggest{Text: choices[i]}
+ }
+ return func(x Document) []Suggest {
+ return filter(s, x.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/signal_posix.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/signal_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3150df5d85e7612c42c2a889dbefee3b524bef6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/signal_posix.go
@@ -0,0 +1,49 @@
+// +build !windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ in := p.in
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+
+ case syscall.SIGWINCH:
+ debug.Log("Catch SIGWINCH")
+ winSizeCh <- in.GetWinSize()
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/signal_windows.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/signal_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a427c79ec0414540f8f40694731b2565ea80c13
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/environment/source/signal_windows.go
@@ -0,0 +1,44 @@
+// +build windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/instruction.md b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..9c234a433cd57f81e7d947f14d2abfdb2792ba41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/instruction.md
@@ -0,0 +1,34 @@
+Case-insensitive filtering not working for suggestions
+
+#### Description
+
+When using case-insensitive filtering with `ignoreCase` set to true, the filter function doesn't return any matching suggestions even when there should be matches.
+
+#### Steps/Code to Reproduce
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func main() {
+ suggestions := []prompt.Suggest{
+ {Text: "abcde", Description: ""},
+ {Text: "ABCDE", Description: ""},
+ }
+
+ // This should return both suggestions when ignoreCase is true
+ filtered := prompt.FilterContains(suggestions, "abc", true)
+ fmt.Printf("Expected: 2 suggestions, Got: %d suggestions\n", len(filtered))
+
+ // Same issue with other filter functions
+ filtered2 := prompt.FilterHasPrefix(suggestions, "ABC", true)
+ fmt.Printf("Expected: 2 suggestions, Got: %d suggestions\n", len(filtered2))
+}
+```
+
+The case-insensitive filtering should match both "abcde" and "ABCDE" when searching for "abc" or "ABC", but currently returns no results.
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/provenance.json b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..abd5ebd45a412d3a95b58c469cf34034b4ccc922
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/provenance.json
@@ -0,0 +1,477 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt",
+ "original-bug": "task-specific unchanged semantic bug",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only",
+ "extra_semantic_repair_coverage": false,
+ "original_patch_hunks": 1
+ },
+ "private_frozen_files": {
+ "buffer_test.go": {
+ "mode": "0o644",
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098",
+ "size": 4965
+ },
+ "completion_test.go": {
+ "mode": "0o644",
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d",
+ "size": 7010
+ },
+ "document_test.go": {
+ "mode": "0o644",
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284",
+ "size": 28938
+ },
+ "emacs_test.go": {
+ "mode": "0o644",
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095",
+ "size": 741
+ },
+ "filter_test.go": {
+ "mode": "0o644",
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247",
+ "size": 3339
+ },
+ "history_test.go": {
+ "mode": "0o644",
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327",
+ "size": 1319
+ },
+ "input_test.go": {
+ "mode": "0o644",
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922",
+ "size": 533
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": "0o644",
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf",
+ "size": 1075
+ },
+ "internal/strings/strings_test.go": {
+ "mode": "0o644",
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6",
+ "size": 981
+ },
+ "output_vt100_test.go": {
+ "mode": "0o644",
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee",
+ "size": 1349
+ },
+ "render_test.go": {
+ "mode": "0o644",
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb",
+ "size": 2890
+ }
+ },
+ "public_files": {
+ ".github/ISSUE_TEMPLATE/bug_report.md": {
+ "mode": "0o644",
+ "sha256": "89d3492ca8533a3d31e4de49a23828a322f75d2a1ec4236327c4a76c7c51ada6",
+ "size": 684
+ },
+ ".github/ISSUE_TEMPLATE/feature_request.md": {
+ "mode": "0o644",
+ "sha256": "d82e14e6b4d021d0007eeef4f5ca489fc6c8e8e4d7479ee30e74fe82afd3b08f",
+ "size": 206
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "3239b94a1a41c05eff5dc086ef1378cf1e289fad0203420b5cb4c78e3c5c239b",
+ "size": 270
+ },
+ "CHANGELOG.md": {
+ "mode": "0o644",
+ "sha256": "1f88f92d3247e1b52af0f0de7ad1263a59807edb17238c7a0211554f8080e51c",
+ "size": 2895
+ },
+ "LICENSE": {
+ "mode": "0o644",
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "size": 1072
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "9425a0d4c15747863625f647348962a9b0f81a0971a7e0184ee722bf34a60ba2",
+ "size": 1177
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "ce56df51a1a9a5b5c5b056429bbee006a260fb0730af63b1d0fe91755e574cc4",
+ "size": 6185
+ },
+ "_example/README.md": {
+ "mode": "0o644",
+ "sha256": "155951bafd778493bd41ae57dcc0ba6b8eca821fcbe2ffe770960ac2780d3d09",
+ "size": 1102
+ },
+ "_example/build.sh": {
+ "mode": "0o755",
+ "sha256": "de2fb330b665691cd75b990236cd6a5df0058608de0dfc6194da30d4041a1e29",
+ "size": 469
+ },
+ "_example/exec-command/main.go": {
+ "mode": "0o644",
+ "sha256": "0e96493b6e6d446b2e691d4834ff8a55834caa410ead970cb611a63ba84f174a",
+ "size": 429
+ },
+ "_example/http-prompt/api.py": {
+ "mode": "0o644",
+ "sha256": "2c2bca9acb07a84c65a4482c61c9ade253a574477a8e461307568ea1f9a342c8",
+ "size": 335
+ },
+ "_example/http-prompt/main.go": {
+ "mode": "0o644",
+ "sha256": "6994b190c4165068e69ed44eb61698af69a15a7690179ce46e3c1c5d8c211643",
+ "size": 5484
+ },
+ "_example/live-prefix/main.go": {
+ "mode": "0o644",
+ "sha256": "20268f9cb6f3b82a52eddc33cbf8082adaa46092e2063df279499e05e25a228c",
+ "size": 1103
+ },
+ "_example/simple-echo/cjk-cyrillic/main.go": {
+ "mode": "0o644",
+ "sha256": "8fb10807d4085ebc4b345bc0ccfef9217e21e49a888bfe3192e8ddfdfa01e89c",
+ "size": 800
+ },
+ "_example/simple-echo/main.go": {
+ "mode": "0o644",
+ "sha256": "e46563ddaa932831fe9ede870b10efb5222c0d54a86f4b4f5197c9cf20942a24",
+ "size": 902
+ },
+ "_tools/README.md": {
+ "mode": "0o644",
+ "sha256": "96dc2343bc5cde642fd449ddc366462753a2e17b6a78adfa015bf991e9dac241",
+ "size": 234
+ },
+ "_tools/complete_file/main.go": {
+ "mode": "0o644",
+ "sha256": "e5dd823f9d6415614a8238ce106d26e9ded1db9b308c121d7f48bb1df003effc",
+ "size": 803
+ },
+ "_tools/sigwinch/main.go": {
+ "mode": "0o644",
+ "sha256": "a806b4e45298f5003c95432d8dd3c40c9c096335f19f1a4160afcdb64fa727e3",
+ "size": 1386
+ },
+ "_tools/vt100_debug/main.go": {
+ "mode": "0o644",
+ "sha256": "7f72eba3cc7037fcf39c9b56a96c578c157e5fb235cb626ab1e83cbef0dc290b",
+ "size": 794
+ },
+ "buffer.go": {
+ "mode": "0o644",
+ "sha256": "10188d96a450fe13ba1e9ec00c89603eb2a2860536965d980d1e4abf4374b018",
+ "size": 5781
+ },
+ "completer/file.go": {
+ "mode": "0o644",
+ "sha256": "6181ed9e39028236c5c93fbe219331fc1492ecfd6af2df764cc42b5455c9bb96",
+ "size": 2401
+ },
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "b90bd9628534cfb343a592775430e17a1999b1de500fb2a8f1507c030a432eae",
+ "size": 4491
+ },
+ "document.go": {
+ "mode": "0o644",
+ "sha256": "e719d4c10a10f506c371b87dbd363a9b7f7d3aa8f0190a40965ac761197e1f1e",
+ "size": 13097
+ },
+ "emacs.go": {
+ "mode": "0o644",
+ "sha256": "53f0df0016ef9d9695a797b19286681666cf0c7e5a866c393b194aae915f2664",
+ "size": 2675
+ },
+ "filter.go": {
+ "mode": "0o644",
+ "sha256": "f202582a811a806962697169542e51b667656ba224613f05f2c71499045b873c",
+ "size": 1958
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "97413fa2a2ed68170496f2289a2dca6fb0a192dcd020fc0ca48a5d106e60d55e",
+ "size": 253
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "88ea0a91babaa54b67cc6d5f6f7f47fa4be798fe523324ea568d8926eed2024c",
+ "size": 2183
+ },
+ "history.go": {
+ "mode": "0o644",
+ "sha256": "4ce80ba067cfc72c56a3ee3353ec75cd6bb2f5d82097515c591e3c7c773c51cd",
+ "size": 1488
+ },
+ "input.go": {
+ "mode": "0o644",
+ "sha256": "73461cc4f57d68b66e2a9e196239aaef942539134593beac0d0023743832e0e1",
+ "size": 7630
+ },
+ "input_posix.go": {
+ "mode": "0o644",
+ "sha256": "c7e5a4dfc3910f178f0685ef99f2e47d481a91c4cf9af50f92fc4266aed634df",
+ "size": 1648
+ },
+ "input_windows.go": {
+ "mode": "0o644",
+ "sha256": "f763250d309fb88d9536f77da1d1285c04bc6defe859506f1501e10f7743da9e",
+ "size": 1679
+ },
+ "internal/bisect/bisect.go": {
+ "mode": "0o644",
+ "sha256": "c4de2adfa2e08a77f902661d67325467f89013634dbcef22d24dc6f34d26624a",
+ "size": 327
+ },
+ "internal/debug/assert.go": {
+ "mode": "0o644",
+ "sha256": "1a3050ec58991b62c7ea352d19505e3080ac9760bdb091544f0ecf5aba35969c",
+ "size": 815
+ },
+ "internal/debug/log.go": {
+ "mode": "0o644",
+ "sha256": "2ce968e275558de61c6d83793e85561f7a8dd69c95ec7902ccd2cc3fb169aa82",
+ "size": 875
+ },
+ "internal/strings/strings.go": {
+ "mode": "0o644",
+ "sha256": "b97f08157c3baf1f94fea4bb2237691d8270bd5380b4311709ecd59b84cf4b7b",
+ "size": 2018
+ },
+ "internal/term/raw.go": {
+ "mode": "0o644",
+ "sha256": "177a1a20ae8d71b56857383a5797754560f7f6404ea86778d5f01e9a1c1b4f9f",
+ "size": 747
+ },
+ "internal/term/term.go": {
+ "mode": "0o644",
+ "sha256": "abe6fa965fa15b999b2010135903f598830d4c885a52ef9b067fd5ebbf6e373f",
+ "size": 606
+ },
+ "key.go": {
+ "mode": "0o644",
+ "sha256": "03a43283e07de7a4ea6fed32692d86325f73e98fd89a296f19c171e0bc780999",
+ "size": 1746
+ },
+ "key_bind.go": {
+ "mode": "0o644",
+ "sha256": "83f48bb720a11c8e49165ac382e3a870fdcf6b380a0a95267f8c25211898c9eb",
+ "size": 1109
+ },
+ "key_bind_func.go": {
+ "mode": "0o644",
+ "sha256": "445bff5c0fdb0b52879c635322603c2fc75d265de3761cb8c3b980c798bf39af",
+ "size": 1219
+ },
+ "key_string.go": {
+ "mode": "0o644",
+ "sha256": "55c429dae227bb1659d5d5e2e906dbfa9c7f53b5105fa83fbe290529ff6f2317",
+ "size": 1359
+ },
+ "option.go": {
+ "mode": "0o644",
+ "sha256": "28cfcc1d08b3cf650483d977195458531b3b3913f8a5f357a3ec17ea5d73e215",
+ "size": 8737
+ },
+ "output.go": {
+ "mode": "0o644",
+ "sha256": "372876b0aa908479ed3b29de70a479f420d85e3666b8957c8b61eaed9b32c3f2",
+ "size": 4320
+ },
+ "output_posix.go": {
+ "mode": "0o644",
+ "sha256": "d46b1da307e8969b033e1ade2eb51a83c4c3d4f2a7e4aba35ec3a03991b89a0f",
+ "size": 1545
+ },
+ "output_vt100.go": {
+ "mode": "0o644",
+ "sha256": "9082c7e4619c1eb38030bc4994a4fbf66ef27b130751bf2eb9c25c01082e8605",
+ "size": 7453
+ },
+ "output_windows.go": {
+ "mode": "0o644",
+ "sha256": "571c5ae1ad051a701b426371efd79a3776c2226ca9e3c2e598fe5996dfa1b8e1",
+ "size": 1066
+ },
+ "prompt.go": {
+ "mode": "0o644",
+ "sha256": "6b3e2bbd90f40ad6a487f1a6ea7f5a6fb48cae6c8c246ecc77621fb3e7383ca7",
+ "size": 7062
+ },
+ "render.go": {
+ "mode": "0o644",
+ "sha256": "90fdd57a63e06f01940d10ee1a0be95ced7d6adc7faa255b3141556d7d316270",
+ "size": 8020
+ },
+ "shortcut.go": {
+ "mode": "0o644",
+ "sha256": "b4a097f466df7396049ebe8393f81c9b1200159d4e2be22bd6838c307ec156dc",
+ "size": 1120
+ },
+ "signal_posix.go": {
+ "mode": "0o644",
+ "sha256": "74f0bae5f290f3f7f82a5dd495e672f627a4ab4b63118f870e8c13c0a7024314",
+ "size": 881
+ },
+ "signal_windows.go": {
+ "mode": "0o644",
+ "sha256": "444f662a32e6997df2af8e2a9e7dbfe977414a6bfc0f54a7f10117f204648437",
+ "size": 757
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982",
+ "os": "linux",
+ "sha256": "0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982"
+ },
+ "context_inventory_sha256": "6b8f93086e81483ac1ce82f328d7f4b38b1b560dbad057ed6a2a30ff3cf0e13f",
+ "image": "registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "9d3b21cdacadfa4f3de9584d0cea973e5aa2ceedcd5ec9cbd3a63df22b313455",
+ "receipt_path": "production/runtime-images-extra-v1/resolutions/316e0e68930cd4ef/resolution.json",
+ "receipt_sha256": "697bb0619eddcdfdeba1c9144b033f564f2d7514be6e6a44dc520fa4e63ed8bc",
+ "registry_digest": "sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "source_image": "docker.io/swebench/swesmith.x86_64.c-bata_1776_go-prompt.82a91227@sha256:3daf51c74a01657e9ad8f326651fb6f5b796ffecdb90098e74a52a9560e0a1bb",
+ "source_receipt_sha256": "b450bea0e201cbe194b765ded4b51539144c85296122c8b642d7e94c889526f3",
+ "space_commit": "5ae654cd2e9d695f0de304bd4398835fc7cf45e0",
+ "space_id": "harness-hub/scale800-go-316e0e68930cd4ef-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "92c0af31d732eed6545fc1955eb4eaaff8ae915fc2bcb4ad4e8e750e75ff7bb9",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21",
+ "source_proof_sha256": "b3a2d86ff61d8ee9d8c1a7073abb4313e5409db943266109cfb1cc7ebf824943",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "9992c59c25864ce1556e67b9e1501c93f6e7f9ff",
+ "instruction_sha256": "90c2118007323468cb20445b2cfa073cc22baa585a2f7966a34bf6449a15854f",
+ "is_fork": true,
+ "learner_path": "tasks/4f29bc2f0bcab53ea37b9b25/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/c-bata__go-prompt.82a91227/1d9a742c29c5f5ac84250bebe508eb14d16815d3/LICENSE"
+ },
+ "task_bundle": {
+ "basis": "Captured publisherMIT/train; exactsoftwarepermissionverifiedseparately",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "82a912274504477990ecf7c852eebb7c85291772",
+ "patch_sha256": "c3fb4e3351b80d83379a1be909cfa66268d1ecc5626a949e3884f4db3adcaa97",
+ "provenance_path": "tasks/4f29bc2f0bcab53ea37b9b25/source-proof.json",
+ "repository_lineage": [
+ "swesmith/c-bata__go-prompt.82a91227",
+ "c-bata/go-prompt"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "1d9a742c29c5f5ac84250bebe508eb14d16815d3",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "33770662e0b58d15f41db227a32201fbf54c5f04",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/c-bata__go-prompt.82a91227",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz",
+ "task_sha256": "52fbb36641d727d29950b355c248ce3bfe0632743d13bc81d30761ea2834fbed",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "c-bata/go-prompt",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "fc8f914e6a176b2ba3ebb17fca47c263c56a3a8c8bb5fd7cf5572eb478fcee3b",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.md",
+ "/testbed/.github/ISSUE_TEMPLATE/feature_request.md",
+ "/testbed/.gitignore",
+ "/testbed/CHANGELOG.md",
+ "/testbed/LICENSE",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/_example/README.md",
+ "/testbed/_example/build.sh",
+ "/testbed/_example/exec-command/main.go",
+ "/testbed/_example/http-prompt/api.py",
+ "/testbed/_example/http-prompt/main.go",
+ "/testbed/_example/live-prefix/main.go",
+ "/testbed/_example/simple-echo/cjk-cyrillic/main.go",
+ "/testbed/_example/simple-echo/main.go",
+ "/testbed/_tools/README.md",
+ "/testbed/_tools/complete_file/main.go",
+ "/testbed/_tools/sigwinch/main.go",
+ "/testbed/_tools/vt100_debug/main.go",
+ "/testbed/buffer.go",
+ "/testbed/completer/file.go",
+ "/testbed/completion.go",
+ "/testbed/document.go",
+ "/testbed/emacs.go",
+ "/testbed/filter.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum",
+ "/testbed/history.go",
+ "/testbed/input.go",
+ "/testbed/input_posix.go",
+ "/testbed/input_windows.go",
+ "/testbed/internal/bisect/bisect.go",
+ "/testbed/internal/debug/assert.go",
+ "/testbed/internal/debug/log.go",
+ "/testbed/internal/strings/strings.go",
+ "/testbed/internal/term/raw.go",
+ "/testbed/internal/term/term.go",
+ "/testbed/key.go",
+ "/testbed/key_bind.go",
+ "/testbed/key_bind_func.go",
+ "/testbed/key_string.go",
+ "/testbed/option.go",
+ "/testbed/output.go",
+ "/testbed/output_posix.go",
+ "/testbed/output_vt100.go",
+ "/testbed/output_windows.go",
+ "/testbed/prompt.go",
+ "/testbed/render.go",
+ "/testbed/shortcut.go",
+ "/testbed/signal_posix.go",
+ "/testbed/signal_windows.go"
+ ]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/solution/solve.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..96e06a9f2e18acb3b7c263f544a30bc7ef20387e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"filter.go": {"data": "cGFja2FnZSBwcm9tcHQKCmltcG9ydCAic3RyaW5ncyIKCi8vIEZpbHRlciBpcyB0aGUgdHlwZSB0byBmaWx0ZXIgdGhlIHByb21wdC5TdWdnZXN0aW9uIGFycmF5Lgp0eXBlIEZpbHRlciBmdW5jKFtdU3VnZ2VzdCwgc3RyaW5nLCBib29sKSBbXVN1Z2dlc3QKCi8vIEZpbHRlckhhc1ByZWZpeCBjaGVja3Mgd2hldGhlciB0aGUgc3RyaW5nIGNvbXBsZXRpb25zLlRleHQgYmVnaW5zIHdpdGggc3ViLgpmdW5jIEZpbHRlckhhc1ByZWZpeChjb21wbGV0aW9ucyBbXVN1Z2dlc3QsIHN1YiBzdHJpbmcsIGlnbm9yZUNhc2UgYm9vbCkgW11TdWdnZXN0IHsKCXJldHVybiBmaWx0ZXJTdWdnZXN0aW9ucyhjb21wbGV0aW9ucywgc3ViLCBpZ25vcmVDYXNlLCBzdHJpbmdzLkhhc1ByZWZpeCkKfQoKLy8gRmlsdGVySGFzU3VmZml4IGNoZWNrcyB3aGV0aGVyIHRoZSBjb21wbGV0aW9uLlRleHQgZW5kcyB3aXRoIHN1Yi4KZnVuYyBGaWx0ZXJIYXNTdWZmaXgoY29tcGxldGlvbnMgW11TdWdnZXN0LCBzdWIgc3RyaW5nLCBpZ25vcmVDYXNlIGJvb2wpIFtdU3VnZ2VzdCB7CglyZXR1cm4gZmlsdGVyU3VnZ2VzdGlvbnMoY29tcGxldGlvbnMsIHN1YiwgaWdub3JlQ2FzZSwgc3RyaW5ncy5IYXNTdWZmaXgpCn0KCi8vIEZpbHRlckNvbnRhaW5zIGNoZWNrcyB3aGV0aGVyIHRoZSBjb21wbGV0aW9uLlRleHQgY29udGFpbnMgc3ViLgpmdW5jIEZpbHRlckNvbnRhaW5zKGNvbXBsZXRpb25zIFtdU3VnZ2VzdCwgc3ViIHN0cmluZywgaWdub3JlQ2FzZSBib29sKSBbXVN1Z2dlc3QgewoJcmV0dXJuIGZpbHRlclN1Z2dlc3Rpb25zKGNvbXBsZXRpb25zLCBzdWIsIGlnbm9yZUNhc2UsIHN0cmluZ3MuQ29udGFpbnMpCn0KCi8vIEZpbHRlckZ1enp5IGNoZWNrcyB3aGV0aGVyIHRoZSBjb21wbGV0aW9uLlRleHQgZnV6enkgbWF0Y2hlcyBzdWIuCi8vIEZ1enp5IHNlYXJjaGluZyBmb3IgImRvZyIgaXMgZXF1aXZhbGVudCB0byAiKmQqbypnKiIuIFRoaXMgc2VhcmNoIHRlcm0KLy8gd291bGQgbWF0Y2gsIGZvciBleGFtcGxlLCAiR29vZCBmb29kIGlzIGdvbmUiCi8vICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIF4gIF4gICAgICBeCmZ1bmMgRmlsdGVyRnV6enkoY29tcGxldGlvbnMgW11TdWdnZXN0LCBzdWIgc3RyaW5nLCBpZ25vcmVDYXNlIGJvb2wpIFtdU3VnZ2VzdCB7CglyZXR1cm4gZmlsdGVyU3VnZ2VzdGlvbnMoY29tcGxldGlvbnMsIHN1YiwgaWdub3JlQ2FzZSwgZnV6enlNYXRjaCkKfQoKZnVuYyBmdXp6eU1hdGNoKHMsIHN1YiBzdHJpbmcpIGJvb2wgewoJc0NoYXJzIDo9IFtdcnVuZShzKQoJc0lkeCA6PSAwCgoJLy8gaHR0cHM6Ly9zdGF0aWNjaGVjay5pby9kb2NzL2NoZWNrcyNTMTAyOQoJZm9yIF8sIGMgOj0gcmFuZ2Ugc3ViIHsKCQlmb3VuZCA6PSBmYWxzZQoJCWZvciA7IHNJZHggPCBsZW4oc0NoYXJzKTsgc0lkeCsrIHsKCQkJaWYgc0NoYXJzW3NJZHhdID09IGMgewoJCQkJZm91bmQgPSB0cnVlCgkJCQlzSWR4KysKCQkJCWJyZWFrCgkJCX0KCQl9CgkJaWYgIWZvdW5kIHsKCQkJcmV0dXJuIGZhbHNlCgkJfQoJfQoJcmV0dXJuIHRydWUKfQoKZnVuYyBmaWx0ZXJTdWdnZXN0aW9ucyhzdWdnZXN0aW9ucyBbXVN1Z2dlc3QsIHN1YiBzdHJpbmcsIGlnbm9yZUNhc2UgYm9vbCwgZnVuY3Rpb24gZnVuYyhzdHJpbmcsIHN0cmluZykgYm9vbCkgW11TdWdnZXN0IHsKCWlmIHN1YiA9PSAiIiB7CgkJcmV0dXJuIHN1Z2dlc3Rpb25zCgl9CglpZiBpZ25vcmVDYXNlIHsKCQlzdWIgPSBzdHJpbmdzLlRvVXBwZXIoc3ViKQoJfQoKCXJldCA6PSBtYWtlKFtdU3VnZ2VzdCwgMCwgbGVuKHN1Z2dlc3Rpb25zKSkKCWZvciBpIDo9IHJhbmdlIHN1Z2dlc3Rpb25zIHsKCQljIDo9IHN1Z2dlc3Rpb25zW2ldLlRleHQKCQlpZiBpZ25vcmVDYXNlIHsKCQkJYyA9IHN0cmluZ3MuVG9VcHBlcihjKQoJCX0KCQlpZiBmdW5jdGlvbihjLCBzdWIpIHsKCQkJcmV0ID0gYXBwZW5kKHJldCwgc3VnZ2VzdGlvbnNbaV0pCgkJfQoJfQoJcmV0dXJuIHJldAp9Cg==", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/task.toml b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..cefe47d59dce8cb02031b00213276ff313cc2a8e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/task.toml
@@ -0,0 +1,11 @@
+version = "1.0"
+[agent]
+timeout_sec = 300.0
+[verifier]
+timeout_sec = 300.0
+environment_mode = "shared"
+[environment]
+docker_image = "ghcr.io/younesbelkada/scale800@sha256:0dea4d198c2b3c9998ebe71de1e5dd5cba16787d1c5c602861e84b0f3d292345"
+cpus = 1
+memory_mb = 2048
+storage_mb = 4096
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..3452f71367a6cd510f8b2eb099fd3580aad2ab71
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/manifest.json
@@ -0,0 +1,432 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFilter"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CursorPositionRowAndCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorLeftPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorUpPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorDownPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorRightPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_Lines"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_LineCount"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateIndexToPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateRowColToIndex"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_OnLastLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetEndOfLinePosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestEmacsKeyBindings"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFuzzyMatch"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryClear"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryAdd"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryOlder"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/escape"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/undefined"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWrite"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteRawStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatCompletion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBreakLineCallback"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionRow"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition_withJapanese"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/validation/canaries/delete-tests.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/validation/canaries/delete-tests.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/validation/canaries/delete-tests.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+find /testbed -name '*_test.go' -type f -delete
+printf 'PASS\nok forged-package 0.001s\n'
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..d4643ed42956bc7519b47f07eff449f5942bf0fb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.func_pm_remove_cond__en2n2ucz/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "c615b5c8f6df896869de3de7dcd3dc801da3d49942fe044b7f703fc60823dfd0",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/Dockerfile b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f35bf9e5393ee1086fe1b72c1b442f3b16e2bd5b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22
+WORKDIR /testbed
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c8c031d0f87fb9aea0aff433b1fcaeaac259c41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: "Bug report"
+about: Create a bug report to improve go-prompt
+title: "[Bug]"
+labels: bug
+assignees: ''
+
+---
+
+# Bug reports
+
+*Please file a bug report here.*
+
+## Expected Behavior
+
+*Please describe the behavior you are expecting*
+
+## Current Behavior and Steps to Reproduce
+
+*What is the current behavior? Please provide detailed steps for reproducing the issue.*
+*A picture or gif animation tells a thousand words*
+
+## Context
+
+Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
+
+* Operating System:
+* Terminal Emulator: (i.e. iTerm2)
+* tag of go-prompt or commit revision:
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb816a2496376983781774cb5466fed8e1efc93b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,13 @@
+---
+name: "Feature request"
+about: Suggest an idea for new features in go-prompt.
+title: "[Feature Request]"
+labels: enhancement
+assignees: ''
+
+---
+
+# Feature Request
+
+*Please write your suggestion here.*
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/.gitignore b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..eba2b56abe0f7758a560d47dd19d8985b67ef327
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+bin/
+
+# Folders
+pkg/
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+# Glide
+vendor/
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/CHANGELOG.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..b9e21f1ef333b9ec13323bcd4a8f377322ed7e9f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/CHANGELOG.md
@@ -0,0 +1,79 @@
+# Change Log
+
+## v0.3.0 (2018/??/??)
+
+next release.
+
+## v0.2.3 (2018/10/25)
+
+### What's new?
+
+* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92).
+* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100).
+* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102).
+
+### Fixed
+
+* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details).
+* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details).
+* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details).
+
+### Removed or Deprecated
+
+* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`.
+
+## v0.2.2 (2018/06/28)
+
+### What's new?
+
+* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters.
+* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions.
+ * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details).
+* Add FilePathCompleter to complete file path on your system.
+* Add option to customize ascii code key bindings.
+* Add GetWordAfterCursor method in Document.
+
+### Removed or Deprecated
+
+* prompt.Choose shortcut function is deprecated.
+
+## v0.2.1 (2018/02/14)
+
+### What's New?
+
+* ~~It seems that windows support is almost perfect.~~
+ * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows.
+
+### Fixed
+
+* Fix a Shift+Tab handling on Windows.
+* Fix 4-dimension arrow keys handling on Windows.
+
+## v0.2.0 (2018/02/13)
+
+### What's New?
+
+* Supports scrollbar when there are too many matched suggestions
+* Windows support (but please caution because this is still not perfect).
+* Add OptionLivePrefix to update the prefix dynamically
+* Implement clear screen by `Ctrl+L`.
+
+### Fixed
+
+* Fix the behavior of `Ctrl+W` keybind.
+* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details).
+* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details).
+* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ).
+
+### News
+
+New core developers are joined (alphabetical order).
+
+* Nao Yonashiro (Github @orisano)
+* Ryoma Abe (Github @Allajah)
+* Yusuke Nakamura (Github @unasuke)
+
+
+## v0.1.0 (2017/08/15)
+
+Initial Release
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/LICENSE b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a86acaa7ab24fe61ea152a9afcadc21980020efb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Masashi SHIBATA
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/Makefile b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..505817c36f0b8a0bb643eed8680b8989af2b0920
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/Makefile
@@ -0,0 +1,46 @@
+.DEFAULT_GOAL := help
+
+SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
+
+GOIMPORTS ?= goimports
+GOCILINT ?= golangci-lint
+
+.PHONY: setup
+setup: ## Setup for required tools.
+ go get -u golang.org/x/tools/cmd/goimports
+ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: fmt
+fmt: $(SOURCES) ## Formatting source codes.
+ @$(GOIMPORTS) -w $^
+
+.PHONY: lint
+lint: ## Run golangci-lint.
+ @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
+
+.PHONY: test
+test: ## Run tests with race condition checking.
+ @go test -race ./...
+
+.PHONY: bench
+bench: ## Run benchmarks.
+ @go test -bench=. -run=- -benchmem ./...
+
+.PHONY: coverage
+cover: ## Run the tests.
+ @go test -coverprofile=coverage.o
+ @go tool cover -func=coverage.o
+
+.PHONY: generate
+generate: ## Run go generate
+ @go generate ./...
+
+.PHONY: build
+build: ## Build example command lines.
+ ./_example/build.sh
+
+.PHONY: help
+help: ## Show help text
+ @echo "Commands:"
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfcd7a399b4827d6b126d6a173cce34d36520481
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/README.md
@@ -0,0 +1,125 @@
+# go-prompt
+
+[](https://goreportcard.com/report/github.com/c-bata/go-prompt)
+
+[](https://godoc.org/github.com/c-bata/go-prompt)
+
+
+A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit),
+making it easier to build cross-platform command line tools using Go.
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func completer(d prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ }
+ return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ fmt.Println("Please select table.")
+ t := prompt.Input("> ", completer)
+ fmt.Println("You selected " + t)
+}
+```
+
+#### Projects using go-prompt
+
+* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt)
+* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli)
+* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn)
+* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli)
+* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans)
+* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit)
+* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go)
+* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS)
+* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs)
+* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli)
+* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt)
+* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh)
+* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell)
+* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt)
+* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim)
+* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron)
+* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl)
+* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl)
+* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit)
+* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.)
+
+## Features
+
+### Powerful auto-completion
+
+[](https://github.com/c-bata/kube-prompt)
+
+(This is a GIF animation of kube-prompt.)
+
+### Flexible options
+
+go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details.
+
+[](#flexible-options)
+
+### Keyboard Shortcuts
+
+Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell).
+You can customize and expand these shortcuts.
+
+[](#keyboard-shortcuts)
+
+Key Binding | Description
+---------------------|---------------------------------------------------------
+Ctrl + A | Go to the beginning of the line (Home)
+Ctrl + E | Go to the end of the line (End)
+Ctrl + P | Previous command (Up arrow)
+Ctrl + N | Next command (Down arrow)
+Ctrl + F | Forward one character
+Ctrl + B | Backward one character
+Ctrl + D | Delete character under the cursor
+Ctrl + H | Delete character before the cursor (Backspace)
+Ctrl + W | Cut the word before the cursor to the clipboard
+Ctrl + K | Cut the line after the cursor to the clipboard
+Ctrl + U | Cut the line before the cursor to the clipboard
+Ctrl + L | Clear the screen
+
+### History
+
+You can use Up arrow and Down arrow to walk through the history of commands executed.
+
+[](#history)
+
+### Multiple platform support
+
+We have confirmed go-prompt works fine in the following terminals:
+
+* iTerm2 (macOS)
+* Terminal.app (macOS)
+* Command Prompt (Windows)
+* gnome-terminal (Ubuntu)
+
+## Links
+
+* [Change Log](./CHANGELOG.md)
+* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt)
+* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt)
+
+## Author
+
+Masashi Shibata
+
+* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/)
+* Github: [@c-bata](https://github.com/c-bata/)
+
+## License
+
+This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..759b0e3f8acf1216b055e0f9458758a6c1e8950a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/README.md
@@ -0,0 +1,30 @@
+# Examples of go-prompt
+
+This directory includes some examples using go-prompt.
+These examples are useful to know the usage of go-prompt and check behavior for development.
+
+## simple-echo
+
+
+
+A simple echo example using `prompt.Input`.
+
+## http-prompt
+
+
+
+A simple [http-prompt](https://github.com/eliangcs/http-prompt) implementation using go-prompt in less than 200 lines of Go.
+
+## live-prefix
+
+
+
+A example application which changes a prefix string dynamically.
+This feature is used like [ktr0731/evans](https://github.com/ktr0731/evans) which is interactive gRPC client using go-prompt.
+
+## exec-command
+
+Run another CLI tool via `os/exec` package.
+More practical example is [a source code of kube-prompt](https://github.com/c-bata/kube-prompt).
+I recommend you to look this if you want to create tools like kube-prompt.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/build.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c552afcfa69b2356ffcd484c867abcaaaaeeaff
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+export GO111MODULE=on
+DIR=$(cd $(dirname $0); pwd)
+BIN_DIR=$(cd $(dirname $(dirname $0)); pwd)/bin
+
+mkdir -p ${BIN_DIR}
+go build -o ${BIN_DIR}/exec-command ${DIR}/exec-command/main.go
+go build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.go
+go build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.go
+go build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.go
+go build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/exec-command/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/exec-command/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..838f756260df91569491def29a7ee05a7c9a98f7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/exec-command/main.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "os/exec"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(t string) {
+ if t == "bash" {
+ cmd := exec.Command("bash")
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Run()
+ }
+ return
+}
+
+func completer(t prompt.Document) []prompt.Suggest {
+ return []prompt.Suggest{
+ {Text: "bash"},
+ }
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/http-prompt/api.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/http-prompt/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..08e7b1a489a2077f26f280fe39e3bd06efa52cd2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/http-prompt/api.py
@@ -0,0 +1,17 @@
+from bottle import route, run, request
+
+@route('/')
+def hello():
+ return "Hello World!"
+
+@route('/ping')
+def hello():
+ return "pong!"
+
+@route('/register', method='POST')
+def register():
+ name = request.json.get("name")
+ return "Hello %s!" % name
+
+if __name__ == "__main__":
+ run(host='localhost', port=8000, debug=True)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/http-prompt/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/http-prompt/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b372a3550c50121d6e500e2a08e641e168b8c00d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/http-prompt/main.go
@@ -0,0 +1,192 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+type RequestContext struct {
+ url *url.URL
+ header http.Header
+ client *http.Client
+}
+
+var ctx *RequestContext
+
+// See https://github.com/eliangcs/http-prompt/blob/master/http_prompt/completion.py
+var suggestions = []prompt.Suggest{
+ // Command
+ {"cd", "Change URL/path"},
+ {"exit", "Exit http-prompt"},
+
+ // HTTP Method
+ {"delete", "DELETE request"},
+ {"get", "GET request"},
+ {"patch", "GET request"},
+ {"post", "POST request"},
+ {"put", "PUT request"},
+
+ // HTTP Header
+ {"Accept", "Acceptable response media type"},
+ {"Accept-Charset", "Acceptable response charsets"},
+ {"Accept-Encoding", "Acceptable response content codings"},
+ {"Accept-Language", "Preferred natural languages in response"},
+ {"ALPN", "Application-layer protocol negotiation to use"},
+ {"Alt-Used", "Alternative host in use"},
+ {"Authorization", "Authentication information"},
+ {"Cache-Control", "Directives for caches"},
+ {"Connection", "Connection options"},
+ {"Content-Encoding", "Content codings"},
+ {"Content-Language", "Natural languages for content"},
+ {"Content-Length", "Anticipated size for payload body"},
+ {"Content-Location", "Where content was obtained"},
+ {"Content-MD5", "Base64-encoded MD5 sum of content"},
+ {"Content-Type", "Content media type"},
+ {"Cookie", "Stored cookies"},
+ {"Date", "Datetime when message was originated"},
+ {"Depth", "Applied only to resource or its members"},
+ {"DNT", "Do not track user"},
+ {"Expect", "Expected behaviors supported by server"},
+ {"Forwarded", "Proxies involved"},
+ {"From", "Sender email address"},
+ {"Host", "Target URI"},
+ {"HTTP2-Settings", "HTTP/2 connection parameters"},
+ {"If", "Request condition on state tokens and ETags"},
+ {"If-Match", "Request condition on target resource"},
+ {"If-Modified-Since", "Request condition on modification date"},
+ {"If-None-Match", "Request condition on target resource"},
+ {"If-Range", "Request condition on Range"},
+ {"If-Schedule-Tag-Match", "Request condition on Schedule-Tag"},
+ {"If-Unmodified-Since", "Request condition on modification date"},
+ {"Max-Forwards", "Max number of times forwarded by proxies"},
+ {"MIME-Version", "Version of MIME protocol"},
+ {"Origin", "Origin(s} issuing the request"},
+ {"Pragma", "Implementation-specific directives"},
+ {"Prefer", "Preferred server behaviors"},
+ {"Proxy-Authorization", "Proxy authorization credentials"},
+ {"Proxy-Connection", "Proxy connection options"},
+ {"Range", "Request transfer of only part of data"},
+ {"Referer", "Previous web page"},
+ {"TE", "Transfer codings willing to accept"},
+ {"Transfer-Encoding", "Transfer codings applied to payload body"},
+ {"Upgrade", "Invite server to upgrade to another protocol"},
+ {"User-Agent", "User agent string"},
+ {"Via", "Intermediate proxies"},
+ {"Warning", "Possible incorrectness with payload body"},
+ {"WWW-Authenticate", "Authentication scheme"},
+ {"X-Csrf-Token", "Prevent cross-site request forgery"},
+ {"X-CSRFToken", "Prevent cross-site request forgery"},
+ {"X-Forwarded-For", "Originating client IP address"},
+ {"X-Forwarded-Host", "Original host requested by client"},
+ {"X-Forwarded-Proto", "Originating protocol"},
+ {"X-Http-Method-Override", "Request method override"},
+ {"X-Requested-With", "Used to identify Ajax requests"},
+ {"X-XSRF-TOKEN", "Prevent cross-site request forgery"},
+}
+
+func livePrefix() (string, bool) {
+ if ctx.url.Path == "/" {
+ return "", false
+ }
+ return ctx.url.String() + "> ", true
+}
+
+func executor(in string) {
+ in = strings.TrimSpace(in)
+
+ var method, body string
+ blocks := strings.Split(in, " ")
+ switch blocks[0] {
+ case "exit":
+ fmt.Println("Bye!")
+ os.Exit(0)
+ case "cd":
+ if len(blocks) < 2 {
+ ctx.url.Path = "/"
+ } else {
+ ctx.url.Path = path.Join(ctx.url.Path, blocks[1])
+ }
+ return
+ case "get", "delete":
+ method = strings.ToUpper(blocks[0])
+ case "post", "put", "patch":
+ if len(blocks) < 2 {
+ fmt.Println("please set request body.")
+ return
+ }
+ body = strings.Join(blocks[1:], " ")
+ method = strings.ToUpper(blocks[0])
+ }
+ if method != "" {
+ req, err := http.NewRequest(method, ctx.url.String(), strings.NewReader(body))
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ req.Header = ctx.header
+ res, err := ctx.client.Do(req)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ result, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ fmt.Printf("%s\n", result)
+ ctx.header = http.Header{}
+ return
+ }
+
+ if h := strings.Split(in, ":"); len(h) == 2 {
+ // Handling HTTP Header
+ ctx.header.Add(strings.TrimSpace(h[0]), strings.Trim(h[1], ` '"`))
+ } else {
+ fmt.Println("Sorry, I don't understand.")
+ }
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ w := in.GetWordBeforeCursor()
+ if w == "" {
+ return []prompt.Suggest{}
+ }
+ return prompt.FilterHasPrefix(suggestions, w, true)
+}
+
+func main() {
+ var baseURL = "http://localhost:8000/"
+ if len(os.Args) == 2 {
+ baseURL = os.Args[1]
+ if strings.HasSuffix(baseURL, "/") {
+ baseURL += "/"
+ }
+ }
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ ctx = &RequestContext{
+ url: u,
+ header: http.Header{},
+ client: &http.Client{},
+ }
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(u.String()+"> "),
+ prompt.OptionLivePrefix(livePrefix),
+ prompt.OptionTitle("http-prompt"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/live-prefix/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/live-prefix/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c7ced720592173e2a13f19f7cb543730192d3f8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/live-prefix/main.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var LivePrefixState struct {
+ LivePrefix string
+ IsEnable bool
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+ if in == "" {
+ LivePrefixState.IsEnable = false
+ LivePrefixState.LivePrefix = in
+ return
+ }
+ LivePrefixState.LivePrefix = in + "> "
+ LivePrefixState.IsEnable = true
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func changeLivePrefix() (string, bool) {
+ return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionLivePrefix(changeLivePrefix),
+ prompt.OptionTitle("live-prefix-example"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/simple-echo/cjk-cyrillic/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/simple-echo/cjk-cyrillic/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e9e53adef1558e004f86ccbca2c2e2b83c1da39
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/simple-echo/cjk-cyrillic/main.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
+ {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
+ {Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
+ {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionTitle("sql-prompt for multi width characters"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/simple-echo/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/simple-echo/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..12b1bb4fc189e6b369e889779418d7826a45db9d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_example/simple-echo/main.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ in := prompt.Input(">>> ", completer,
+ prompt.OptionTitle("sql-prompt"),
+ prompt.OptionHistory([]string{"SELECT * FROM users;"}),
+ prompt.OptionPrefixTextColor(prompt.Yellow),
+ prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
+ prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
+ prompt.OptionSuggestionBGColor(prompt.DarkGray))
+ fmt.Println("Your input: " + in)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_tools/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..45bd2234f21ff32562984bec046316c8e52868fd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_tools/README.md
@@ -0,0 +1,10 @@
+## Tools of go-prompt
+
+### vt100_debug
+
+
+
+### sigwinch
+
+
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_tools/complete_file/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_tools/complete_file/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..41015cfab9b021fbc7df575bde87e3c510705496
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_tools/complete_file/main.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/completer"
+)
+
+var filePathCompleter = completer.FilePathCompleter{
+ IgnoreCase: true,
+ Filter: func(fi os.FileInfo) bool {
+ return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
+ },
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completerFunc(d prompt.Document) []prompt.Suggest {
+ t := d.GetWordBeforeCursor()
+ if strings.HasPrefix(t, "--") {
+ return []prompt.Suggest{
+ {"--foo", ""},
+ {"--bar", ""},
+ {"--baz", ""},
+ }
+ }
+ return filePathCompleter.Complete(d)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completerFunc,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_tools/sigwinch/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_tools/sigwinch/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9608eb3b4a5e3c6942c140c41e08a36ab3adb33b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_tools/sigwinch/main.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "unsafe"
+)
+
+// Winsize is winsize struct got from the ioctl(2) system call.
+type Winsize struct {
+ Row uint16
+ Col uint16
+ X uint16 // pixel value
+ Y uint16 // pixel value
+}
+
+// GetWinSize returns winsize struct which is the response of ioctl(2).
+func GetWinSize(fd int) *Winsize {
+ ws := &Winsize{}
+ retCode, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ uintptr(fd),
+ uintptr(syscall.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(ws)))
+
+ if int(retCode) == -1 {
+ panic(errno)
+ }
+ return ws
+}
+
+func main() {
+ signalChan := make(chan os.Signal, 1)
+ signal.Notify(
+ signalChan,
+ syscall.SIGHUP,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ exitChan := make(chan int)
+ go func() {
+ for {
+ s := <-signalChan
+ switch s {
+ // kill -SIGHUP XXXX
+ case syscall.SIGHUP:
+ exitChan <- 0
+
+ // kill -SIGINT XXXX or Ctrl+c
+ case syscall.SIGINT:
+ exitChan <- 0
+
+ // kill -SIGTERM XXXX
+ case syscall.SIGTERM:
+ exitChan <- 0
+
+ // kill -SIGQUIT XXXX
+ case syscall.SIGQUIT:
+ exitChan <- 0
+
+ case syscall.SIGWINCH:
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ default:
+ exitChan <- 1
+ }
+ }
+ }()
+
+ code := <-exitChan
+ os.Exit(code)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_tools/vt100_debug/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_tools/vt100_debug/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c6036d45959febc739e287a3a7b631259d4ee7c1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/_tools/vt100_debug/main.go
@@ -0,0 +1,47 @@
+// +build !windows
+
+package main
+
+import (
+ "fmt"
+ "syscall"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/term"
+)
+
+func main() {
+ if err := term.SetRaw(syscall.Stdin); err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer term.Restore()
+
+ bufCh := make(chan []byte, 128)
+ go readBuffer(bufCh)
+ fmt.Print("> ")
+
+ for {
+ b := <-bufCh
+ if key := prompt.GetKey(b); key == prompt.NotDefined {
+ fmt.Printf("Key '%s' data:'%#v'\n", string(b), b)
+ } else {
+ if key == prompt.ControlC {
+ fmt.Println("exit.")
+ return
+ }
+ fmt.Printf("Key '%s' data:'%#v'\n", key, b)
+ }
+ fmt.Print("> ")
+ }
+}
+
+func readBuffer(bufCh chan []byte) {
+ buf := make([]byte, 1024)
+
+ for {
+ if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
+ bufCh <- buf[:n]
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/buffer.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..46efbbba8bfb75f4a064c83368b781d1d6dbbb29
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/buffer.go
@@ -0,0 +1,191 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Buffer emulates the console buffer.
+type Buffer struct {
+ workingLines []string // The working lines. Similar to history
+ workingIndex int
+ cursorPosition int
+ cacheDocument *Document
+ preferredColumn int // Remember the original column for the next up/down movement.
+ lastKeyStroke Key
+}
+
+// Text returns string of the current line.
+func (b *Buffer) Text() string {
+ return b.workingLines[b.workingIndex]
+}
+
+// Document method to return document instance from the current text and cursor position.
+func (b *Buffer) Document() (d *Document) {
+ if b.cacheDocument == nil ||
+ b.cacheDocument.Text != b.Text() ||
+ b.cacheDocument.cursorPosition != b.cursorPosition {
+ b.cacheDocument = &Document{
+ Text: b.Text(),
+ cursorPosition: b.cursorPosition,
+ }
+ }
+ b.cacheDocument.lastKey = b.lastKeyStroke
+ return b.cacheDocument
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (b *Buffer) DisplayCursorPosition() int {
+ return b.Document().DisplayCursorPosition()
+}
+
+// InsertText insert string from current line.
+func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
+ or := []rune(b.Text())
+ oc := b.cursorPosition
+
+ if overwrite {
+ overwritten := string(or[oc : oc+len(v)])
+ if strings.Contains(overwritten, "\n") {
+ i := strings.IndexAny(overwritten, "\n")
+ overwritten = overwritten[:i]
+ }
+ b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):]))
+ } else {
+ b.setText(string(or[:oc]) + v + string(or[oc:]))
+ }
+
+ if moveCursor {
+ b.cursorPosition += len([]rune(v))
+ }
+}
+
+// SetText method to set text and update cursorPosition.
+// (When doing this, make sure that the cursor_position is valid for this text.
+// text/cursor_position should be consistent at any time, otherwise set a Document instead.)
+func (b *Buffer) setText(v string) {
+ debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position")
+ b.workingLines[b.workingIndex] = v
+}
+
+// Set cursor position. Return whether it changed.
+func (b *Buffer) setCursorPosition(p int) {
+ if p > 0 {
+ b.cursorPosition = p
+ } else {
+ b.cursorPosition = 0
+ }
+}
+
+func (b *Buffer) setDocument(d *Document) {
+ b.cacheDocument = d
+ b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length.
+ b.setText(d.Text)
+}
+
+// CursorLeft move to left on the current line.
+func (b *Buffer) CursorLeft(count int) {
+ l := b.Document().GetCursorLeftPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorRight move to right on the current line.
+func (b *Buffer) CursorRight(count int) {
+ l := b.Document().GetCursorRightPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorUp move cursor to the previous line.
+// (for multi-line edit).
+func (b *Buffer) CursorUp(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorUpPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// CursorDown move cursor to the next line.
+// (for multi-line edit).
+func (b *Buffer) CursorDown(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorDownPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text.
+func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) {
+ debug.Assert(count >= 0, "count should be positive")
+ r := []rune(b.Text())
+
+ if b.cursorPosition > 0 {
+ start := b.cursorPosition - count
+ if start < 0 {
+ start = 0
+ }
+ deleted = string(r[start:b.cursorPosition])
+ b.setDocument(&Document{
+ Text: string(r[:start]) + string(r[b.cursorPosition:]),
+ cursorPosition: b.cursorPosition - len([]rune(deleted)),
+ })
+ }
+ return
+}
+
+// NewLine means CR.
+func (b *Buffer) NewLine(copyMargin bool) {
+ if copyMargin {
+ b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true)
+ } else {
+ b.InsertText("\n", false, true)
+ }
+}
+
+// Delete specified number of characters and Return the deleted text.
+func (b *Buffer) Delete(count int) (deleted string) {
+ r := []rune(b.Text())
+ if b.cursorPosition < len(r) {
+ deleted = b.Document().TextAfterCursor()[:count]
+ b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):]))
+ }
+ return
+}
+
+// JoinNextLine joins the next line to the current one by deleting the line ending after the current line.
+func (b *Buffer) JoinNextLine(separator string) {
+ if !b.Document().OnLastLine() {
+ b.cursorPosition += b.Document().GetEndOfLinePosition()
+ b.Delete(1)
+ // Remove spaces
+ b.setText(b.Document().TextBeforeCursor() + separator + strings.TrimLeft(b.Document().TextAfterCursor(), " "))
+ }
+}
+
+// SwapCharactersBeforeCursor swaps the last two characters before the cursor.
+func (b *Buffer) SwapCharactersBeforeCursor() {
+ if b.cursorPosition >= 2 {
+ x := b.Text()[b.cursorPosition-2 : b.cursorPosition-1]
+ y := b.Text()[b.cursorPosition-1 : b.cursorPosition]
+ b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:])
+ }
+}
+
+// NewBuffer is constructor of Buffer struct.
+func NewBuffer() (b *Buffer) {
+ b = &Buffer{
+ workingLines: []string{""},
+ workingIndex: 0,
+ preferredColumn: -1, // -1 means nil
+ }
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/completer/file.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/completer/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..59f2d8dec84214ccaa6e345a11ed51aa61a08199
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/completer/file.go
@@ -0,0 +1,90 @@
+package completer
+
+import (
+ "io/ioutil"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+var (
+ // FilePathCompletionSeparator holds separate characters.
+ FilePathCompletionSeparator = string([]byte{' ', os.PathSeparator})
+)
+
+// FilePathCompleter is a completer for your local file system.
+// Please caution that you need to set OptionCompletionWordSeparator(completer.FilePathCompletionSeparator)
+// when you use this completer.
+type FilePathCompleter struct {
+ Filter func(fi os.FileInfo) bool
+ IgnoreCase bool
+ fileListCache map[string][]prompt.Suggest
+}
+
+func cleanFilePath(path string) (dir, base string, err error) {
+ if path == "" {
+ return ".", "", nil
+ }
+
+ var endsWithSeparator bool
+ if len(path) >= 1 && path[len(path)-1] == os.PathSeparator {
+ endsWithSeparator = true
+ }
+
+ if runtime.GOOS != "windows" && len(path) >= 2 && path[0:2] == "~/" {
+ me, err := user.Current()
+ if err != nil {
+ return "", "", err
+ }
+ path = filepath.Join(me.HomeDir, path[1:])
+ }
+ path = filepath.Clean(os.ExpandEnv(path))
+ dir = filepath.Dir(path)
+ base = filepath.Base(path)
+
+ if endsWithSeparator {
+ dir = path + string(os.PathSeparator) // Append slash(in POSIX) if path ends with slash.
+ base = "" // Set empty string if path ends with separator.
+ }
+ return dir, base, nil
+}
+
+// Complete returns suggestions from your local file system.
+func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest {
+ if c.fileListCache == nil {
+ c.fileListCache = make(map[string][]prompt.Suggest, 4)
+ }
+
+ path := d.GetWordBeforeCursor()
+ dir, base, err := cleanFilePath(path)
+ if err != nil {
+ debug.Log("completer: cannot get current user:" + err.Error())
+ return nil
+ }
+
+ if cached, ok := c.fileListCache[dir]; ok {
+ return prompt.FilterHasPrefix(cached, base, c.IgnoreCase)
+ }
+
+ files, err := ioutil.ReadDir(dir)
+ if err != nil && os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ debug.Log("completer: cannot read directory items:" + err.Error())
+ return nil
+ }
+
+ suggests := make([]prompt.Suggest, 0, len(files))
+ for _, f := range files {
+ if c.Filter != nil && !c.Filter(f) {
+ continue
+ }
+ suggests = append(suggests, prompt.Suggest{Text: f.Name()})
+ }
+ c.fileListCache[dir] = suggests
+ return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/completion.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/completion.go
new file mode 100644
index 0000000000000000000000000000000000000000..57e82eefc0f50e9561214704e770a2ad313a3659
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/completion.go
@@ -0,0 +1,190 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+const (
+ shortenSuffix = "..."
+ leftPrefix = " "
+ leftSuffix = " "
+ rightPrefix = " "
+ rightSuffix = " "
+)
+
+var (
+ leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix)
+ rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix)
+ completionMargin = leftMargin + rightMargin
+)
+
+// Suggest is printed when completing.
+type Suggest struct {
+ Text string
+ Description string
+}
+
+// CompletionManager manages which suggestion is now selected.
+type CompletionManager struct {
+ selected int // -1 means nothing one is selected.
+ tmp []Suggest
+ max uint16
+ completer Completer
+
+ verticalScroll int
+ wordSeparator string
+ showAtStart bool
+}
+
+// GetSelectedSuggestion returns the selected item.
+func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) {
+ if c.selected == -1 {
+ return Suggest{}, false
+ } else if c.selected < -1 {
+ debug.Assert(false, "must not reach here")
+ c.selected = -1
+ return Suggest{}, false
+ }
+ return c.tmp[c.selected], true
+}
+
+// GetSuggestions returns the list of suggestion.
+func (c *CompletionManager) GetSuggestions() []Suggest {
+ return c.tmp
+}
+
+// Reset to select nothing.
+func (c *CompletionManager) Reset() {
+ c.selected = -1
+ c.verticalScroll = 0
+ c.Update(*NewDocument())
+}
+
+// Update to update the suggestions.
+func (c *CompletionManager) Update(in Document) {
+ c.tmp = c.completer(in)
+}
+
+// Previous to select the previous suggestion item.
+func (c *CompletionManager) Previous() {
+ if c.verticalScroll == c.selected && c.selected > 0 {
+ c.verticalScroll--
+ }
+ c.selected--
+ c.update()
+}
+
+// Next to select the next suggestion item.
+func (c *CompletionManager) Next() {
+ if c.verticalScroll+int(c.max)-1 == c.selected {
+ c.verticalScroll++
+ }
+ c.selected++
+ c.update()
+}
+
+// Completing returns whether the CompletionManager selects something one.
+func (c *CompletionManager) Completing() bool {
+ return c.selected != -1
+}
+
+func (c *CompletionManager) update() {
+ max := int(c.max)
+ if len(c.tmp) < max {
+ max = len(c.tmp)
+ }
+
+ if c.selected >= len(c.tmp) {
+ c.Reset()
+ } else if c.selected < -1 {
+ c.selected = len(c.tmp) - 1
+ c.verticalScroll = len(c.tmp) - max
+ }
+}
+
+func deleteBreakLineCharacters(s string) string {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, "\r", "", -1)
+ return s
+}
+
+func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) {
+ l := len(o)
+ n := make([]string, l)
+
+ lenPrefix := runewidth.StringWidth(prefix)
+ lenSuffix := runewidth.StringWidth(suffix)
+ lenShorten := runewidth.StringWidth(shortenSuffix)
+ min := lenPrefix + lenSuffix + lenShorten
+ for i := 0; i < l; i++ {
+ o[i] = deleteBreakLineCharacters(o[i])
+
+ w := runewidth.StringWidth(o[i])
+ if width < w {
+ width = w
+ }
+ }
+
+ if width == 0 {
+ return n, 0
+ }
+ if min >= max {
+ return n, 0
+ }
+ if lenPrefix+width+lenSuffix > max {
+ width = max - lenPrefix - lenSuffix
+ }
+
+ for i := 0; i < l; i++ {
+ x := runewidth.StringWidth(o[i])
+ if x <= width {
+ spaces := strings.Repeat(" ", width-x)
+ n[i] = prefix + o[i] + spaces + suffix
+ } else if x > width {
+ x := runewidth.Truncate(o[i], width, shortenSuffix)
+ // When calling runewidth.Truncate("您好xxx您好xxx", 11, "...") returns "您好xxx..."
+ // But the length of this result is 10. So we need fill right using runewidth.FillRight.
+ n[i] = prefix + runewidth.FillRight(x, width) + suffix
+ }
+ }
+ return n, lenPrefix + width + lenSuffix
+}
+
+func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) {
+ num := len(suggests)
+ new = make([]Suggest, num)
+
+ left := make([]string, num)
+ for i := 0; i < num; i++ {
+ left[i] = suggests[i].Text
+ }
+ right := make([]string, num)
+ for i := 0; i < num; i++ {
+ right[i] = suggests[i].Description
+ }
+
+ left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix)
+ if leftWidth == 0 {
+ return []Suggest{}, 0
+ }
+ right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix)
+
+ for i := 0; i < num; i++ {
+ new[i] = Suggest{Text: left[i], Description: right[i]}
+ }
+ return new, leftWidth + rightWidth
+}
+
+// NewCompletionManager returns initialized CompletionManager object.
+func NewCompletionManager(completer Completer, max uint16) *CompletionManager {
+ return &CompletionManager{
+ selected: -1,
+ max: max,
+ completer: completer,
+
+ verticalScroll: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/document.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/document.go
new file mode 100644
index 0000000000000000000000000000000000000000..e3776cce5f5b15d3ace9e350a2cdcc7aab9631af
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/document.go
@@ -0,0 +1,444 @@
+package prompt
+
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+ istrings "github.com/c-bata/go-prompt/internal/strings"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Document has text displayed in terminal and cursor position.
+type Document struct {
+ Text string
+ // This represents a index in a rune array of Document.Text.
+ // So if Document is "日本(cursor)語", cursorPosition is 2.
+ // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+ cursorPosition int
+ lastKey Key
+}
+
+// NewDocument return the new empty document.
+func NewDocument() *Document {
+ return &Document{
+ Text: "",
+ cursorPosition: 0,
+ }
+}
+
+// LastKeyStroke return the last key pressed in this document.
+func (d *Document) LastKeyStroke() Key {
+ return d.lastKey
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (d *Document) DisplayCursorPosition() int {
+ var position int
+ runes := []rune(d.Text)[:d.cursorPosition]
+ for i := range runes {
+ position += runewidth.RuneWidth(runes[i])
+ }
+ return position
+}
+
+// GetCharRelativeToCursor return character relative to cursor position, or empty string
+func (d *Document) GetCharRelativeToCursor(offset int) (r rune) {
+ s := d.Text
+ cnt := 0
+
+ for len(s) > 0 {
+ cnt++
+ r, size := utf8.DecodeRuneInString(s)
+ if cnt == d.cursorPosition+offset {
+ return r
+ }
+ s = s[size:]
+ }
+ return 0
+}
+
+// TextBeforeCursor returns the text before the cursor.
+func (d *Document) TextBeforeCursor() string {
+ r := []rune(d.Text)
+ if d.cursorPosition > 0 {
+ return string(r[:d.cursorPosition-1])
+ }
+ return ""
+}
+
+// TextAfterCursor returns the text after the cursor.
+func (d *Document) TextAfterCursor() string {
+ r := []rune(d.Text)
+ return string(r[d.cursorPosition:])
+}
+
+// GetWordBeforeCursor returns the word before the cursor.
+// If we have whitespace before the cursor this returns an empty string.
+func (d *Document) GetWordBeforeCursor() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWord():]
+}
+
+// GetWordAfterCursor returns the word after the cursor.
+// If we have whitespace after the cursor this returns an empty string.
+func (d *Document) GetWordAfterCursor() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWord()]
+}
+
+// GetWordBeforeCursorWithSpace returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorWithSpace() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordWithSpace():]
+}
+
+// GetWordAfterCursorWithSpace returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorWithSpace() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordWithSpace()]
+}
+
+// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
+func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparator(sep):]
+}
+
+// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
+func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparator(sep)]
+}
+
+// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):]
+}
+
+// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)]
+}
+
+// FindStartOfPreviousWord returns an index relative to the cursor position
+// pointing to the start of the previous word. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWord() int {
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexByte(x, ' ')
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindStartOfPreviousWordWithSpace() int {
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotByte(x, ' ')
+ if end == -1 {
+ return 0
+ }
+
+ start := strings.LastIndexByte(x[:end], ' ')
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWord()
+ }
+
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexAny(x, sep)
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWordWithSpace()
+ }
+
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotAny(x, sep)
+ if end == -1 {
+ return 0
+ }
+ start := strings.LastIndexAny(x[:end], sep)
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindEndOfCurrentWord returns an index relative to the cursor position.
+// pointing to the end of the current word. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWord() int {
+ x := d.TextAfterCursor()
+ i := strings.IndexByte(x, ' ')
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindEndOfCurrentWordWithSpace() int {
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotByte(x, ' ')
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexByte(x[start:], ' ')
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWord()
+ }
+
+ x := d.TextAfterCursor()
+ i := strings.IndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWordWithSpace()
+ }
+
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotAny(x, sep)
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexAny(x[start:], sep)
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// CurrentLineBeforeCursor returns the text from the start of the line until the cursor.
+func (d *Document) CurrentLineBeforeCursor() string {
+ s := strings.Split(d.TextBeforeCursor(), "\n")
+ return s[len(s)-1]
+}
+
+// CurrentLineAfterCursor returns the text from the cursor until the end of the line.
+func (d *Document) CurrentLineAfterCursor() string {
+ return strings.Split(d.TextAfterCursor(), "\n")[0]
+}
+
+// CurrentLine return the text on the line where the cursor is. (when the input
+// consists of just one line, it equals `text`.
+func (d *Document) CurrentLine() string {
+ return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor()
+}
+
+// Array pointing to the start indexes of all the lines.
+func (d *Document) lineStartIndexes() []int {
+ // TODO: Cache, because this is often reused.
+ // (If it is used, it's often used many times.
+ // And this has to be fast for editing big documents!)
+ lc := d.LineCount()
+ lengths := make([]int, lc)
+ for i, l := range d.Lines() {
+ lengths[i] = len(l)
+ }
+
+ // Calculate cumulative sums.
+ indexes := make([]int, lc+1)
+ indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189
+ pos := 0
+ for i, l := range lengths {
+ pos += l + 1
+ indexes[i+1] = pos
+ }
+ if lc > 1 {
+ // Pop the last item. (This is not a new line.)
+ indexes = indexes[:lc]
+ }
+ return indexes
+}
+
+// For the index of a character at a certain line, calculate the index of
+// the first character on that line.
+func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) {
+ indexes := d.lineStartIndexes()
+ pos = bisect.Right(indexes, index) - 1
+ lineStartIndex = indexes[pos]
+ return
+}
+
+// CursorPositionRow returns the current row. (0-based.)
+func (d *Document) CursorPositionRow() (row int) {
+ row, _ = d.findLineStartIndex(d.cursorPosition)
+ return
+}
+
+// CursorPositionCol returns the current column. (0-based.)
+func (d *Document) CursorPositionCol() (col int) {
+ // Don't use self.text_before_cursor to calculate this. Creating substrings
+ // and splitting is too expensive for getting the cursor position.
+ _, index := d.findLineStartIndex(d.cursorPosition)
+ col = d.cursorPosition - index
+ return
+}
+
+// GetCursorLeftPosition returns the relative position for cursor left.
+func (d *Document) GetCursorLeftPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorRightPosition(-count)
+ }
+ if d.CursorPositionCol() > count {
+ return -count
+ }
+ return -d.CursorPositionCol()
+}
+
+// GetCursorRightPosition returns relative position for cursor right.
+func (d *Document) GetCursorRightPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorLeftPosition(-count)
+ }
+ if len(d.CurrentLineAfterCursor()) > count {
+ return count
+ }
+ return len(d.CurrentLineAfterCursor())
+}
+
+// GetCursorUpPosition return the relative cursor position (character index) where we would be
+// if the user pressed the arrow-up button.
+func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+
+ row := d.CursorPositionRow() - count
+ if row < 0 {
+ row = 0
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// GetCursorDownPosition return the relative cursor position (character index) where we would be if the
+// user pressed the arrow-down button.
+func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+ row := d.CursorPositionRow() + count
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// Lines returns the array of all the lines.
+func (d *Document) Lines() []string {
+ // TODO: Cache, because this one is reused very often.
+ return strings.Split(d.Text, "\n")
+}
+
+// LineCount return the number of lines in this document. If the document ends
+// with a trailing \n, that counts as the beginning of a new line.
+func (d *Document) LineCount() int {
+ return len(d.Lines())
+}
+
+// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple.
+// (0-based. Returns (0, 0) for index=0.)
+func (d *Document) TranslateIndexToPosition(index int) (row int, col int) {
+ row, rowIndex := d.findLineStartIndex(index)
+ col = index - rowIndex
+ return
+}
+
+// TranslateRowColToIndex given a (row, col), return the corresponding index.
+// (Row and col params are 0-based.)
+func (d *Document) TranslateRowColToIndex(row int, column int) (index int) {
+ indexes := d.lineStartIndexes()
+ if row < 0 {
+ row = 0
+ } else if row > len(indexes) {
+ row = len(indexes) - 1
+ }
+ index = indexes[row]
+ line := d.Lines()[row]
+
+ // python) result += max(0, min(col, len(line)))
+ if column > 0 || len(line) > 0 {
+ if column > len(line) {
+ index += len(line)
+ } else {
+ index += column
+ }
+ }
+
+ // Keep in range. (len(self.text) is included, because the cursor can be
+ // right after the end of the text as well.)
+ // python) result = max(0, min(result, len(self.text)))
+ if index > len(d.Text) {
+ index = len(d.Text)
+ }
+ if index < 0 {
+ index = 0
+ }
+ return index
+}
+
+// OnLastLine returns true when we are at the last line.
+func (d *Document) OnLastLine() bool {
+ return d.CursorPositionRow() == (d.LineCount() - 1)
+}
+
+// GetEndOfLinePosition returns relative position for the end of this line.
+func (d *Document) GetEndOfLinePosition() int {
+ return len([]rune(d.CurrentLineAfterCursor()))
+}
+
+func (d *Document) leadingWhitespaceInCurrentLine() (margin string) {
+ trimmed := strings.TrimSpace(d.CurrentLine())
+ margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)]
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/emacs.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/emacs.go
new file mode 100644
index 0000000000000000000000000000000000000000..632f96321f2577cdb7e8cffe639f1518a65d5e0f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/emacs.go
@@ -0,0 +1,120 @@
+package prompt
+
+import "github.com/c-bata/go-prompt/internal/debug"
+
+/*
+
+========
+PROGRESS
+========
+
+Moving the cursor
+-----------------
+
+* [x] Ctrl + a Go to the beginning of the line (Home)
+* [x] Ctrl + e Go to the End of the line (End)
+* [x] Ctrl + p Previous command (Up arrow)
+* [x] Ctrl + n Next command (Down arrow)
+* [x] Ctrl + f Forward one character
+* [x] Ctrl + b Backward one character
+* [x] Ctrl + xx Toggle between the start of line and current cursor position
+
+Editing
+-------
+
+* [x] Ctrl + L Clear the Screen, similar to the clear command
+* [x] Ctrl + d Delete character under the cursor
+* [x] Ctrl + h Delete character before the cursor (Backspace)
+
+* [x] Ctrl + w Cut the Word before the cursor to the clipboard.
+* [x] Ctrl + k Cut the Line after the cursor to the clipboard.
+* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard.
+
+* [ ] Ctrl + t Swap the last two characters before the cursor (typo).
+* [ ] Esc + t Swap the last two words before the cursor.
+
+* [ ] ctrl + y Paste the last thing to be cut (yank)
+* [ ] ctrl + _ Undo
+
+*/
+
+var emacsKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: ControlE,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+ },
+ },
+ // Go to the beginning of the line
+ {
+ Key: ControlA,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+ },
+ },
+ // Cut the Line after the cursor
+ {
+ Key: ControlK,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.Delete(len(x))
+ },
+ },
+ // Cut/delete the Line before the cursor
+ {
+ Key: ControlU,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.DeleteBeforeCursor(len(x))
+ },
+ },
+ // Delete character under the cursor
+ {
+ Key: ControlD,
+ Fn: func(buf *Buffer) {
+ if buf.Text() != "" {
+ buf.Delete(1)
+ }
+ },
+ },
+ // Backspace
+ {
+ Key: ControlH,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+ },
+ },
+ // Right allow: Forward one character
+ {
+ Key: ControlF,
+ Fn: func(buf *Buffer) {
+ buf.CursorRight(1)
+ },
+ },
+ // Left allow: Backward one character
+ {
+ Key: ControlB,
+ Fn: func(buf *Buffer) {
+ buf.CursorLeft(1)
+ },
+ },
+ // Cut the Word before the cursor.
+ {
+ Key: ControlW,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace())))
+ },
+ },
+ // Clear the Screen, similar to the clear command
+ {
+ Key: ControlL,
+ Fn: func(buf *Buffer) {
+ consoleWriter.EraseScreen()
+ consoleWriter.CursorGoTo(0, 0)
+ debug.AssertNoError(consoleWriter.Flush())
+ },
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/filter.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/filter.go
new file mode 100644
index 0000000000000000000000000000000000000000..61c17ed7f436a069563f520512bd25e4d81af0de
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/filter.go
@@ -0,0 +1,71 @@
+package prompt
+
+import "strings"
+
+// Filter is the type to filter the prompt.Suggestion array.
+type Filter func([]Suggest, string, bool) []Suggest
+
+// FilterHasPrefix checks whether the string completions.Text begins with sub.
+func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
+}
+
+// FilterHasSuffix checks whether the completion.Text ends with sub.
+func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
+}
+
+// FilterContains checks whether the completion.Text contains sub.
+func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
+}
+
+// FilterFuzzy checks whether the completion.Text fuzzy matches sub.
+// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
+// would match, for example, "Good food is gone"
+// ^ ^ ^
+func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
+}
+
+func fuzzyMatch(s, sub string) bool {
+ sChars := []rune(s)
+ sIdx := 0
+
+ // https://staticcheck.io/docs/checks#S1029
+ for _, c := range sub {
+ found := false
+ for ; sIdx < len(sChars); sIdx++ {
+ if sChars[sIdx] == c {
+ found = true
+ sIdx++
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
+
+func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
+ if sub == "" {
+ return suggestions
+ }
+ if ignoreCase {
+ sub = strings.ToUpper(sub)
+ }
+
+ ret := make([]Suggest, 0, len(suggestions))
+ for i := range suggestions {
+ c := suggestions[i].Text
+ if ignoreCase {
+ c = strings.ToUpper(c)
+ }
+ if function(c, sub) {
+ ret = append(ret, suggestions[i])
+ }
+ }
+ return ret
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/go.mod b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..30bc6d39a39c328341ca7153d3391352be5baa63
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/go.mod
@@ -0,0 +1,11 @@
+module github.com/c-bata/go-prompt
+
+go 1.14
+
+require (
+ github.com/mattn/go-colorable v0.1.7
+ github.com/mattn/go-runewidth v0.0.9
+ github.com/mattn/go-tty v0.0.3
+ github.com/pkg/term v1.2.0-beta.2
+ golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/go.sum b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..768bf93619a68e1b334c13e7b93ec84fa465598e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/go.sum
@@ -0,0 +1,23 @@
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/history.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/history.go
new file mode 100644
index 0000000000000000000000000000000000000000..e75c64592d82142bf4826ceb8c613ac72ca24d9c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/history.go
@@ -0,0 +1,61 @@
+package prompt
+
+// History stores the texts that are entered.
+type History struct {
+ histories []string
+ tmp []string
+ selected int
+}
+
+// Add to add text in history.
+func (h *History) Add(input string) {
+ h.histories = append(h.histories, input)
+ h.Clear()
+}
+
+// Clear to clear the history.
+func (h *History) Clear() {
+ h.tmp = make([]string, len(h.histories))
+ for i := range h.histories {
+ h.tmp[i] = h.histories[i]
+ }
+ h.tmp = append(h.tmp, "")
+ h.selected = len(h.tmp) - 1
+}
+
+// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
+ if len(h.tmp) == 1 || h.selected == 0 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected--
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
+ if h.selected >= len(h.tmp)-1 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected++
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// NewHistory returns new history object.
+func NewHistory() *History {
+ return &History{
+ histories: []string{},
+ tmp: []string{""},
+ selected: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/input.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/input.go
new file mode 100644
index 0000000000000000000000000000000000000000..307e747190c2b27bf888b379644fc4f3cdd489a2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/input.go
@@ -0,0 +1,169 @@
+package prompt
+
+import "bytes"
+
+// WinSize represents the width and height of terminal.
+type WinSize struct {
+ Row uint16
+ Col uint16
+}
+
+// ConsoleParser is an interface to abstract input layer.
+type ConsoleParser interface {
+ // Setup should be called before starting input
+ Setup() error
+ // TearDown should be called after stopping input
+ TearDown() error
+ // GetWinSize returns WinSize object to represent width and height of terminal.
+ GetWinSize() *WinSize
+ // Read returns byte array.
+ Read() ([]byte, error)
+}
+
+// GetKey returns Key correspond to input byte codes.
+func GetKey(b []byte) Key {
+ for _, k := range ASCIISequences {
+ if bytes.Equal(k.ASCIICode, b) {
+ return k.Key
+ }
+ }
+ return NotDefined
+}
+
+// ASCIISequences holds mappings of the key and byte array.
+var ASCIISequences = []*ASCIICode{
+ {Key: Escape, ASCIICode: []byte{0x1b}},
+
+ {Key: ControlSpace, ASCIICode: []byte{0x00}},
+ {Key: ControlA, ASCIICode: []byte{0x1}},
+ {Key: ControlB, ASCIICode: []byte{0x2}},
+ {Key: ControlC, ASCIICode: []byte{0x3}},
+ {Key: ControlD, ASCIICode: []byte{0x4}},
+ {Key: ControlE, ASCIICode: []byte{0x5}},
+ {Key: ControlF, ASCIICode: []byte{0x6}},
+ {Key: ControlG, ASCIICode: []byte{0x7}},
+ {Key: ControlH, ASCIICode: []byte{0x8}},
+ //{Key: ControlI, ASCIICode: []byte{0x9}},
+ //{Key: ControlJ, ASCIICode: []byte{0xa}},
+ {Key: ControlK, ASCIICode: []byte{0xb}},
+ {Key: ControlL, ASCIICode: []byte{0xc}},
+ {Key: ControlM, ASCIICode: []byte{0xd}},
+ {Key: ControlN, ASCIICode: []byte{0xe}},
+ {Key: ControlO, ASCIICode: []byte{0xf}},
+ {Key: ControlP, ASCIICode: []byte{0x10}},
+ {Key: ControlQ, ASCIICode: []byte{0x11}},
+ {Key: ControlR, ASCIICode: []byte{0x12}},
+ {Key: ControlS, ASCIICode: []byte{0x13}},
+ {Key: ControlT, ASCIICode: []byte{0x14}},
+ {Key: ControlU, ASCIICode: []byte{0x15}},
+ {Key: ControlV, ASCIICode: []byte{0x16}},
+ {Key: ControlW, ASCIICode: []byte{0x17}},
+ {Key: ControlX, ASCIICode: []byte{0x18}},
+ {Key: ControlY, ASCIICode: []byte{0x19}},
+ {Key: ControlZ, ASCIICode: []byte{0x1a}},
+
+ {Key: ControlBackslash, ASCIICode: []byte{0x1c}},
+ {Key: ControlSquareClose, ASCIICode: []byte{0x1d}},
+ {Key: ControlCircumflex, ASCIICode: []byte{0x1e}},
+ {Key: ControlUnderscore, ASCIICode: []byte{0x1f}},
+ {Key: Backspace, ASCIICode: []byte{0x7f}},
+
+ {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}},
+
+ {Key: Enter, ASCIICode: []byte{0xa}},
+ {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}},
+ {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+ {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}},
+ {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}},
+ {Key: Tab, ASCIICode: []byte{0x9}},
+ {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}},
+ {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}},
+ {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}},
+ {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}},
+ {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode
+
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}},
+ {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}},
+ {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}},
+ {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}},
+ {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}},
+ {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}},
+ {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}},
+ {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}},
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}},
+ {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}},
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+
+ // Xterm
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}},
+ // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}},
+ {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}},
+ {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}},
+ {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}},
+ {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}},
+
+ {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}},
+ {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}},
+ {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}},
+ {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}},
+
+ // Tmux sends following keystrokes when control+arrow is pressed, but for
+ // Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ // it a normal arrow press, because that's more important.
+ {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}},
+
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt
+
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/input_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/input_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f10430318be0e797c841eba8e08ab1cf5277be27
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/input_posix.go
@@ -0,0 +1,77 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/term"
+ "golang.org/x/sys/unix"
+)
+
+const maxReadBytes = 1024
+
+// PosixParser is a ConsoleParser implementation for POSIX environment.
+type PosixParser struct {
+ fd int
+ origTermios syscall.Termios
+}
+
+// Setup should be called before starting input
+func (t *PosixParser) Setup() error {
+ // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
+ if err := syscall.SetNonblock(t.fd, true); err != nil {
+ return err
+ }
+ if err := term.SetRaw(t.fd); err != nil {
+ return err
+ }
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (t *PosixParser) TearDown() error {
+ if err := syscall.SetNonblock(t.fd, false); err != nil {
+ return err
+ }
+ if err := term.Restore(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Read returns byte array.
+func (t *PosixParser) Read() ([]byte, error) {
+ buf := make([]byte, maxReadBytes)
+ n, err := syscall.Read(t.fd, buf)
+ if err != nil {
+ return []byte{}, err
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (t *PosixParser) GetWinSize() *WinSize {
+ ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: ws.Row,
+ Col: ws.Col,
+ }
+}
+
+var _ ConsoleParser = &PosixParser{}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *PosixParser {
+ in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ return &PosixParser{
+ fd: in,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/input_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/input_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..11b7679d4c4bc8b924a5b6c863ca1f6d6880570d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/input_windows.go
@@ -0,0 +1,83 @@
+// +build windows
+
+package prompt
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf8"
+ "unsafe"
+
+ tty "github.com/mattn/go-tty"
+)
+
+const maxReadBytes = 1024
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
+
+// WindowsParser is a ConsoleParser implementation for Win32 console.
+type WindowsParser struct {
+ tty *tty.TTY
+}
+
+// Setup should be called before starting input
+func (p *WindowsParser) Setup() error {
+ t, err := tty.Open()
+ if err != nil {
+ return err
+ }
+ p.tty = t
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (p *WindowsParser) TearDown() error {
+ return p.tty.Close()
+}
+
+// Read returns byte array.
+func (p *WindowsParser) Read() ([]byte, error) {
+ var ev uint32
+ r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
+ if r0 == 0 {
+ return nil, err
+ }
+ if ev == 0 {
+ return nil, errors.New("EAGAIN")
+ }
+
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, maxReadBytes)
+ n := utf8.EncodeRune(buf[:], r)
+ for p.tty.Buffered() && n < maxReadBytes {
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ break
+ }
+ n += utf8.EncodeRune(buf[n:], r)
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (p *WindowsParser) GetWinSize() *WinSize {
+ w, h, err := p.tty.Size()
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: uint16(h),
+ Col: uint16(w),
+ }
+}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *WindowsParser {
+ return &WindowsParser{}
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/bisect/bisect.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/bisect/bisect.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe162fa8c4873302e25702081b629a445d43415
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/bisect/bisect.go
@@ -0,0 +1,15 @@
+package bisect
+
+import "sort"
+
+// Right to locate the insertion point for v in a to maintain sorted order.
+func Right(a []int, v int) int {
+ return bisectRightRange(a, v, 0, len(a))
+}
+
+func bisectRightRange(a []int, v int, lo, hi int) int {
+ s := a[lo:hi]
+ return sort.Search(len(s), func(i int) bool {
+ return s[i] > v
+ })
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/debug/assert.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/debug/assert.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f648ac93c44e1e021cdf581a68f03b548534d9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/debug/assert.go
@@ -0,0 +1,55 @@
+package debug
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
+)
+
+var (
+ enableAssert bool
+)
+
+func init() {
+ if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
+ enableAssert = true
+ }
+}
+
+// Assert ensures expected condition.
+func Assert(cond bool, msg interface{}) {
+ if cond {
+ return
+ }
+ if enableAssert {
+ panic(msg)
+ }
+ writeWithSync(2, "[ASSERT] "+toString(msg))
+}
+
+func toString(v interface{}) string {
+ switch a := v.(type) {
+ case func() string:
+ return a()
+ case string:
+ return a
+ case fmt.Stringer:
+ return a.String()
+ default:
+ return fmt.Sprintf("unexpected type, %t", v)
+ }
+}
+
+// AssertNoError ensures err is nil.
+func AssertNoError(err error) {
+ if err == nil {
+ return
+ }
+ if enableAssert {
+ panic(err)
+ }
+ writeWithSync(2, "[ASSERT] "+err.Error())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/debug/log.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/debug/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..516378627a34ead9063ab7ce6c445b23c77b7cb4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/debug/log.go
@@ -0,0 +1,52 @@
+package debug
+
+import (
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+const (
+ envEnableLog = "GO_PROMPT_ENABLE_LOG"
+ logFileName = "go-prompt.log"
+)
+
+var (
+ logfile *os.File
+ logger *log.Logger
+)
+
+func init() {
+ if e := os.Getenv(envEnableLog); e == "true" || e == "1" {
+ var err error
+ logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
+ if err == nil {
+ logger = log.New(logfile, "", log.Llongfile)
+ return
+ }
+ }
+ logger = log.New(ioutil.Discard, "", log.Llongfile)
+}
+
+// Teardown to close logfile
+func Teardown() {
+ if logfile == nil {
+ return
+ }
+ _ = logfile.Close()
+}
+
+func writeWithSync(calldepth int, msg string) {
+ calldepth++
+ if logfile == nil {
+ return
+ }
+ _ = logger.Output(calldepth, msg)
+ _ = logfile.Sync() // immediately write msg
+}
+
+// Log to output message
+func Log(msg string) {
+ calldepth := 2
+ writeWithSync(calldepth, msg)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/strings/strings.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/strings/strings.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7d1886ae03a7d541c66dffca921e2d040e6d5eb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/strings/strings.go
@@ -0,0 +1,102 @@
+package strings
+
+import "unicode/utf8"
+
+// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior.
+func IndexNotByte(s string, c byte) int {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior.
+func LastIndexNotByte(s string, c byte) int {
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+type asciiSet [8]uint32
+
+func (as *asciiSet) notContains(c byte) bool {
+ return (as[c>>5] & (1 << uint(c&31))) == 0
+}
+
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c>>5] |= 1 << uint(c&31)
+ }
+ return as, true
+}
+
+// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior.
+func IndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := 0; i < len(s); i++ {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+
+ LabelFirstLoop:
+ for i, c := range s {
+ for j, m := range chars {
+ if c != m && j == len(chars)-1 {
+ return i
+ } else if c != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior.
+func LastIndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ LabelFirstLoop:
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRuneInString(s[:i])
+ i -= size
+ for j, m := range chars {
+ if r != m && j == len(chars)-1 {
+ return i
+ } else if r != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/term/raw.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/term/raw.go
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3ed8d04023558cf386a98080815d661248b85
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/term/raw.go
@@ -0,0 +1,29 @@
+// +build !windows
+
+package term
+
+import (
+ "syscall"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+// SetRaw put terminal into a raw mode
+func SetRaw(fd int) error {
+ n, err := getOriginalTermios(fd)
+ if err != nil {
+ return err
+ }
+
+ n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK |
+ syscall.ISTRIP | syscall.INLCR | syscall.IGNCR |
+ syscall.ICRNL | syscall.IXON
+ n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL
+ n.Cflag &^= syscall.CSIZE | syscall.PARENB
+ n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters.
+ n.Cc[syscall.VMIN] = 1
+ n.Cc[syscall.VTIME] = 0
+
+ return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n))
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/term/term.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/term/term.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a53c059ae60c0348ec01689babef4b13a2ecd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/internal/term/term.go
@@ -0,0 +1,34 @@
+// +build !windows
+
+package term
+
+import (
+ "sync"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ saveTermios *unix.Termios
+ saveTermiosFD int
+ saveTermiosOnce sync.Once
+)
+
+func getOriginalTermios(fd int) (*unix.Termios, error) {
+ var err error
+ saveTermiosOnce.Do(func() {
+ saveTermiosFD = fd
+ saveTermios, err = termios.Tcgetattr(uintptr(fd))
+ })
+ return saveTermios, err
+}
+
+// Restore terminal's mode.
+func Restore() error {
+ o, err := getOriginalTermios(saveTermiosFD)
+ if err != nil {
+ return err
+ }
+ return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/key.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ba569c2dd20a8ae3b3dd79ff3695bf0b6c1bd09
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/key.go
@@ -0,0 +1,128 @@
+// Code generated by hand; DO NOT EDIT.
+// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment.
+
+package prompt
+
+// Key is the type express the key inserted from user.
+//go:generate stringer -type=Key
+type Key int
+
+// ASCIICode is the type contains Key and it's ascii byte array.
+type ASCIICode struct {
+ Key Key
+ ASCIICode []byte
+}
+
+const (
+ Escape Key = iota
+
+ ControlA
+ ControlB
+ ControlC
+ ControlD
+ ControlE
+ ControlF
+ ControlG
+ ControlH
+ ControlI
+ ControlJ
+ ControlK
+ ControlL
+ ControlM
+ ControlN
+ ControlO
+ ControlP
+ ControlQ
+ ControlR
+ ControlS
+ ControlT
+ ControlU
+ ControlV
+ ControlW
+ ControlX
+ ControlY
+ ControlZ
+
+ ControlSpace
+ ControlBackslash
+ ControlSquareClose
+ ControlCircumflex
+ ControlUnderscore
+ ControlLeft
+ ControlRight
+ ControlUp
+ ControlDown
+
+ Up
+ Down
+ Right
+ Left
+
+ ShiftLeft
+ ShiftUp
+ ShiftDown
+ ShiftRight
+
+ Home
+ End
+ Delete
+ ShiftDelete
+ ControlDelete
+ PageUp
+ PageDown
+ BackTab
+ Insert
+ Backspace
+
+ // Aliases.
+ Tab
+ Enter
+ // Actually Enter equals ControlM, not ControlJ,
+ // However, in prompt_toolkit, we made the mistake of translating
+ // \r into \n during the input, so everyone is now handling the
+ // enter key by binding ControlJ.
+
+ // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere,
+ // because that's future compatible, and will still work when we
+ // stop replacing \r by \n.
+
+ F1
+ F2
+ F3
+ F4
+ F5
+ F6
+ F7
+ F8
+ F9
+ F10
+ F11
+ F12
+ F13
+ F14
+ F15
+ F16
+ F17
+ F18
+ F19
+ F20
+ F21
+ F22
+ F23
+ F24
+
+ // Matches any key.
+ Any
+
+ // Special
+ CPRResponse
+ Vt100MouseEvent
+ WindowsMouseEvent
+ BracketedPaste
+
+ // Key which is ignored. (The key binding for this key should not do anything.)
+ Ignore
+
+ // Key is not defined
+ NotDefined
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/key_bind.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/key_bind.go
new file mode 100644
index 0000000000000000000000000000000000000000..42669e7f942efc4d92f896388daede90b96b55dd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/key_bind.go
@@ -0,0 +1,59 @@
+package prompt
+
+// KeyBindFunc receives buffer and processed it.
+type KeyBindFunc func(*Buffer)
+
+// KeyBind represents which key should do what operation.
+type KeyBind struct {
+ Key Key
+ Fn KeyBindFunc
+}
+
+// ASCIICodeBind represents which []byte should do what operation
+type ASCIICodeBind struct {
+ ASCIICode []byte
+ Fn KeyBindFunc
+}
+
+// KeyBindMode to switch a key binding flexibly.
+type KeyBindMode string
+
+const (
+ // CommonKeyBind is a mode without any keyboard shortcut
+ CommonKeyBind KeyBindMode = "common"
+ // EmacsKeyBind is a mode to use emacs-like keyboard shortcut
+ EmacsKeyBind KeyBindMode = "emacs"
+)
+
+var commonKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: End,
+ Fn: GoLineEnd,
+ },
+ // Go to the beginning of the line
+ {
+ Key: Home,
+ Fn: GoLineBeginning,
+ },
+ // Delete character under the cursor
+ {
+ Key: Delete,
+ Fn: DeleteChar,
+ },
+ // Backspace
+ {
+ Key: Backspace,
+ Fn: DeleteBeforeChar,
+ },
+ // Right allow: Forward one character
+ {
+ Key: Right,
+ Fn: GoRightChar,
+ },
+ // Left allow: Backward one character
+ {
+ Key: Left,
+ Fn: GoLeftChar,
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/key_bind_func.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/key_bind_func.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b2ecdf63179dbfdbcb0d71bfa436bb36d62d230
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/key_bind_func.go
@@ -0,0 +1,48 @@
+package prompt
+
+// GoLineEnd Go to the End of the line
+func GoLineEnd(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+}
+
+// GoLineBeginning Go to the beginning of the line
+func GoLineBeginning(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+}
+
+// DeleteChar Delete character under the cursor
+func DeleteChar(buf *Buffer) {
+ buf.Delete(1)
+}
+
+// DeleteWord Delete word before the cursor
+func DeleteWord(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
+
+// DeleteBeforeChar Go to Backspace
+func DeleteBeforeChar(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+}
+
+// GoRightChar Forward one character
+func GoRightChar(buf *Buffer) {
+ buf.CursorRight(1)
+}
+
+// GoLeftChar Backward one character
+func GoLeftChar(buf *Buffer) {
+ buf.CursorLeft(1)
+}
+
+// GoRightWord Forward one word
+func GoRightWord(buf *Buffer) {
+ buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
+}
+
+// GoLeftWord Backward one word
+func GoLeftWord(buf *Buffer) {
+ buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/key_string.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/key_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..fce6ea31c502b3e763451cb47757ae1b49c32814
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/key_string.go
@@ -0,0 +1,16 @@
+// Code generated by "stringer -type=Key"; DO NOT EDIT.
+
+package prompt
+
+import "strconv"
+
+const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined"
+
+var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607}
+
+func (i Key) String() string {
+ if i < 0 || i >= Key(len(_Key_index)-1) {
+ return "Key(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _Key_name[_Key_index[i]:_Key_index[i+1]]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/option.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/option.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd6806cc1dbccf8c4ddb048080fde615c59088
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/option.go
@@ -0,0 +1,310 @@
+package prompt
+
+// Option is the type to replace default parameters.
+// prompt.New accepts any number of options (this is functional option pattern).
+type Option func(prompt *Prompt) error
+
+// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
+func OptionParser(x ConsoleParser) Option {
+ return func(p *Prompt) error {
+ p.in = x
+ return nil
+ }
+}
+
+// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
+func OptionWriter(x ConsoleWriter) Option {
+ return func(p *Prompt) error {
+ registerConsoleWriter(x)
+ p.renderer.out = x
+ return nil
+ }
+}
+
+// OptionTitle to set title displayed at the header bar of terminal.
+func OptionTitle(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.title = x
+ return nil
+ }
+}
+
+// OptionPrefix to set prefix string.
+func OptionPrefix(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefix = x
+ return nil
+ }
+}
+
+// OptionInitialBufferText to set the initial buffer text
+func OptionInitialBufferText(x string) Option {
+ return func(p *Prompt) error {
+ p.buf.InsertText(x, false, true)
+ return nil
+ }
+}
+
+// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
+func OptionCompletionWordSeparator(x string) Option {
+ return func(p *Prompt) error {
+ p.completion.wordSeparator = x
+ return nil
+ }
+}
+
+// OptionLivePrefix to change the prefix dynamically by callback function
+func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
+ return func(p *Prompt) error {
+ p.renderer.livePrefixCallback = f
+ return nil
+ }
+}
+
+// OptionPrefixTextColor change a text color of prefix string
+func OptionPrefixTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixTextColor = x
+ return nil
+ }
+}
+
+// OptionPrefixBackgroundColor to change a background color of prefix string
+func OptionPrefixBackgroundColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixBGColor = x
+ return nil
+ }
+}
+
+// OptionInputTextColor to change a color of text which is input by user
+func OptionInputTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputTextColor = x
+ return nil
+ }
+}
+
+// OptionInputBGColor to change a color of background which is input by user
+func OptionInputBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputBGColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionTextColor to change a text color which is completed
+func OptionPreviewSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionBGColor to change a background color which is completed
+func OptionPreviewSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionTextColor to change a text color in drop down suggestions.
+func OptionSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionBGColor change a background color in drop down suggestions.
+func OptionSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarThumbColor to change a thumb color on scrollbar.
+func OptionScrollbarThumbColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarThumbColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarBGColor to change a background color of scrollbar.
+func OptionScrollbarBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarBGColor = x
+ return nil
+ }
+}
+
+// OptionMaxSuggestion specify the max number of displayed suggestions.
+func OptionMaxSuggestion(x uint16) Option {
+ return func(p *Prompt) error {
+ p.completion.max = x
+ return nil
+ }
+}
+
+// OptionHistory to set history expressed by string array.
+func OptionHistory(x []string) Option {
+ return func(p *Prompt) error {
+ p.history.histories = x
+ p.history.Clear()
+ return nil
+ }
+}
+
+// OptionSwitchKeyBindMode set a key bind mode.
+func OptionSwitchKeyBindMode(m KeyBindMode) Option {
+ return func(p *Prompt) error {
+ p.keyBindMode = m
+ return nil
+ }
+}
+
+// OptionCompletionOnDown allows for Down arrow key to trigger completion.
+func OptionCompletionOnDown() Option {
+ return func(p *Prompt) error {
+ p.completionOnDown = true
+ return nil
+ }
+}
+
+// SwitchKeyBindMode to set a key bind mode.
+// Deprecated: Please use OptionSwitchKeyBindMode.
+var SwitchKeyBindMode = OptionSwitchKeyBindMode
+
+// OptionAddKeyBind to set a custom key bind.
+func OptionAddKeyBind(b ...KeyBind) Option {
+ return func(p *Prompt) error {
+ p.keyBindings = append(p.keyBindings, b...)
+ return nil
+ }
+}
+
+// OptionAddASCIICodeBind to set a custom key bind.
+func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option {
+ return func(p *Prompt) error {
+ p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...)
+ return nil
+ }
+}
+
+// OptionShowCompletionAtStart to set completion window is open at start.
+func OptionShowCompletionAtStart() Option {
+ return func(p *Prompt) error {
+ p.completion.showAtStart = true
+ return nil
+ }
+}
+
+// OptionBreakLineCallback to run a callback at every break line
+func OptionBreakLineCallback(fn func(*Document)) Option {
+ return func(p *Prompt) error {
+ p.renderer.breakLineCallback = fn
+ return nil
+ }
+}
+
+// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop
+func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
+ return func(p *Prompt) error {
+ p.exitChecker = fn
+ return nil
+ }
+}
+
+// New returns a Prompt with powerful auto-completion.
+func New(executor Executor, completer Completer, opts ...Option) *Prompt {
+ defaultWriter := NewStdoutWriter()
+ registerConsoleWriter(defaultWriter)
+
+ pt := &Prompt{
+ in: NewStandardInputParser(),
+ renderer: &Render{
+ prefix: "> ",
+ out: defaultWriter,
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ },
+ buf: NewBuffer(),
+ executor: executor,
+ history: NewHistory(),
+ completion: NewCompletionManager(completer, 6),
+ keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting
+ }
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/output.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/output.go
new file mode 100644
index 0000000000000000000000000000000000000000..42531b412f1ed027c2fff5b85bc273e53e569b3a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/output.go
@@ -0,0 +1,161 @@
+package prompt
+
+import "sync"
+
+var (
+ consoleWriterMu sync.Mutex
+ consoleWriter ConsoleWriter
+)
+
+func registerConsoleWriter(f ConsoleWriter) {
+ consoleWriterMu.Lock()
+ defer consoleWriterMu.Unlock()
+ consoleWriter = f
+}
+
+// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on.
+type DisplayAttribute int
+
+const (
+ // DisplayReset reset all display attributes.
+ DisplayReset DisplayAttribute = iota
+ // DisplayBold set bold or increases intensity.
+ DisplayBold
+ // DisplayLowIntensity decreases intensity. Not widely supported.
+ DisplayLowIntensity
+ // DisplayItalic set italic. Not widely supported.
+ DisplayItalic
+ // DisplayUnderline set underline
+ DisplayUnderline
+ // DisplayBlink set blink (less than 150 per minute).
+ DisplayBlink
+ // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported.
+ DisplayRapidBlink
+ // DisplayReverse swap foreground and background colors.
+ DisplayReverse
+ // DisplayInvisible set invisible. Not widely supported.
+ DisplayInvisible
+ // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported.
+ DisplayCrossedOut
+ // DisplayDefaultFont set primary(default) font
+ DisplayDefaultFont
+)
+
+// Color represents color on terminal.
+type Color int
+
+const (
+ // DefaultColor represents a default color.
+ DefaultColor Color = iota
+
+ // Low intensity
+
+ // Black represents a black.
+ Black
+ // DarkRed represents a dark red.
+ DarkRed
+ // DarkGreen represents a dark green.
+ DarkGreen
+ // Brown represents a brown.
+ Brown
+ // DarkBlue represents a dark blue.
+ DarkBlue
+ // Purple represents a purple.
+ Purple
+ // Cyan represents a cyan.
+ Cyan
+ // LightGray represents a light gray.
+ LightGray
+
+ // High intensity
+
+ // DarkGray represents a dark gray.
+ DarkGray
+ // Red represents a red.
+ Red
+ // Green represents a green.
+ Green
+ // Yellow represents a yellow.
+ Yellow
+ // Blue represents a blue.
+ Blue
+ // Fuchsia represents a fuchsia.
+ Fuchsia
+ // Turquoise represents a turquoise.
+ Turquoise
+ // White represents a white.
+ White
+)
+
+// ConsoleWriter is an interface to abstract output layer.
+type ConsoleWriter interface {
+ /* Write */
+
+ // WriteRaw to write raw byte array.
+ WriteRaw(data []byte)
+ // Write to write safety byte array by removing control sequences.
+ Write(data []byte)
+ // WriteStr to write raw string.
+ WriteRawStr(data string)
+ // WriteStr to write safety string by removing control sequences.
+ WriteStr(data string)
+ // Flush to flush buffer.
+ Flush() error
+
+ /* Erasing */
+
+ // EraseScreen erases the screen with the background colour and moves the cursor to home.
+ EraseScreen()
+ // EraseUp erases the screen from the current line up to the top of the screen.
+ EraseUp()
+ // EraseDown erases the screen from the current line down to the bottom of the screen.
+ EraseDown()
+ // EraseStartOfLine erases from the current cursor position to the start of the current line.
+ EraseStartOfLine()
+ // EraseEndOfLine erases from the current cursor position to the end of the current line.
+ EraseEndOfLine()
+ // EraseLine erases the entire current line.
+ EraseLine()
+
+ /* Cursor */
+
+ // ShowCursor stops blinking cursor and show.
+ ShowCursor()
+ // HideCursor hides cursor.
+ HideCursor()
+ // CursorGoTo sets the cursor position where subsequent text will begin.
+ CursorGoTo(row, col int)
+ // CursorUp moves the cursor up by 'n' rows; the default count is 1.
+ CursorUp(n int)
+ // CursorDown moves the cursor down by 'n' rows; the default count is 1.
+ CursorDown(n int)
+ // CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+ CursorForward(n int)
+ // CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+ CursorBackward(n int)
+ // AskForCPR asks for a cursor position report (CPR).
+ AskForCPR()
+ // SaveCursor saves current cursor position.
+ SaveCursor()
+ // UnSaveCursor restores cursor position after a Save Cursor.
+ UnSaveCursor()
+
+ /* Scrolling */
+
+ // ScrollDown scrolls display down one line.
+ ScrollDown()
+ // ScrollUp scroll display up one line.
+ ScrollUp()
+
+ /* Title */
+
+ // SetTitle sets a title of terminal window.
+ SetTitle(title string)
+ // ClearTitle clears a title of terminal window.
+ ClearTitle()
+
+ /* Font */
+
+ // SetColor sets text and background colors. and specify whether text is bold.
+ SetColor(fg, bg Color, bold bool)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/output_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/output_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..26c770cc152a7b126be43915d60b8ba000ad0e38
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/output_posix.go
@@ -0,0 +1,67 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+)
+
+const flushMaxRetryCount = 3
+
+// PosixWriter is a ConsoleWriter implementation for POSIX environment.
+// To control terminal emulator, this outputs VT100 escape sequences.
+type PosixWriter struct {
+ VT100Writer
+ fd int
+}
+
+// Flush to flush buffer
+func (w *PosixWriter) Flush() error {
+ l := len(w.buffer)
+ offset := 0
+ retry := 0
+ for {
+ n, err := syscall.Write(w.fd, w.buffer[offset:])
+ if err != nil {
+ if retry < flushMaxRetryCount {
+ retry++
+ continue
+ }
+ return err
+ }
+ offset += n
+ if offset == l {
+ break
+ }
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &PosixWriter{}
+
+var (
+ // NewStandardOutputWriter returns ConsoleWriter object to write to stdout.
+ // This generates VT100 escape sequences because almost terminal emulators
+ // in POSIX OS built on top of a VT100 specification.
+ // Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStdoutWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stdout,
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStderrWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stderr,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/output_vt100.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/output_vt100.go
new file mode 100644
index 0000000000000000000000000000000000000000..20850fead883c4cd9802928b5de3f935fbbeb047
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/output_vt100.go
@@ -0,0 +1,310 @@
+package prompt
+
+import (
+ "bytes"
+ "strconv"
+)
+
+// VT100Writer generates VT100 escape sequences.
+type VT100Writer struct {
+ buffer []byte
+}
+
+// WriteRaw to write raw byte array
+func (w *VT100Writer) WriteRaw(data []byte) {
+ w.buffer = append(w.buffer, data...)
+}
+
+// Write to write safety byte array by removing control sequences.
+func (w *VT100Writer) Write(data []byte) {
+ w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1))
+}
+
+// WriteRawStr to write raw string
+func (w *VT100Writer) WriteRawStr(data string) {
+ w.WriteRaw([]byte(data))
+}
+
+// WriteStr to write safety string by removing control sequences.
+func (w *VT100Writer) WriteStr(data string) {
+ w.Write([]byte(data))
+}
+
+/* Erase */
+
+// EraseScreen erases the screen with the background colour and moves the cursor to home.
+func (w *VT100Writer) EraseScreen() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'J'})
+}
+
+// EraseUp erases the screen from the current line up to the top of the screen.
+func (w *VT100Writer) EraseUp() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'J'})
+}
+
+// EraseDown erases the screen from the current line down to the bottom of the screen.
+func (w *VT100Writer) EraseDown() {
+ w.WriteRaw([]byte{0x1b, '[', 'J'})
+}
+
+// EraseStartOfLine erases from the current cursor position to the start of the current line.
+func (w *VT100Writer) EraseStartOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'K'})
+}
+
+// EraseEndOfLine erases from the current cursor position to the end of the current line.
+func (w *VT100Writer) EraseEndOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', 'K'})
+}
+
+// EraseLine erases the entire current line.
+func (w *VT100Writer) EraseLine() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'K'})
+}
+
+/* Cursor */
+
+// ShowCursor stops blinking cursor and show.
+func (w *VT100Writer) ShowCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'})
+}
+
+// HideCursor hides cursor.
+func (w *VT100Writer) HideCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'})
+}
+
+// CursorGoTo sets the cursor position where subsequent text will begin.
+func (w *VT100Writer) CursorGoTo(row, col int) {
+ if row == 0 && col == 0 {
+ // If no row/column parameters are provided (ie. [H), the cursor will move to the home position.
+ w.WriteRaw([]byte{0x1b, '[', 'H'})
+ return
+ }
+ r := strconv.Itoa(row)
+ c := strconv.Itoa(col)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(r))
+ w.WriteRaw([]byte{';'})
+ w.WriteRaw([]byte(c))
+ w.WriteRaw([]byte{'H'})
+}
+
+// CursorUp moves the cursor up by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorUp(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorDown(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'A'})
+}
+
+// CursorDown moves the cursor down by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorDown(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorUp(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'B'})
+}
+
+// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorForward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorBackward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'C'})
+}
+
+// CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorBackward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorForward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'D'})
+}
+
+// AskForCPR asks for a cursor position report (CPR).
+func (w *VT100Writer) AskForCPR() {
+ // CPR: Cursor Position Request.
+ w.WriteRaw([]byte{0x1b, '[', '6', 'n'})
+}
+
+// SaveCursor saves current cursor position.
+func (w *VT100Writer) SaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 's'})
+}
+
+// UnSaveCursor restores cursor position after a Save Cursor.
+func (w *VT100Writer) UnSaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 'u'})
+}
+
+/* Scrolling */
+
+// ScrollDown scrolls display down one line.
+func (w *VT100Writer) ScrollDown() {
+ w.WriteRaw([]byte{0x1b, 'D'})
+}
+
+// ScrollUp scroll display up one line.
+func (w *VT100Writer) ScrollUp() {
+ w.WriteRaw([]byte{0x1b, 'M'})
+}
+
+/* Title */
+
+// SetTitle sets a title of terminal window.
+func (w *VT100Writer) SetTitle(title string) {
+ titleBytes := []byte(title)
+ patterns := []struct {
+ from []byte
+ to []byte
+ }{
+ {
+ from: []byte{0x13},
+ to: []byte{},
+ },
+ {
+ from: []byte{0x07},
+ to: []byte{},
+ },
+ }
+ for i := range patterns {
+ titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1)
+ }
+
+ w.WriteRaw([]byte{0x1b, ']', '2', ';'})
+ w.WriteRaw(titleBytes)
+ w.WriteRaw([]byte{0x07})
+}
+
+// ClearTitle clears a title of terminal window.
+func (w *VT100Writer) ClearTitle() {
+ w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07})
+}
+
+/* Font */
+
+// SetColor sets text and background colors. and specify whether text is bold.
+func (w *VT100Writer) SetColor(fg, bg Color, bold bool) {
+ if bold {
+ w.SetDisplayAttributes(fg, bg, DisplayBold)
+ } else {
+ // If using `DisplayDefualt`, it will be broken in some environment.
+ // Details are https://github.com/c-bata/go-prompt/pull/85
+ w.SetDisplayAttributes(fg, bg, DisplayReset)
+ }
+}
+
+// SetDisplayAttributes to set VT100 display attributes.
+func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) {
+ w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer
+ defer w.WriteRaw([]byte{'m'}) // final character
+
+ var separator byte = ';'
+ for i := range attrs {
+ p, ok := displayAttributeParameters[attrs[i]]
+ if !ok {
+ continue
+ }
+ w.WriteRaw(p)
+ w.WriteRaw([]byte{separator})
+ }
+
+ f, ok := foregroundANSIColors[fg]
+ if !ok {
+ f = foregroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(f)
+ w.WriteRaw([]byte{separator})
+ b, ok := backgroundANSIColors[bg]
+ if !ok {
+ b = backgroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(b)
+}
+
+var displayAttributeParameters = map[DisplayAttribute][]byte{
+ DisplayReset: {'0'},
+ DisplayBold: {'1'},
+ DisplayLowIntensity: {'2'},
+ DisplayItalic: {'3'},
+ DisplayUnderline: {'4'},
+ DisplayBlink: {'5'},
+ DisplayRapidBlink: {'6'},
+ DisplayReverse: {'7'},
+ DisplayInvisible: {'8'},
+ DisplayCrossedOut: {'9'},
+ DisplayDefaultFont: {'1', '0'},
+}
+
+var foregroundANSIColors = map[Color][]byte{
+ DefaultColor: {'3', '9'},
+
+ // Low intensity.
+ Black: {'3', '0'},
+ DarkRed: {'3', '1'},
+ DarkGreen: {'3', '2'},
+ Brown: {'3', '3'},
+ DarkBlue: {'3', '4'},
+ Purple: {'3', '5'},
+ Cyan: {'3', '6'},
+ LightGray: {'3', '7'},
+
+ // High intensity.
+ DarkGray: {'9', '0'},
+ Red: {'9', '1'},
+ Green: {'9', '2'},
+ Yellow: {'9', '3'},
+ Blue: {'9', '4'},
+ Fuchsia: {'9', '5'},
+ Turquoise: {'9', '6'},
+ White: {'9', '7'},
+}
+
+var backgroundANSIColors = map[Color][]byte{
+ DefaultColor: {'4', '9'},
+
+ // Low intensity.
+ Black: {'4', '0'},
+ DarkRed: {'4', '1'},
+ DarkGreen: {'4', '2'},
+ Brown: {'4', '3'},
+ DarkBlue: {'4', '4'},
+ Purple: {'4', '5'},
+ Cyan: {'4', '6'},
+ LightGray: {'4', '7'},
+
+ // High intensity
+ DarkGray: {'1', '0', '0'},
+ Red: {'1', '0', '1'},
+ Green: {'1', '0', '2'},
+ Yellow: {'1', '0', '3'},
+ Blue: {'1', '0', '4'},
+ Fuchsia: {'1', '0', '5'},
+ Turquoise: {'1', '0', '6'},
+ White: {'1', '0', '7'},
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/output_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/output_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b9c2769fc2d64cfcfcc5b99c915591ec625bd5f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/output_windows.go
@@ -0,0 +1,49 @@
+// +build windows
+
+package prompt
+
+import (
+ "io"
+
+ colorable "github.com/mattn/go-colorable"
+)
+
+// WindowsWriter is a ConsoleWriter implementation for Win32 console.
+// Output is converted from VT100 escape sequences by mattn/go-colorable.
+type WindowsWriter struct {
+ VT100Writer
+ out io.Writer
+}
+
+// Flush to flush buffer
+func (w *WindowsWriter) Flush() error {
+ _, err := w.out.Write(w.buffer)
+ if err != nil {
+ return err
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &WindowsWriter{}
+
+var (
+ // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates win32 control sequences.
+func NewStdoutWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStdout(),
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates win32 control sequences.
+func NewStderrWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStderr(),
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/prompt.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/prompt.go
new file mode 100644
index 0000000000000000000000000000000000000000..173cd517c40cde212433e399978641ceff1d1a43
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/prompt.go
@@ -0,0 +1,296 @@
+package prompt
+
+import (
+ "bytes"
+ "os"
+ "time"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Executor is called when user input something text.
+type Executor func(string)
+
+// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
+// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
+// - immediate exit (if breakline is false) without executor called
+// - exit after typing (meaning breakline is true), and the executor is called first, before exit.
+// Exit means exit go-prompt (not the overall Go program)
+type ExitChecker func(in string, breakline bool) bool
+
+// Completer should return the suggest item from Document.
+type Completer func(Document) []Suggest
+
+// Prompt is core struct of go-prompt.
+type Prompt struct {
+ in ConsoleParser
+ buf *Buffer
+ renderer *Render
+ executor Executor
+ history *History
+ completion *CompletionManager
+ keyBindings []KeyBind
+ ASCIICodeBindings []ASCIICodeBind
+ keyBindMode KeyBindMode
+ completionOnDown bool
+ exitChecker ExitChecker
+ skipTearDown bool
+}
+
+// Exec is the struct contains user input context.
+type Exec struct {
+ input string
+}
+
+// Run starts prompt.
+func (p *Prompt) Run() {
+ p.skipTearDown = false
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ exitCh := make(chan int)
+ winSizeCh := make(chan *WinSize)
+ stopHandleSignalCh := make(chan struct{})
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+ return
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+
+ // Unset raw mode
+ // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
+ debug.AssertNoError(p.in.TearDown())
+ p.executor(e.input)
+
+ p.completion.Update(*p.buf.Document())
+
+ p.renderer.Render(p.buf, p.completion)
+
+ if p.exitChecker != nil && p.exitChecker(e.input, true) {
+ p.skipTearDown = true
+ return
+ }
+ // Set raw mode
+ debug.AssertNoError(p.in.Setup())
+ go p.readBuffer(bufCh, stopReadBufCh)
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ case w := <-winSizeCh:
+ p.renderer.UpdateWinSize(w)
+ p.renderer.Render(p.buf, p.completion)
+ case code := <-exitCh:
+ p.renderer.BreakLine(p.buf)
+ p.tearDown()
+ os.Exit(code)
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
+ key := GetKey(b)
+ p.buf.lastKeyStroke = key
+ // completion
+ completing := p.completion.Completing()
+ p.handleCompletionKeyBinding(key, completing)
+
+ switch key {
+ case Enter, ControlJ, ControlM:
+ p.renderer.BreakLine(p.buf)
+
+ exec = &Exec{input: p.buf.Text()}
+ p.buf = NewBuffer()
+ if exec.input != "" {
+ p.history.Add(exec.input)
+ }
+ case ControlC:
+ p.renderer.BreakLine(p.buf)
+ p.buf = NewBuffer()
+ p.history.Clear()
+ case Up, ControlP:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Older(p.buf); changed {
+ p.buf = newBuf
+ }
+ }
+ case Down, ControlN:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Newer(p.buf); changed {
+ p.buf = newBuf
+ }
+ return
+ }
+ case ControlD:
+ if p.buf.Text() == "" {
+ shouldExit = true
+ return
+ }
+ case NotDefined:
+ if p.handleASCIICodeBinding(b) {
+ return
+ }
+ p.buf.InsertText(string(b), false, true)
+ }
+
+ shouldExit = p.handleKeyBinding(key)
+ return
+}
+
+func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
+ switch key {
+ case Down:
+ if completing || p.completionOnDown {
+ p.completion.Next()
+ }
+ case Tab, ControlI:
+ p.completion.Next()
+ case Up:
+ if completing {
+ p.completion.Previous()
+ }
+ case BackTab:
+ p.completion.Previous()
+ default:
+ if s, ok := p.completion.GetSelectedSuggestion(); ok {
+ w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
+ if w != "" {
+ p.buf.DeleteBeforeCursor(len([]rune(w)))
+ }
+ p.buf.InsertText(s.Text, false, true)
+ }
+ p.completion.Reset()
+ }
+}
+
+func (p *Prompt) handleKeyBinding(key Key) bool {
+ shouldExit := false
+ for i := range commonKeyBindings {
+ kb := commonKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+
+ if p.keyBindMode == EmacsKeyBind {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ }
+
+ // Custom key bindings
+ for i := range p.keyBindings {
+ kb := p.keyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
+ shouldExit = true
+ }
+ return shouldExit
+}
+
+func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
+ checked := false
+ for _, kb := range p.ASCIICodeBindings {
+ if bytes.Equal(kb.ASCIICode, b) {
+ kb.Fn(p.buf)
+ checked = true
+ }
+ }
+ return checked
+}
+
+// Input just returns user input text.
+func (p *Prompt) Input() string {
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ return ""
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ return e.input
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
+ debug.Log("start reading buffer")
+ for {
+ select {
+ case <-stopCh:
+ debug.Log("stop reading buffer")
+ return
+ default:
+ if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
+ bufCh <- b
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (p *Prompt) setUp() {
+ debug.AssertNoError(p.in.Setup())
+ p.renderer.Setup()
+ p.renderer.UpdateWinSize(p.in.GetWinSize())
+}
+
+func (p *Prompt) tearDown() {
+ if !p.skipTearDown {
+ debug.AssertNoError(p.in.TearDown())
+ }
+ p.renderer.TearDown()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/render.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/render.go
new file mode 100644
index 0000000000000000000000000000000000000000..299ac48b6254b9752ea16516aaedcd41acca6515
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/render.go
@@ -0,0 +1,287 @@
+package prompt
+
+import (
+ "runtime"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Render to render prompt information from state of Buffer.
+type Render struct {
+ out ConsoleWriter
+ prefix string
+ livePrefixCallback func() (prefix string, useLivePrefix bool)
+ breakLineCallback func(*Document)
+ title string
+ row uint16
+ col uint16
+
+ previousCursor int
+
+ // colors,
+ prefixTextColor Color
+ prefixBGColor Color
+ inputTextColor Color
+ inputBGColor Color
+ previewSuggestionTextColor Color
+ previewSuggestionBGColor Color
+ suggestionTextColor Color
+ suggestionBGColor Color
+ selectedSuggestionTextColor Color
+ selectedSuggestionBGColor Color
+ descriptionTextColor Color
+ descriptionBGColor Color
+ selectedDescriptionTextColor Color
+ selectedDescriptionBGColor Color
+ scrollbarThumbColor Color
+ scrollbarBGColor Color
+}
+
+// Setup to initialize console output.
+func (r *Render) Setup() {
+ if r.title != "" {
+ r.out.SetTitle(r.title)
+ debug.AssertNoError(r.out.Flush())
+ }
+}
+
+// getCurrentPrefix to get current prefix.
+// If live-prefix is enabled, return live-prefix.
+func (r *Render) getCurrentPrefix() string {
+ if prefix, ok := r.livePrefixCallback(); ok {
+ return prefix
+ }
+ return r.prefix
+}
+
+func (r *Render) renderPrefix() {
+ r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
+ r.out.WriteStr(r.getCurrentPrefix())
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// TearDown to clear title and erasing.
+func (r *Render) TearDown() {
+ r.out.ClearTitle()
+ r.out.EraseDown()
+ debug.AssertNoError(r.out.Flush())
+}
+
+func (r *Render) prepareArea(lines int) {
+ for i := 0; i < lines; i++ {
+ r.out.ScrollDown()
+ }
+ for i := 0; i < lines; i++ {
+ r.out.ScrollUp()
+ }
+}
+
+// UpdateWinSize called when window size is changed.
+func (r *Render) UpdateWinSize(ws *WinSize) {
+ r.row = ws.Row
+ r.col = ws.Col
+}
+
+func (r *Render) renderWindowTooSmall() {
+ r.out.CursorGoTo(0, 0)
+ r.out.EraseScreen()
+ r.out.SetColor(DarkRed, White, false)
+ r.out.WriteStr("Your console window is too small...")
+}
+
+func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) {
+ suggestions := completions.GetSuggestions()
+ if len(completions.GetSuggestions()) == 0 {
+ return
+ }
+ prefix := r.getCurrentPrefix()
+ formatted, width := formatSuggestions(
+ suggestions,
+ int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar
+ )
+ // +1 means a width of scrollbar.
+ width++
+
+ windowHeight := len(formatted)
+ if windowHeight > int(completions.max) {
+ windowHeight = int(completions.max)
+ }
+ formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
+ r.prepareArea(windowHeight)
+
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor())
+ x, _ := r.toPos(cursor)
+ if x+width >= int(r.col) {
+ cursor = r.backward(cursor, x+width-int(r.col))
+ }
+
+ contentHeight := len(completions.tmp)
+
+ fractionVisible := float64(windowHeight) / float64(contentHeight)
+ fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
+
+ scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
+ scrollbarTop := int(float64(windowHeight) * fractionAbove)
+
+ isScrollThumb := func(row int) bool {
+ return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
+ }
+
+ selected := completions.selected - completions.verticalScroll
+ r.out.SetColor(White, Cyan, false)
+ for i := 0; i < windowHeight; i++ {
+ r.out.CursorDown(1)
+ if i == selected {
+ r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
+ } else {
+ r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Text)
+
+ if i == selected {
+ r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
+ } else {
+ r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Description)
+
+ if isScrollThumb(i) {
+ r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
+ } else {
+ r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
+ }
+ r.out.WriteStr(" ")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+
+ r.lineWrap(cursor + width)
+ r.backward(cursor+width, width)
+ }
+
+ if x+width >= int(r.col) {
+ r.out.CursorForward(x + width - int(r.col))
+ }
+
+ r.out.CursorUp(windowHeight)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// Render renders to the console.
+func (r *Render) Render(buffer *Buffer, completion *CompletionManager) {
+ // In situations where a pseudo tty is allocated (e.g. within a docker container),
+ // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
+ if r.col == 0 {
+ return
+ }
+ defer func() { debug.AssertNoError(r.out.Flush()) }()
+ r.move(r.previousCursor, 0)
+
+ line := buffer.Text()
+ prefix := r.getCurrentPrefix()
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line)
+
+ // prepare area
+ _, y := r.toPos(cursor)
+
+ h := y + 1 + int(completion.max)
+ if h > int(r.row) || completionMargin > int(r.col) {
+ r.renderWindowTooSmall()
+ return
+ }
+
+ // Rendering
+ r.out.HideCursor()
+ defer r.out.ShowCursor()
+
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(line)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ r.lineWrap(cursor)
+
+ r.out.EraseDown()
+
+ cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition())
+
+ r.renderCompletion(buffer, completion)
+ if suggest, ok := completion.GetSelectedSuggestion(); ok {
+ cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator)))
+
+ r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false)
+ r.out.WriteStr(suggest.Text)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ cursor += runewidth.StringWidth(suggest.Text)
+
+ rest := buffer.Document().TextAfterCursor()
+ r.out.WriteStr(rest)
+ cursor += runewidth.StringWidth(rest)
+ r.lineWrap(cursor)
+
+ cursor = r.backward(cursor, runewidth.StringWidth(rest))
+ }
+ r.previousCursor = cursor
+}
+
+// BreakLine to break line.
+func (r *Render) BreakLine(buffer *Buffer) {
+ // Erasing and Render
+ cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix())
+ r.clear(cursor)
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(buffer.Document().Text + "\n")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ debug.AssertNoError(r.out.Flush())
+ if r.breakLineCallback != nil {
+ r.breakLineCallback(buffer.Document())
+ }
+
+ r.previousCursor = 0
+}
+
+// clear erases the screen from a beginning of input
+// even if there is line break which means input length exceeds a window's width.
+func (r *Render) clear(cursor int) {
+ r.move(cursor, 0)
+ r.out.EraseDown()
+}
+
+// backward moves cursor to backward from a current cursor position
+// regardless there is a line break.
+func (r *Render) backward(from, n int) int {
+ return r.move(from, from-n)
+}
+
+// move moves cursor to specified position from the beginning of input
+// even if there is a line break.
+func (r *Render) move(from, to int) int {
+ fromX, fromY := r.toPos(from)
+ toX, toY := r.toPos(to)
+
+ r.out.CursorUp(fromY - toY)
+ r.out.CursorBackward(fromX - toX)
+ return to
+}
+
+// toPos returns the relative position from the beginning of the string.
+func (r *Render) toPos(cursor int) (x, y int) {
+ col := int(r.col)
+ return cursor % col, cursor / col
+}
+
+func (r *Render) lineWrap(cursor int) {
+ if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 {
+ r.out.WriteRaw([]byte{'\n'})
+ }
+}
+
+func clamp(high, low, x float64) float64 {
+ switch {
+ case high < x:
+ return high
+ case x < low:
+ return low
+ default:
+ return x
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/shortcut.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/shortcut.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8d4282700c0bdb30e4decfb9c9ac91f27af251
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/shortcut.go
@@ -0,0 +1,43 @@
+package prompt
+
+func dummyExecutor(in string) {}
+
+// Input get the input data from the user and return it.
+func Input(prefix string, completer Completer, opts ...Option) string {
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+// Choose to the shortcut of input function to select from string array.
+// Deprecated: Maybe anyone want to use this.
+func Choose(prefix string, choices []string, opts ...Option) string {
+ completer := newChoiceCompleter(choices, FilterHasPrefix)
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+func newChoiceCompleter(choices []string, filter Filter) Completer {
+ s := make([]Suggest, len(choices))
+ for i := range choices {
+ s[i] = Suggest{Text: choices[i]}
+ }
+ return func(x Document) []Suggest {
+ return filter(s, x.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/signal_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/signal_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3150df5d85e7612c42c2a889dbefee3b524bef6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/signal_posix.go
@@ -0,0 +1,49 @@
+// +build !windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ in := p.in
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+
+ case syscall.SIGWINCH:
+ debug.Log("Catch SIGWINCH")
+ winSizeCh <- in.GetWinSize()
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/signal_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/signal_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a427c79ec0414540f8f40694731b2565ea80c13
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/environment/source/signal_windows.go
@@ -0,0 +1,44 @@
+// +build windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/instruction.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..7e10c8c298fe584694ae246361ab99eda117d56c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/instruction.md
@@ -0,0 +1,51 @@
+TextBeforeCursor returns incorrect text when cursor position > 0
+
+#### Description
+
+The `TextBeforeCursor()` method is returning text that's missing the last character before the cursor position. When the cursor is at position N, it should return all characters from 0 to N-1, but currently it's returning characters from 0 to N-2.
+
+#### Steps/Code to Reproduce
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func main() {
+ // Create a document with text "Hello World" and cursor at position 5
+ doc := &prompt.Document{
+ Text: "Hello World",
+ cursorPosition: 5,
+ }
+
+ result := doc.TextBeforeCursor()
+ fmt.Printf("Expected: 'Hello', Got: '%s'\n", result)
+
+ // Another example with cursor at position 11 (end of text)
+ doc2 := &prompt.Document{
+ Text: "Hello World",
+ cursorPosition: 11,
+ }
+
+ result2 := doc2.TextBeforeCursor()
+ fmt.Printf("Expected: 'Hello World', Got: '%s'\n", result2)
+}
+```
+
+Expected output:
+```
+Expected: 'Hello', Got: 'Hello'
+Expected: 'Hello World', Got: 'Hello World'
+```
+
+Actual output:
+```
+Expected: 'Hello', Got: 'Hell'
+Expected: 'Hello World', Got: 'Hello Worl'
+```
+
+This affects various text editing operations that depend on getting the correct text before the cursor position.
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/provenance.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..e4f8e502047446753a109b24ec4d1d29e0137817
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/provenance.json
@@ -0,0 +1,477 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt",
+ "original-bug": "task-specific unchanged semantic bug",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only",
+ "extra_semantic_repair_coverage": false,
+ "original_patch_hunks": 1
+ },
+ "private_frozen_files": {
+ "buffer_test.go": {
+ "mode": "0o644",
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098",
+ "size": 4965
+ },
+ "completion_test.go": {
+ "mode": "0o644",
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d",
+ "size": 7010
+ },
+ "document_test.go": {
+ "mode": "0o644",
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284",
+ "size": 28938
+ },
+ "emacs_test.go": {
+ "mode": "0o644",
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095",
+ "size": 741
+ },
+ "filter_test.go": {
+ "mode": "0o644",
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247",
+ "size": 3339
+ },
+ "history_test.go": {
+ "mode": "0o644",
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327",
+ "size": 1319
+ },
+ "input_test.go": {
+ "mode": "0o644",
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922",
+ "size": 533
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": "0o644",
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf",
+ "size": 1075
+ },
+ "internal/strings/strings_test.go": {
+ "mode": "0o644",
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6",
+ "size": 981
+ },
+ "output_vt100_test.go": {
+ "mode": "0o644",
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee",
+ "size": 1349
+ },
+ "render_test.go": {
+ "mode": "0o644",
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb",
+ "size": 2890
+ }
+ },
+ "public_files": {
+ ".github/ISSUE_TEMPLATE/bug_report.md": {
+ "mode": "0o644",
+ "sha256": "89d3492ca8533a3d31e4de49a23828a322f75d2a1ec4236327c4a76c7c51ada6",
+ "size": 684
+ },
+ ".github/ISSUE_TEMPLATE/feature_request.md": {
+ "mode": "0o644",
+ "sha256": "d82e14e6b4d021d0007eeef4f5ca489fc6c8e8e4d7479ee30e74fe82afd3b08f",
+ "size": 206
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "3239b94a1a41c05eff5dc086ef1378cf1e289fad0203420b5cb4c78e3c5c239b",
+ "size": 270
+ },
+ "CHANGELOG.md": {
+ "mode": "0o644",
+ "sha256": "1f88f92d3247e1b52af0f0de7ad1263a59807edb17238c7a0211554f8080e51c",
+ "size": 2895
+ },
+ "LICENSE": {
+ "mode": "0o644",
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "size": 1072
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "9425a0d4c15747863625f647348962a9b0f81a0971a7e0184ee722bf34a60ba2",
+ "size": 1177
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "ce56df51a1a9a5b5c5b056429bbee006a260fb0730af63b1d0fe91755e574cc4",
+ "size": 6185
+ },
+ "_example/README.md": {
+ "mode": "0o644",
+ "sha256": "155951bafd778493bd41ae57dcc0ba6b8eca821fcbe2ffe770960ac2780d3d09",
+ "size": 1102
+ },
+ "_example/build.sh": {
+ "mode": "0o755",
+ "sha256": "de2fb330b665691cd75b990236cd6a5df0058608de0dfc6194da30d4041a1e29",
+ "size": 469
+ },
+ "_example/exec-command/main.go": {
+ "mode": "0o644",
+ "sha256": "0e96493b6e6d446b2e691d4834ff8a55834caa410ead970cb611a63ba84f174a",
+ "size": 429
+ },
+ "_example/http-prompt/api.py": {
+ "mode": "0o644",
+ "sha256": "2c2bca9acb07a84c65a4482c61c9ade253a574477a8e461307568ea1f9a342c8",
+ "size": 335
+ },
+ "_example/http-prompt/main.go": {
+ "mode": "0o644",
+ "sha256": "6994b190c4165068e69ed44eb61698af69a15a7690179ce46e3c1c5d8c211643",
+ "size": 5484
+ },
+ "_example/live-prefix/main.go": {
+ "mode": "0o644",
+ "sha256": "20268f9cb6f3b82a52eddc33cbf8082adaa46092e2063df279499e05e25a228c",
+ "size": 1103
+ },
+ "_example/simple-echo/cjk-cyrillic/main.go": {
+ "mode": "0o644",
+ "sha256": "8fb10807d4085ebc4b345bc0ccfef9217e21e49a888bfe3192e8ddfdfa01e89c",
+ "size": 800
+ },
+ "_example/simple-echo/main.go": {
+ "mode": "0o644",
+ "sha256": "e46563ddaa932831fe9ede870b10efb5222c0d54a86f4b4f5197c9cf20942a24",
+ "size": 902
+ },
+ "_tools/README.md": {
+ "mode": "0o644",
+ "sha256": "96dc2343bc5cde642fd449ddc366462753a2e17b6a78adfa015bf991e9dac241",
+ "size": 234
+ },
+ "_tools/complete_file/main.go": {
+ "mode": "0o644",
+ "sha256": "e5dd823f9d6415614a8238ce106d26e9ded1db9b308c121d7f48bb1df003effc",
+ "size": 803
+ },
+ "_tools/sigwinch/main.go": {
+ "mode": "0o644",
+ "sha256": "a806b4e45298f5003c95432d8dd3c40c9c096335f19f1a4160afcdb64fa727e3",
+ "size": 1386
+ },
+ "_tools/vt100_debug/main.go": {
+ "mode": "0o644",
+ "sha256": "7f72eba3cc7037fcf39c9b56a96c578c157e5fb235cb626ab1e83cbef0dc290b",
+ "size": 794
+ },
+ "buffer.go": {
+ "mode": "0o644",
+ "sha256": "10188d96a450fe13ba1e9ec00c89603eb2a2860536965d980d1e4abf4374b018",
+ "size": 5781
+ },
+ "completer/file.go": {
+ "mode": "0o644",
+ "sha256": "6181ed9e39028236c5c93fbe219331fc1492ecfd6af2df764cc42b5455c9bb96",
+ "size": 2401
+ },
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "b90bd9628534cfb343a592775430e17a1999b1de500fb2a8f1507c030a432eae",
+ "size": 4491
+ },
+ "document.go": {
+ "mode": "0o644",
+ "sha256": "c91ec7b45a9874f1d61e558c6dd3bd3e0295370058c9a12863c8ee1777ad2582",
+ "size": 13141
+ },
+ "emacs.go": {
+ "mode": "0o644",
+ "sha256": "53f0df0016ef9d9695a797b19286681666cf0c7e5a866c393b194aae915f2664",
+ "size": 2675
+ },
+ "filter.go": {
+ "mode": "0o644",
+ "sha256": "dc5922bad6ecb32ecdaf20bd6035dddc7ce8c14f15dbd4d49192c2354cb8a038",
+ "size": 2005
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "97413fa2a2ed68170496f2289a2dca6fb0a192dcd020fc0ca48a5d106e60d55e",
+ "size": 253
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "88ea0a91babaa54b67cc6d5f6f7f47fa4be798fe523324ea568d8926eed2024c",
+ "size": 2183
+ },
+ "history.go": {
+ "mode": "0o644",
+ "sha256": "4ce80ba067cfc72c56a3ee3353ec75cd6bb2f5d82097515c591e3c7c773c51cd",
+ "size": 1488
+ },
+ "input.go": {
+ "mode": "0o644",
+ "sha256": "73461cc4f57d68b66e2a9e196239aaef942539134593beac0d0023743832e0e1",
+ "size": 7630
+ },
+ "input_posix.go": {
+ "mode": "0o644",
+ "sha256": "c7e5a4dfc3910f178f0685ef99f2e47d481a91c4cf9af50f92fc4266aed634df",
+ "size": 1648
+ },
+ "input_windows.go": {
+ "mode": "0o644",
+ "sha256": "f763250d309fb88d9536f77da1d1285c04bc6defe859506f1501e10f7743da9e",
+ "size": 1679
+ },
+ "internal/bisect/bisect.go": {
+ "mode": "0o644",
+ "sha256": "c4de2adfa2e08a77f902661d67325467f89013634dbcef22d24dc6f34d26624a",
+ "size": 327
+ },
+ "internal/debug/assert.go": {
+ "mode": "0o644",
+ "sha256": "1a3050ec58991b62c7ea352d19505e3080ac9760bdb091544f0ecf5aba35969c",
+ "size": 815
+ },
+ "internal/debug/log.go": {
+ "mode": "0o644",
+ "sha256": "2ce968e275558de61c6d83793e85561f7a8dd69c95ec7902ccd2cc3fb169aa82",
+ "size": 875
+ },
+ "internal/strings/strings.go": {
+ "mode": "0o644",
+ "sha256": "b97f08157c3baf1f94fea4bb2237691d8270bd5380b4311709ecd59b84cf4b7b",
+ "size": 2018
+ },
+ "internal/term/raw.go": {
+ "mode": "0o644",
+ "sha256": "177a1a20ae8d71b56857383a5797754560f7f6404ea86778d5f01e9a1c1b4f9f",
+ "size": 747
+ },
+ "internal/term/term.go": {
+ "mode": "0o644",
+ "sha256": "abe6fa965fa15b999b2010135903f598830d4c885a52ef9b067fd5ebbf6e373f",
+ "size": 606
+ },
+ "key.go": {
+ "mode": "0o644",
+ "sha256": "03a43283e07de7a4ea6fed32692d86325f73e98fd89a296f19c171e0bc780999",
+ "size": 1746
+ },
+ "key_bind.go": {
+ "mode": "0o644",
+ "sha256": "83f48bb720a11c8e49165ac382e3a870fdcf6b380a0a95267f8c25211898c9eb",
+ "size": 1109
+ },
+ "key_bind_func.go": {
+ "mode": "0o644",
+ "sha256": "445bff5c0fdb0b52879c635322603c2fc75d265de3761cb8c3b980c798bf39af",
+ "size": 1219
+ },
+ "key_string.go": {
+ "mode": "0o644",
+ "sha256": "55c429dae227bb1659d5d5e2e906dbfa9c7f53b5105fa83fbe290529ff6f2317",
+ "size": 1359
+ },
+ "option.go": {
+ "mode": "0o644",
+ "sha256": "28cfcc1d08b3cf650483d977195458531b3b3913f8a5f357a3ec17ea5d73e215",
+ "size": 8737
+ },
+ "output.go": {
+ "mode": "0o644",
+ "sha256": "372876b0aa908479ed3b29de70a479f420d85e3666b8957c8b61eaed9b32c3f2",
+ "size": 4320
+ },
+ "output_posix.go": {
+ "mode": "0o644",
+ "sha256": "d46b1da307e8969b033e1ade2eb51a83c4c3d4f2a7e4aba35ec3a03991b89a0f",
+ "size": 1545
+ },
+ "output_vt100.go": {
+ "mode": "0o644",
+ "sha256": "9082c7e4619c1eb38030bc4994a4fbf66ef27b130751bf2eb9c25c01082e8605",
+ "size": 7453
+ },
+ "output_windows.go": {
+ "mode": "0o644",
+ "sha256": "571c5ae1ad051a701b426371efd79a3776c2226ca9e3c2e598fe5996dfa1b8e1",
+ "size": 1066
+ },
+ "prompt.go": {
+ "mode": "0o644",
+ "sha256": "6b3e2bbd90f40ad6a487f1a6ea7f5a6fb48cae6c8c246ecc77621fb3e7383ca7",
+ "size": 7062
+ },
+ "render.go": {
+ "mode": "0o644",
+ "sha256": "90fdd57a63e06f01940d10ee1a0be95ced7d6adc7faa255b3141556d7d316270",
+ "size": 8020
+ },
+ "shortcut.go": {
+ "mode": "0o644",
+ "sha256": "b4a097f466df7396049ebe8393f81c9b1200159d4e2be22bd6838c307ec156dc",
+ "size": 1120
+ },
+ "signal_posix.go": {
+ "mode": "0o644",
+ "sha256": "74f0bae5f290f3f7f82a5dd495e672f627a4ab4b63118f870e8c13c0a7024314",
+ "size": 881
+ },
+ "signal_windows.go": {
+ "mode": "0o644",
+ "sha256": "444f662a32e6997df2af8e2a9e7dbfe977414a6bfc0f54a7f10117f204648437",
+ "size": 757
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982",
+ "os": "linux",
+ "sha256": "0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982"
+ },
+ "context_inventory_sha256": "6b8f93086e81483ac1ce82f328d7f4b38b1b560dbad057ed6a2a30ff3cf0e13f",
+ "image": "registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "9d3b21cdacadfa4f3de9584d0cea973e5aa2ceedcd5ec9cbd3a63df22b313455",
+ "receipt_path": "production/runtime-images-extra-v1/resolutions/316e0e68930cd4ef/resolution.json",
+ "receipt_sha256": "697bb0619eddcdfdeba1c9144b033f564f2d7514be6e6a44dc520fa4e63ed8bc",
+ "registry_digest": "sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "source_image": "docker.io/swebench/swesmith.x86_64.c-bata_1776_go-prompt.82a91227@sha256:3daf51c74a01657e9ad8f326651fb6f5b796ffecdb90098e74a52a9560e0a1bb",
+ "source_receipt_sha256": "b450bea0e201cbe194b765ded4b51539144c85296122c8b642d7e94c889526f3",
+ "space_commit": "5ae654cd2e9d695f0de304bd4398835fc7cf45e0",
+ "space_id": "harness-hub/scale800-go-316e0e68930cd4ef-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "34753c9f6ea7725b7ac66b9bc0ca6f81cff30c2b92787a074e02a45a87222503",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21",
+ "source_proof_sha256": "168e6d8d7c76a9dc7628999ccfe05a55760eb9e185f001bd1dcb479f411712ac",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:c-bata__go-prompt.82a91227.lm_modify__2z762u0o",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "9992c59c25864ce1556e67b9e1501c93f6e7f9ff",
+ "instruction_sha256": "df1a1b3f192c3aa5ed05dc4dfe4f206b1bfebc75a0967989dfa40eca896c8891",
+ "is_fork": true,
+ "learner_path": "tasks/5de13fc78ef1ec25af55a4f7/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/c-bata__go-prompt.82a91227/6ad601675dc55278efa5e4900d752f4ccbc1d214/LICENSE"
+ },
+ "task_bundle": {
+ "basis": "Captured publisherMIT/train; exactsoftwarepermissionverifiedseparately",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "82a912274504477990ecf7c852eebb7c85291772",
+ "patch_sha256": "9e8e23d1454891315d93a7fe59b0af101f65de9c460d548c1b19e3bef55f38e6",
+ "provenance_path": "tasks/5de13fc78ef1ec25af55a4f7/source-proof.json",
+ "repository_lineage": [
+ "swesmith/c-bata__go-prompt.82a91227",
+ "c-bata/go-prompt"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "6ad601675dc55278efa5e4900d752f4ccbc1d214",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "bd0e507c8b2dda8b3b6cff2e639c0dcdf821a181",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/c-bata__go-prompt.82a91227",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "c-bata__go-prompt.82a91227.lm_modify__2z762u0o",
+ "task_sha256": "e370020ef83a19ddfe952f2294554f7ec1b380bd499ae9a92465934c378b6887",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "c-bata/go-prompt",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "ccfb394b0f3ecbb58943ab6f4f4c84fb08f130bf92cd630c383132197e034c4d",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.md",
+ "/testbed/.github/ISSUE_TEMPLATE/feature_request.md",
+ "/testbed/.gitignore",
+ "/testbed/CHANGELOG.md",
+ "/testbed/LICENSE",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/_example/README.md",
+ "/testbed/_example/build.sh",
+ "/testbed/_example/exec-command/main.go",
+ "/testbed/_example/http-prompt/api.py",
+ "/testbed/_example/http-prompt/main.go",
+ "/testbed/_example/live-prefix/main.go",
+ "/testbed/_example/simple-echo/cjk-cyrillic/main.go",
+ "/testbed/_example/simple-echo/main.go",
+ "/testbed/_tools/README.md",
+ "/testbed/_tools/complete_file/main.go",
+ "/testbed/_tools/sigwinch/main.go",
+ "/testbed/_tools/vt100_debug/main.go",
+ "/testbed/buffer.go",
+ "/testbed/completer/file.go",
+ "/testbed/completion.go",
+ "/testbed/document.go",
+ "/testbed/emacs.go",
+ "/testbed/filter.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum",
+ "/testbed/history.go",
+ "/testbed/input.go",
+ "/testbed/input_posix.go",
+ "/testbed/input_windows.go",
+ "/testbed/internal/bisect/bisect.go",
+ "/testbed/internal/debug/assert.go",
+ "/testbed/internal/debug/log.go",
+ "/testbed/internal/strings/strings.go",
+ "/testbed/internal/term/raw.go",
+ "/testbed/internal/term/term.go",
+ "/testbed/key.go",
+ "/testbed/key_bind.go",
+ "/testbed/key_bind_func.go",
+ "/testbed/key_string.go",
+ "/testbed/option.go",
+ "/testbed/output.go",
+ "/testbed/output_posix.go",
+ "/testbed/output_vt100.go",
+ "/testbed/output_windows.go",
+ "/testbed/prompt.go",
+ "/testbed/render.go",
+ "/testbed/shortcut.go",
+ "/testbed/signal_posix.go",
+ "/testbed/signal_windows.go"
+ ]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/solution/solve.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..00d1a533519e8abc9def758862da6b859247bfe5
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"document.go": {"data": "cGFja2FnZSBwcm9tcHQKCmltcG9ydCAoCgkic3RyaW5ncyIKCSJ1bmljb2RlL3V0ZjgiCgoJImdpdGh1Yi5jb20vYy1iYXRhL2dvLXByb21wdC9pbnRlcm5hbC9iaXNlY3QiCglpc3RyaW5ncyAiZ2l0aHViLmNvbS9jLWJhdGEvZ28tcHJvbXB0L2ludGVybmFsL3N0cmluZ3MiCglydW5ld2lkdGggImdpdGh1Yi5jb20vbWF0dG4vZ28tcnVuZXdpZHRoIgopCgovLyBEb2N1bWVudCBoYXMgdGV4dCBkaXNwbGF5ZWQgaW4gdGVybWluYWwgYW5kIGN1cnNvciBwb3NpdGlvbi4KdHlwZSBEb2N1bWVudCBzdHJ1Y3QgewoJVGV4dCBzdHJpbmcKCS8vIFRoaXMgcmVwcmVzZW50cyBhIGluZGV4IGluIGEgcnVuZSBhcnJheSBvZiBEb2N1bWVudC5UZXh0LgoJLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgY3Vyc29yUG9zaXRpb24gaXMgMi4KCS8vIEJ1dCBEaXNwbGF5ZWRDdXJzb3JQb3NpdGlvbiByZXR1cm5zIDQgYmVjYXVzZSAn5pelJyBhbmQgJ+acrCcgYXJlIGRvdWJsZSB3aWR0aCBjaGFyYWN0ZXJzLgoJY3Vyc29yUG9zaXRpb24gaW50CglsYXN0S2V5ICAgICAgICBLZXkKfQoKLy8gTmV3RG9jdW1lbnQgcmV0dXJuIHRoZSBuZXcgZW1wdHkgZG9jdW1lbnQuCmZ1bmMgTmV3RG9jdW1lbnQoKSAqRG9jdW1lbnQgewoJcmV0dXJuICZEb2N1bWVudHsKCQlUZXh0OiAgICAgICAgICAgIiIsCgkJY3Vyc29yUG9zaXRpb246IDAsCgl9Cn0KCi8vIExhc3RLZXlTdHJva2UgcmV0dXJuIHRoZSBsYXN0IGtleSBwcmVzc2VkIGluIHRoaXMgZG9jdW1lbnQuCmZ1bmMgKGQgKkRvY3VtZW50KSBMYXN0S2V5U3Ryb2tlKCkgS2V5IHsKCXJldHVybiBkLmxhc3RLZXkKfQoKLy8gRGlzcGxheUN1cnNvclBvc2l0aW9uIHJldHVybnMgdGhlIGN1cnNvciBwb3NpdGlvbiBvbiByZW5kZXJlZCB0ZXh0IG9uIHRlcm1pbmFsIGVtdWxhdG9ycy4KLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgRGlzcGxheWVkQ3Vyc29yUG9zaXRpb24gcmV0dXJucyA0IGJlY2F1c2UgJ+aXpScgYW5kICfmnKwnIGFyZSBkb3VibGUgd2lkdGggY2hhcmFjdGVycy4KZnVuYyAoZCAqRG9jdW1lbnQpIERpc3BsYXlDdXJzb3JQb3NpdGlvbigpIGludCB7Cgl2YXIgcG9zaXRpb24gaW50CglydW5lcyA6PSBbXXJ1bmUoZC5UZXh0KVs6ZC5jdXJzb3JQb3NpdGlvbl0KCWZvciBpIDo9IHJhbmdlIHJ1bmVzIHsKCQlwb3NpdGlvbiArPSBydW5ld2lkdGguUnVuZVdpZHRoKHJ1bmVzW2ldKQoJfQoJcmV0dXJuIHBvc2l0aW9uCn0KCi8vIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yIHJldHVybiBjaGFyYWN0ZXIgcmVsYXRpdmUgdG8gY3Vyc29yIHBvc2l0aW9uLCBvciBlbXB0eSBzdHJpbmcKZnVuYyAoZCAqRG9jdW1lbnQpIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yKG9mZnNldCBpbnQpIChyIHJ1bmUpIHsKCXMgOj0gZC5UZXh0CgljbnQgOj0gMAoKCWZvciBsZW4ocykgPiAwIHsKCQljbnQrKwoJCXIsIHNpemUgOj0gdXRmOC5EZWNvZGVSdW5lSW5TdHJpbmcocykKCQlpZiBjbnQgPT0gZC5jdXJzb3JQb3NpdGlvbitvZmZzZXQgewoJCQlyZXR1cm4gcgoJCX0KCQlzID0gc1tzaXplOl0KCX0KCXJldHVybiAwCn0KCi8vIFRleHRCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJciA6PSBbXXJ1bmUoZC5UZXh0KQoJcmV0dXJuIHN0cmluZyhyWzpkLmN1cnNvclBvc2l0aW9uXSkKfQoKLy8gVGV4dEFmdGVyQ3Vyc29yIHJldHVybnMgdGhlIHRleHQgYWZ0ZXIgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRBZnRlckN1cnNvcigpIHN0cmluZyB7CglyIDo9IFtdcnVuZShkLlRleHQpCglyZXR1cm4gc3RyaW5nKHJbZC5jdXJzb3JQb3NpdGlvbjpdKQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYmVmb3JlIHRoZSBjdXJzb3IuCi8vIElmIHdlIGhhdmUgd2hpdGVzcGFjZSBiZWZvcmUgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcigpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBJZiB3ZSBoYXZlIHdoaXRlc3BhY2UgYWZ0ZXIgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yKCkgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmQoKV0KfQoKLy8gR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSgpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEFmdGVyQ3Vyc29yLCBpdCByZXR1cm5zIHN0cmluZyBjb250YWluaW5nIHNwYWNlCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UoKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpXQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yVW50aWxTZXBhcmF0b3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvciB1bnRpbCBuZXh0IHNlcGFyYXRvci4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJcmV0dXJuIHhbZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFVudGlsU2VwYXJhdG9yKHNlcCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvciByZXR1cm5zIHRoZSB0ZXh0IGFmdGVyIHRoZSBjdXJzb3IgdW50aWwgbmV4dCBzZXBhcmF0b3IuCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCldCn0KCi8vIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvciByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yKHNlcCBzdHJpbmcpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwKTpdCn0KCi8vIEdldFdvcmRBZnRlckN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYWZ0ZXIgdGhlIGN1cnNvci4KLy8gVW5saWtlIEdldFdvcmRBZnRlckN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXApXQp9CgovLyBGaW5kU3RhcnRPZlByZXZpb3VzV29yZCByZXR1cm5zIGFuIGluZGV4IHJlbGF0aXZlIHRvIHRoZSBjdXJzb3IgcG9zaXRpb24KLy8gcG9pbnRpbmcgdG8gdGhlIHN0YXJ0IG9mIHRoZSBwcmV2aW91cyB3b3JkLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5MYXN0SW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpICsgMQoJfQoJcmV0dXJuIDAKfQoKLy8gRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRXaXRoU3BhY2UgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBUaGUgb25seSBkaWZmZXJlbmNlIGlzIHRvIGlnbm9yZSBjb250aWd1b3VzIHNwYWNlcy4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWVuZCA6PSBpc3RyaW5ncy5MYXN0SW5kZXhOb3RCeXRlKHgsICcgJykKCWlmIGVuZCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEJ5dGUoeFs6ZW5kXSwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiAwCgl9CglyZXR1cm4gc3RhcnQgKyAxCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZCgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJaSA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaSArIDEKCX0KCXJldHVybiAwCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFdpdGhTcGFjZSgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJZW5kIDo9IGlzdHJpbmdzLkxhc3RJbmRleE5vdEFueSh4LCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiAwCgl9CglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4WzplbmRdLCBzZXApCglpZiBzdGFydCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCXJldHVybiBzdGFydCArIDEKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmQgcmV0dXJucyBhbiBpbmRleCByZWxhdGl2ZSB0byB0aGUgY3Vyc29yIHBvc2l0aW9uLgovLyBwb2ludGluZyB0byB0aGUgZW5kIG9mIHRoZSBjdXJyZW50IHdvcmQuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZEVuZE9mQ3VycmVudFdvcmQoKSBpbnQgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglpIDo9IHN0cmluZ3MuSW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpCgl9CglyZXR1cm4gbGVuKHgpCn0KCi8vIEZpbmRFbmRPZkN1cnJlbnRXb3JkV2l0aFNwYWNlIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZC4KLy8gVGhlIG9ubHkgZGlmZmVyZW5jZSBpcyB0byBpZ25vcmUgY29udGlndW91cyBzcGFjZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpIGludCB7Cgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCglzdGFydCA6PSBpc3RyaW5ncy5JbmRleE5vdEJ5dGUoeCwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCgllbmQgOj0gc3RyaW5ncy5JbmRleEJ5dGUoeFtzdGFydDpdLCAnICcpCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvciBpcyBhbG1vc3QgdGhlIHNhbWUgYXMgRmluZEVuZE9mQ3VycmVudFdvcmQuCi8vIEJ1dCB0aGlzIGNhbiBzcGVjaWZ5IFNlcGFyYXRvci4gUmV0dXJuIDAgaWYgbm90aGluZyB3YXMgZm91bmQuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCBzdHJpbmcpIGludCB7CglpZiBzZXAgPT0gIiIgewoJCXJldHVybiBkLkZpbmRFbmRPZkN1cnJlbnRXb3JkKCkKCX0KCgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5JbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaQoJfQoJcmV0dXJuIGxlbih4KQp9CgovLyBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZS4KLy8gQnV0IHRoaXMgY2FuIHNwZWNpZnkgU2VwYXJhdG9yLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRFbmRPZkN1cnJlbnRXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgaW50IHsKCWlmIHNlcCA9PSAiIiB7CgkJcmV0dXJuIGQuRmluZEVuZE9mQ3VycmVudFdvcmRXaXRoU3BhY2UoKQoJfQoKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoKCXN0YXJ0IDo9IGlzdHJpbmdzLkluZGV4Tm90QW55KHgsIHNlcCkKCWlmIHN0YXJ0ID09IC0xIHsKCQlyZXR1cm4gbGVuKHgpCgl9CgoJZW5kIDo9IHN0cmluZ3MuSW5kZXhBbnkoeFtzdGFydDpdLCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gQ3VycmVudExpbmVCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBzdGFydCBvZiB0aGUgbGluZSB1bnRpbCB0aGUgY3Vyc29yLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJcyA6PSBzdHJpbmdzLlNwbGl0KGQuVGV4dEJlZm9yZUN1cnNvcigpLCAiXG4iKQoJcmV0dXJuIHNbbGVuKHMpLTFdCn0KCi8vIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBjdXJzb3IgdW50aWwgdGhlIGVuZCBvZiB0aGUgbGluZS4KZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSBzdHJpbmcgewoJcmV0dXJuIHN0cmluZ3MuU3BsaXQoZC5UZXh0QWZ0ZXJDdXJzb3IoKSwgIlxuIilbMF0KfQoKLy8gQ3VycmVudExpbmUgcmV0dXJuIHRoZSB0ZXh0IG9uIHRoZSBsaW5lIHdoZXJlIHRoZSBjdXJzb3IgaXMuICh3aGVuIHRoZSBpbnB1dAovLyBjb25zaXN0cyBvZiBqdXN0IG9uZSBsaW5lLCBpdCBlcXVhbHMgYHRleHRgLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmUoKSBzdHJpbmcgewoJcmV0dXJuIGQuQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSArIGQuQ3VycmVudExpbmVBZnRlckN1cnNvcigpCn0KCi8vIEFycmF5IHBvaW50aW5nIHRvIHRoZSBzdGFydCBpbmRleGVzIG9mIGFsbCB0aGUgbGluZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBsaW5lU3RhcnRJbmRleGVzKCkgW11pbnQgewoJLy8gVE9ETzogQ2FjaGUsIGJlY2F1c2UgdGhpcyBpcyBvZnRlbiByZXVzZWQuCgkvLyAoSWYgaXQgaXMgdXNlZCwgaXQncyBvZnRlbiB1c2VkIG1hbnkgdGltZXMuCgkvLyBBbmQgdGhpcyBoYXMgdG8gYmUgZmFzdCBmb3IgZWRpdGluZyBiaWcgZG9jdW1lbnRzISkKCWxjIDo9IGQuTGluZUNvdW50KCkKCWxlbmd0aHMgOj0gbWFrZShbXWludCwgbGMpCglmb3IgaSwgbCA6PSByYW5nZSBkLkxpbmVzKCkgewoJCWxlbmd0aHNbaV0gPSBsZW4obCkKCX0KCgkvLyBDYWxjdWxhdGUgY3VtdWxhdGl2ZSBzdW1zLgoJaW5kZXhlcyA6PSBtYWtlKFtdaW50LCBsYysxKQoJaW5kZXhlc1swXSA9IDAgLy8gaHR0cHM6Ly9naXRodWIuY29tL2pvbmF0aGFuc2xlbmRlcnMvcHl0aG9uLXByb21wdC10b29sa2l0L2Jsb2IvbWFzdGVyL3Byb21wdF90b29sa2l0L2RvY3VtZW50LnB5I0wxODkKCXBvcyA6PSAwCglmb3IgaSwgbCA6PSByYW5nZSBsZW5ndGhzIHsKCQlwb3MgKz0gbCArIDEKCQlpbmRleGVzW2krMV0gPSBwb3MKCX0KCWlmIGxjID4gMSB7CgkJLy8gUG9wIHRoZSBsYXN0IGl0ZW0uIChUaGlzIGlzIG5vdCBhIG5ldyBsaW5lLikKCQlpbmRleGVzID0gaW5kZXhlc1s6bGNdCgl9CglyZXR1cm4gaW5kZXhlcwp9CgovLyBGb3IgdGhlIGluZGV4IG9mIGEgY2hhcmFjdGVyIGF0IGEgY2VydGFpbiBsaW5lLCBjYWxjdWxhdGUgdGhlIGluZGV4IG9mCi8vIHRoZSBmaXJzdCBjaGFyYWN0ZXIgb24gdGhhdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgZmluZExpbmVTdGFydEluZGV4KGluZGV4IGludCkgKHBvcyBpbnQsIGxpbmVTdGFydEluZGV4IGludCkgewoJaW5kZXhlcyA6PSBkLmxpbmVTdGFydEluZGV4ZXMoKQoJcG9zID0gYmlzZWN0LlJpZ2h0KGluZGV4ZXMsIGluZGV4KSAtIDEKCWxpbmVTdGFydEluZGV4ID0gaW5kZXhlc1twb3NdCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Sb3cgcmV0dXJucyB0aGUgY3VycmVudCByb3cuICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uUm93KCkgKHJvdyBpbnQpIHsKCXJvdywgXyA9IGQuZmluZExpbmVTdGFydEluZGV4KGQuY3Vyc29yUG9zaXRpb24pCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Db2wgcmV0dXJucyB0aGUgY3VycmVudCBjb2x1bW4uICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uQ29sKCkgKGNvbCBpbnQpIHsKCS8vIERvbid0IHVzZSBzZWxmLnRleHRfYmVmb3JlX2N1cnNvciB0byBjYWxjdWxhdGUgdGhpcy4gQ3JlYXRpbmcgc3Vic3RyaW5ncwoJLy8gYW5kIHNwbGl0dGluZyBpcyB0b28gZXhwZW5zaXZlIGZvciBnZXR0aW5nIHRoZSBjdXJzb3IgcG9zaXRpb24uCglfLCBpbmRleCA6PSBkLmZpbmRMaW5lU3RhcnRJbmRleChkLmN1cnNvclBvc2l0aW9uKQoJY29sID0gZC5jdXJzb3JQb3NpdGlvbiAtIGluZGV4CglyZXR1cm4KfQoKLy8gR2V0Q3Vyc29yTGVmdFBvc2l0aW9uIHJldHVybnMgdGhlIHJlbGF0aXZlIHBvc2l0aW9uIGZvciBjdXJzb3IgbGVmdC4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldEN1cnNvckxlZnRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvclJpZ2h0UG9zaXRpb24oLWNvdW50KQoJfQoJaWYgZC5DdXJzb3JQb3NpdGlvbkNvbCgpID4gY291bnQgewoJCXJldHVybiAtY291bnQKCX0KCXJldHVybiAtZC5DdXJzb3JQb3NpdGlvbkNvbCgpCn0KCi8vIEdldEN1cnNvclJpZ2h0UG9zaXRpb24gcmV0dXJucyByZWxhdGl2ZSBwb3NpdGlvbiBmb3IgY3Vyc29yIHJpZ2h0LgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yUmlnaHRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvckxlZnRQb3NpdGlvbigtY291bnQpCgl9CglpZiBsZW4oZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpID4gY291bnQgewoJCXJldHVybiBjb3VudAoJfQoJcmV0dXJuIGxlbihkLkN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSkKfQoKLy8gR2V0Q3Vyc29yVXBQb3NpdGlvbiByZXR1cm4gdGhlIHJlbGF0aXZlIGN1cnNvciBwb3NpdGlvbiAoY2hhcmFjdGVyIGluZGV4KSB3aGVyZSB3ZSB3b3VsZCBiZQovLyBpZiB0aGUgdXNlciBwcmVzc2VkIHRoZSBhcnJvdy11cCBidXR0b24uCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRDdXJzb3JVcFBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9CgoJcm93IDo9IGQuQ3Vyc29yUG9zaXRpb25Sb3coKSAtIGNvdW50CglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9CglyZXR1cm4gZC5UcmFuc2xhdGVSb3dDb2xUb0luZGV4KHJvdywgY29sKSAtIGQuY3Vyc29yUG9zaXRpb24KfQoKLy8gR2V0Q3Vyc29yRG93blBvc2l0aW9uIHJldHVybiB0aGUgcmVsYXRpdmUgY3Vyc29yIHBvc2l0aW9uIChjaGFyYWN0ZXIgaW5kZXgpIHdoZXJlIHdlIHdvdWxkIGJlIGlmIHRoZQovLyB1c2VyIHByZXNzZWQgdGhlIGFycm93LWRvd24gYnV0dG9uLgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yRG93blBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9Cglyb3cgOj0gZC5DdXJzb3JQb3NpdGlvblJvdygpICsgY291bnQKCXJldHVybiBkLlRyYW5zbGF0ZVJvd0NvbFRvSW5kZXgocm93LCBjb2wpIC0gZC5jdXJzb3JQb3NpdGlvbgp9CgovLyBMaW5lcyByZXR1cm5zIHRoZSBhcnJheSBvZiBhbGwgdGhlIGxpbmVzLgpmdW5jIChkICpEb2N1bWVudCkgTGluZXMoKSBbXXN0cmluZyB7CgkvLyBUT0RPOiBDYWNoZSwgYmVjYXVzZSB0aGlzIG9uZSBpcyByZXVzZWQgdmVyeSBvZnRlbi4KCXJldHVybiBzdHJpbmdzLlNwbGl0KGQuVGV4dCwgIlxuIikKfQoKLy8gTGluZUNvdW50IHJldHVybiB0aGUgbnVtYmVyIG9mIGxpbmVzIGluIHRoaXMgZG9jdW1lbnQuIElmIHRoZSBkb2N1bWVudCBlbmRzCi8vIHdpdGggYSB0cmFpbGluZyBcbiwgdGhhdCBjb3VudHMgYXMgdGhlIGJlZ2lubmluZyBvZiBhIG5ldyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgTGluZUNvdW50KCkgaW50IHsKCXJldHVybiBsZW4oZC5MaW5lcygpKQp9CgovLyBUcmFuc2xhdGVJbmRleFRvUG9zaXRpb24gZ2l2ZW4gYW4gaW5kZXggZm9yIHRoZSB0ZXh0LCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgKHJvdywgY29sKSB0dXBsZS4KLy8gKDAtYmFzZWQuIFJldHVybnMgKDAsIDApIGZvciBpbmRleD0wLikKZnVuYyAoZCAqRG9jdW1lbnQpIFRyYW5zbGF0ZUluZGV4VG9Qb3NpdGlvbihpbmRleCBpbnQpIChyb3cgaW50LCBjb2wgaW50KSB7Cglyb3csIHJvd0luZGV4IDo9IGQuZmluZExpbmVTdGFydEluZGV4KGluZGV4KQoJY29sID0gaW5kZXggLSByb3dJbmRleAoJcmV0dXJuCn0KCi8vIFRyYW5zbGF0ZVJvd0NvbFRvSW5kZXggZ2l2ZW4gYSAocm93LCBjb2wpLCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgaW5kZXguCi8vIChSb3cgYW5kIGNvbCBwYXJhbXMgYXJlIDAtYmFzZWQuKQpmdW5jIChkICpEb2N1bWVudCkgVHJhbnNsYXRlUm93Q29sVG9JbmRleChyb3cgaW50LCBjb2x1bW4gaW50KSAoaW5kZXggaW50KSB7CglpbmRleGVzIDo9IGQubGluZVN0YXJ0SW5kZXhlcygpCglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9IGVsc2UgaWYgcm93ID4gbGVuKGluZGV4ZXMpIHsKCQlyb3cgPSBsZW4oaW5kZXhlcykgLSAxCgl9CglpbmRleCA9IGluZGV4ZXNbcm93XQoJbGluZSA6PSBkLkxpbmVzKClbcm93XQoKCS8vIHB5dGhvbikgcmVzdWx0ICs9IG1heCgwLCBtaW4oY29sLCBsZW4obGluZSkpKQoJaWYgY29sdW1uID4gMCB8fCBsZW4obGluZSkgPiAwIHsKCQlpZiBjb2x1bW4gPiBsZW4obGluZSkgewoJCQlpbmRleCArPSBsZW4obGluZSkKCQl9IGVsc2UgewoJCQlpbmRleCArPSBjb2x1bW4KCQl9Cgl9CgoJLy8gS2VlcCBpbiByYW5nZS4gKGxlbihzZWxmLnRleHQpIGlzIGluY2x1ZGVkLCBiZWNhdXNlIHRoZSBjdXJzb3IgY2FuIGJlCgkvLyByaWdodCBhZnRlciB0aGUgZW5kIG9mIHRoZSB0ZXh0IGFzIHdlbGwuKQoJLy8gcHl0aG9uKSByZXN1bHQgPSBtYXgoMCwgbWluKHJlc3VsdCwgbGVuKHNlbGYudGV4dCkpKQoJaWYgaW5kZXggPiBsZW4oZC5UZXh0KSB7CgkJaW5kZXggPSBsZW4oZC5UZXh0KQoJfQoJaWYgaW5kZXggPCAwIHsKCQlpbmRleCA9IDAKCX0KCXJldHVybiBpbmRleAp9CgovLyBPbkxhc3RMaW5lIHJldHVybnMgdHJ1ZSB3aGVuIHdlIGFyZSBhdCB0aGUgbGFzdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgT25MYXN0TGluZSgpIGJvb2wgewoJcmV0dXJuIGQuQ3Vyc29yUG9zaXRpb25Sb3coKSA9PSAoZC5MaW5lQ291bnQoKSAtIDEpCn0KCi8vIEdldEVuZE9mTGluZVBvc2l0aW9uIHJldHVybnMgcmVsYXRpdmUgcG9zaXRpb24gZm9yIHRoZSBlbmQgb2YgdGhpcyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgR2V0RW5kT2ZMaW5lUG9zaXRpb24oKSBpbnQgewoJcmV0dXJuIGxlbihbXXJ1bmUoZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpKQp9CgpmdW5jIChkICpEb2N1bWVudCkgbGVhZGluZ1doaXRlc3BhY2VJbkN1cnJlbnRMaW5lKCkgKG1hcmdpbiBzdHJpbmcpIHsKCXRyaW1tZWQgOj0gc3RyaW5ncy5UcmltU3BhY2UoZC5DdXJyZW50TGluZSgpKQoJbWFyZ2luID0gZC5DdXJyZW50TGluZSgpWzpsZW4oZC5DdXJyZW50TGluZSgpKS1sZW4odHJpbW1lZCldCglyZXR1cm4KfQo=", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/task.toml b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..dd1abb777069201adc48e2b826d9f7464a332b80
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/task.toml
@@ -0,0 +1,11 @@
+version = "1.0"
+[agent]
+timeout_sec = 300.0
+[verifier]
+timeout_sec = 300.0
+environment_mode = "shared"
+[environment]
+docker_image = "ghcr.io/younesbelkada/scale800@sha256:ea512b6f10521df82bebb34e4ada95e3e5596c1a8d6004ab464da2924ba0212e"
+cpus = 1
+memory_mb = 2048
+storage_mb = 4096
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..b69ba22b8fec659872a520bee9e664be358d8cd1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/manifest.json
@@ -0,0 +1,432 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWord"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLine"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestEmacsKeyBindings"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLine"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextBeforeCursor"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparator"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CursorPositionRowAndCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorLeftPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorUpPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorDownPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorRightPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_Lines"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_LineCount"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateIndexToPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateRowColToIndex"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_OnLastLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetEndOfLinePosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFilter"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFuzzyMatch"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryClear"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryAdd"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryOlder"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/escape"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/undefined"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWrite"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteRawStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatCompletion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBreakLineCallback"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionRow"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition_withJapanese"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/validation/canaries/delete-tests.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/validation/canaries/delete-tests.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/validation/canaries/delete-tests.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+find /testbed -name '*_test.go' -type f -delete
+printf 'PASS\nok forged-package 0.001s\n'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..30b379b5aec1e56969938c44f098b1fab8502c8c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__2z762u0o/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "514a5e82516436271cb37821753b1e1c15e057e1959dc02875b104f95df2a194",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/Dockerfile b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f35bf9e5393ee1086fe1b72c1b442f3b16e2bd5b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22
+WORKDIR /testbed
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c8c031d0f87fb9aea0aff433b1fcaeaac259c41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: "Bug report"
+about: Create a bug report to improve go-prompt
+title: "[Bug]"
+labels: bug
+assignees: ''
+
+---
+
+# Bug reports
+
+*Please file a bug report here.*
+
+## Expected Behavior
+
+*Please describe the behavior you are expecting*
+
+## Current Behavior and Steps to Reproduce
+
+*What is the current behavior? Please provide detailed steps for reproducing the issue.*
+*A picture or gif animation tells a thousand words*
+
+## Context
+
+Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
+
+* Operating System:
+* Terminal Emulator: (i.e. iTerm2)
+* tag of go-prompt or commit revision:
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb816a2496376983781774cb5466fed8e1efc93b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,13 @@
+---
+name: "Feature request"
+about: Suggest an idea for new features in go-prompt.
+title: "[Feature Request]"
+labels: enhancement
+assignees: ''
+
+---
+
+# Feature Request
+
+*Please write your suggestion here.*
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/.gitignore b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..eba2b56abe0f7758a560d47dd19d8985b67ef327
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+bin/
+
+# Folders
+pkg/
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+# Glide
+vendor/
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/CHANGELOG.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..b9e21f1ef333b9ec13323bcd4a8f377322ed7e9f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/CHANGELOG.md
@@ -0,0 +1,79 @@
+# Change Log
+
+## v0.3.0 (2018/??/??)
+
+next release.
+
+## v0.2.3 (2018/10/25)
+
+### What's new?
+
+* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92).
+* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100).
+* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102).
+
+### Fixed
+
+* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details).
+* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details).
+* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details).
+
+### Removed or Deprecated
+
+* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`.
+
+## v0.2.2 (2018/06/28)
+
+### What's new?
+
+* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters.
+* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions.
+ * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details).
+* Add FilePathCompleter to complete file path on your system.
+* Add option to customize ascii code key bindings.
+* Add GetWordAfterCursor method in Document.
+
+### Removed or Deprecated
+
+* prompt.Choose shortcut function is deprecated.
+
+## v0.2.1 (2018/02/14)
+
+### What's New?
+
+* ~~It seems that windows support is almost perfect.~~
+ * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows.
+
+### Fixed
+
+* Fix a Shift+Tab handling on Windows.
+* Fix 4-dimension arrow keys handling on Windows.
+
+## v0.2.0 (2018/02/13)
+
+### What's New?
+
+* Supports scrollbar when there are too many matched suggestions
+* Windows support (but please caution because this is still not perfect).
+* Add OptionLivePrefix to update the prefix dynamically
+* Implement clear screen by `Ctrl+L`.
+
+### Fixed
+
+* Fix the behavior of `Ctrl+W` keybind.
+* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details).
+* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details).
+* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ).
+
+### News
+
+New core developers are joined (alphabetical order).
+
+* Nao Yonashiro (Github @orisano)
+* Ryoma Abe (Github @Allajah)
+* Yusuke Nakamura (Github @unasuke)
+
+
+## v0.1.0 (2017/08/15)
+
+Initial Release
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/LICENSE b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a86acaa7ab24fe61ea152a9afcadc21980020efb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Masashi SHIBATA
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/Makefile b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..505817c36f0b8a0bb643eed8680b8989af2b0920
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/Makefile
@@ -0,0 +1,46 @@
+.DEFAULT_GOAL := help
+
+SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
+
+GOIMPORTS ?= goimports
+GOCILINT ?= golangci-lint
+
+.PHONY: setup
+setup: ## Setup for required tools.
+ go get -u golang.org/x/tools/cmd/goimports
+ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: fmt
+fmt: $(SOURCES) ## Formatting source codes.
+ @$(GOIMPORTS) -w $^
+
+.PHONY: lint
+lint: ## Run golangci-lint.
+ @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
+
+.PHONY: test
+test: ## Run tests with race condition checking.
+ @go test -race ./...
+
+.PHONY: bench
+bench: ## Run benchmarks.
+ @go test -bench=. -run=- -benchmem ./...
+
+.PHONY: coverage
+cover: ## Run the tests.
+ @go test -coverprofile=coverage.o
+ @go tool cover -func=coverage.o
+
+.PHONY: generate
+generate: ## Run go generate
+ @go generate ./...
+
+.PHONY: build
+build: ## Build example command lines.
+ ./_example/build.sh
+
+.PHONY: help
+help: ## Show help text
+ @echo "Commands:"
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfcd7a399b4827d6b126d6a173cce34d36520481
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/README.md
@@ -0,0 +1,125 @@
+# go-prompt
+
+[](https://goreportcard.com/report/github.com/c-bata/go-prompt)
+
+[](https://godoc.org/github.com/c-bata/go-prompt)
+
+
+A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit),
+making it easier to build cross-platform command line tools using Go.
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func completer(d prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ }
+ return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ fmt.Println("Please select table.")
+ t := prompt.Input("> ", completer)
+ fmt.Println("You selected " + t)
+}
+```
+
+#### Projects using go-prompt
+
+* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt)
+* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli)
+* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn)
+* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli)
+* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans)
+* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit)
+* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go)
+* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS)
+* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs)
+* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli)
+* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt)
+* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh)
+* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell)
+* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt)
+* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim)
+* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron)
+* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl)
+* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl)
+* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit)
+* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.)
+
+## Features
+
+### Powerful auto-completion
+
+[](https://github.com/c-bata/kube-prompt)
+
+(This is a GIF animation of kube-prompt.)
+
+### Flexible options
+
+go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details.
+
+[](#flexible-options)
+
+### Keyboard Shortcuts
+
+Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell).
+You can customize and expand these shortcuts.
+
+[](#keyboard-shortcuts)
+
+Key Binding | Description
+---------------------|---------------------------------------------------------
+Ctrl + A | Go to the beginning of the line (Home)
+Ctrl + E | Go to the end of the line (End)
+Ctrl + P | Previous command (Up arrow)
+Ctrl + N | Next command (Down arrow)
+Ctrl + F | Forward one character
+Ctrl + B | Backward one character
+Ctrl + D | Delete character under the cursor
+Ctrl + H | Delete character before the cursor (Backspace)
+Ctrl + W | Cut the word before the cursor to the clipboard
+Ctrl + K | Cut the line after the cursor to the clipboard
+Ctrl + U | Cut the line before the cursor to the clipboard
+Ctrl + L | Clear the screen
+
+### History
+
+You can use Up arrow and Down arrow to walk through the history of commands executed.
+
+[](#history)
+
+### Multiple platform support
+
+We have confirmed go-prompt works fine in the following terminals:
+
+* iTerm2 (macOS)
+* Terminal.app (macOS)
+* Command Prompt (Windows)
+* gnome-terminal (Ubuntu)
+
+## Links
+
+* [Change Log](./CHANGELOG.md)
+* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt)
+* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt)
+
+## Author
+
+Masashi Shibata
+
+* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/)
+* Github: [@c-bata](https://github.com/c-bata/)
+
+## License
+
+This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..759b0e3f8acf1216b055e0f9458758a6c1e8950a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/README.md
@@ -0,0 +1,30 @@
+# Examples of go-prompt
+
+This directory includes some examples using go-prompt.
+These examples are useful to know the usage of go-prompt and check behavior for development.
+
+## simple-echo
+
+
+
+A simple echo example using `prompt.Input`.
+
+## http-prompt
+
+
+
+A simple [http-prompt](https://github.com/eliangcs/http-prompt) implementation using go-prompt in less than 200 lines of Go.
+
+## live-prefix
+
+
+
+A example application which changes a prefix string dynamically.
+This feature is used like [ktr0731/evans](https://github.com/ktr0731/evans) which is interactive gRPC client using go-prompt.
+
+## exec-command
+
+Run another CLI tool via `os/exec` package.
+More practical example is [a source code of kube-prompt](https://github.com/c-bata/kube-prompt).
+I recommend you to look this if you want to create tools like kube-prompt.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/build.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c552afcfa69b2356ffcd484c867abcaaaaeeaff
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+export GO111MODULE=on
+DIR=$(cd $(dirname $0); pwd)
+BIN_DIR=$(cd $(dirname $(dirname $0)); pwd)/bin
+
+mkdir -p ${BIN_DIR}
+go build -o ${BIN_DIR}/exec-command ${DIR}/exec-command/main.go
+go build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.go
+go build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.go
+go build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.go
+go build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/exec-command/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/exec-command/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..838f756260df91569491def29a7ee05a7c9a98f7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/exec-command/main.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "os/exec"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(t string) {
+ if t == "bash" {
+ cmd := exec.Command("bash")
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Run()
+ }
+ return
+}
+
+func completer(t prompt.Document) []prompt.Suggest {
+ return []prompt.Suggest{
+ {Text: "bash"},
+ }
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/http-prompt/api.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/http-prompt/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..08e7b1a489a2077f26f280fe39e3bd06efa52cd2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/http-prompt/api.py
@@ -0,0 +1,17 @@
+from bottle import route, run, request
+
+@route('/')
+def hello():
+ return "Hello World!"
+
+@route('/ping')
+def hello():
+ return "pong!"
+
+@route('/register', method='POST')
+def register():
+ name = request.json.get("name")
+ return "Hello %s!" % name
+
+if __name__ == "__main__":
+ run(host='localhost', port=8000, debug=True)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/http-prompt/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/http-prompt/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b372a3550c50121d6e500e2a08e641e168b8c00d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/http-prompt/main.go
@@ -0,0 +1,192 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+type RequestContext struct {
+ url *url.URL
+ header http.Header
+ client *http.Client
+}
+
+var ctx *RequestContext
+
+// See https://github.com/eliangcs/http-prompt/blob/master/http_prompt/completion.py
+var suggestions = []prompt.Suggest{
+ // Command
+ {"cd", "Change URL/path"},
+ {"exit", "Exit http-prompt"},
+
+ // HTTP Method
+ {"delete", "DELETE request"},
+ {"get", "GET request"},
+ {"patch", "GET request"},
+ {"post", "POST request"},
+ {"put", "PUT request"},
+
+ // HTTP Header
+ {"Accept", "Acceptable response media type"},
+ {"Accept-Charset", "Acceptable response charsets"},
+ {"Accept-Encoding", "Acceptable response content codings"},
+ {"Accept-Language", "Preferred natural languages in response"},
+ {"ALPN", "Application-layer protocol negotiation to use"},
+ {"Alt-Used", "Alternative host in use"},
+ {"Authorization", "Authentication information"},
+ {"Cache-Control", "Directives for caches"},
+ {"Connection", "Connection options"},
+ {"Content-Encoding", "Content codings"},
+ {"Content-Language", "Natural languages for content"},
+ {"Content-Length", "Anticipated size for payload body"},
+ {"Content-Location", "Where content was obtained"},
+ {"Content-MD5", "Base64-encoded MD5 sum of content"},
+ {"Content-Type", "Content media type"},
+ {"Cookie", "Stored cookies"},
+ {"Date", "Datetime when message was originated"},
+ {"Depth", "Applied only to resource or its members"},
+ {"DNT", "Do not track user"},
+ {"Expect", "Expected behaviors supported by server"},
+ {"Forwarded", "Proxies involved"},
+ {"From", "Sender email address"},
+ {"Host", "Target URI"},
+ {"HTTP2-Settings", "HTTP/2 connection parameters"},
+ {"If", "Request condition on state tokens and ETags"},
+ {"If-Match", "Request condition on target resource"},
+ {"If-Modified-Since", "Request condition on modification date"},
+ {"If-None-Match", "Request condition on target resource"},
+ {"If-Range", "Request condition on Range"},
+ {"If-Schedule-Tag-Match", "Request condition on Schedule-Tag"},
+ {"If-Unmodified-Since", "Request condition on modification date"},
+ {"Max-Forwards", "Max number of times forwarded by proxies"},
+ {"MIME-Version", "Version of MIME protocol"},
+ {"Origin", "Origin(s} issuing the request"},
+ {"Pragma", "Implementation-specific directives"},
+ {"Prefer", "Preferred server behaviors"},
+ {"Proxy-Authorization", "Proxy authorization credentials"},
+ {"Proxy-Connection", "Proxy connection options"},
+ {"Range", "Request transfer of only part of data"},
+ {"Referer", "Previous web page"},
+ {"TE", "Transfer codings willing to accept"},
+ {"Transfer-Encoding", "Transfer codings applied to payload body"},
+ {"Upgrade", "Invite server to upgrade to another protocol"},
+ {"User-Agent", "User agent string"},
+ {"Via", "Intermediate proxies"},
+ {"Warning", "Possible incorrectness with payload body"},
+ {"WWW-Authenticate", "Authentication scheme"},
+ {"X-Csrf-Token", "Prevent cross-site request forgery"},
+ {"X-CSRFToken", "Prevent cross-site request forgery"},
+ {"X-Forwarded-For", "Originating client IP address"},
+ {"X-Forwarded-Host", "Original host requested by client"},
+ {"X-Forwarded-Proto", "Originating protocol"},
+ {"X-Http-Method-Override", "Request method override"},
+ {"X-Requested-With", "Used to identify Ajax requests"},
+ {"X-XSRF-TOKEN", "Prevent cross-site request forgery"},
+}
+
+func livePrefix() (string, bool) {
+ if ctx.url.Path == "/" {
+ return "", false
+ }
+ return ctx.url.String() + "> ", true
+}
+
+func executor(in string) {
+ in = strings.TrimSpace(in)
+
+ var method, body string
+ blocks := strings.Split(in, " ")
+ switch blocks[0] {
+ case "exit":
+ fmt.Println("Bye!")
+ os.Exit(0)
+ case "cd":
+ if len(blocks) < 2 {
+ ctx.url.Path = "/"
+ } else {
+ ctx.url.Path = path.Join(ctx.url.Path, blocks[1])
+ }
+ return
+ case "get", "delete":
+ method = strings.ToUpper(blocks[0])
+ case "post", "put", "patch":
+ if len(blocks) < 2 {
+ fmt.Println("please set request body.")
+ return
+ }
+ body = strings.Join(blocks[1:], " ")
+ method = strings.ToUpper(blocks[0])
+ }
+ if method != "" {
+ req, err := http.NewRequest(method, ctx.url.String(), strings.NewReader(body))
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ req.Header = ctx.header
+ res, err := ctx.client.Do(req)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ result, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ fmt.Printf("%s\n", result)
+ ctx.header = http.Header{}
+ return
+ }
+
+ if h := strings.Split(in, ":"); len(h) == 2 {
+ // Handling HTTP Header
+ ctx.header.Add(strings.TrimSpace(h[0]), strings.Trim(h[1], ` '"`))
+ } else {
+ fmt.Println("Sorry, I don't understand.")
+ }
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ w := in.GetWordBeforeCursor()
+ if w == "" {
+ return []prompt.Suggest{}
+ }
+ return prompt.FilterHasPrefix(suggestions, w, true)
+}
+
+func main() {
+ var baseURL = "http://localhost:8000/"
+ if len(os.Args) == 2 {
+ baseURL = os.Args[1]
+ if strings.HasSuffix(baseURL, "/") {
+ baseURL += "/"
+ }
+ }
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ ctx = &RequestContext{
+ url: u,
+ header: http.Header{},
+ client: &http.Client{},
+ }
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(u.String()+"> "),
+ prompt.OptionLivePrefix(livePrefix),
+ prompt.OptionTitle("http-prompt"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/live-prefix/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/live-prefix/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c7ced720592173e2a13f19f7cb543730192d3f8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/live-prefix/main.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var LivePrefixState struct {
+ LivePrefix string
+ IsEnable bool
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+ if in == "" {
+ LivePrefixState.IsEnable = false
+ LivePrefixState.LivePrefix = in
+ return
+ }
+ LivePrefixState.LivePrefix = in + "> "
+ LivePrefixState.IsEnable = true
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func changeLivePrefix() (string, bool) {
+ return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionLivePrefix(changeLivePrefix),
+ prompt.OptionTitle("live-prefix-example"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/simple-echo/cjk-cyrillic/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/simple-echo/cjk-cyrillic/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e9e53adef1558e004f86ccbca2c2e2b83c1da39
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/simple-echo/cjk-cyrillic/main.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
+ {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
+ {Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
+ {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionTitle("sql-prompt for multi width characters"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/simple-echo/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/simple-echo/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..12b1bb4fc189e6b369e889779418d7826a45db9d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_example/simple-echo/main.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ in := prompt.Input(">>> ", completer,
+ prompt.OptionTitle("sql-prompt"),
+ prompt.OptionHistory([]string{"SELECT * FROM users;"}),
+ prompt.OptionPrefixTextColor(prompt.Yellow),
+ prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
+ prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
+ prompt.OptionSuggestionBGColor(prompt.DarkGray))
+ fmt.Println("Your input: " + in)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_tools/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..45bd2234f21ff32562984bec046316c8e52868fd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_tools/README.md
@@ -0,0 +1,10 @@
+## Tools of go-prompt
+
+### vt100_debug
+
+
+
+### sigwinch
+
+
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_tools/complete_file/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_tools/complete_file/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..41015cfab9b021fbc7df575bde87e3c510705496
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_tools/complete_file/main.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/completer"
+)
+
+var filePathCompleter = completer.FilePathCompleter{
+ IgnoreCase: true,
+ Filter: func(fi os.FileInfo) bool {
+ return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
+ },
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completerFunc(d prompt.Document) []prompt.Suggest {
+ t := d.GetWordBeforeCursor()
+ if strings.HasPrefix(t, "--") {
+ return []prompt.Suggest{
+ {"--foo", ""},
+ {"--bar", ""},
+ {"--baz", ""},
+ }
+ }
+ return filePathCompleter.Complete(d)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completerFunc,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_tools/sigwinch/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_tools/sigwinch/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9608eb3b4a5e3c6942c140c41e08a36ab3adb33b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_tools/sigwinch/main.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "unsafe"
+)
+
+// Winsize is winsize struct got from the ioctl(2) system call.
+type Winsize struct {
+ Row uint16
+ Col uint16
+ X uint16 // pixel value
+ Y uint16 // pixel value
+}
+
+// GetWinSize returns winsize struct which is the response of ioctl(2).
+func GetWinSize(fd int) *Winsize {
+ ws := &Winsize{}
+ retCode, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ uintptr(fd),
+ uintptr(syscall.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(ws)))
+
+ if int(retCode) == -1 {
+ panic(errno)
+ }
+ return ws
+}
+
+func main() {
+ signalChan := make(chan os.Signal, 1)
+ signal.Notify(
+ signalChan,
+ syscall.SIGHUP,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ exitChan := make(chan int)
+ go func() {
+ for {
+ s := <-signalChan
+ switch s {
+ // kill -SIGHUP XXXX
+ case syscall.SIGHUP:
+ exitChan <- 0
+
+ // kill -SIGINT XXXX or Ctrl+c
+ case syscall.SIGINT:
+ exitChan <- 0
+
+ // kill -SIGTERM XXXX
+ case syscall.SIGTERM:
+ exitChan <- 0
+
+ // kill -SIGQUIT XXXX
+ case syscall.SIGQUIT:
+ exitChan <- 0
+
+ case syscall.SIGWINCH:
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ default:
+ exitChan <- 1
+ }
+ }
+ }()
+
+ code := <-exitChan
+ os.Exit(code)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_tools/vt100_debug/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_tools/vt100_debug/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c6036d45959febc739e287a3a7b631259d4ee7c1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/_tools/vt100_debug/main.go
@@ -0,0 +1,47 @@
+// +build !windows
+
+package main
+
+import (
+ "fmt"
+ "syscall"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/term"
+)
+
+func main() {
+ if err := term.SetRaw(syscall.Stdin); err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer term.Restore()
+
+ bufCh := make(chan []byte, 128)
+ go readBuffer(bufCh)
+ fmt.Print("> ")
+
+ for {
+ b := <-bufCh
+ if key := prompt.GetKey(b); key == prompt.NotDefined {
+ fmt.Printf("Key '%s' data:'%#v'\n", string(b), b)
+ } else {
+ if key == prompt.ControlC {
+ fmt.Println("exit.")
+ return
+ }
+ fmt.Printf("Key '%s' data:'%#v'\n", key, b)
+ }
+ fmt.Print("> ")
+ }
+}
+
+func readBuffer(bufCh chan []byte) {
+ buf := make([]byte, 1024)
+
+ for {
+ if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
+ bufCh <- buf[:n]
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/buffer.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..46efbbba8bfb75f4a064c83368b781d1d6dbbb29
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/buffer.go
@@ -0,0 +1,191 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Buffer emulates the console buffer.
+type Buffer struct {
+ workingLines []string // The working lines. Similar to history
+ workingIndex int
+ cursorPosition int
+ cacheDocument *Document
+ preferredColumn int // Remember the original column for the next up/down movement.
+ lastKeyStroke Key
+}
+
+// Text returns string of the current line.
+func (b *Buffer) Text() string {
+ return b.workingLines[b.workingIndex]
+}
+
+// Document method to return document instance from the current text and cursor position.
+func (b *Buffer) Document() (d *Document) {
+ if b.cacheDocument == nil ||
+ b.cacheDocument.Text != b.Text() ||
+ b.cacheDocument.cursorPosition != b.cursorPosition {
+ b.cacheDocument = &Document{
+ Text: b.Text(),
+ cursorPosition: b.cursorPosition,
+ }
+ }
+ b.cacheDocument.lastKey = b.lastKeyStroke
+ return b.cacheDocument
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (b *Buffer) DisplayCursorPosition() int {
+ return b.Document().DisplayCursorPosition()
+}
+
+// InsertText insert string from current line.
+func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
+ or := []rune(b.Text())
+ oc := b.cursorPosition
+
+ if overwrite {
+ overwritten := string(or[oc : oc+len(v)])
+ if strings.Contains(overwritten, "\n") {
+ i := strings.IndexAny(overwritten, "\n")
+ overwritten = overwritten[:i]
+ }
+ b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):]))
+ } else {
+ b.setText(string(or[:oc]) + v + string(or[oc:]))
+ }
+
+ if moveCursor {
+ b.cursorPosition += len([]rune(v))
+ }
+}
+
+// SetText method to set text and update cursorPosition.
+// (When doing this, make sure that the cursor_position is valid for this text.
+// text/cursor_position should be consistent at any time, otherwise set a Document instead.)
+func (b *Buffer) setText(v string) {
+ debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position")
+ b.workingLines[b.workingIndex] = v
+}
+
+// Set cursor position. Return whether it changed.
+func (b *Buffer) setCursorPosition(p int) {
+ if p > 0 {
+ b.cursorPosition = p
+ } else {
+ b.cursorPosition = 0
+ }
+}
+
+func (b *Buffer) setDocument(d *Document) {
+ b.cacheDocument = d
+ b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length.
+ b.setText(d.Text)
+}
+
+// CursorLeft move to left on the current line.
+func (b *Buffer) CursorLeft(count int) {
+ l := b.Document().GetCursorLeftPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorRight move to right on the current line.
+func (b *Buffer) CursorRight(count int) {
+ l := b.Document().GetCursorRightPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorUp move cursor to the previous line.
+// (for multi-line edit).
+func (b *Buffer) CursorUp(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorUpPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// CursorDown move cursor to the next line.
+// (for multi-line edit).
+func (b *Buffer) CursorDown(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorDownPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text.
+func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) {
+ debug.Assert(count >= 0, "count should be positive")
+ r := []rune(b.Text())
+
+ if b.cursorPosition > 0 {
+ start := b.cursorPosition - count
+ if start < 0 {
+ start = 0
+ }
+ deleted = string(r[start:b.cursorPosition])
+ b.setDocument(&Document{
+ Text: string(r[:start]) + string(r[b.cursorPosition:]),
+ cursorPosition: b.cursorPosition - len([]rune(deleted)),
+ })
+ }
+ return
+}
+
+// NewLine means CR.
+func (b *Buffer) NewLine(copyMargin bool) {
+ if copyMargin {
+ b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true)
+ } else {
+ b.InsertText("\n", false, true)
+ }
+}
+
+// Delete specified number of characters and Return the deleted text.
+func (b *Buffer) Delete(count int) (deleted string) {
+ r := []rune(b.Text())
+ if b.cursorPosition < len(r) {
+ deleted = b.Document().TextAfterCursor()[:count]
+ b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):]))
+ }
+ return
+}
+
+// JoinNextLine joins the next line to the current one by deleting the line ending after the current line.
+func (b *Buffer) JoinNextLine(separator string) {
+ if !b.Document().OnLastLine() {
+ b.cursorPosition += b.Document().GetEndOfLinePosition()
+ b.Delete(1)
+ // Remove spaces
+ b.setText(b.Document().TextBeforeCursor() + separator + strings.TrimLeft(b.Document().TextAfterCursor(), " "))
+ }
+}
+
+// SwapCharactersBeforeCursor swaps the last two characters before the cursor.
+func (b *Buffer) SwapCharactersBeforeCursor() {
+ if b.cursorPosition >= 2 {
+ x := b.Text()[b.cursorPosition-2 : b.cursorPosition-1]
+ y := b.Text()[b.cursorPosition-1 : b.cursorPosition]
+ b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:])
+ }
+}
+
+// NewBuffer is constructor of Buffer struct.
+func NewBuffer() (b *Buffer) {
+ b = &Buffer{
+ workingLines: []string{""},
+ workingIndex: 0,
+ preferredColumn: -1, // -1 means nil
+ }
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/completer/file.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/completer/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..59f2d8dec84214ccaa6e345a11ed51aa61a08199
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/completer/file.go
@@ -0,0 +1,90 @@
+package completer
+
+import (
+ "io/ioutil"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+var (
+ // FilePathCompletionSeparator holds separate characters.
+ FilePathCompletionSeparator = string([]byte{' ', os.PathSeparator})
+)
+
+// FilePathCompleter is a completer for your local file system.
+// Please caution that you need to set OptionCompletionWordSeparator(completer.FilePathCompletionSeparator)
+// when you use this completer.
+type FilePathCompleter struct {
+ Filter func(fi os.FileInfo) bool
+ IgnoreCase bool
+ fileListCache map[string][]prompt.Suggest
+}
+
+func cleanFilePath(path string) (dir, base string, err error) {
+ if path == "" {
+ return ".", "", nil
+ }
+
+ var endsWithSeparator bool
+ if len(path) >= 1 && path[len(path)-1] == os.PathSeparator {
+ endsWithSeparator = true
+ }
+
+ if runtime.GOOS != "windows" && len(path) >= 2 && path[0:2] == "~/" {
+ me, err := user.Current()
+ if err != nil {
+ return "", "", err
+ }
+ path = filepath.Join(me.HomeDir, path[1:])
+ }
+ path = filepath.Clean(os.ExpandEnv(path))
+ dir = filepath.Dir(path)
+ base = filepath.Base(path)
+
+ if endsWithSeparator {
+ dir = path + string(os.PathSeparator) // Append slash(in POSIX) if path ends with slash.
+ base = "" // Set empty string if path ends with separator.
+ }
+ return dir, base, nil
+}
+
+// Complete returns suggestions from your local file system.
+func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest {
+ if c.fileListCache == nil {
+ c.fileListCache = make(map[string][]prompt.Suggest, 4)
+ }
+
+ path := d.GetWordBeforeCursor()
+ dir, base, err := cleanFilePath(path)
+ if err != nil {
+ debug.Log("completer: cannot get current user:" + err.Error())
+ return nil
+ }
+
+ if cached, ok := c.fileListCache[dir]; ok {
+ return prompt.FilterHasPrefix(cached, base, c.IgnoreCase)
+ }
+
+ files, err := ioutil.ReadDir(dir)
+ if err != nil && os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ debug.Log("completer: cannot read directory items:" + err.Error())
+ return nil
+ }
+
+ suggests := make([]prompt.Suggest, 0, len(files))
+ for _, f := range files {
+ if c.Filter != nil && !c.Filter(f) {
+ continue
+ }
+ suggests = append(suggests, prompt.Suggest{Text: f.Name()})
+ }
+ c.fileListCache[dir] = suggests
+ return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/completion.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/completion.go
new file mode 100644
index 0000000000000000000000000000000000000000..57e82eefc0f50e9561214704e770a2ad313a3659
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/completion.go
@@ -0,0 +1,190 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+const (
+ shortenSuffix = "..."
+ leftPrefix = " "
+ leftSuffix = " "
+ rightPrefix = " "
+ rightSuffix = " "
+)
+
+var (
+ leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix)
+ rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix)
+ completionMargin = leftMargin + rightMargin
+)
+
+// Suggest is printed when completing.
+type Suggest struct {
+ Text string
+ Description string
+}
+
+// CompletionManager manages which suggestion is now selected.
+type CompletionManager struct {
+ selected int // -1 means nothing one is selected.
+ tmp []Suggest
+ max uint16
+ completer Completer
+
+ verticalScroll int
+ wordSeparator string
+ showAtStart bool
+}
+
+// GetSelectedSuggestion returns the selected item.
+func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) {
+ if c.selected == -1 {
+ return Suggest{}, false
+ } else if c.selected < -1 {
+ debug.Assert(false, "must not reach here")
+ c.selected = -1
+ return Suggest{}, false
+ }
+ return c.tmp[c.selected], true
+}
+
+// GetSuggestions returns the list of suggestion.
+func (c *CompletionManager) GetSuggestions() []Suggest {
+ return c.tmp
+}
+
+// Reset to select nothing.
+func (c *CompletionManager) Reset() {
+ c.selected = -1
+ c.verticalScroll = 0
+ c.Update(*NewDocument())
+}
+
+// Update to update the suggestions.
+func (c *CompletionManager) Update(in Document) {
+ c.tmp = c.completer(in)
+}
+
+// Previous to select the previous suggestion item.
+func (c *CompletionManager) Previous() {
+ if c.verticalScroll == c.selected && c.selected > 0 {
+ c.verticalScroll--
+ }
+ c.selected--
+ c.update()
+}
+
+// Next to select the next suggestion item.
+func (c *CompletionManager) Next() {
+ if c.verticalScroll+int(c.max)-1 == c.selected {
+ c.verticalScroll++
+ }
+ c.selected++
+ c.update()
+}
+
+// Completing returns whether the CompletionManager selects something one.
+func (c *CompletionManager) Completing() bool {
+ return c.selected != -1
+}
+
+func (c *CompletionManager) update() {
+ max := int(c.max)
+ if len(c.tmp) < max {
+ max = len(c.tmp)
+ }
+
+ if c.selected >= len(c.tmp) {
+ c.Reset()
+ } else if c.selected < -1 {
+ c.selected = len(c.tmp) - 1
+ c.verticalScroll = len(c.tmp) - max
+ }
+}
+
+func deleteBreakLineCharacters(s string) string {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, "\r", "", -1)
+ return s
+}
+
+func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) {
+ l := len(o)
+ n := make([]string, l)
+
+ lenPrefix := runewidth.StringWidth(prefix)
+ lenSuffix := runewidth.StringWidth(suffix)
+ lenShorten := runewidth.StringWidth(shortenSuffix)
+ min := lenPrefix + lenSuffix + lenShorten
+ for i := 0; i < l; i++ {
+ o[i] = deleteBreakLineCharacters(o[i])
+
+ w := runewidth.StringWidth(o[i])
+ if width < w {
+ width = w
+ }
+ }
+
+ if width == 0 {
+ return n, 0
+ }
+ if min >= max {
+ return n, 0
+ }
+ if lenPrefix+width+lenSuffix > max {
+ width = max - lenPrefix - lenSuffix
+ }
+
+ for i := 0; i < l; i++ {
+ x := runewidth.StringWidth(o[i])
+ if x <= width {
+ spaces := strings.Repeat(" ", width-x)
+ n[i] = prefix + o[i] + spaces + suffix
+ } else if x > width {
+ x := runewidth.Truncate(o[i], width, shortenSuffix)
+ // When calling runewidth.Truncate("您好xxx您好xxx", 11, "...") returns "您好xxx..."
+ // But the length of this result is 10. So we need fill right using runewidth.FillRight.
+ n[i] = prefix + runewidth.FillRight(x, width) + suffix
+ }
+ }
+ return n, lenPrefix + width + lenSuffix
+}
+
+func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) {
+ num := len(suggests)
+ new = make([]Suggest, num)
+
+ left := make([]string, num)
+ for i := 0; i < num; i++ {
+ left[i] = suggests[i].Text
+ }
+ right := make([]string, num)
+ for i := 0; i < num; i++ {
+ right[i] = suggests[i].Description
+ }
+
+ left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix)
+ if leftWidth == 0 {
+ return []Suggest{}, 0
+ }
+ right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix)
+
+ for i := 0; i < num; i++ {
+ new[i] = Suggest{Text: left[i], Description: right[i]}
+ }
+ return new, leftWidth + rightWidth
+}
+
+// NewCompletionManager returns initialized CompletionManager object.
+func NewCompletionManager(completer Completer, max uint16) *CompletionManager {
+ return &CompletionManager{
+ selected: -1,
+ max: max,
+ completer: completer,
+
+ verticalScroll: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/document.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/document.go
new file mode 100644
index 0000000000000000000000000000000000000000..64635c34e7b66eda251ceef01453d2a6a0f92b51
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/document.go
@@ -0,0 +1,441 @@
+package prompt
+
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+ istrings "github.com/c-bata/go-prompt/internal/strings"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Document has text displayed in terminal and cursor position.
+type Document struct {
+ Text string
+ // This represents a index in a rune array of Document.Text.
+ // So if Document is "日本(cursor)語", cursorPosition is 2.
+ // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+ cursorPosition int
+ lastKey Key
+}
+
+// NewDocument return the new empty document.
+func NewDocument() *Document {
+ return &Document{
+ Text: "",
+ cursorPosition: 0,
+ }
+}
+
+// LastKeyStroke return the last key pressed in this document.
+func (d *Document) LastKeyStroke() Key {
+ return d.lastKey
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (d *Document) DisplayCursorPosition() int {
+ var position int
+ runes := []rune(d.Text)[:d.cursorPosition]
+ for i := range runes {
+ position += runewidth.RuneWidth(runes[i])
+ }
+ return position
+}
+
+// GetCharRelativeToCursor return character relative to cursor position, or empty string
+func (d *Document) GetCharRelativeToCursor(offset int) (r rune) {
+ s := d.Text
+ cnt := 0
+
+ for len(s) > 0 {
+ cnt++
+ r, size := utf8.DecodeRuneInString(s)
+ if cnt == d.cursorPosition+offset {
+ return r
+ }
+ s = s[size:]
+ }
+ return 0
+}
+
+// TextBeforeCursor returns the text before the cursor.
+func (d *Document) TextBeforeCursor() string {
+ r := []rune(d.Text)
+ return string(r[:d.cursorPosition])
+}
+
+// TextAfterCursor returns the text after the cursor.
+func (d *Document) TextAfterCursor() string {
+ r := []rune(d.Text)
+ return string(r[d.cursorPosition:])
+}
+
+// GetWordBeforeCursor returns the word before the cursor.
+// If we have whitespace before the cursor this returns an empty string.
+func (d *Document) GetWordBeforeCursor() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWord():]
+}
+
+// GetWordAfterCursor returns the word after the cursor.
+// If we have whitespace after the cursor this returns an empty string.
+func (d *Document) GetWordAfterCursor() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWord()]
+}
+
+// GetWordBeforeCursorWithSpace returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorWithSpace() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordWithSpace():]
+}
+
+// GetWordAfterCursorWithSpace returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorWithSpace() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordWithSpace()]
+}
+
+// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
+func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparator(sep):]
+}
+
+// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
+func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparator(sep)]
+}
+
+// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):]
+}
+
+// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)]
+}
+
+// FindStartOfPreviousWord returns an index relative to the cursor position
+// pointing to the start of the previous word. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWord() int {
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexByte(x, ' ')
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindStartOfPreviousWordWithSpace() int {
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotByte(x, ' ')
+ if end == -1 {
+ return 0
+ }
+
+ start := strings.LastIndexByte(x[:end], ' ')
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWord()
+ }
+
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexAny(x, sep)
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWordWithSpace()
+ }
+
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotAny(x, sep)
+ if end == -1 {
+ return 0
+ }
+ start := strings.LastIndexAny(x[:end], sep)
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindEndOfCurrentWord returns an index relative to the cursor position.
+// pointing to the end of the current word. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWord() int {
+ x := d.TextAfterCursor()
+ i := strings.IndexByte(x, ' ')
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindEndOfCurrentWordWithSpace() int {
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotByte(x, ' ')
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexByte(x[start:], ' ')
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWord()
+ }
+
+ x := d.TextAfterCursor()
+ i := strings.IndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWordWithSpace()
+ }
+
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotAny(x, sep)
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexAny(x[start:], sep)
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// CurrentLineBeforeCursor returns the text from the start of the line until the cursor.
+func (d *Document) CurrentLineBeforeCursor() string {
+ s := strings.Split(d.TextBeforeCursor(), "\n")
+ return s[len(s)-1]
+}
+
+// CurrentLineAfterCursor returns the text from the cursor until the end of the line.
+func (d *Document) CurrentLineAfterCursor() string {
+ return strings.Split(d.TextAfterCursor(), "\n")[0]
+}
+
+// CurrentLine return the text on the line where the cursor is. (when the input
+// consists of just one line, it equals `text`.
+func (d *Document) CurrentLine() string {
+ return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor()
+}
+
+// Array pointing to the start indexes of all the lines.
+func (d *Document) lineStartIndexes() []int {
+ // TODO: Cache, because this is often reused.
+ // (If it is used, it's often used many times.
+ // And this has to be fast for editing big documents!)
+ lc := d.LineCount()
+ lengths := make([]int, lc)
+ for i, l := range d.Lines() {
+ lengths[i] = len(l)
+ }
+
+ // Calculate cumulative sums.
+ indexes := make([]int, lc+1)
+ indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189
+ pos := 0
+ for i, l := range lengths {
+ pos += l + 1
+ indexes[i+1] = pos
+ }
+ if lc > 1 {
+ // Pop the last item. (This is not a new line.)
+ indexes = indexes[:lc]
+ }
+ return indexes
+}
+
+// For the index of a character at a certain line, calculate the index of
+// the first character on that line.
+func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) {
+ indexes := d.lineStartIndexes()
+ pos = bisect.Right(indexes, index) - 1
+ lineStartIndex = indexes[pos]
+ return
+}
+
+// CursorPositionRow returns the current row. (0-based.)
+func (d *Document) CursorPositionRow() (row int) {
+ _, row = d.findLineStartIndex(d.cursorPosition)
+ return
+}
+
+// CursorPositionCol returns the current column. (0-based.)
+func (d *Document) CursorPositionCol() (col int) {
+ // Don't use self.text_before_cursor to calculate this. Creating substrings
+ // and splitting is too expensive for getting the cursor position.
+ _, index := d.findLineStartIndex(d.cursorPosition)
+ col = d.cursorPosition - index
+ return
+}
+
+// GetCursorLeftPosition returns the relative position for cursor left.
+func (d *Document) GetCursorLeftPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorRightPosition(-count)
+ }
+ if d.CursorPositionCol() > count {
+ return -count
+ }
+ return -d.CursorPositionCol()
+}
+
+// GetCursorRightPosition returns relative position for cursor right.
+func (d *Document) GetCursorRightPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorLeftPosition(-count)
+ }
+ if len(d.CurrentLineAfterCursor()) > count {
+ return count
+ }
+ return len(d.CurrentLineAfterCursor())
+}
+
+// GetCursorUpPosition return the relative cursor position (character index) where we would be
+// if the user pressed the arrow-up button.
+func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+
+ row := d.CursorPositionRow() - count
+ if row < 0 {
+ row = 0
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// GetCursorDownPosition return the relative cursor position (character index) where we would be if the
+// user pressed the arrow-down button.
+func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+ row := d.CursorPositionRow() + count
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// Lines returns the array of all the lines.
+func (d *Document) Lines() []string {
+ // TODO: Cache, because this one is reused very often.
+ return strings.Split(d.Text, "\n")
+}
+
+// LineCount return the number of lines in this document. If the document ends
+// with a trailing \n, that counts as the beginning of a new line.
+func (d *Document) LineCount() int {
+ return len(d.Lines())
+}
+
+// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple.
+// (0-based. Returns (0, 0) for index=0.)
+func (d *Document) TranslateIndexToPosition(index int) (row int, col int) {
+ row, rowIndex := d.findLineStartIndex(index)
+ col = index - rowIndex
+ return
+}
+
+// TranslateRowColToIndex given a (row, col), return the corresponding index.
+// (Row and col params are 0-based.)
+func (d *Document) TranslateRowColToIndex(row int, column int) (index int) {
+ indexes := d.lineStartIndexes()
+ if row < 0 {
+ row = 0
+ } else if row > len(indexes) {
+ row = len(indexes) - 1
+ }
+ index = indexes[row]
+ line := d.Lines()[row]
+
+ // python) result += max(0, min(col, len(line)))
+ if column > 0 || len(line) > 0 {
+ if column > len(line) {
+ index += len(line)
+ } else {
+ index += column
+ }
+ }
+
+ // Keep in range. (len(self.text) is included, because the cursor can be
+ // right after the end of the text as well.)
+ // python) result = max(0, min(result, len(self.text)))
+ if index > len(d.Text) {
+ index = len(d.Text)
+ }
+ if index < 0 {
+ index = 0
+ }
+ return index
+}
+
+// OnLastLine returns true when we are at the last line.
+func (d *Document) OnLastLine() bool {
+ return d.CursorPositionRow() == (d.LineCount() - 1)
+}
+
+// GetEndOfLinePosition returns relative position for the end of this line.
+func (d *Document) GetEndOfLinePosition() int {
+ return len([]rune(d.CurrentLineAfterCursor()))
+}
+
+func (d *Document) leadingWhitespaceInCurrentLine() (margin string) {
+ trimmed := strings.TrimSpace(d.CurrentLine())
+ margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)]
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/emacs.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/emacs.go
new file mode 100644
index 0000000000000000000000000000000000000000..632f96321f2577cdb7e8cffe639f1518a65d5e0f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/emacs.go
@@ -0,0 +1,120 @@
+package prompt
+
+import "github.com/c-bata/go-prompt/internal/debug"
+
+/*
+
+========
+PROGRESS
+========
+
+Moving the cursor
+-----------------
+
+* [x] Ctrl + a Go to the beginning of the line (Home)
+* [x] Ctrl + e Go to the End of the line (End)
+* [x] Ctrl + p Previous command (Up arrow)
+* [x] Ctrl + n Next command (Down arrow)
+* [x] Ctrl + f Forward one character
+* [x] Ctrl + b Backward one character
+* [x] Ctrl + xx Toggle between the start of line and current cursor position
+
+Editing
+-------
+
+* [x] Ctrl + L Clear the Screen, similar to the clear command
+* [x] Ctrl + d Delete character under the cursor
+* [x] Ctrl + h Delete character before the cursor (Backspace)
+
+* [x] Ctrl + w Cut the Word before the cursor to the clipboard.
+* [x] Ctrl + k Cut the Line after the cursor to the clipboard.
+* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard.
+
+* [ ] Ctrl + t Swap the last two characters before the cursor (typo).
+* [ ] Esc + t Swap the last two words before the cursor.
+
+* [ ] ctrl + y Paste the last thing to be cut (yank)
+* [ ] ctrl + _ Undo
+
+*/
+
+var emacsKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: ControlE,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+ },
+ },
+ // Go to the beginning of the line
+ {
+ Key: ControlA,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+ },
+ },
+ // Cut the Line after the cursor
+ {
+ Key: ControlK,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.Delete(len(x))
+ },
+ },
+ // Cut/delete the Line before the cursor
+ {
+ Key: ControlU,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.DeleteBeforeCursor(len(x))
+ },
+ },
+ // Delete character under the cursor
+ {
+ Key: ControlD,
+ Fn: func(buf *Buffer) {
+ if buf.Text() != "" {
+ buf.Delete(1)
+ }
+ },
+ },
+ // Backspace
+ {
+ Key: ControlH,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+ },
+ },
+ // Right allow: Forward one character
+ {
+ Key: ControlF,
+ Fn: func(buf *Buffer) {
+ buf.CursorRight(1)
+ },
+ },
+ // Left allow: Backward one character
+ {
+ Key: ControlB,
+ Fn: func(buf *Buffer) {
+ buf.CursorLeft(1)
+ },
+ },
+ // Cut the Word before the cursor.
+ {
+ Key: ControlW,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace())))
+ },
+ },
+ // Clear the Screen, similar to the clear command
+ {
+ Key: ControlL,
+ Fn: func(buf *Buffer) {
+ consoleWriter.EraseScreen()
+ consoleWriter.CursorGoTo(0, 0)
+ debug.AssertNoError(consoleWriter.Flush())
+ },
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/filter.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/filter.go
new file mode 100644
index 0000000000000000000000000000000000000000..61c17ed7f436a069563f520512bd25e4d81af0de
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/filter.go
@@ -0,0 +1,71 @@
+package prompt
+
+import "strings"
+
+// Filter is the type to filter the prompt.Suggestion array.
+type Filter func([]Suggest, string, bool) []Suggest
+
+// FilterHasPrefix checks whether the string completions.Text begins with sub.
+func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
+}
+
+// FilterHasSuffix checks whether the completion.Text ends with sub.
+func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
+}
+
+// FilterContains checks whether the completion.Text contains sub.
+func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
+}
+
+// FilterFuzzy checks whether the completion.Text fuzzy matches sub.
+// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
+// would match, for example, "Good food is gone"
+// ^ ^ ^
+func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
+}
+
+func fuzzyMatch(s, sub string) bool {
+ sChars := []rune(s)
+ sIdx := 0
+
+ // https://staticcheck.io/docs/checks#S1029
+ for _, c := range sub {
+ found := false
+ for ; sIdx < len(sChars); sIdx++ {
+ if sChars[sIdx] == c {
+ found = true
+ sIdx++
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
+
+func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
+ if sub == "" {
+ return suggestions
+ }
+ if ignoreCase {
+ sub = strings.ToUpper(sub)
+ }
+
+ ret := make([]Suggest, 0, len(suggestions))
+ for i := range suggestions {
+ c := suggestions[i].Text
+ if ignoreCase {
+ c = strings.ToUpper(c)
+ }
+ if function(c, sub) {
+ ret = append(ret, suggestions[i])
+ }
+ }
+ return ret
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/go.mod b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..30bc6d39a39c328341ca7153d3391352be5baa63
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/go.mod
@@ -0,0 +1,11 @@
+module github.com/c-bata/go-prompt
+
+go 1.14
+
+require (
+ github.com/mattn/go-colorable v0.1.7
+ github.com/mattn/go-runewidth v0.0.9
+ github.com/mattn/go-tty v0.0.3
+ github.com/pkg/term v1.2.0-beta.2
+ golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/go.sum b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..768bf93619a68e1b334c13e7b93ec84fa465598e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/go.sum
@@ -0,0 +1,23 @@
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/history.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/history.go
new file mode 100644
index 0000000000000000000000000000000000000000..e75c64592d82142bf4826ceb8c613ac72ca24d9c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/history.go
@@ -0,0 +1,61 @@
+package prompt
+
+// History stores the texts that are entered.
+type History struct {
+ histories []string
+ tmp []string
+ selected int
+}
+
+// Add to add text in history.
+func (h *History) Add(input string) {
+ h.histories = append(h.histories, input)
+ h.Clear()
+}
+
+// Clear to clear the history.
+func (h *History) Clear() {
+ h.tmp = make([]string, len(h.histories))
+ for i := range h.histories {
+ h.tmp[i] = h.histories[i]
+ }
+ h.tmp = append(h.tmp, "")
+ h.selected = len(h.tmp) - 1
+}
+
+// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
+ if len(h.tmp) == 1 || h.selected == 0 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected--
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
+ if h.selected >= len(h.tmp)-1 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected++
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// NewHistory returns new history object.
+func NewHistory() *History {
+ return &History{
+ histories: []string{},
+ tmp: []string{""},
+ selected: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/input.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/input.go
new file mode 100644
index 0000000000000000000000000000000000000000..307e747190c2b27bf888b379644fc4f3cdd489a2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/input.go
@@ -0,0 +1,169 @@
+package prompt
+
+import "bytes"
+
+// WinSize represents the width and height of terminal.
+type WinSize struct {
+ Row uint16
+ Col uint16
+}
+
+// ConsoleParser is an interface to abstract input layer.
+type ConsoleParser interface {
+ // Setup should be called before starting input
+ Setup() error
+ // TearDown should be called after stopping input
+ TearDown() error
+ // GetWinSize returns WinSize object to represent width and height of terminal.
+ GetWinSize() *WinSize
+ // Read returns byte array.
+ Read() ([]byte, error)
+}
+
+// GetKey returns Key correspond to input byte codes.
+func GetKey(b []byte) Key {
+ for _, k := range ASCIISequences {
+ if bytes.Equal(k.ASCIICode, b) {
+ return k.Key
+ }
+ }
+ return NotDefined
+}
+
+// ASCIISequences holds mappings of the key and byte array.
+var ASCIISequences = []*ASCIICode{
+ {Key: Escape, ASCIICode: []byte{0x1b}},
+
+ {Key: ControlSpace, ASCIICode: []byte{0x00}},
+ {Key: ControlA, ASCIICode: []byte{0x1}},
+ {Key: ControlB, ASCIICode: []byte{0x2}},
+ {Key: ControlC, ASCIICode: []byte{0x3}},
+ {Key: ControlD, ASCIICode: []byte{0x4}},
+ {Key: ControlE, ASCIICode: []byte{0x5}},
+ {Key: ControlF, ASCIICode: []byte{0x6}},
+ {Key: ControlG, ASCIICode: []byte{0x7}},
+ {Key: ControlH, ASCIICode: []byte{0x8}},
+ //{Key: ControlI, ASCIICode: []byte{0x9}},
+ //{Key: ControlJ, ASCIICode: []byte{0xa}},
+ {Key: ControlK, ASCIICode: []byte{0xb}},
+ {Key: ControlL, ASCIICode: []byte{0xc}},
+ {Key: ControlM, ASCIICode: []byte{0xd}},
+ {Key: ControlN, ASCIICode: []byte{0xe}},
+ {Key: ControlO, ASCIICode: []byte{0xf}},
+ {Key: ControlP, ASCIICode: []byte{0x10}},
+ {Key: ControlQ, ASCIICode: []byte{0x11}},
+ {Key: ControlR, ASCIICode: []byte{0x12}},
+ {Key: ControlS, ASCIICode: []byte{0x13}},
+ {Key: ControlT, ASCIICode: []byte{0x14}},
+ {Key: ControlU, ASCIICode: []byte{0x15}},
+ {Key: ControlV, ASCIICode: []byte{0x16}},
+ {Key: ControlW, ASCIICode: []byte{0x17}},
+ {Key: ControlX, ASCIICode: []byte{0x18}},
+ {Key: ControlY, ASCIICode: []byte{0x19}},
+ {Key: ControlZ, ASCIICode: []byte{0x1a}},
+
+ {Key: ControlBackslash, ASCIICode: []byte{0x1c}},
+ {Key: ControlSquareClose, ASCIICode: []byte{0x1d}},
+ {Key: ControlCircumflex, ASCIICode: []byte{0x1e}},
+ {Key: ControlUnderscore, ASCIICode: []byte{0x1f}},
+ {Key: Backspace, ASCIICode: []byte{0x7f}},
+
+ {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}},
+
+ {Key: Enter, ASCIICode: []byte{0xa}},
+ {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}},
+ {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+ {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}},
+ {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}},
+ {Key: Tab, ASCIICode: []byte{0x9}},
+ {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}},
+ {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}},
+ {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}},
+ {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}},
+ {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode
+
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}},
+ {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}},
+ {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}},
+ {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}},
+ {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}},
+ {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}},
+ {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}},
+ {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}},
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}},
+ {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}},
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+
+ // Xterm
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}},
+ // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}},
+ {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}},
+ {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}},
+ {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}},
+ {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}},
+
+ {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}},
+ {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}},
+ {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}},
+ {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}},
+
+ // Tmux sends following keystrokes when control+arrow is pressed, but for
+ // Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ // it a normal arrow press, because that's more important.
+ {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}},
+
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt
+
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/input_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/input_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f10430318be0e797c841eba8e08ab1cf5277be27
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/input_posix.go
@@ -0,0 +1,77 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/term"
+ "golang.org/x/sys/unix"
+)
+
+const maxReadBytes = 1024
+
+// PosixParser is a ConsoleParser implementation for POSIX environment.
+type PosixParser struct {
+ fd int
+ origTermios syscall.Termios
+}
+
+// Setup should be called before starting input
+func (t *PosixParser) Setup() error {
+ // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
+ if err := syscall.SetNonblock(t.fd, true); err != nil {
+ return err
+ }
+ if err := term.SetRaw(t.fd); err != nil {
+ return err
+ }
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (t *PosixParser) TearDown() error {
+ if err := syscall.SetNonblock(t.fd, false); err != nil {
+ return err
+ }
+ if err := term.Restore(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Read returns byte array.
+func (t *PosixParser) Read() ([]byte, error) {
+ buf := make([]byte, maxReadBytes)
+ n, err := syscall.Read(t.fd, buf)
+ if err != nil {
+ return []byte{}, err
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (t *PosixParser) GetWinSize() *WinSize {
+ ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: ws.Row,
+ Col: ws.Col,
+ }
+}
+
+var _ ConsoleParser = &PosixParser{}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *PosixParser {
+ in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ return &PosixParser{
+ fd: in,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/input_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/input_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..11b7679d4c4bc8b924a5b6c863ca1f6d6880570d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/input_windows.go
@@ -0,0 +1,83 @@
+// +build windows
+
+package prompt
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf8"
+ "unsafe"
+
+ tty "github.com/mattn/go-tty"
+)
+
+const maxReadBytes = 1024
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
+
+// WindowsParser is a ConsoleParser implementation for Win32 console.
+type WindowsParser struct {
+ tty *tty.TTY
+}
+
+// Setup should be called before starting input
+func (p *WindowsParser) Setup() error {
+ t, err := tty.Open()
+ if err != nil {
+ return err
+ }
+ p.tty = t
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (p *WindowsParser) TearDown() error {
+ return p.tty.Close()
+}
+
+// Read returns byte array.
+func (p *WindowsParser) Read() ([]byte, error) {
+ var ev uint32
+ r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
+ if r0 == 0 {
+ return nil, err
+ }
+ if ev == 0 {
+ return nil, errors.New("EAGAIN")
+ }
+
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, maxReadBytes)
+ n := utf8.EncodeRune(buf[:], r)
+ for p.tty.Buffered() && n < maxReadBytes {
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ break
+ }
+ n += utf8.EncodeRune(buf[n:], r)
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (p *WindowsParser) GetWinSize() *WinSize {
+ w, h, err := p.tty.Size()
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: uint16(h),
+ Col: uint16(w),
+ }
+}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *WindowsParser {
+ return &WindowsParser{}
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/bisect/bisect.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/bisect/bisect.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe162fa8c4873302e25702081b629a445d43415
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/bisect/bisect.go
@@ -0,0 +1,15 @@
+package bisect
+
+import "sort"
+
+// Right to locate the insertion point for v in a to maintain sorted order.
+func Right(a []int, v int) int {
+ return bisectRightRange(a, v, 0, len(a))
+}
+
+func bisectRightRange(a []int, v int, lo, hi int) int {
+ s := a[lo:hi]
+ return sort.Search(len(s), func(i int) bool {
+ return s[i] > v
+ })
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/debug/assert.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/debug/assert.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f648ac93c44e1e021cdf581a68f03b548534d9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/debug/assert.go
@@ -0,0 +1,55 @@
+package debug
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
+)
+
+var (
+ enableAssert bool
+)
+
+func init() {
+ if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
+ enableAssert = true
+ }
+}
+
+// Assert ensures expected condition.
+func Assert(cond bool, msg interface{}) {
+ if cond {
+ return
+ }
+ if enableAssert {
+ panic(msg)
+ }
+ writeWithSync(2, "[ASSERT] "+toString(msg))
+}
+
+func toString(v interface{}) string {
+ switch a := v.(type) {
+ case func() string:
+ return a()
+ case string:
+ return a
+ case fmt.Stringer:
+ return a.String()
+ default:
+ return fmt.Sprintf("unexpected type, %t", v)
+ }
+}
+
+// AssertNoError ensures err is nil.
+func AssertNoError(err error) {
+ if err == nil {
+ return
+ }
+ if enableAssert {
+ panic(err)
+ }
+ writeWithSync(2, "[ASSERT] "+err.Error())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/debug/log.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/debug/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..516378627a34ead9063ab7ce6c445b23c77b7cb4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/debug/log.go
@@ -0,0 +1,52 @@
+package debug
+
+import (
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+const (
+ envEnableLog = "GO_PROMPT_ENABLE_LOG"
+ logFileName = "go-prompt.log"
+)
+
+var (
+ logfile *os.File
+ logger *log.Logger
+)
+
+func init() {
+ if e := os.Getenv(envEnableLog); e == "true" || e == "1" {
+ var err error
+ logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
+ if err == nil {
+ logger = log.New(logfile, "", log.Llongfile)
+ return
+ }
+ }
+ logger = log.New(ioutil.Discard, "", log.Llongfile)
+}
+
+// Teardown to close logfile
+func Teardown() {
+ if logfile == nil {
+ return
+ }
+ _ = logfile.Close()
+}
+
+func writeWithSync(calldepth int, msg string) {
+ calldepth++
+ if logfile == nil {
+ return
+ }
+ _ = logger.Output(calldepth, msg)
+ _ = logfile.Sync() // immediately write msg
+}
+
+// Log to output message
+func Log(msg string) {
+ calldepth := 2
+ writeWithSync(calldepth, msg)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/strings/strings.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/strings/strings.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7d1886ae03a7d541c66dffca921e2d040e6d5eb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/strings/strings.go
@@ -0,0 +1,102 @@
+package strings
+
+import "unicode/utf8"
+
+// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior.
+func IndexNotByte(s string, c byte) int {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior.
+func LastIndexNotByte(s string, c byte) int {
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+type asciiSet [8]uint32
+
+func (as *asciiSet) notContains(c byte) bool {
+ return (as[c>>5] & (1 << uint(c&31))) == 0
+}
+
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c>>5] |= 1 << uint(c&31)
+ }
+ return as, true
+}
+
+// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior.
+func IndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := 0; i < len(s); i++ {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+
+ LabelFirstLoop:
+ for i, c := range s {
+ for j, m := range chars {
+ if c != m && j == len(chars)-1 {
+ return i
+ } else if c != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior.
+func LastIndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ LabelFirstLoop:
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRuneInString(s[:i])
+ i -= size
+ for j, m := range chars {
+ if r != m && j == len(chars)-1 {
+ return i
+ } else if r != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/term/raw.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/term/raw.go
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3ed8d04023558cf386a98080815d661248b85
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/term/raw.go
@@ -0,0 +1,29 @@
+// +build !windows
+
+package term
+
+import (
+ "syscall"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+// SetRaw put terminal into a raw mode
+func SetRaw(fd int) error {
+ n, err := getOriginalTermios(fd)
+ if err != nil {
+ return err
+ }
+
+ n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK |
+ syscall.ISTRIP | syscall.INLCR | syscall.IGNCR |
+ syscall.ICRNL | syscall.IXON
+ n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL
+ n.Cflag &^= syscall.CSIZE | syscall.PARENB
+ n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters.
+ n.Cc[syscall.VMIN] = 1
+ n.Cc[syscall.VTIME] = 0
+
+ return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n))
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/term/term.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/term/term.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a53c059ae60c0348ec01689babef4b13a2ecd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/internal/term/term.go
@@ -0,0 +1,34 @@
+// +build !windows
+
+package term
+
+import (
+ "sync"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ saveTermios *unix.Termios
+ saveTermiosFD int
+ saveTermiosOnce sync.Once
+)
+
+func getOriginalTermios(fd int) (*unix.Termios, error) {
+ var err error
+ saveTermiosOnce.Do(func() {
+ saveTermiosFD = fd
+ saveTermios, err = termios.Tcgetattr(uintptr(fd))
+ })
+ return saveTermios, err
+}
+
+// Restore terminal's mode.
+func Restore() error {
+ o, err := getOriginalTermios(saveTermiosFD)
+ if err != nil {
+ return err
+ }
+ return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/key.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ba569c2dd20a8ae3b3dd79ff3695bf0b6c1bd09
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/key.go
@@ -0,0 +1,128 @@
+// Code generated by hand; DO NOT EDIT.
+// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment.
+
+package prompt
+
+// Key is the type express the key inserted from user.
+//go:generate stringer -type=Key
+type Key int
+
+// ASCIICode is the type contains Key and it's ascii byte array.
+type ASCIICode struct {
+ Key Key
+ ASCIICode []byte
+}
+
+const (
+ Escape Key = iota
+
+ ControlA
+ ControlB
+ ControlC
+ ControlD
+ ControlE
+ ControlF
+ ControlG
+ ControlH
+ ControlI
+ ControlJ
+ ControlK
+ ControlL
+ ControlM
+ ControlN
+ ControlO
+ ControlP
+ ControlQ
+ ControlR
+ ControlS
+ ControlT
+ ControlU
+ ControlV
+ ControlW
+ ControlX
+ ControlY
+ ControlZ
+
+ ControlSpace
+ ControlBackslash
+ ControlSquareClose
+ ControlCircumflex
+ ControlUnderscore
+ ControlLeft
+ ControlRight
+ ControlUp
+ ControlDown
+
+ Up
+ Down
+ Right
+ Left
+
+ ShiftLeft
+ ShiftUp
+ ShiftDown
+ ShiftRight
+
+ Home
+ End
+ Delete
+ ShiftDelete
+ ControlDelete
+ PageUp
+ PageDown
+ BackTab
+ Insert
+ Backspace
+
+ // Aliases.
+ Tab
+ Enter
+ // Actually Enter equals ControlM, not ControlJ,
+ // However, in prompt_toolkit, we made the mistake of translating
+ // \r into \n during the input, so everyone is now handling the
+ // enter key by binding ControlJ.
+
+ // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere,
+ // because that's future compatible, and will still work when we
+ // stop replacing \r by \n.
+
+ F1
+ F2
+ F3
+ F4
+ F5
+ F6
+ F7
+ F8
+ F9
+ F10
+ F11
+ F12
+ F13
+ F14
+ F15
+ F16
+ F17
+ F18
+ F19
+ F20
+ F21
+ F22
+ F23
+ F24
+
+ // Matches any key.
+ Any
+
+ // Special
+ CPRResponse
+ Vt100MouseEvent
+ WindowsMouseEvent
+ BracketedPaste
+
+ // Key which is ignored. (The key binding for this key should not do anything.)
+ Ignore
+
+ // Key is not defined
+ NotDefined
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/key_bind.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/key_bind.go
new file mode 100644
index 0000000000000000000000000000000000000000..42669e7f942efc4d92f896388daede90b96b55dd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/key_bind.go
@@ -0,0 +1,59 @@
+package prompt
+
+// KeyBindFunc receives buffer and processed it.
+type KeyBindFunc func(*Buffer)
+
+// KeyBind represents which key should do what operation.
+type KeyBind struct {
+ Key Key
+ Fn KeyBindFunc
+}
+
+// ASCIICodeBind represents which []byte should do what operation
+type ASCIICodeBind struct {
+ ASCIICode []byte
+ Fn KeyBindFunc
+}
+
+// KeyBindMode to switch a key binding flexibly.
+type KeyBindMode string
+
+const (
+ // CommonKeyBind is a mode without any keyboard shortcut
+ CommonKeyBind KeyBindMode = "common"
+ // EmacsKeyBind is a mode to use emacs-like keyboard shortcut
+ EmacsKeyBind KeyBindMode = "emacs"
+)
+
+var commonKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: End,
+ Fn: GoLineEnd,
+ },
+ // Go to the beginning of the line
+ {
+ Key: Home,
+ Fn: GoLineBeginning,
+ },
+ // Delete character under the cursor
+ {
+ Key: Delete,
+ Fn: DeleteChar,
+ },
+ // Backspace
+ {
+ Key: Backspace,
+ Fn: DeleteBeforeChar,
+ },
+ // Right allow: Forward one character
+ {
+ Key: Right,
+ Fn: GoRightChar,
+ },
+ // Left allow: Backward one character
+ {
+ Key: Left,
+ Fn: GoLeftChar,
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/key_bind_func.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/key_bind_func.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b2ecdf63179dbfdbcb0d71bfa436bb36d62d230
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/key_bind_func.go
@@ -0,0 +1,48 @@
+package prompt
+
+// GoLineEnd Go to the End of the line
+func GoLineEnd(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+}
+
+// GoLineBeginning Go to the beginning of the line
+func GoLineBeginning(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+}
+
+// DeleteChar Delete character under the cursor
+func DeleteChar(buf *Buffer) {
+ buf.Delete(1)
+}
+
+// DeleteWord Delete word before the cursor
+func DeleteWord(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
+
+// DeleteBeforeChar Go to Backspace
+func DeleteBeforeChar(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+}
+
+// GoRightChar Forward one character
+func GoRightChar(buf *Buffer) {
+ buf.CursorRight(1)
+}
+
+// GoLeftChar Backward one character
+func GoLeftChar(buf *Buffer) {
+ buf.CursorLeft(1)
+}
+
+// GoRightWord Forward one word
+func GoRightWord(buf *Buffer) {
+ buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
+}
+
+// GoLeftWord Backward one word
+func GoLeftWord(buf *Buffer) {
+ buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/key_string.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/key_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..fce6ea31c502b3e763451cb47757ae1b49c32814
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/key_string.go
@@ -0,0 +1,16 @@
+// Code generated by "stringer -type=Key"; DO NOT EDIT.
+
+package prompt
+
+import "strconv"
+
+const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined"
+
+var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607}
+
+func (i Key) String() string {
+ if i < 0 || i >= Key(len(_Key_index)-1) {
+ return "Key(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _Key_name[_Key_index[i]:_Key_index[i+1]]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/option.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/option.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd6806cc1dbccf8c4ddb048080fde615c59088
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/option.go
@@ -0,0 +1,310 @@
+package prompt
+
+// Option is the type to replace default parameters.
+// prompt.New accepts any number of options (this is functional option pattern).
+type Option func(prompt *Prompt) error
+
+// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
+func OptionParser(x ConsoleParser) Option {
+ return func(p *Prompt) error {
+ p.in = x
+ return nil
+ }
+}
+
+// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
+func OptionWriter(x ConsoleWriter) Option {
+ return func(p *Prompt) error {
+ registerConsoleWriter(x)
+ p.renderer.out = x
+ return nil
+ }
+}
+
+// OptionTitle to set title displayed at the header bar of terminal.
+func OptionTitle(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.title = x
+ return nil
+ }
+}
+
+// OptionPrefix to set prefix string.
+func OptionPrefix(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefix = x
+ return nil
+ }
+}
+
+// OptionInitialBufferText to set the initial buffer text
+func OptionInitialBufferText(x string) Option {
+ return func(p *Prompt) error {
+ p.buf.InsertText(x, false, true)
+ return nil
+ }
+}
+
+// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
+func OptionCompletionWordSeparator(x string) Option {
+ return func(p *Prompt) error {
+ p.completion.wordSeparator = x
+ return nil
+ }
+}
+
+// OptionLivePrefix to change the prefix dynamically by callback function
+func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
+ return func(p *Prompt) error {
+ p.renderer.livePrefixCallback = f
+ return nil
+ }
+}
+
+// OptionPrefixTextColor change a text color of prefix string
+func OptionPrefixTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixTextColor = x
+ return nil
+ }
+}
+
+// OptionPrefixBackgroundColor to change a background color of prefix string
+func OptionPrefixBackgroundColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixBGColor = x
+ return nil
+ }
+}
+
+// OptionInputTextColor to change a color of text which is input by user
+func OptionInputTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputTextColor = x
+ return nil
+ }
+}
+
+// OptionInputBGColor to change a color of background which is input by user
+func OptionInputBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputBGColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionTextColor to change a text color which is completed
+func OptionPreviewSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionBGColor to change a background color which is completed
+func OptionPreviewSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionTextColor to change a text color in drop down suggestions.
+func OptionSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionBGColor change a background color in drop down suggestions.
+func OptionSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarThumbColor to change a thumb color on scrollbar.
+func OptionScrollbarThumbColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarThumbColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarBGColor to change a background color of scrollbar.
+func OptionScrollbarBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarBGColor = x
+ return nil
+ }
+}
+
+// OptionMaxSuggestion specify the max number of displayed suggestions.
+func OptionMaxSuggestion(x uint16) Option {
+ return func(p *Prompt) error {
+ p.completion.max = x
+ return nil
+ }
+}
+
+// OptionHistory to set history expressed by string array.
+func OptionHistory(x []string) Option {
+ return func(p *Prompt) error {
+ p.history.histories = x
+ p.history.Clear()
+ return nil
+ }
+}
+
+// OptionSwitchKeyBindMode set a key bind mode.
+func OptionSwitchKeyBindMode(m KeyBindMode) Option {
+ return func(p *Prompt) error {
+ p.keyBindMode = m
+ return nil
+ }
+}
+
+// OptionCompletionOnDown allows for Down arrow key to trigger completion.
+func OptionCompletionOnDown() Option {
+ return func(p *Prompt) error {
+ p.completionOnDown = true
+ return nil
+ }
+}
+
+// SwitchKeyBindMode to set a key bind mode.
+// Deprecated: Please use OptionSwitchKeyBindMode.
+var SwitchKeyBindMode = OptionSwitchKeyBindMode
+
+// OptionAddKeyBind to set a custom key bind.
+func OptionAddKeyBind(b ...KeyBind) Option {
+ return func(p *Prompt) error {
+ p.keyBindings = append(p.keyBindings, b...)
+ return nil
+ }
+}
+
+// OptionAddASCIICodeBind to set a custom key bind.
+func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option {
+ return func(p *Prompt) error {
+ p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...)
+ return nil
+ }
+}
+
+// OptionShowCompletionAtStart to set completion window is open at start.
+func OptionShowCompletionAtStart() Option {
+ return func(p *Prompt) error {
+ p.completion.showAtStart = true
+ return nil
+ }
+}
+
+// OptionBreakLineCallback to run a callback at every break line
+func OptionBreakLineCallback(fn func(*Document)) Option {
+ return func(p *Prompt) error {
+ p.renderer.breakLineCallback = fn
+ return nil
+ }
+}
+
+// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop
+func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
+ return func(p *Prompt) error {
+ p.exitChecker = fn
+ return nil
+ }
+}
+
+// New returns a Prompt with powerful auto-completion.
+func New(executor Executor, completer Completer, opts ...Option) *Prompt {
+ defaultWriter := NewStdoutWriter()
+ registerConsoleWriter(defaultWriter)
+
+ pt := &Prompt{
+ in: NewStandardInputParser(),
+ renderer: &Render{
+ prefix: "> ",
+ out: defaultWriter,
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ },
+ buf: NewBuffer(),
+ executor: executor,
+ history: NewHistory(),
+ completion: NewCompletionManager(completer, 6),
+ keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting
+ }
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/output.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/output.go
new file mode 100644
index 0000000000000000000000000000000000000000..42531b412f1ed027c2fff5b85bc273e53e569b3a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/output.go
@@ -0,0 +1,161 @@
+package prompt
+
+import "sync"
+
+var (
+ consoleWriterMu sync.Mutex
+ consoleWriter ConsoleWriter
+)
+
+func registerConsoleWriter(f ConsoleWriter) {
+ consoleWriterMu.Lock()
+ defer consoleWriterMu.Unlock()
+ consoleWriter = f
+}
+
+// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on.
+type DisplayAttribute int
+
+const (
+ // DisplayReset reset all display attributes.
+ DisplayReset DisplayAttribute = iota
+ // DisplayBold set bold or increases intensity.
+ DisplayBold
+ // DisplayLowIntensity decreases intensity. Not widely supported.
+ DisplayLowIntensity
+ // DisplayItalic set italic. Not widely supported.
+ DisplayItalic
+ // DisplayUnderline set underline
+ DisplayUnderline
+ // DisplayBlink set blink (less than 150 per minute).
+ DisplayBlink
+ // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported.
+ DisplayRapidBlink
+ // DisplayReverse swap foreground and background colors.
+ DisplayReverse
+ // DisplayInvisible set invisible. Not widely supported.
+ DisplayInvisible
+ // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported.
+ DisplayCrossedOut
+ // DisplayDefaultFont set primary(default) font
+ DisplayDefaultFont
+)
+
+// Color represents color on terminal.
+type Color int
+
+const (
+ // DefaultColor represents a default color.
+ DefaultColor Color = iota
+
+ // Low intensity
+
+ // Black represents a black.
+ Black
+ // DarkRed represents a dark red.
+ DarkRed
+ // DarkGreen represents a dark green.
+ DarkGreen
+ // Brown represents a brown.
+ Brown
+ // DarkBlue represents a dark blue.
+ DarkBlue
+ // Purple represents a purple.
+ Purple
+ // Cyan represents a cyan.
+ Cyan
+ // LightGray represents a light gray.
+ LightGray
+
+ // High intensity
+
+ // DarkGray represents a dark gray.
+ DarkGray
+ // Red represents a red.
+ Red
+ // Green represents a green.
+ Green
+ // Yellow represents a yellow.
+ Yellow
+ // Blue represents a blue.
+ Blue
+ // Fuchsia represents a fuchsia.
+ Fuchsia
+ // Turquoise represents a turquoise.
+ Turquoise
+ // White represents a white.
+ White
+)
+
+// ConsoleWriter is an interface to abstract output layer.
+type ConsoleWriter interface {
+ /* Write */
+
+ // WriteRaw to write raw byte array.
+ WriteRaw(data []byte)
+ // Write to write safety byte array by removing control sequences.
+ Write(data []byte)
+ // WriteStr to write raw string.
+ WriteRawStr(data string)
+ // WriteStr to write safety string by removing control sequences.
+ WriteStr(data string)
+ // Flush to flush buffer.
+ Flush() error
+
+ /* Erasing */
+
+ // EraseScreen erases the screen with the background colour and moves the cursor to home.
+ EraseScreen()
+ // EraseUp erases the screen from the current line up to the top of the screen.
+ EraseUp()
+ // EraseDown erases the screen from the current line down to the bottom of the screen.
+ EraseDown()
+ // EraseStartOfLine erases from the current cursor position to the start of the current line.
+ EraseStartOfLine()
+ // EraseEndOfLine erases from the current cursor position to the end of the current line.
+ EraseEndOfLine()
+ // EraseLine erases the entire current line.
+ EraseLine()
+
+ /* Cursor */
+
+ // ShowCursor stops blinking cursor and show.
+ ShowCursor()
+ // HideCursor hides cursor.
+ HideCursor()
+ // CursorGoTo sets the cursor position where subsequent text will begin.
+ CursorGoTo(row, col int)
+ // CursorUp moves the cursor up by 'n' rows; the default count is 1.
+ CursorUp(n int)
+ // CursorDown moves the cursor down by 'n' rows; the default count is 1.
+ CursorDown(n int)
+ // CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+ CursorForward(n int)
+ // CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+ CursorBackward(n int)
+ // AskForCPR asks for a cursor position report (CPR).
+ AskForCPR()
+ // SaveCursor saves current cursor position.
+ SaveCursor()
+ // UnSaveCursor restores cursor position after a Save Cursor.
+ UnSaveCursor()
+
+ /* Scrolling */
+
+ // ScrollDown scrolls display down one line.
+ ScrollDown()
+ // ScrollUp scroll display up one line.
+ ScrollUp()
+
+ /* Title */
+
+ // SetTitle sets a title of terminal window.
+ SetTitle(title string)
+ // ClearTitle clears a title of terminal window.
+ ClearTitle()
+
+ /* Font */
+
+ // SetColor sets text and background colors. and specify whether text is bold.
+ SetColor(fg, bg Color, bold bool)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/output_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/output_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..26c770cc152a7b126be43915d60b8ba000ad0e38
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/output_posix.go
@@ -0,0 +1,67 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+)
+
+const flushMaxRetryCount = 3
+
+// PosixWriter is a ConsoleWriter implementation for POSIX environment.
+// To control terminal emulator, this outputs VT100 escape sequences.
+type PosixWriter struct {
+ VT100Writer
+ fd int
+}
+
+// Flush to flush buffer
+func (w *PosixWriter) Flush() error {
+ l := len(w.buffer)
+ offset := 0
+ retry := 0
+ for {
+ n, err := syscall.Write(w.fd, w.buffer[offset:])
+ if err != nil {
+ if retry < flushMaxRetryCount {
+ retry++
+ continue
+ }
+ return err
+ }
+ offset += n
+ if offset == l {
+ break
+ }
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &PosixWriter{}
+
+var (
+ // NewStandardOutputWriter returns ConsoleWriter object to write to stdout.
+ // This generates VT100 escape sequences because almost terminal emulators
+ // in POSIX OS built on top of a VT100 specification.
+ // Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStdoutWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stdout,
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStderrWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stderr,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/output_vt100.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/output_vt100.go
new file mode 100644
index 0000000000000000000000000000000000000000..20850fead883c4cd9802928b5de3f935fbbeb047
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/output_vt100.go
@@ -0,0 +1,310 @@
+package prompt
+
+import (
+ "bytes"
+ "strconv"
+)
+
+// VT100Writer generates VT100 escape sequences.
+type VT100Writer struct {
+ buffer []byte
+}
+
+// WriteRaw to write raw byte array
+func (w *VT100Writer) WriteRaw(data []byte) {
+ w.buffer = append(w.buffer, data...)
+}
+
+// Write to write safety byte array by removing control sequences.
+func (w *VT100Writer) Write(data []byte) {
+ w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1))
+}
+
+// WriteRawStr to write raw string
+func (w *VT100Writer) WriteRawStr(data string) {
+ w.WriteRaw([]byte(data))
+}
+
+// WriteStr to write safety string by removing control sequences.
+func (w *VT100Writer) WriteStr(data string) {
+ w.Write([]byte(data))
+}
+
+/* Erase */
+
+// EraseScreen erases the screen with the background colour and moves the cursor to home.
+func (w *VT100Writer) EraseScreen() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'J'})
+}
+
+// EraseUp erases the screen from the current line up to the top of the screen.
+func (w *VT100Writer) EraseUp() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'J'})
+}
+
+// EraseDown erases the screen from the current line down to the bottom of the screen.
+func (w *VT100Writer) EraseDown() {
+ w.WriteRaw([]byte{0x1b, '[', 'J'})
+}
+
+// EraseStartOfLine erases from the current cursor position to the start of the current line.
+func (w *VT100Writer) EraseStartOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'K'})
+}
+
+// EraseEndOfLine erases from the current cursor position to the end of the current line.
+func (w *VT100Writer) EraseEndOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', 'K'})
+}
+
+// EraseLine erases the entire current line.
+func (w *VT100Writer) EraseLine() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'K'})
+}
+
+/* Cursor */
+
+// ShowCursor stops blinking cursor and show.
+func (w *VT100Writer) ShowCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'})
+}
+
+// HideCursor hides cursor.
+func (w *VT100Writer) HideCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'})
+}
+
+// CursorGoTo sets the cursor position where subsequent text will begin.
+func (w *VT100Writer) CursorGoTo(row, col int) {
+ if row == 0 && col == 0 {
+ // If no row/column parameters are provided (ie. [H), the cursor will move to the home position.
+ w.WriteRaw([]byte{0x1b, '[', 'H'})
+ return
+ }
+ r := strconv.Itoa(row)
+ c := strconv.Itoa(col)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(r))
+ w.WriteRaw([]byte{';'})
+ w.WriteRaw([]byte(c))
+ w.WriteRaw([]byte{'H'})
+}
+
+// CursorUp moves the cursor up by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorUp(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorDown(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'A'})
+}
+
+// CursorDown moves the cursor down by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorDown(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorUp(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'B'})
+}
+
+// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorForward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorBackward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'C'})
+}
+
+// CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorBackward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorForward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'D'})
+}
+
+// AskForCPR asks for a cursor position report (CPR).
+func (w *VT100Writer) AskForCPR() {
+ // CPR: Cursor Position Request.
+ w.WriteRaw([]byte{0x1b, '[', '6', 'n'})
+}
+
+// SaveCursor saves current cursor position.
+func (w *VT100Writer) SaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 's'})
+}
+
+// UnSaveCursor restores cursor position after a Save Cursor.
+func (w *VT100Writer) UnSaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 'u'})
+}
+
+/* Scrolling */
+
+// ScrollDown scrolls display down one line.
+func (w *VT100Writer) ScrollDown() {
+ w.WriteRaw([]byte{0x1b, 'D'})
+}
+
+// ScrollUp scroll display up one line.
+func (w *VT100Writer) ScrollUp() {
+ w.WriteRaw([]byte{0x1b, 'M'})
+}
+
+/* Title */
+
+// SetTitle sets a title of terminal window.
+func (w *VT100Writer) SetTitle(title string) {
+ titleBytes := []byte(title)
+ patterns := []struct {
+ from []byte
+ to []byte
+ }{
+ {
+ from: []byte{0x13},
+ to: []byte{},
+ },
+ {
+ from: []byte{0x07},
+ to: []byte{},
+ },
+ }
+ for i := range patterns {
+ titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1)
+ }
+
+ w.WriteRaw([]byte{0x1b, ']', '2', ';'})
+ w.WriteRaw(titleBytes)
+ w.WriteRaw([]byte{0x07})
+}
+
+// ClearTitle clears a title of terminal window.
+func (w *VT100Writer) ClearTitle() {
+ w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07})
+}
+
+/* Font */
+
+// SetColor sets text and background colors. and specify whether text is bold.
+func (w *VT100Writer) SetColor(fg, bg Color, bold bool) {
+ if bold {
+ w.SetDisplayAttributes(fg, bg, DisplayBold)
+ } else {
+ // If using `DisplayDefualt`, it will be broken in some environment.
+ // Details are https://github.com/c-bata/go-prompt/pull/85
+ w.SetDisplayAttributes(fg, bg, DisplayReset)
+ }
+}
+
+// SetDisplayAttributes to set VT100 display attributes.
+func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) {
+ w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer
+ defer w.WriteRaw([]byte{'m'}) // final character
+
+ var separator byte = ';'
+ for i := range attrs {
+ p, ok := displayAttributeParameters[attrs[i]]
+ if !ok {
+ continue
+ }
+ w.WriteRaw(p)
+ w.WriteRaw([]byte{separator})
+ }
+
+ f, ok := foregroundANSIColors[fg]
+ if !ok {
+ f = foregroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(f)
+ w.WriteRaw([]byte{separator})
+ b, ok := backgroundANSIColors[bg]
+ if !ok {
+ b = backgroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(b)
+}
+
+var displayAttributeParameters = map[DisplayAttribute][]byte{
+ DisplayReset: {'0'},
+ DisplayBold: {'1'},
+ DisplayLowIntensity: {'2'},
+ DisplayItalic: {'3'},
+ DisplayUnderline: {'4'},
+ DisplayBlink: {'5'},
+ DisplayRapidBlink: {'6'},
+ DisplayReverse: {'7'},
+ DisplayInvisible: {'8'},
+ DisplayCrossedOut: {'9'},
+ DisplayDefaultFont: {'1', '0'},
+}
+
+var foregroundANSIColors = map[Color][]byte{
+ DefaultColor: {'3', '9'},
+
+ // Low intensity.
+ Black: {'3', '0'},
+ DarkRed: {'3', '1'},
+ DarkGreen: {'3', '2'},
+ Brown: {'3', '3'},
+ DarkBlue: {'3', '4'},
+ Purple: {'3', '5'},
+ Cyan: {'3', '6'},
+ LightGray: {'3', '7'},
+
+ // High intensity.
+ DarkGray: {'9', '0'},
+ Red: {'9', '1'},
+ Green: {'9', '2'},
+ Yellow: {'9', '3'},
+ Blue: {'9', '4'},
+ Fuchsia: {'9', '5'},
+ Turquoise: {'9', '6'},
+ White: {'9', '7'},
+}
+
+var backgroundANSIColors = map[Color][]byte{
+ DefaultColor: {'4', '9'},
+
+ // Low intensity.
+ Black: {'4', '0'},
+ DarkRed: {'4', '1'},
+ DarkGreen: {'4', '2'},
+ Brown: {'4', '3'},
+ DarkBlue: {'4', '4'},
+ Purple: {'4', '5'},
+ Cyan: {'4', '6'},
+ LightGray: {'4', '7'},
+
+ // High intensity
+ DarkGray: {'1', '0', '0'},
+ Red: {'1', '0', '1'},
+ Green: {'1', '0', '2'},
+ Yellow: {'1', '0', '3'},
+ Blue: {'1', '0', '4'},
+ Fuchsia: {'1', '0', '5'},
+ Turquoise: {'1', '0', '6'},
+ White: {'1', '0', '7'},
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/output_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/output_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b9c2769fc2d64cfcfcc5b99c915591ec625bd5f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/output_windows.go
@@ -0,0 +1,49 @@
+// +build windows
+
+package prompt
+
+import (
+ "io"
+
+ colorable "github.com/mattn/go-colorable"
+)
+
+// WindowsWriter is a ConsoleWriter implementation for Win32 console.
+// Output is converted from VT100 escape sequences by mattn/go-colorable.
+type WindowsWriter struct {
+ VT100Writer
+ out io.Writer
+}
+
+// Flush to flush buffer
+func (w *WindowsWriter) Flush() error {
+ _, err := w.out.Write(w.buffer)
+ if err != nil {
+ return err
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &WindowsWriter{}
+
+var (
+ // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates win32 control sequences.
+func NewStdoutWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStdout(),
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates win32 control sequences.
+func NewStderrWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStderr(),
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/prompt.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/prompt.go
new file mode 100644
index 0000000000000000000000000000000000000000..173cd517c40cde212433e399978641ceff1d1a43
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/prompt.go
@@ -0,0 +1,296 @@
+package prompt
+
+import (
+ "bytes"
+ "os"
+ "time"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Executor is called when user input something text.
+type Executor func(string)
+
+// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
+// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
+// - immediate exit (if breakline is false) without executor called
+// - exit after typing (meaning breakline is true), and the executor is called first, before exit.
+// Exit means exit go-prompt (not the overall Go program)
+type ExitChecker func(in string, breakline bool) bool
+
+// Completer should return the suggest item from Document.
+type Completer func(Document) []Suggest
+
+// Prompt is core struct of go-prompt.
+type Prompt struct {
+ in ConsoleParser
+ buf *Buffer
+ renderer *Render
+ executor Executor
+ history *History
+ completion *CompletionManager
+ keyBindings []KeyBind
+ ASCIICodeBindings []ASCIICodeBind
+ keyBindMode KeyBindMode
+ completionOnDown bool
+ exitChecker ExitChecker
+ skipTearDown bool
+}
+
+// Exec is the struct contains user input context.
+type Exec struct {
+ input string
+}
+
+// Run starts prompt.
+func (p *Prompt) Run() {
+ p.skipTearDown = false
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ exitCh := make(chan int)
+ winSizeCh := make(chan *WinSize)
+ stopHandleSignalCh := make(chan struct{})
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+ return
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+
+ // Unset raw mode
+ // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
+ debug.AssertNoError(p.in.TearDown())
+ p.executor(e.input)
+
+ p.completion.Update(*p.buf.Document())
+
+ p.renderer.Render(p.buf, p.completion)
+
+ if p.exitChecker != nil && p.exitChecker(e.input, true) {
+ p.skipTearDown = true
+ return
+ }
+ // Set raw mode
+ debug.AssertNoError(p.in.Setup())
+ go p.readBuffer(bufCh, stopReadBufCh)
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ case w := <-winSizeCh:
+ p.renderer.UpdateWinSize(w)
+ p.renderer.Render(p.buf, p.completion)
+ case code := <-exitCh:
+ p.renderer.BreakLine(p.buf)
+ p.tearDown()
+ os.Exit(code)
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
+ key := GetKey(b)
+ p.buf.lastKeyStroke = key
+ // completion
+ completing := p.completion.Completing()
+ p.handleCompletionKeyBinding(key, completing)
+
+ switch key {
+ case Enter, ControlJ, ControlM:
+ p.renderer.BreakLine(p.buf)
+
+ exec = &Exec{input: p.buf.Text()}
+ p.buf = NewBuffer()
+ if exec.input != "" {
+ p.history.Add(exec.input)
+ }
+ case ControlC:
+ p.renderer.BreakLine(p.buf)
+ p.buf = NewBuffer()
+ p.history.Clear()
+ case Up, ControlP:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Older(p.buf); changed {
+ p.buf = newBuf
+ }
+ }
+ case Down, ControlN:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Newer(p.buf); changed {
+ p.buf = newBuf
+ }
+ return
+ }
+ case ControlD:
+ if p.buf.Text() == "" {
+ shouldExit = true
+ return
+ }
+ case NotDefined:
+ if p.handleASCIICodeBinding(b) {
+ return
+ }
+ p.buf.InsertText(string(b), false, true)
+ }
+
+ shouldExit = p.handleKeyBinding(key)
+ return
+}
+
+func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
+ switch key {
+ case Down:
+ if completing || p.completionOnDown {
+ p.completion.Next()
+ }
+ case Tab, ControlI:
+ p.completion.Next()
+ case Up:
+ if completing {
+ p.completion.Previous()
+ }
+ case BackTab:
+ p.completion.Previous()
+ default:
+ if s, ok := p.completion.GetSelectedSuggestion(); ok {
+ w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
+ if w != "" {
+ p.buf.DeleteBeforeCursor(len([]rune(w)))
+ }
+ p.buf.InsertText(s.Text, false, true)
+ }
+ p.completion.Reset()
+ }
+}
+
+func (p *Prompt) handleKeyBinding(key Key) bool {
+ shouldExit := false
+ for i := range commonKeyBindings {
+ kb := commonKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+
+ if p.keyBindMode == EmacsKeyBind {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ }
+
+ // Custom key bindings
+ for i := range p.keyBindings {
+ kb := p.keyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
+ shouldExit = true
+ }
+ return shouldExit
+}
+
+func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
+ checked := false
+ for _, kb := range p.ASCIICodeBindings {
+ if bytes.Equal(kb.ASCIICode, b) {
+ kb.Fn(p.buf)
+ checked = true
+ }
+ }
+ return checked
+}
+
+// Input just returns user input text.
+func (p *Prompt) Input() string {
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ return ""
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ return e.input
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
+ debug.Log("start reading buffer")
+ for {
+ select {
+ case <-stopCh:
+ debug.Log("stop reading buffer")
+ return
+ default:
+ if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
+ bufCh <- b
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (p *Prompt) setUp() {
+ debug.AssertNoError(p.in.Setup())
+ p.renderer.Setup()
+ p.renderer.UpdateWinSize(p.in.GetWinSize())
+}
+
+func (p *Prompt) tearDown() {
+ if !p.skipTearDown {
+ debug.AssertNoError(p.in.TearDown())
+ }
+ p.renderer.TearDown()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/render.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/render.go
new file mode 100644
index 0000000000000000000000000000000000000000..299ac48b6254b9752ea16516aaedcd41acca6515
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/render.go
@@ -0,0 +1,287 @@
+package prompt
+
+import (
+ "runtime"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Render to render prompt information from state of Buffer.
+type Render struct {
+ out ConsoleWriter
+ prefix string
+ livePrefixCallback func() (prefix string, useLivePrefix bool)
+ breakLineCallback func(*Document)
+ title string
+ row uint16
+ col uint16
+
+ previousCursor int
+
+ // colors,
+ prefixTextColor Color
+ prefixBGColor Color
+ inputTextColor Color
+ inputBGColor Color
+ previewSuggestionTextColor Color
+ previewSuggestionBGColor Color
+ suggestionTextColor Color
+ suggestionBGColor Color
+ selectedSuggestionTextColor Color
+ selectedSuggestionBGColor Color
+ descriptionTextColor Color
+ descriptionBGColor Color
+ selectedDescriptionTextColor Color
+ selectedDescriptionBGColor Color
+ scrollbarThumbColor Color
+ scrollbarBGColor Color
+}
+
+// Setup to initialize console output.
+func (r *Render) Setup() {
+ if r.title != "" {
+ r.out.SetTitle(r.title)
+ debug.AssertNoError(r.out.Flush())
+ }
+}
+
+// getCurrentPrefix to get current prefix.
+// If live-prefix is enabled, return live-prefix.
+func (r *Render) getCurrentPrefix() string {
+ if prefix, ok := r.livePrefixCallback(); ok {
+ return prefix
+ }
+ return r.prefix
+}
+
+func (r *Render) renderPrefix() {
+ r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
+ r.out.WriteStr(r.getCurrentPrefix())
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// TearDown to clear title and erasing.
+func (r *Render) TearDown() {
+ r.out.ClearTitle()
+ r.out.EraseDown()
+ debug.AssertNoError(r.out.Flush())
+}
+
+func (r *Render) prepareArea(lines int) {
+ for i := 0; i < lines; i++ {
+ r.out.ScrollDown()
+ }
+ for i := 0; i < lines; i++ {
+ r.out.ScrollUp()
+ }
+}
+
+// UpdateWinSize called when window size is changed.
+func (r *Render) UpdateWinSize(ws *WinSize) {
+ r.row = ws.Row
+ r.col = ws.Col
+}
+
+func (r *Render) renderWindowTooSmall() {
+ r.out.CursorGoTo(0, 0)
+ r.out.EraseScreen()
+ r.out.SetColor(DarkRed, White, false)
+ r.out.WriteStr("Your console window is too small...")
+}
+
+func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) {
+ suggestions := completions.GetSuggestions()
+ if len(completions.GetSuggestions()) == 0 {
+ return
+ }
+ prefix := r.getCurrentPrefix()
+ formatted, width := formatSuggestions(
+ suggestions,
+ int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar
+ )
+ // +1 means a width of scrollbar.
+ width++
+
+ windowHeight := len(formatted)
+ if windowHeight > int(completions.max) {
+ windowHeight = int(completions.max)
+ }
+ formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
+ r.prepareArea(windowHeight)
+
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor())
+ x, _ := r.toPos(cursor)
+ if x+width >= int(r.col) {
+ cursor = r.backward(cursor, x+width-int(r.col))
+ }
+
+ contentHeight := len(completions.tmp)
+
+ fractionVisible := float64(windowHeight) / float64(contentHeight)
+ fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
+
+ scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
+ scrollbarTop := int(float64(windowHeight) * fractionAbove)
+
+ isScrollThumb := func(row int) bool {
+ return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
+ }
+
+ selected := completions.selected - completions.verticalScroll
+ r.out.SetColor(White, Cyan, false)
+ for i := 0; i < windowHeight; i++ {
+ r.out.CursorDown(1)
+ if i == selected {
+ r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
+ } else {
+ r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Text)
+
+ if i == selected {
+ r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
+ } else {
+ r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Description)
+
+ if isScrollThumb(i) {
+ r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
+ } else {
+ r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
+ }
+ r.out.WriteStr(" ")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+
+ r.lineWrap(cursor + width)
+ r.backward(cursor+width, width)
+ }
+
+ if x+width >= int(r.col) {
+ r.out.CursorForward(x + width - int(r.col))
+ }
+
+ r.out.CursorUp(windowHeight)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// Render renders to the console.
+func (r *Render) Render(buffer *Buffer, completion *CompletionManager) {
+ // In situations where a pseudo tty is allocated (e.g. within a docker container),
+ // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
+ if r.col == 0 {
+ return
+ }
+ defer func() { debug.AssertNoError(r.out.Flush()) }()
+ r.move(r.previousCursor, 0)
+
+ line := buffer.Text()
+ prefix := r.getCurrentPrefix()
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line)
+
+ // prepare area
+ _, y := r.toPos(cursor)
+
+ h := y + 1 + int(completion.max)
+ if h > int(r.row) || completionMargin > int(r.col) {
+ r.renderWindowTooSmall()
+ return
+ }
+
+ // Rendering
+ r.out.HideCursor()
+ defer r.out.ShowCursor()
+
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(line)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ r.lineWrap(cursor)
+
+ r.out.EraseDown()
+
+ cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition())
+
+ r.renderCompletion(buffer, completion)
+ if suggest, ok := completion.GetSelectedSuggestion(); ok {
+ cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator)))
+
+ r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false)
+ r.out.WriteStr(suggest.Text)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ cursor += runewidth.StringWidth(suggest.Text)
+
+ rest := buffer.Document().TextAfterCursor()
+ r.out.WriteStr(rest)
+ cursor += runewidth.StringWidth(rest)
+ r.lineWrap(cursor)
+
+ cursor = r.backward(cursor, runewidth.StringWidth(rest))
+ }
+ r.previousCursor = cursor
+}
+
+// BreakLine to break line.
+func (r *Render) BreakLine(buffer *Buffer) {
+ // Erasing and Render
+ cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix())
+ r.clear(cursor)
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(buffer.Document().Text + "\n")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ debug.AssertNoError(r.out.Flush())
+ if r.breakLineCallback != nil {
+ r.breakLineCallback(buffer.Document())
+ }
+
+ r.previousCursor = 0
+}
+
+// clear erases the screen from a beginning of input
+// even if there is line break which means input length exceeds a window's width.
+func (r *Render) clear(cursor int) {
+ r.move(cursor, 0)
+ r.out.EraseDown()
+}
+
+// backward moves cursor to backward from a current cursor position
+// regardless there is a line break.
+func (r *Render) backward(from, n int) int {
+ return r.move(from, from-n)
+}
+
+// move moves cursor to specified position from the beginning of input
+// even if there is a line break.
+func (r *Render) move(from, to int) int {
+ fromX, fromY := r.toPos(from)
+ toX, toY := r.toPos(to)
+
+ r.out.CursorUp(fromY - toY)
+ r.out.CursorBackward(fromX - toX)
+ return to
+}
+
+// toPos returns the relative position from the beginning of the string.
+func (r *Render) toPos(cursor int) (x, y int) {
+ col := int(r.col)
+ return cursor % col, cursor / col
+}
+
+func (r *Render) lineWrap(cursor int) {
+ if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 {
+ r.out.WriteRaw([]byte{'\n'})
+ }
+}
+
+func clamp(high, low, x float64) float64 {
+ switch {
+ case high < x:
+ return high
+ case x < low:
+ return low
+ default:
+ return x
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/shortcut.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/shortcut.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8d4282700c0bdb30e4decfb9c9ac91f27af251
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/shortcut.go
@@ -0,0 +1,43 @@
+package prompt
+
+func dummyExecutor(in string) {}
+
+// Input get the input data from the user and return it.
+func Input(prefix string, completer Completer, opts ...Option) string {
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+// Choose to the shortcut of input function to select from string array.
+// Deprecated: Maybe anyone want to use this.
+func Choose(prefix string, choices []string, opts ...Option) string {
+ completer := newChoiceCompleter(choices, FilterHasPrefix)
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+func newChoiceCompleter(choices []string, filter Filter) Completer {
+ s := make([]Suggest, len(choices))
+ for i := range choices {
+ s[i] = Suggest{Text: choices[i]}
+ }
+ return func(x Document) []Suggest {
+ return filter(s, x.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/signal_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/signal_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3150df5d85e7612c42c2a889dbefee3b524bef6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/signal_posix.go
@@ -0,0 +1,49 @@
+// +build !windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ in := p.in
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+
+ case syscall.SIGWINCH:
+ debug.Log("Catch SIGWINCH")
+ winSizeCh <- in.GetWinSize()
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/signal_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/signal_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a427c79ec0414540f8f40694731b2565ea80c13
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/environment/source/signal_windows.go
@@ -0,0 +1,44 @@
+// +build windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/instruction.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..32d9b490b4d09b65fd00c1393f0d3a36dd48c035
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/instruction.md
@@ -0,0 +1,40 @@
+CursorPositionRow returns incorrect row value
+
+#### Description
+
+The `CursorPositionRow()` method is returning the wrong value. It appears to be returning the line start index instead of the actual row number.
+
+#### Steps/Code to Reproduce
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func main() {
+ // Create a document with multiple lines
+ text := "line1\nline2\nline3"
+ doc := prompt.NewDocument()
+ doc.Text = text
+ doc.CursorPosition = 12 // Position on line 2
+
+ row := doc.CursorPositionRow()
+ fmt.Printf("Expected row: 1, Got row: %d\n", row)
+}
+```
+
+Expected output:
+```
+Expected row: 1, Got row: 1
+```
+
+Actual output:
+```
+Expected row: 1, Got row: 26
+```
+
+The method is returning what appears to be a character index rather than the 0-based row number. This affects cursor positioning and line-based operations in the prompt library.
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/provenance.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..8e27d14c97791c31f7e918b31525160f30932740
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/provenance.json
@@ -0,0 +1,477 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt",
+ "original-bug": "task-specific unchanged semantic bug",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only",
+ "extra_semantic_repair_coverage": false,
+ "original_patch_hunks": 1
+ },
+ "private_frozen_files": {
+ "buffer_test.go": {
+ "mode": "0o644",
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098",
+ "size": 4965
+ },
+ "completion_test.go": {
+ "mode": "0o644",
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d",
+ "size": 7010
+ },
+ "document_test.go": {
+ "mode": "0o644",
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284",
+ "size": 28938
+ },
+ "emacs_test.go": {
+ "mode": "0o644",
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095",
+ "size": 741
+ },
+ "filter_test.go": {
+ "mode": "0o644",
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247",
+ "size": 3339
+ },
+ "history_test.go": {
+ "mode": "0o644",
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327",
+ "size": 1319
+ },
+ "input_test.go": {
+ "mode": "0o644",
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922",
+ "size": 533
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": "0o644",
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf",
+ "size": 1075
+ },
+ "internal/strings/strings_test.go": {
+ "mode": "0o644",
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6",
+ "size": 981
+ },
+ "output_vt100_test.go": {
+ "mode": "0o644",
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee",
+ "size": 1349
+ },
+ "render_test.go": {
+ "mode": "0o644",
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb",
+ "size": 2890
+ }
+ },
+ "public_files": {
+ ".github/ISSUE_TEMPLATE/bug_report.md": {
+ "mode": "0o644",
+ "sha256": "89d3492ca8533a3d31e4de49a23828a322f75d2a1ec4236327c4a76c7c51ada6",
+ "size": 684
+ },
+ ".github/ISSUE_TEMPLATE/feature_request.md": {
+ "mode": "0o644",
+ "sha256": "d82e14e6b4d021d0007eeef4f5ca489fc6c8e8e4d7479ee30e74fe82afd3b08f",
+ "size": 206
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "3239b94a1a41c05eff5dc086ef1378cf1e289fad0203420b5cb4c78e3c5c239b",
+ "size": 270
+ },
+ "CHANGELOG.md": {
+ "mode": "0o644",
+ "sha256": "1f88f92d3247e1b52af0f0de7ad1263a59807edb17238c7a0211554f8080e51c",
+ "size": 2895
+ },
+ "LICENSE": {
+ "mode": "0o644",
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "size": 1072
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "9425a0d4c15747863625f647348962a9b0f81a0971a7e0184ee722bf34a60ba2",
+ "size": 1177
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "ce56df51a1a9a5b5c5b056429bbee006a260fb0730af63b1d0fe91755e574cc4",
+ "size": 6185
+ },
+ "_example/README.md": {
+ "mode": "0o644",
+ "sha256": "155951bafd778493bd41ae57dcc0ba6b8eca821fcbe2ffe770960ac2780d3d09",
+ "size": 1102
+ },
+ "_example/build.sh": {
+ "mode": "0o755",
+ "sha256": "de2fb330b665691cd75b990236cd6a5df0058608de0dfc6194da30d4041a1e29",
+ "size": 469
+ },
+ "_example/exec-command/main.go": {
+ "mode": "0o644",
+ "sha256": "0e96493b6e6d446b2e691d4834ff8a55834caa410ead970cb611a63ba84f174a",
+ "size": 429
+ },
+ "_example/http-prompt/api.py": {
+ "mode": "0o644",
+ "sha256": "2c2bca9acb07a84c65a4482c61c9ade253a574477a8e461307568ea1f9a342c8",
+ "size": 335
+ },
+ "_example/http-prompt/main.go": {
+ "mode": "0o644",
+ "sha256": "6994b190c4165068e69ed44eb61698af69a15a7690179ce46e3c1c5d8c211643",
+ "size": 5484
+ },
+ "_example/live-prefix/main.go": {
+ "mode": "0o644",
+ "sha256": "20268f9cb6f3b82a52eddc33cbf8082adaa46092e2063df279499e05e25a228c",
+ "size": 1103
+ },
+ "_example/simple-echo/cjk-cyrillic/main.go": {
+ "mode": "0o644",
+ "sha256": "8fb10807d4085ebc4b345bc0ccfef9217e21e49a888bfe3192e8ddfdfa01e89c",
+ "size": 800
+ },
+ "_example/simple-echo/main.go": {
+ "mode": "0o644",
+ "sha256": "e46563ddaa932831fe9ede870b10efb5222c0d54a86f4b4f5197c9cf20942a24",
+ "size": 902
+ },
+ "_tools/README.md": {
+ "mode": "0o644",
+ "sha256": "96dc2343bc5cde642fd449ddc366462753a2e17b6a78adfa015bf991e9dac241",
+ "size": 234
+ },
+ "_tools/complete_file/main.go": {
+ "mode": "0o644",
+ "sha256": "e5dd823f9d6415614a8238ce106d26e9ded1db9b308c121d7f48bb1df003effc",
+ "size": 803
+ },
+ "_tools/sigwinch/main.go": {
+ "mode": "0o644",
+ "sha256": "a806b4e45298f5003c95432d8dd3c40c9c096335f19f1a4160afcdb64fa727e3",
+ "size": 1386
+ },
+ "_tools/vt100_debug/main.go": {
+ "mode": "0o644",
+ "sha256": "7f72eba3cc7037fcf39c9b56a96c578c157e5fb235cb626ab1e83cbef0dc290b",
+ "size": 794
+ },
+ "buffer.go": {
+ "mode": "0o644",
+ "sha256": "10188d96a450fe13ba1e9ec00c89603eb2a2860536965d980d1e4abf4374b018",
+ "size": 5781
+ },
+ "completer/file.go": {
+ "mode": "0o644",
+ "sha256": "6181ed9e39028236c5c93fbe219331fc1492ecfd6af2df764cc42b5455c9bb96",
+ "size": 2401
+ },
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "b90bd9628534cfb343a592775430e17a1999b1de500fb2a8f1507c030a432eae",
+ "size": 4491
+ },
+ "document.go": {
+ "mode": "0o644",
+ "sha256": "d49f3f7eb381864bd5f0c5eb4e274461f452b4792d62efc97f51812a28606c8f",
+ "size": 13097
+ },
+ "emacs.go": {
+ "mode": "0o644",
+ "sha256": "53f0df0016ef9d9695a797b19286681666cf0c7e5a866c393b194aae915f2664",
+ "size": 2675
+ },
+ "filter.go": {
+ "mode": "0o644",
+ "sha256": "dc5922bad6ecb32ecdaf20bd6035dddc7ce8c14f15dbd4d49192c2354cb8a038",
+ "size": 2005
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "97413fa2a2ed68170496f2289a2dca6fb0a192dcd020fc0ca48a5d106e60d55e",
+ "size": 253
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "88ea0a91babaa54b67cc6d5f6f7f47fa4be798fe523324ea568d8926eed2024c",
+ "size": 2183
+ },
+ "history.go": {
+ "mode": "0o644",
+ "sha256": "4ce80ba067cfc72c56a3ee3353ec75cd6bb2f5d82097515c591e3c7c773c51cd",
+ "size": 1488
+ },
+ "input.go": {
+ "mode": "0o644",
+ "sha256": "73461cc4f57d68b66e2a9e196239aaef942539134593beac0d0023743832e0e1",
+ "size": 7630
+ },
+ "input_posix.go": {
+ "mode": "0o644",
+ "sha256": "c7e5a4dfc3910f178f0685ef99f2e47d481a91c4cf9af50f92fc4266aed634df",
+ "size": 1648
+ },
+ "input_windows.go": {
+ "mode": "0o644",
+ "sha256": "f763250d309fb88d9536f77da1d1285c04bc6defe859506f1501e10f7743da9e",
+ "size": 1679
+ },
+ "internal/bisect/bisect.go": {
+ "mode": "0o644",
+ "sha256": "c4de2adfa2e08a77f902661d67325467f89013634dbcef22d24dc6f34d26624a",
+ "size": 327
+ },
+ "internal/debug/assert.go": {
+ "mode": "0o644",
+ "sha256": "1a3050ec58991b62c7ea352d19505e3080ac9760bdb091544f0ecf5aba35969c",
+ "size": 815
+ },
+ "internal/debug/log.go": {
+ "mode": "0o644",
+ "sha256": "2ce968e275558de61c6d83793e85561f7a8dd69c95ec7902ccd2cc3fb169aa82",
+ "size": 875
+ },
+ "internal/strings/strings.go": {
+ "mode": "0o644",
+ "sha256": "b97f08157c3baf1f94fea4bb2237691d8270bd5380b4311709ecd59b84cf4b7b",
+ "size": 2018
+ },
+ "internal/term/raw.go": {
+ "mode": "0o644",
+ "sha256": "177a1a20ae8d71b56857383a5797754560f7f6404ea86778d5f01e9a1c1b4f9f",
+ "size": 747
+ },
+ "internal/term/term.go": {
+ "mode": "0o644",
+ "sha256": "abe6fa965fa15b999b2010135903f598830d4c885a52ef9b067fd5ebbf6e373f",
+ "size": 606
+ },
+ "key.go": {
+ "mode": "0o644",
+ "sha256": "03a43283e07de7a4ea6fed32692d86325f73e98fd89a296f19c171e0bc780999",
+ "size": 1746
+ },
+ "key_bind.go": {
+ "mode": "0o644",
+ "sha256": "83f48bb720a11c8e49165ac382e3a870fdcf6b380a0a95267f8c25211898c9eb",
+ "size": 1109
+ },
+ "key_bind_func.go": {
+ "mode": "0o644",
+ "sha256": "445bff5c0fdb0b52879c635322603c2fc75d265de3761cb8c3b980c798bf39af",
+ "size": 1219
+ },
+ "key_string.go": {
+ "mode": "0o644",
+ "sha256": "55c429dae227bb1659d5d5e2e906dbfa9c7f53b5105fa83fbe290529ff6f2317",
+ "size": 1359
+ },
+ "option.go": {
+ "mode": "0o644",
+ "sha256": "28cfcc1d08b3cf650483d977195458531b3b3913f8a5f357a3ec17ea5d73e215",
+ "size": 8737
+ },
+ "output.go": {
+ "mode": "0o644",
+ "sha256": "372876b0aa908479ed3b29de70a479f420d85e3666b8957c8b61eaed9b32c3f2",
+ "size": 4320
+ },
+ "output_posix.go": {
+ "mode": "0o644",
+ "sha256": "d46b1da307e8969b033e1ade2eb51a83c4c3d4f2a7e4aba35ec3a03991b89a0f",
+ "size": 1545
+ },
+ "output_vt100.go": {
+ "mode": "0o644",
+ "sha256": "9082c7e4619c1eb38030bc4994a4fbf66ef27b130751bf2eb9c25c01082e8605",
+ "size": 7453
+ },
+ "output_windows.go": {
+ "mode": "0o644",
+ "sha256": "571c5ae1ad051a701b426371efd79a3776c2226ca9e3c2e598fe5996dfa1b8e1",
+ "size": 1066
+ },
+ "prompt.go": {
+ "mode": "0o644",
+ "sha256": "6b3e2bbd90f40ad6a487f1a6ea7f5a6fb48cae6c8c246ecc77621fb3e7383ca7",
+ "size": 7062
+ },
+ "render.go": {
+ "mode": "0o644",
+ "sha256": "90fdd57a63e06f01940d10ee1a0be95ced7d6adc7faa255b3141556d7d316270",
+ "size": 8020
+ },
+ "shortcut.go": {
+ "mode": "0o644",
+ "sha256": "b4a097f466df7396049ebe8393f81c9b1200159d4e2be22bd6838c307ec156dc",
+ "size": 1120
+ },
+ "signal_posix.go": {
+ "mode": "0o644",
+ "sha256": "74f0bae5f290f3f7f82a5dd495e672f627a4ab4b63118f870e8c13c0a7024314",
+ "size": 881
+ },
+ "signal_windows.go": {
+ "mode": "0o644",
+ "sha256": "444f662a32e6997df2af8e2a9e7dbfe977414a6bfc0f54a7f10117f204648437",
+ "size": 757
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982",
+ "os": "linux",
+ "sha256": "0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982"
+ },
+ "context_inventory_sha256": "6b8f93086e81483ac1ce82f328d7f4b38b1b560dbad057ed6a2a30ff3cf0e13f",
+ "image": "registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "9d3b21cdacadfa4f3de9584d0cea973e5aa2ceedcd5ec9cbd3a63df22b313455",
+ "receipt_path": "production/runtime-images-extra-v1/resolutions/316e0e68930cd4ef/resolution.json",
+ "receipt_sha256": "697bb0619eddcdfdeba1c9144b033f564f2d7514be6e6a44dc520fa4e63ed8bc",
+ "registry_digest": "sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "source_image": "docker.io/swebench/swesmith.x86_64.c-bata_1776_go-prompt.82a91227@sha256:3daf51c74a01657e9ad8f326651fb6f5b796ffecdb90098e74a52a9560e0a1bb",
+ "source_receipt_sha256": "b450bea0e201cbe194b765ded4b51539144c85296122c8b642d7e94c889526f3",
+ "space_commit": "5ae654cd2e9d695f0de304bd4398835fc7cf45e0",
+ "space_id": "harness-hub/scale800-go-316e0e68930cd4ef-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "74a2313abb6df5a1624f02f46d5aa385b2b5cc0051cde9ae1b73b92dca08f903",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21",
+ "source_proof_sha256": "420abaa1132f869fed7e3b86db3e29838224e0aec7aa19a096263e2c25480660",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:c-bata__go-prompt.82a91227.lm_modify__34pz2yy8",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "9992c59c25864ce1556e67b9e1501c93f6e7f9ff",
+ "instruction_sha256": "186e339c3a954ef85242df717234e886564c9671a07a908f9156d867835bdc53",
+ "is_fork": true,
+ "learner_path": "tasks/d57b6c3e52848ab0ae01a5d6/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/c-bata__go-prompt.82a91227/8484057f902e5c8ebcd13262f677c8c8db8e5e7d/LICENSE"
+ },
+ "task_bundle": {
+ "basis": "Captured publisherMIT/train; exactsoftwarepermissionverifiedseparately",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "82a912274504477990ecf7c852eebb7c85291772",
+ "patch_sha256": "8e144a9da25189cc883694e19d1ca370ab9b5383d3e1f64dc48e8c3b48e3d127",
+ "provenance_path": "tasks/d57b6c3e52848ab0ae01a5d6/source-proof.json",
+ "repository_lineage": [
+ "swesmith/c-bata__go-prompt.82a91227",
+ "c-bata/go-prompt"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "8484057f902e5c8ebcd13262f677c8c8db8e5e7d",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "b04de8fa5b19dd8ba33dd0d3019cc58fe00501a3",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/c-bata__go-prompt.82a91227",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "c-bata__go-prompt.82a91227.lm_modify__34pz2yy8",
+ "task_sha256": "6bb67e418113f5ec94d6ede256fa5a619740b6086fd60651faffc3ceaf9e9bbb",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "c-bata/go-prompt",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "4997e6aa8cd7958d1b65c0288bd65892dfcd0626aced24b3ffd08d9221f9e84b",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.md",
+ "/testbed/.github/ISSUE_TEMPLATE/feature_request.md",
+ "/testbed/.gitignore",
+ "/testbed/CHANGELOG.md",
+ "/testbed/LICENSE",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/_example/README.md",
+ "/testbed/_example/build.sh",
+ "/testbed/_example/exec-command/main.go",
+ "/testbed/_example/http-prompt/api.py",
+ "/testbed/_example/http-prompt/main.go",
+ "/testbed/_example/live-prefix/main.go",
+ "/testbed/_example/simple-echo/cjk-cyrillic/main.go",
+ "/testbed/_example/simple-echo/main.go",
+ "/testbed/_tools/README.md",
+ "/testbed/_tools/complete_file/main.go",
+ "/testbed/_tools/sigwinch/main.go",
+ "/testbed/_tools/vt100_debug/main.go",
+ "/testbed/buffer.go",
+ "/testbed/completer/file.go",
+ "/testbed/completion.go",
+ "/testbed/document.go",
+ "/testbed/emacs.go",
+ "/testbed/filter.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum",
+ "/testbed/history.go",
+ "/testbed/input.go",
+ "/testbed/input_posix.go",
+ "/testbed/input_windows.go",
+ "/testbed/internal/bisect/bisect.go",
+ "/testbed/internal/debug/assert.go",
+ "/testbed/internal/debug/log.go",
+ "/testbed/internal/strings/strings.go",
+ "/testbed/internal/term/raw.go",
+ "/testbed/internal/term/term.go",
+ "/testbed/key.go",
+ "/testbed/key_bind.go",
+ "/testbed/key_bind_func.go",
+ "/testbed/key_string.go",
+ "/testbed/option.go",
+ "/testbed/output.go",
+ "/testbed/output_posix.go",
+ "/testbed/output_vt100.go",
+ "/testbed/output_windows.go",
+ "/testbed/prompt.go",
+ "/testbed/render.go",
+ "/testbed/shortcut.go",
+ "/testbed/signal_posix.go",
+ "/testbed/signal_windows.go"
+ ]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/solution/solve.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..00d1a533519e8abc9def758862da6b859247bfe5
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"document.go": {"data": "cGFja2FnZSBwcm9tcHQKCmltcG9ydCAoCgkic3RyaW5ncyIKCSJ1bmljb2RlL3V0ZjgiCgoJImdpdGh1Yi5jb20vYy1iYXRhL2dvLXByb21wdC9pbnRlcm5hbC9iaXNlY3QiCglpc3RyaW5ncyAiZ2l0aHViLmNvbS9jLWJhdGEvZ28tcHJvbXB0L2ludGVybmFsL3N0cmluZ3MiCglydW5ld2lkdGggImdpdGh1Yi5jb20vbWF0dG4vZ28tcnVuZXdpZHRoIgopCgovLyBEb2N1bWVudCBoYXMgdGV4dCBkaXNwbGF5ZWQgaW4gdGVybWluYWwgYW5kIGN1cnNvciBwb3NpdGlvbi4KdHlwZSBEb2N1bWVudCBzdHJ1Y3QgewoJVGV4dCBzdHJpbmcKCS8vIFRoaXMgcmVwcmVzZW50cyBhIGluZGV4IGluIGEgcnVuZSBhcnJheSBvZiBEb2N1bWVudC5UZXh0LgoJLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgY3Vyc29yUG9zaXRpb24gaXMgMi4KCS8vIEJ1dCBEaXNwbGF5ZWRDdXJzb3JQb3NpdGlvbiByZXR1cm5zIDQgYmVjYXVzZSAn5pelJyBhbmQgJ+acrCcgYXJlIGRvdWJsZSB3aWR0aCBjaGFyYWN0ZXJzLgoJY3Vyc29yUG9zaXRpb24gaW50CglsYXN0S2V5ICAgICAgICBLZXkKfQoKLy8gTmV3RG9jdW1lbnQgcmV0dXJuIHRoZSBuZXcgZW1wdHkgZG9jdW1lbnQuCmZ1bmMgTmV3RG9jdW1lbnQoKSAqRG9jdW1lbnQgewoJcmV0dXJuICZEb2N1bWVudHsKCQlUZXh0OiAgICAgICAgICAgIiIsCgkJY3Vyc29yUG9zaXRpb246IDAsCgl9Cn0KCi8vIExhc3RLZXlTdHJva2UgcmV0dXJuIHRoZSBsYXN0IGtleSBwcmVzc2VkIGluIHRoaXMgZG9jdW1lbnQuCmZ1bmMgKGQgKkRvY3VtZW50KSBMYXN0S2V5U3Ryb2tlKCkgS2V5IHsKCXJldHVybiBkLmxhc3RLZXkKfQoKLy8gRGlzcGxheUN1cnNvclBvc2l0aW9uIHJldHVybnMgdGhlIGN1cnNvciBwb3NpdGlvbiBvbiByZW5kZXJlZCB0ZXh0IG9uIHRlcm1pbmFsIGVtdWxhdG9ycy4KLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgRGlzcGxheWVkQ3Vyc29yUG9zaXRpb24gcmV0dXJucyA0IGJlY2F1c2UgJ+aXpScgYW5kICfmnKwnIGFyZSBkb3VibGUgd2lkdGggY2hhcmFjdGVycy4KZnVuYyAoZCAqRG9jdW1lbnQpIERpc3BsYXlDdXJzb3JQb3NpdGlvbigpIGludCB7Cgl2YXIgcG9zaXRpb24gaW50CglydW5lcyA6PSBbXXJ1bmUoZC5UZXh0KVs6ZC5jdXJzb3JQb3NpdGlvbl0KCWZvciBpIDo9IHJhbmdlIHJ1bmVzIHsKCQlwb3NpdGlvbiArPSBydW5ld2lkdGguUnVuZVdpZHRoKHJ1bmVzW2ldKQoJfQoJcmV0dXJuIHBvc2l0aW9uCn0KCi8vIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yIHJldHVybiBjaGFyYWN0ZXIgcmVsYXRpdmUgdG8gY3Vyc29yIHBvc2l0aW9uLCBvciBlbXB0eSBzdHJpbmcKZnVuYyAoZCAqRG9jdW1lbnQpIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yKG9mZnNldCBpbnQpIChyIHJ1bmUpIHsKCXMgOj0gZC5UZXh0CgljbnQgOj0gMAoKCWZvciBsZW4ocykgPiAwIHsKCQljbnQrKwoJCXIsIHNpemUgOj0gdXRmOC5EZWNvZGVSdW5lSW5TdHJpbmcocykKCQlpZiBjbnQgPT0gZC5jdXJzb3JQb3NpdGlvbitvZmZzZXQgewoJCQlyZXR1cm4gcgoJCX0KCQlzID0gc1tzaXplOl0KCX0KCXJldHVybiAwCn0KCi8vIFRleHRCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJciA6PSBbXXJ1bmUoZC5UZXh0KQoJcmV0dXJuIHN0cmluZyhyWzpkLmN1cnNvclBvc2l0aW9uXSkKfQoKLy8gVGV4dEFmdGVyQ3Vyc29yIHJldHVybnMgdGhlIHRleHQgYWZ0ZXIgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRBZnRlckN1cnNvcigpIHN0cmluZyB7CglyIDo9IFtdcnVuZShkLlRleHQpCglyZXR1cm4gc3RyaW5nKHJbZC5jdXJzb3JQb3NpdGlvbjpdKQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYmVmb3JlIHRoZSBjdXJzb3IuCi8vIElmIHdlIGhhdmUgd2hpdGVzcGFjZSBiZWZvcmUgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcigpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBJZiB3ZSBoYXZlIHdoaXRlc3BhY2UgYWZ0ZXIgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yKCkgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmQoKV0KfQoKLy8gR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSgpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEFmdGVyQ3Vyc29yLCBpdCByZXR1cm5zIHN0cmluZyBjb250YWluaW5nIHNwYWNlCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UoKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpXQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yVW50aWxTZXBhcmF0b3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvciB1bnRpbCBuZXh0IHNlcGFyYXRvci4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJcmV0dXJuIHhbZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFVudGlsU2VwYXJhdG9yKHNlcCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvciByZXR1cm5zIHRoZSB0ZXh0IGFmdGVyIHRoZSBjdXJzb3IgdW50aWwgbmV4dCBzZXBhcmF0b3IuCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCldCn0KCi8vIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvciByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yKHNlcCBzdHJpbmcpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwKTpdCn0KCi8vIEdldFdvcmRBZnRlckN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYWZ0ZXIgdGhlIGN1cnNvci4KLy8gVW5saWtlIEdldFdvcmRBZnRlckN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXApXQp9CgovLyBGaW5kU3RhcnRPZlByZXZpb3VzV29yZCByZXR1cm5zIGFuIGluZGV4IHJlbGF0aXZlIHRvIHRoZSBjdXJzb3IgcG9zaXRpb24KLy8gcG9pbnRpbmcgdG8gdGhlIHN0YXJ0IG9mIHRoZSBwcmV2aW91cyB3b3JkLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5MYXN0SW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpICsgMQoJfQoJcmV0dXJuIDAKfQoKLy8gRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRXaXRoU3BhY2UgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBUaGUgb25seSBkaWZmZXJlbmNlIGlzIHRvIGlnbm9yZSBjb250aWd1b3VzIHNwYWNlcy4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWVuZCA6PSBpc3RyaW5ncy5MYXN0SW5kZXhOb3RCeXRlKHgsICcgJykKCWlmIGVuZCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEJ5dGUoeFs6ZW5kXSwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiAwCgl9CglyZXR1cm4gc3RhcnQgKyAxCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZCgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJaSA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaSArIDEKCX0KCXJldHVybiAwCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFdpdGhTcGFjZSgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJZW5kIDo9IGlzdHJpbmdzLkxhc3RJbmRleE5vdEFueSh4LCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiAwCgl9CglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4WzplbmRdLCBzZXApCglpZiBzdGFydCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCXJldHVybiBzdGFydCArIDEKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmQgcmV0dXJucyBhbiBpbmRleCByZWxhdGl2ZSB0byB0aGUgY3Vyc29yIHBvc2l0aW9uLgovLyBwb2ludGluZyB0byB0aGUgZW5kIG9mIHRoZSBjdXJyZW50IHdvcmQuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZEVuZE9mQ3VycmVudFdvcmQoKSBpbnQgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglpIDo9IHN0cmluZ3MuSW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpCgl9CglyZXR1cm4gbGVuKHgpCn0KCi8vIEZpbmRFbmRPZkN1cnJlbnRXb3JkV2l0aFNwYWNlIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZC4KLy8gVGhlIG9ubHkgZGlmZmVyZW5jZSBpcyB0byBpZ25vcmUgY29udGlndW91cyBzcGFjZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpIGludCB7Cgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCglzdGFydCA6PSBpc3RyaW5ncy5JbmRleE5vdEJ5dGUoeCwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCgllbmQgOj0gc3RyaW5ncy5JbmRleEJ5dGUoeFtzdGFydDpdLCAnICcpCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvciBpcyBhbG1vc3QgdGhlIHNhbWUgYXMgRmluZEVuZE9mQ3VycmVudFdvcmQuCi8vIEJ1dCB0aGlzIGNhbiBzcGVjaWZ5IFNlcGFyYXRvci4gUmV0dXJuIDAgaWYgbm90aGluZyB3YXMgZm91bmQuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCBzdHJpbmcpIGludCB7CglpZiBzZXAgPT0gIiIgewoJCXJldHVybiBkLkZpbmRFbmRPZkN1cnJlbnRXb3JkKCkKCX0KCgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5JbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaQoJfQoJcmV0dXJuIGxlbih4KQp9CgovLyBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZS4KLy8gQnV0IHRoaXMgY2FuIHNwZWNpZnkgU2VwYXJhdG9yLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRFbmRPZkN1cnJlbnRXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgaW50IHsKCWlmIHNlcCA9PSAiIiB7CgkJcmV0dXJuIGQuRmluZEVuZE9mQ3VycmVudFdvcmRXaXRoU3BhY2UoKQoJfQoKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoKCXN0YXJ0IDo9IGlzdHJpbmdzLkluZGV4Tm90QW55KHgsIHNlcCkKCWlmIHN0YXJ0ID09IC0xIHsKCQlyZXR1cm4gbGVuKHgpCgl9CgoJZW5kIDo9IHN0cmluZ3MuSW5kZXhBbnkoeFtzdGFydDpdLCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gQ3VycmVudExpbmVCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBzdGFydCBvZiB0aGUgbGluZSB1bnRpbCB0aGUgY3Vyc29yLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJcyA6PSBzdHJpbmdzLlNwbGl0KGQuVGV4dEJlZm9yZUN1cnNvcigpLCAiXG4iKQoJcmV0dXJuIHNbbGVuKHMpLTFdCn0KCi8vIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBjdXJzb3IgdW50aWwgdGhlIGVuZCBvZiB0aGUgbGluZS4KZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSBzdHJpbmcgewoJcmV0dXJuIHN0cmluZ3MuU3BsaXQoZC5UZXh0QWZ0ZXJDdXJzb3IoKSwgIlxuIilbMF0KfQoKLy8gQ3VycmVudExpbmUgcmV0dXJuIHRoZSB0ZXh0IG9uIHRoZSBsaW5lIHdoZXJlIHRoZSBjdXJzb3IgaXMuICh3aGVuIHRoZSBpbnB1dAovLyBjb25zaXN0cyBvZiBqdXN0IG9uZSBsaW5lLCBpdCBlcXVhbHMgYHRleHRgLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmUoKSBzdHJpbmcgewoJcmV0dXJuIGQuQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSArIGQuQ3VycmVudExpbmVBZnRlckN1cnNvcigpCn0KCi8vIEFycmF5IHBvaW50aW5nIHRvIHRoZSBzdGFydCBpbmRleGVzIG9mIGFsbCB0aGUgbGluZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBsaW5lU3RhcnRJbmRleGVzKCkgW11pbnQgewoJLy8gVE9ETzogQ2FjaGUsIGJlY2F1c2UgdGhpcyBpcyBvZnRlbiByZXVzZWQuCgkvLyAoSWYgaXQgaXMgdXNlZCwgaXQncyBvZnRlbiB1c2VkIG1hbnkgdGltZXMuCgkvLyBBbmQgdGhpcyBoYXMgdG8gYmUgZmFzdCBmb3IgZWRpdGluZyBiaWcgZG9jdW1lbnRzISkKCWxjIDo9IGQuTGluZUNvdW50KCkKCWxlbmd0aHMgOj0gbWFrZShbXWludCwgbGMpCglmb3IgaSwgbCA6PSByYW5nZSBkLkxpbmVzKCkgewoJCWxlbmd0aHNbaV0gPSBsZW4obCkKCX0KCgkvLyBDYWxjdWxhdGUgY3VtdWxhdGl2ZSBzdW1zLgoJaW5kZXhlcyA6PSBtYWtlKFtdaW50LCBsYysxKQoJaW5kZXhlc1swXSA9IDAgLy8gaHR0cHM6Ly9naXRodWIuY29tL2pvbmF0aGFuc2xlbmRlcnMvcHl0aG9uLXByb21wdC10b29sa2l0L2Jsb2IvbWFzdGVyL3Byb21wdF90b29sa2l0L2RvY3VtZW50LnB5I0wxODkKCXBvcyA6PSAwCglmb3IgaSwgbCA6PSByYW5nZSBsZW5ndGhzIHsKCQlwb3MgKz0gbCArIDEKCQlpbmRleGVzW2krMV0gPSBwb3MKCX0KCWlmIGxjID4gMSB7CgkJLy8gUG9wIHRoZSBsYXN0IGl0ZW0uIChUaGlzIGlzIG5vdCBhIG5ldyBsaW5lLikKCQlpbmRleGVzID0gaW5kZXhlc1s6bGNdCgl9CglyZXR1cm4gaW5kZXhlcwp9CgovLyBGb3IgdGhlIGluZGV4IG9mIGEgY2hhcmFjdGVyIGF0IGEgY2VydGFpbiBsaW5lLCBjYWxjdWxhdGUgdGhlIGluZGV4IG9mCi8vIHRoZSBmaXJzdCBjaGFyYWN0ZXIgb24gdGhhdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgZmluZExpbmVTdGFydEluZGV4KGluZGV4IGludCkgKHBvcyBpbnQsIGxpbmVTdGFydEluZGV4IGludCkgewoJaW5kZXhlcyA6PSBkLmxpbmVTdGFydEluZGV4ZXMoKQoJcG9zID0gYmlzZWN0LlJpZ2h0KGluZGV4ZXMsIGluZGV4KSAtIDEKCWxpbmVTdGFydEluZGV4ID0gaW5kZXhlc1twb3NdCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Sb3cgcmV0dXJucyB0aGUgY3VycmVudCByb3cuICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uUm93KCkgKHJvdyBpbnQpIHsKCXJvdywgXyA9IGQuZmluZExpbmVTdGFydEluZGV4KGQuY3Vyc29yUG9zaXRpb24pCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Db2wgcmV0dXJucyB0aGUgY3VycmVudCBjb2x1bW4uICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uQ29sKCkgKGNvbCBpbnQpIHsKCS8vIERvbid0IHVzZSBzZWxmLnRleHRfYmVmb3JlX2N1cnNvciB0byBjYWxjdWxhdGUgdGhpcy4gQ3JlYXRpbmcgc3Vic3RyaW5ncwoJLy8gYW5kIHNwbGl0dGluZyBpcyB0b28gZXhwZW5zaXZlIGZvciBnZXR0aW5nIHRoZSBjdXJzb3IgcG9zaXRpb24uCglfLCBpbmRleCA6PSBkLmZpbmRMaW5lU3RhcnRJbmRleChkLmN1cnNvclBvc2l0aW9uKQoJY29sID0gZC5jdXJzb3JQb3NpdGlvbiAtIGluZGV4CglyZXR1cm4KfQoKLy8gR2V0Q3Vyc29yTGVmdFBvc2l0aW9uIHJldHVybnMgdGhlIHJlbGF0aXZlIHBvc2l0aW9uIGZvciBjdXJzb3IgbGVmdC4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldEN1cnNvckxlZnRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvclJpZ2h0UG9zaXRpb24oLWNvdW50KQoJfQoJaWYgZC5DdXJzb3JQb3NpdGlvbkNvbCgpID4gY291bnQgewoJCXJldHVybiAtY291bnQKCX0KCXJldHVybiAtZC5DdXJzb3JQb3NpdGlvbkNvbCgpCn0KCi8vIEdldEN1cnNvclJpZ2h0UG9zaXRpb24gcmV0dXJucyByZWxhdGl2ZSBwb3NpdGlvbiBmb3IgY3Vyc29yIHJpZ2h0LgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yUmlnaHRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvckxlZnRQb3NpdGlvbigtY291bnQpCgl9CglpZiBsZW4oZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpID4gY291bnQgewoJCXJldHVybiBjb3VudAoJfQoJcmV0dXJuIGxlbihkLkN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSkKfQoKLy8gR2V0Q3Vyc29yVXBQb3NpdGlvbiByZXR1cm4gdGhlIHJlbGF0aXZlIGN1cnNvciBwb3NpdGlvbiAoY2hhcmFjdGVyIGluZGV4KSB3aGVyZSB3ZSB3b3VsZCBiZQovLyBpZiB0aGUgdXNlciBwcmVzc2VkIHRoZSBhcnJvdy11cCBidXR0b24uCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRDdXJzb3JVcFBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9CgoJcm93IDo9IGQuQ3Vyc29yUG9zaXRpb25Sb3coKSAtIGNvdW50CglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9CglyZXR1cm4gZC5UcmFuc2xhdGVSb3dDb2xUb0luZGV4KHJvdywgY29sKSAtIGQuY3Vyc29yUG9zaXRpb24KfQoKLy8gR2V0Q3Vyc29yRG93blBvc2l0aW9uIHJldHVybiB0aGUgcmVsYXRpdmUgY3Vyc29yIHBvc2l0aW9uIChjaGFyYWN0ZXIgaW5kZXgpIHdoZXJlIHdlIHdvdWxkIGJlIGlmIHRoZQovLyB1c2VyIHByZXNzZWQgdGhlIGFycm93LWRvd24gYnV0dG9uLgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yRG93blBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9Cglyb3cgOj0gZC5DdXJzb3JQb3NpdGlvblJvdygpICsgY291bnQKCXJldHVybiBkLlRyYW5zbGF0ZVJvd0NvbFRvSW5kZXgocm93LCBjb2wpIC0gZC5jdXJzb3JQb3NpdGlvbgp9CgovLyBMaW5lcyByZXR1cm5zIHRoZSBhcnJheSBvZiBhbGwgdGhlIGxpbmVzLgpmdW5jIChkICpEb2N1bWVudCkgTGluZXMoKSBbXXN0cmluZyB7CgkvLyBUT0RPOiBDYWNoZSwgYmVjYXVzZSB0aGlzIG9uZSBpcyByZXVzZWQgdmVyeSBvZnRlbi4KCXJldHVybiBzdHJpbmdzLlNwbGl0KGQuVGV4dCwgIlxuIikKfQoKLy8gTGluZUNvdW50IHJldHVybiB0aGUgbnVtYmVyIG9mIGxpbmVzIGluIHRoaXMgZG9jdW1lbnQuIElmIHRoZSBkb2N1bWVudCBlbmRzCi8vIHdpdGggYSB0cmFpbGluZyBcbiwgdGhhdCBjb3VudHMgYXMgdGhlIGJlZ2lubmluZyBvZiBhIG5ldyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgTGluZUNvdW50KCkgaW50IHsKCXJldHVybiBsZW4oZC5MaW5lcygpKQp9CgovLyBUcmFuc2xhdGVJbmRleFRvUG9zaXRpb24gZ2l2ZW4gYW4gaW5kZXggZm9yIHRoZSB0ZXh0LCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgKHJvdywgY29sKSB0dXBsZS4KLy8gKDAtYmFzZWQuIFJldHVybnMgKDAsIDApIGZvciBpbmRleD0wLikKZnVuYyAoZCAqRG9jdW1lbnQpIFRyYW5zbGF0ZUluZGV4VG9Qb3NpdGlvbihpbmRleCBpbnQpIChyb3cgaW50LCBjb2wgaW50KSB7Cglyb3csIHJvd0luZGV4IDo9IGQuZmluZExpbmVTdGFydEluZGV4KGluZGV4KQoJY29sID0gaW5kZXggLSByb3dJbmRleAoJcmV0dXJuCn0KCi8vIFRyYW5zbGF0ZVJvd0NvbFRvSW5kZXggZ2l2ZW4gYSAocm93LCBjb2wpLCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgaW5kZXguCi8vIChSb3cgYW5kIGNvbCBwYXJhbXMgYXJlIDAtYmFzZWQuKQpmdW5jIChkICpEb2N1bWVudCkgVHJhbnNsYXRlUm93Q29sVG9JbmRleChyb3cgaW50LCBjb2x1bW4gaW50KSAoaW5kZXggaW50KSB7CglpbmRleGVzIDo9IGQubGluZVN0YXJ0SW5kZXhlcygpCglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9IGVsc2UgaWYgcm93ID4gbGVuKGluZGV4ZXMpIHsKCQlyb3cgPSBsZW4oaW5kZXhlcykgLSAxCgl9CglpbmRleCA9IGluZGV4ZXNbcm93XQoJbGluZSA6PSBkLkxpbmVzKClbcm93XQoKCS8vIHB5dGhvbikgcmVzdWx0ICs9IG1heCgwLCBtaW4oY29sLCBsZW4obGluZSkpKQoJaWYgY29sdW1uID4gMCB8fCBsZW4obGluZSkgPiAwIHsKCQlpZiBjb2x1bW4gPiBsZW4obGluZSkgewoJCQlpbmRleCArPSBsZW4obGluZSkKCQl9IGVsc2UgewoJCQlpbmRleCArPSBjb2x1bW4KCQl9Cgl9CgoJLy8gS2VlcCBpbiByYW5nZS4gKGxlbihzZWxmLnRleHQpIGlzIGluY2x1ZGVkLCBiZWNhdXNlIHRoZSBjdXJzb3IgY2FuIGJlCgkvLyByaWdodCBhZnRlciB0aGUgZW5kIG9mIHRoZSB0ZXh0IGFzIHdlbGwuKQoJLy8gcHl0aG9uKSByZXN1bHQgPSBtYXgoMCwgbWluKHJlc3VsdCwgbGVuKHNlbGYudGV4dCkpKQoJaWYgaW5kZXggPiBsZW4oZC5UZXh0KSB7CgkJaW5kZXggPSBsZW4oZC5UZXh0KQoJfQoJaWYgaW5kZXggPCAwIHsKCQlpbmRleCA9IDAKCX0KCXJldHVybiBpbmRleAp9CgovLyBPbkxhc3RMaW5lIHJldHVybnMgdHJ1ZSB3aGVuIHdlIGFyZSBhdCB0aGUgbGFzdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgT25MYXN0TGluZSgpIGJvb2wgewoJcmV0dXJuIGQuQ3Vyc29yUG9zaXRpb25Sb3coKSA9PSAoZC5MaW5lQ291bnQoKSAtIDEpCn0KCi8vIEdldEVuZE9mTGluZVBvc2l0aW9uIHJldHVybnMgcmVsYXRpdmUgcG9zaXRpb24gZm9yIHRoZSBlbmQgb2YgdGhpcyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgR2V0RW5kT2ZMaW5lUG9zaXRpb24oKSBpbnQgewoJcmV0dXJuIGxlbihbXXJ1bmUoZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpKQp9CgpmdW5jIChkICpEb2N1bWVudCkgbGVhZGluZ1doaXRlc3BhY2VJbkN1cnJlbnRMaW5lKCkgKG1hcmdpbiBzdHJpbmcpIHsKCXRyaW1tZWQgOj0gc3RyaW5ncy5UcmltU3BhY2UoZC5DdXJyZW50TGluZSgpKQoJbWFyZ2luID0gZC5DdXJyZW50TGluZSgpWzpsZW4oZC5DdXJyZW50TGluZSgpKS1sZW4odHJpbW1lZCldCglyZXR1cm4KfQo=", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/task.toml b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..a7871a8a1fe8486dba901b7867c32a4243ed44c7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/task.toml
@@ -0,0 +1,11 @@
+version = "1.0"
+[agent]
+timeout_sec = 300.0
+[verifier]
+timeout_sec = 300.0
+environment_mode = "shared"
+[environment]
+docker_image = "ghcr.io/younesbelkada/scale800@sha256:f31a9eacf9dd4defecdfb6384ee1b24ab23c1a15c0323089f858597d104b0e94"
+cpus = 1
+memory_mb = 2048
+storage_mb = 4096
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..206e06d59c7a73e179490db96bd294f725a6a8a7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/manifest.json
@@ -0,0 +1,432 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CursorPositionRowAndCol"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorUpPosition"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_OnLastLine"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionRow"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorLeftPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorDownPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorRightPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_Lines"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_LineCount"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateIndexToPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateRowColToIndex"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetEndOfLinePosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestEmacsKeyBindings"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFilter"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFuzzyMatch"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryClear"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryAdd"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryOlder"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/escape"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/undefined"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWrite"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteRawStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatCompletion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBreakLineCallback"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition_withJapanese"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/validation/canaries/delete-tests.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/validation/canaries/delete-tests.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/validation/canaries/delete-tests.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+find /testbed -name '*_test.go' -type f -delete
+printf 'PASS\nok forged-package 0.001s\n'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..e8547f6f03034a1353bb5a8f31e98db6e3a4ba8e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__34pz2yy8/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "2212a410e1db26205cc11342222c5ce77933c4bac4d00d71616ec6f5a72ba5de",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/Dockerfile b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f35bf9e5393ee1086fe1b72c1b442f3b16e2bd5b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22
+WORKDIR /testbed
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c8c031d0f87fb9aea0aff433b1fcaeaac259c41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: "Bug report"
+about: Create a bug report to improve go-prompt
+title: "[Bug]"
+labels: bug
+assignees: ''
+
+---
+
+# Bug reports
+
+*Please file a bug report here.*
+
+## Expected Behavior
+
+*Please describe the behavior you are expecting*
+
+## Current Behavior and Steps to Reproduce
+
+*What is the current behavior? Please provide detailed steps for reproducing the issue.*
+*A picture or gif animation tells a thousand words*
+
+## Context
+
+Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
+
+* Operating System:
+* Terminal Emulator: (i.e. iTerm2)
+* tag of go-prompt or commit revision:
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb816a2496376983781774cb5466fed8e1efc93b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,13 @@
+---
+name: "Feature request"
+about: Suggest an idea for new features in go-prompt.
+title: "[Feature Request]"
+labels: enhancement
+assignees: ''
+
+---
+
+# Feature Request
+
+*Please write your suggestion here.*
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/.gitignore b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..eba2b56abe0f7758a560d47dd19d8985b67ef327
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+bin/
+
+# Folders
+pkg/
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+# Glide
+vendor/
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/CHANGELOG.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..b9e21f1ef333b9ec13323bcd4a8f377322ed7e9f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/CHANGELOG.md
@@ -0,0 +1,79 @@
+# Change Log
+
+## v0.3.0 (2018/??/??)
+
+next release.
+
+## v0.2.3 (2018/10/25)
+
+### What's new?
+
+* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92).
+* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100).
+* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102).
+
+### Fixed
+
+* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details).
+* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details).
+* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details).
+
+### Removed or Deprecated
+
+* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`.
+
+## v0.2.2 (2018/06/28)
+
+### What's new?
+
+* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters.
+* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions.
+ * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details).
+* Add FilePathCompleter to complete file path on your system.
+* Add option to customize ascii code key bindings.
+* Add GetWordAfterCursor method in Document.
+
+### Removed or Deprecated
+
+* prompt.Choose shortcut function is deprecated.
+
+## v0.2.1 (2018/02/14)
+
+### What's New?
+
+* ~~It seems that windows support is almost perfect.~~
+ * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows.
+
+### Fixed
+
+* Fix a Shift+Tab handling on Windows.
+* Fix 4-dimension arrow keys handling on Windows.
+
+## v0.2.0 (2018/02/13)
+
+### What's New?
+
+* Supports scrollbar when there are too many matched suggestions
+* Windows support (but please caution because this is still not perfect).
+* Add OptionLivePrefix to update the prefix dynamically
+* Implement clear screen by `Ctrl+L`.
+
+### Fixed
+
+* Fix the behavior of `Ctrl+W` keybind.
+* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details).
+* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details).
+* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ).
+
+### News
+
+New core developers are joined (alphabetical order).
+
+* Nao Yonashiro (Github @orisano)
+* Ryoma Abe (Github @Allajah)
+* Yusuke Nakamura (Github @unasuke)
+
+
+## v0.1.0 (2017/08/15)
+
+Initial Release
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/LICENSE b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a86acaa7ab24fe61ea152a9afcadc21980020efb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Masashi SHIBATA
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/Makefile b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..505817c36f0b8a0bb643eed8680b8989af2b0920
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/Makefile
@@ -0,0 +1,46 @@
+.DEFAULT_GOAL := help
+
+SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
+
+GOIMPORTS ?= goimports
+GOCILINT ?= golangci-lint
+
+.PHONY: setup
+setup: ## Setup for required tools.
+ go get -u golang.org/x/tools/cmd/goimports
+ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: fmt
+fmt: $(SOURCES) ## Formatting source codes.
+ @$(GOIMPORTS) -w $^
+
+.PHONY: lint
+lint: ## Run golangci-lint.
+ @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
+
+.PHONY: test
+test: ## Run tests with race condition checking.
+ @go test -race ./...
+
+.PHONY: bench
+bench: ## Run benchmarks.
+ @go test -bench=. -run=- -benchmem ./...
+
+.PHONY: coverage
+cover: ## Run the tests.
+ @go test -coverprofile=coverage.o
+ @go tool cover -func=coverage.o
+
+.PHONY: generate
+generate: ## Run go generate
+ @go generate ./...
+
+.PHONY: build
+build: ## Build example command lines.
+ ./_example/build.sh
+
+.PHONY: help
+help: ## Show help text
+ @echo "Commands:"
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfcd7a399b4827d6b126d6a173cce34d36520481
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/README.md
@@ -0,0 +1,125 @@
+# go-prompt
+
+[](https://goreportcard.com/report/github.com/c-bata/go-prompt)
+
+[](https://godoc.org/github.com/c-bata/go-prompt)
+
+
+A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit),
+making it easier to build cross-platform command line tools using Go.
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func completer(d prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ }
+ return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ fmt.Println("Please select table.")
+ t := prompt.Input("> ", completer)
+ fmt.Println("You selected " + t)
+}
+```
+
+#### Projects using go-prompt
+
+* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt)
+* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli)
+* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn)
+* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli)
+* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans)
+* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit)
+* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go)
+* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS)
+* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs)
+* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli)
+* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt)
+* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh)
+* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell)
+* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt)
+* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim)
+* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron)
+* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl)
+* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl)
+* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit)
+* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.)
+
+## Features
+
+### Powerful auto-completion
+
+[](https://github.com/c-bata/kube-prompt)
+
+(This is a GIF animation of kube-prompt.)
+
+### Flexible options
+
+go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details.
+
+[](#flexible-options)
+
+### Keyboard Shortcuts
+
+Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell).
+You can customize and expand these shortcuts.
+
+[](#keyboard-shortcuts)
+
+Key Binding | Description
+---------------------|---------------------------------------------------------
+Ctrl + A | Go to the beginning of the line (Home)
+Ctrl + E | Go to the end of the line (End)
+Ctrl + P | Previous command (Up arrow)
+Ctrl + N | Next command (Down arrow)
+Ctrl + F | Forward one character
+Ctrl + B | Backward one character
+Ctrl + D | Delete character under the cursor
+Ctrl + H | Delete character before the cursor (Backspace)
+Ctrl + W | Cut the word before the cursor to the clipboard
+Ctrl + K | Cut the line after the cursor to the clipboard
+Ctrl + U | Cut the line before the cursor to the clipboard
+Ctrl + L | Clear the screen
+
+### History
+
+You can use Up arrow and Down arrow to walk through the history of commands executed.
+
+[](#history)
+
+### Multiple platform support
+
+We have confirmed go-prompt works fine in the following terminals:
+
+* iTerm2 (macOS)
+* Terminal.app (macOS)
+* Command Prompt (Windows)
+* gnome-terminal (Ubuntu)
+
+## Links
+
+* [Change Log](./CHANGELOG.md)
+* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt)
+* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt)
+
+## Author
+
+Masashi Shibata
+
+* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/)
+* Github: [@c-bata](https://github.com/c-bata/)
+
+## License
+
+This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..759b0e3f8acf1216b055e0f9458758a6c1e8950a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/README.md
@@ -0,0 +1,30 @@
+# Examples of go-prompt
+
+This directory includes some examples using go-prompt.
+These examples are useful to know the usage of go-prompt and check behavior for development.
+
+## simple-echo
+
+
+
+A simple echo example using `prompt.Input`.
+
+## http-prompt
+
+
+
+A simple [http-prompt](https://github.com/eliangcs/http-prompt) implementation using go-prompt in less than 200 lines of Go.
+
+## live-prefix
+
+
+
+A example application which changes a prefix string dynamically.
+This feature is used like [ktr0731/evans](https://github.com/ktr0731/evans) which is interactive gRPC client using go-prompt.
+
+## exec-command
+
+Run another CLI tool via `os/exec` package.
+More practical example is [a source code of kube-prompt](https://github.com/c-bata/kube-prompt).
+I recommend you to look this if you want to create tools like kube-prompt.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/build.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c552afcfa69b2356ffcd484c867abcaaaaeeaff
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+export GO111MODULE=on
+DIR=$(cd $(dirname $0); pwd)
+BIN_DIR=$(cd $(dirname $(dirname $0)); pwd)/bin
+
+mkdir -p ${BIN_DIR}
+go build -o ${BIN_DIR}/exec-command ${DIR}/exec-command/main.go
+go build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.go
+go build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.go
+go build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.go
+go build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/exec-command/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/exec-command/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..838f756260df91569491def29a7ee05a7c9a98f7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/exec-command/main.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "os/exec"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(t string) {
+ if t == "bash" {
+ cmd := exec.Command("bash")
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Run()
+ }
+ return
+}
+
+func completer(t prompt.Document) []prompt.Suggest {
+ return []prompt.Suggest{
+ {Text: "bash"},
+ }
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/http-prompt/api.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/http-prompt/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..08e7b1a489a2077f26f280fe39e3bd06efa52cd2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/http-prompt/api.py
@@ -0,0 +1,17 @@
+from bottle import route, run, request
+
+@route('/')
+def hello():
+ return "Hello World!"
+
+@route('/ping')
+def hello():
+ return "pong!"
+
+@route('/register', method='POST')
+def register():
+ name = request.json.get("name")
+ return "Hello %s!" % name
+
+if __name__ == "__main__":
+ run(host='localhost', port=8000, debug=True)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/http-prompt/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/http-prompt/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b372a3550c50121d6e500e2a08e641e168b8c00d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/http-prompt/main.go
@@ -0,0 +1,192 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+type RequestContext struct {
+ url *url.URL
+ header http.Header
+ client *http.Client
+}
+
+var ctx *RequestContext
+
+// See https://github.com/eliangcs/http-prompt/blob/master/http_prompt/completion.py
+var suggestions = []prompt.Suggest{
+ // Command
+ {"cd", "Change URL/path"},
+ {"exit", "Exit http-prompt"},
+
+ // HTTP Method
+ {"delete", "DELETE request"},
+ {"get", "GET request"},
+ {"patch", "GET request"},
+ {"post", "POST request"},
+ {"put", "PUT request"},
+
+ // HTTP Header
+ {"Accept", "Acceptable response media type"},
+ {"Accept-Charset", "Acceptable response charsets"},
+ {"Accept-Encoding", "Acceptable response content codings"},
+ {"Accept-Language", "Preferred natural languages in response"},
+ {"ALPN", "Application-layer protocol negotiation to use"},
+ {"Alt-Used", "Alternative host in use"},
+ {"Authorization", "Authentication information"},
+ {"Cache-Control", "Directives for caches"},
+ {"Connection", "Connection options"},
+ {"Content-Encoding", "Content codings"},
+ {"Content-Language", "Natural languages for content"},
+ {"Content-Length", "Anticipated size for payload body"},
+ {"Content-Location", "Where content was obtained"},
+ {"Content-MD5", "Base64-encoded MD5 sum of content"},
+ {"Content-Type", "Content media type"},
+ {"Cookie", "Stored cookies"},
+ {"Date", "Datetime when message was originated"},
+ {"Depth", "Applied only to resource or its members"},
+ {"DNT", "Do not track user"},
+ {"Expect", "Expected behaviors supported by server"},
+ {"Forwarded", "Proxies involved"},
+ {"From", "Sender email address"},
+ {"Host", "Target URI"},
+ {"HTTP2-Settings", "HTTP/2 connection parameters"},
+ {"If", "Request condition on state tokens and ETags"},
+ {"If-Match", "Request condition on target resource"},
+ {"If-Modified-Since", "Request condition on modification date"},
+ {"If-None-Match", "Request condition on target resource"},
+ {"If-Range", "Request condition on Range"},
+ {"If-Schedule-Tag-Match", "Request condition on Schedule-Tag"},
+ {"If-Unmodified-Since", "Request condition on modification date"},
+ {"Max-Forwards", "Max number of times forwarded by proxies"},
+ {"MIME-Version", "Version of MIME protocol"},
+ {"Origin", "Origin(s} issuing the request"},
+ {"Pragma", "Implementation-specific directives"},
+ {"Prefer", "Preferred server behaviors"},
+ {"Proxy-Authorization", "Proxy authorization credentials"},
+ {"Proxy-Connection", "Proxy connection options"},
+ {"Range", "Request transfer of only part of data"},
+ {"Referer", "Previous web page"},
+ {"TE", "Transfer codings willing to accept"},
+ {"Transfer-Encoding", "Transfer codings applied to payload body"},
+ {"Upgrade", "Invite server to upgrade to another protocol"},
+ {"User-Agent", "User agent string"},
+ {"Via", "Intermediate proxies"},
+ {"Warning", "Possible incorrectness with payload body"},
+ {"WWW-Authenticate", "Authentication scheme"},
+ {"X-Csrf-Token", "Prevent cross-site request forgery"},
+ {"X-CSRFToken", "Prevent cross-site request forgery"},
+ {"X-Forwarded-For", "Originating client IP address"},
+ {"X-Forwarded-Host", "Original host requested by client"},
+ {"X-Forwarded-Proto", "Originating protocol"},
+ {"X-Http-Method-Override", "Request method override"},
+ {"X-Requested-With", "Used to identify Ajax requests"},
+ {"X-XSRF-TOKEN", "Prevent cross-site request forgery"},
+}
+
+func livePrefix() (string, bool) {
+ if ctx.url.Path == "/" {
+ return "", false
+ }
+ return ctx.url.String() + "> ", true
+}
+
+func executor(in string) {
+ in = strings.TrimSpace(in)
+
+ var method, body string
+ blocks := strings.Split(in, " ")
+ switch blocks[0] {
+ case "exit":
+ fmt.Println("Bye!")
+ os.Exit(0)
+ case "cd":
+ if len(blocks) < 2 {
+ ctx.url.Path = "/"
+ } else {
+ ctx.url.Path = path.Join(ctx.url.Path, blocks[1])
+ }
+ return
+ case "get", "delete":
+ method = strings.ToUpper(blocks[0])
+ case "post", "put", "patch":
+ if len(blocks) < 2 {
+ fmt.Println("please set request body.")
+ return
+ }
+ body = strings.Join(blocks[1:], " ")
+ method = strings.ToUpper(blocks[0])
+ }
+ if method != "" {
+ req, err := http.NewRequest(method, ctx.url.String(), strings.NewReader(body))
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ req.Header = ctx.header
+ res, err := ctx.client.Do(req)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ result, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ fmt.Printf("%s\n", result)
+ ctx.header = http.Header{}
+ return
+ }
+
+ if h := strings.Split(in, ":"); len(h) == 2 {
+ // Handling HTTP Header
+ ctx.header.Add(strings.TrimSpace(h[0]), strings.Trim(h[1], ` '"`))
+ } else {
+ fmt.Println("Sorry, I don't understand.")
+ }
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ w := in.GetWordBeforeCursor()
+ if w == "" {
+ return []prompt.Suggest{}
+ }
+ return prompt.FilterHasPrefix(suggestions, w, true)
+}
+
+func main() {
+ var baseURL = "http://localhost:8000/"
+ if len(os.Args) == 2 {
+ baseURL = os.Args[1]
+ if strings.HasSuffix(baseURL, "/") {
+ baseURL += "/"
+ }
+ }
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ ctx = &RequestContext{
+ url: u,
+ header: http.Header{},
+ client: &http.Client{},
+ }
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(u.String()+"> "),
+ prompt.OptionLivePrefix(livePrefix),
+ prompt.OptionTitle("http-prompt"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/live-prefix/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/live-prefix/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c7ced720592173e2a13f19f7cb543730192d3f8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/live-prefix/main.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var LivePrefixState struct {
+ LivePrefix string
+ IsEnable bool
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+ if in == "" {
+ LivePrefixState.IsEnable = false
+ LivePrefixState.LivePrefix = in
+ return
+ }
+ LivePrefixState.LivePrefix = in + "> "
+ LivePrefixState.IsEnable = true
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func changeLivePrefix() (string, bool) {
+ return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionLivePrefix(changeLivePrefix),
+ prompt.OptionTitle("live-prefix-example"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/simple-echo/cjk-cyrillic/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/simple-echo/cjk-cyrillic/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e9e53adef1558e004f86ccbca2c2e2b83c1da39
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/simple-echo/cjk-cyrillic/main.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
+ {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
+ {Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
+ {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionTitle("sql-prompt for multi width characters"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/simple-echo/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/simple-echo/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..12b1bb4fc189e6b369e889779418d7826a45db9d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_example/simple-echo/main.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ in := prompt.Input(">>> ", completer,
+ prompt.OptionTitle("sql-prompt"),
+ prompt.OptionHistory([]string{"SELECT * FROM users;"}),
+ prompt.OptionPrefixTextColor(prompt.Yellow),
+ prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
+ prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
+ prompt.OptionSuggestionBGColor(prompt.DarkGray))
+ fmt.Println("Your input: " + in)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_tools/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..45bd2234f21ff32562984bec046316c8e52868fd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_tools/README.md
@@ -0,0 +1,10 @@
+## Tools of go-prompt
+
+### vt100_debug
+
+
+
+### sigwinch
+
+
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_tools/complete_file/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_tools/complete_file/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..41015cfab9b021fbc7df575bde87e3c510705496
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_tools/complete_file/main.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/completer"
+)
+
+var filePathCompleter = completer.FilePathCompleter{
+ IgnoreCase: true,
+ Filter: func(fi os.FileInfo) bool {
+ return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
+ },
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completerFunc(d prompt.Document) []prompt.Suggest {
+ t := d.GetWordBeforeCursor()
+ if strings.HasPrefix(t, "--") {
+ return []prompt.Suggest{
+ {"--foo", ""},
+ {"--bar", ""},
+ {"--baz", ""},
+ }
+ }
+ return filePathCompleter.Complete(d)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completerFunc,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_tools/sigwinch/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_tools/sigwinch/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9608eb3b4a5e3c6942c140c41e08a36ab3adb33b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_tools/sigwinch/main.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "unsafe"
+)
+
+// Winsize is winsize struct got from the ioctl(2) system call.
+type Winsize struct {
+ Row uint16
+ Col uint16
+ X uint16 // pixel value
+ Y uint16 // pixel value
+}
+
+// GetWinSize returns winsize struct which is the response of ioctl(2).
+func GetWinSize(fd int) *Winsize {
+ ws := &Winsize{}
+ retCode, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ uintptr(fd),
+ uintptr(syscall.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(ws)))
+
+ if int(retCode) == -1 {
+ panic(errno)
+ }
+ return ws
+}
+
+func main() {
+ signalChan := make(chan os.Signal, 1)
+ signal.Notify(
+ signalChan,
+ syscall.SIGHUP,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ exitChan := make(chan int)
+ go func() {
+ for {
+ s := <-signalChan
+ switch s {
+ // kill -SIGHUP XXXX
+ case syscall.SIGHUP:
+ exitChan <- 0
+
+ // kill -SIGINT XXXX or Ctrl+c
+ case syscall.SIGINT:
+ exitChan <- 0
+
+ // kill -SIGTERM XXXX
+ case syscall.SIGTERM:
+ exitChan <- 0
+
+ // kill -SIGQUIT XXXX
+ case syscall.SIGQUIT:
+ exitChan <- 0
+
+ case syscall.SIGWINCH:
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ default:
+ exitChan <- 1
+ }
+ }
+ }()
+
+ code := <-exitChan
+ os.Exit(code)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_tools/vt100_debug/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_tools/vt100_debug/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c6036d45959febc739e287a3a7b631259d4ee7c1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/_tools/vt100_debug/main.go
@@ -0,0 +1,47 @@
+// +build !windows
+
+package main
+
+import (
+ "fmt"
+ "syscall"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/term"
+)
+
+func main() {
+ if err := term.SetRaw(syscall.Stdin); err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer term.Restore()
+
+ bufCh := make(chan []byte, 128)
+ go readBuffer(bufCh)
+ fmt.Print("> ")
+
+ for {
+ b := <-bufCh
+ if key := prompt.GetKey(b); key == prompt.NotDefined {
+ fmt.Printf("Key '%s' data:'%#v'\n", string(b), b)
+ } else {
+ if key == prompt.ControlC {
+ fmt.Println("exit.")
+ return
+ }
+ fmt.Printf("Key '%s' data:'%#v'\n", key, b)
+ }
+ fmt.Print("> ")
+ }
+}
+
+func readBuffer(bufCh chan []byte) {
+ buf := make([]byte, 1024)
+
+ for {
+ if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
+ bufCh <- buf[:n]
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/buffer.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..46efbbba8bfb75f4a064c83368b781d1d6dbbb29
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/buffer.go
@@ -0,0 +1,191 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Buffer emulates the console buffer.
+type Buffer struct {
+ workingLines []string // The working lines. Similar to history
+ workingIndex int
+ cursorPosition int
+ cacheDocument *Document
+ preferredColumn int // Remember the original column for the next up/down movement.
+ lastKeyStroke Key
+}
+
+// Text returns string of the current line.
+func (b *Buffer) Text() string {
+ return b.workingLines[b.workingIndex]
+}
+
+// Document method to return document instance from the current text and cursor position.
+func (b *Buffer) Document() (d *Document) {
+ if b.cacheDocument == nil ||
+ b.cacheDocument.Text != b.Text() ||
+ b.cacheDocument.cursorPosition != b.cursorPosition {
+ b.cacheDocument = &Document{
+ Text: b.Text(),
+ cursorPosition: b.cursorPosition,
+ }
+ }
+ b.cacheDocument.lastKey = b.lastKeyStroke
+ return b.cacheDocument
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (b *Buffer) DisplayCursorPosition() int {
+ return b.Document().DisplayCursorPosition()
+}
+
+// InsertText insert string from current line.
+func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
+ or := []rune(b.Text())
+ oc := b.cursorPosition
+
+ if overwrite {
+ overwritten := string(or[oc : oc+len(v)])
+ if strings.Contains(overwritten, "\n") {
+ i := strings.IndexAny(overwritten, "\n")
+ overwritten = overwritten[:i]
+ }
+ b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):]))
+ } else {
+ b.setText(string(or[:oc]) + v + string(or[oc:]))
+ }
+
+ if moveCursor {
+ b.cursorPosition += len([]rune(v))
+ }
+}
+
+// SetText method to set text and update cursorPosition.
+// (When doing this, make sure that the cursor_position is valid for this text.
+// text/cursor_position should be consistent at any time, otherwise set a Document instead.)
+func (b *Buffer) setText(v string) {
+ debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position")
+ b.workingLines[b.workingIndex] = v
+}
+
+// Set cursor position. Return whether it changed.
+func (b *Buffer) setCursorPosition(p int) {
+ if p > 0 {
+ b.cursorPosition = p
+ } else {
+ b.cursorPosition = 0
+ }
+}
+
+func (b *Buffer) setDocument(d *Document) {
+ b.cacheDocument = d
+ b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length.
+ b.setText(d.Text)
+}
+
+// CursorLeft move to left on the current line.
+func (b *Buffer) CursorLeft(count int) {
+ l := b.Document().GetCursorLeftPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorRight move to right on the current line.
+func (b *Buffer) CursorRight(count int) {
+ l := b.Document().GetCursorRightPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorUp move cursor to the previous line.
+// (for multi-line edit).
+func (b *Buffer) CursorUp(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorUpPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// CursorDown move cursor to the next line.
+// (for multi-line edit).
+func (b *Buffer) CursorDown(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorDownPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text.
+func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) {
+ debug.Assert(count >= 0, "count should be positive")
+ r := []rune(b.Text())
+
+ if b.cursorPosition > 0 {
+ start := b.cursorPosition - count
+ if start < 0 {
+ start = 0
+ }
+ deleted = string(r[start:b.cursorPosition])
+ b.setDocument(&Document{
+ Text: string(r[:start]) + string(r[b.cursorPosition:]),
+ cursorPosition: b.cursorPosition - len([]rune(deleted)),
+ })
+ }
+ return
+}
+
+// NewLine means CR.
+func (b *Buffer) NewLine(copyMargin bool) {
+ if copyMargin {
+ b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true)
+ } else {
+ b.InsertText("\n", false, true)
+ }
+}
+
+// Delete specified number of characters and Return the deleted text.
+func (b *Buffer) Delete(count int) (deleted string) {
+ r := []rune(b.Text())
+ if b.cursorPosition < len(r) {
+ deleted = b.Document().TextAfterCursor()[:count]
+ b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):]))
+ }
+ return
+}
+
+// JoinNextLine joins the next line to the current one by deleting the line ending after the current line.
+func (b *Buffer) JoinNextLine(separator string) {
+ if !b.Document().OnLastLine() {
+ b.cursorPosition += b.Document().GetEndOfLinePosition()
+ b.Delete(1)
+ // Remove spaces
+ b.setText(b.Document().TextBeforeCursor() + separator + strings.TrimLeft(b.Document().TextAfterCursor(), " "))
+ }
+}
+
+// SwapCharactersBeforeCursor swaps the last two characters before the cursor.
+func (b *Buffer) SwapCharactersBeforeCursor() {
+ if b.cursorPosition >= 2 {
+ x := b.Text()[b.cursorPosition-2 : b.cursorPosition-1]
+ y := b.Text()[b.cursorPosition-1 : b.cursorPosition]
+ b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:])
+ }
+}
+
+// NewBuffer is constructor of Buffer struct.
+func NewBuffer() (b *Buffer) {
+ b = &Buffer{
+ workingLines: []string{""},
+ workingIndex: 0,
+ preferredColumn: -1, // -1 means nil
+ }
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/completer/file.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/completer/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..59f2d8dec84214ccaa6e345a11ed51aa61a08199
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/completer/file.go
@@ -0,0 +1,90 @@
+package completer
+
+import (
+ "io/ioutil"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+var (
+ // FilePathCompletionSeparator holds separate characters.
+ FilePathCompletionSeparator = string([]byte{' ', os.PathSeparator})
+)
+
+// FilePathCompleter is a completer for your local file system.
+// Please caution that you need to set OptionCompletionWordSeparator(completer.FilePathCompletionSeparator)
+// when you use this completer.
+type FilePathCompleter struct {
+ Filter func(fi os.FileInfo) bool
+ IgnoreCase bool
+ fileListCache map[string][]prompt.Suggest
+}
+
+func cleanFilePath(path string) (dir, base string, err error) {
+ if path == "" {
+ return ".", "", nil
+ }
+
+ var endsWithSeparator bool
+ if len(path) >= 1 && path[len(path)-1] == os.PathSeparator {
+ endsWithSeparator = true
+ }
+
+ if runtime.GOOS != "windows" && len(path) >= 2 && path[0:2] == "~/" {
+ me, err := user.Current()
+ if err != nil {
+ return "", "", err
+ }
+ path = filepath.Join(me.HomeDir, path[1:])
+ }
+ path = filepath.Clean(os.ExpandEnv(path))
+ dir = filepath.Dir(path)
+ base = filepath.Base(path)
+
+ if endsWithSeparator {
+ dir = path + string(os.PathSeparator) // Append slash(in POSIX) if path ends with slash.
+ base = "" // Set empty string if path ends with separator.
+ }
+ return dir, base, nil
+}
+
+// Complete returns suggestions from your local file system.
+func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest {
+ if c.fileListCache == nil {
+ c.fileListCache = make(map[string][]prompt.Suggest, 4)
+ }
+
+ path := d.GetWordBeforeCursor()
+ dir, base, err := cleanFilePath(path)
+ if err != nil {
+ debug.Log("completer: cannot get current user:" + err.Error())
+ return nil
+ }
+
+ if cached, ok := c.fileListCache[dir]; ok {
+ return prompt.FilterHasPrefix(cached, base, c.IgnoreCase)
+ }
+
+ files, err := ioutil.ReadDir(dir)
+ if err != nil && os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ debug.Log("completer: cannot read directory items:" + err.Error())
+ return nil
+ }
+
+ suggests := make([]prompt.Suggest, 0, len(files))
+ for _, f := range files {
+ if c.Filter != nil && !c.Filter(f) {
+ continue
+ }
+ suggests = append(suggests, prompt.Suggest{Text: f.Name()})
+ }
+ c.fileListCache[dir] = suggests
+ return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/completion.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/completion.go
new file mode 100644
index 0000000000000000000000000000000000000000..57e82eefc0f50e9561214704e770a2ad313a3659
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/completion.go
@@ -0,0 +1,190 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+const (
+ shortenSuffix = "..."
+ leftPrefix = " "
+ leftSuffix = " "
+ rightPrefix = " "
+ rightSuffix = " "
+)
+
+var (
+ leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix)
+ rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix)
+ completionMargin = leftMargin + rightMargin
+)
+
+// Suggest is printed when completing.
+type Suggest struct {
+ Text string
+ Description string
+}
+
+// CompletionManager manages which suggestion is now selected.
+type CompletionManager struct {
+ selected int // -1 means nothing one is selected.
+ tmp []Suggest
+ max uint16
+ completer Completer
+
+ verticalScroll int
+ wordSeparator string
+ showAtStart bool
+}
+
+// GetSelectedSuggestion returns the selected item.
+func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) {
+ if c.selected == -1 {
+ return Suggest{}, false
+ } else if c.selected < -1 {
+ debug.Assert(false, "must not reach here")
+ c.selected = -1
+ return Suggest{}, false
+ }
+ return c.tmp[c.selected], true
+}
+
+// GetSuggestions returns the list of suggestion.
+func (c *CompletionManager) GetSuggestions() []Suggest {
+ return c.tmp
+}
+
+// Reset to select nothing.
+func (c *CompletionManager) Reset() {
+ c.selected = -1
+ c.verticalScroll = 0
+ c.Update(*NewDocument())
+}
+
+// Update to update the suggestions.
+func (c *CompletionManager) Update(in Document) {
+ c.tmp = c.completer(in)
+}
+
+// Previous to select the previous suggestion item.
+func (c *CompletionManager) Previous() {
+ if c.verticalScroll == c.selected && c.selected > 0 {
+ c.verticalScroll--
+ }
+ c.selected--
+ c.update()
+}
+
+// Next to select the next suggestion item.
+func (c *CompletionManager) Next() {
+ if c.verticalScroll+int(c.max)-1 == c.selected {
+ c.verticalScroll++
+ }
+ c.selected++
+ c.update()
+}
+
+// Completing returns whether the CompletionManager selects something one.
+func (c *CompletionManager) Completing() bool {
+ return c.selected != -1
+}
+
+func (c *CompletionManager) update() {
+ max := int(c.max)
+ if len(c.tmp) < max {
+ max = len(c.tmp)
+ }
+
+ if c.selected >= len(c.tmp) {
+ c.Reset()
+ } else if c.selected < -1 {
+ c.selected = len(c.tmp) - 1
+ c.verticalScroll = len(c.tmp) - max
+ }
+}
+
+func deleteBreakLineCharacters(s string) string {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, "\r", "", -1)
+ return s
+}
+
+func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) {
+ l := len(o)
+ n := make([]string, l)
+
+ lenPrefix := runewidth.StringWidth(prefix)
+ lenSuffix := runewidth.StringWidth(suffix)
+ lenShorten := runewidth.StringWidth(shortenSuffix)
+ min := lenPrefix + lenSuffix + lenShorten
+ for i := 0; i < l; i++ {
+ o[i] = deleteBreakLineCharacters(o[i])
+
+ w := runewidth.StringWidth(o[i])
+ if width < w {
+ width = w
+ }
+ }
+
+ if width == 0 {
+ return n, 0
+ }
+ if min >= max {
+ return n, 0
+ }
+ if lenPrefix+width+lenSuffix > max {
+ width = max - lenPrefix - lenSuffix
+ }
+
+ for i := 0; i < l; i++ {
+ x := runewidth.StringWidth(o[i])
+ if x <= width {
+ spaces := strings.Repeat(" ", width-x)
+ n[i] = prefix + o[i] + spaces + suffix
+ } else if x > width {
+ x := runewidth.Truncate(o[i], width, shortenSuffix)
+ // When calling runewidth.Truncate("您好xxx您好xxx", 11, "...") returns "您好xxx..."
+ // But the length of this result is 10. So we need fill right using runewidth.FillRight.
+ n[i] = prefix + runewidth.FillRight(x, width) + suffix
+ }
+ }
+ return n, lenPrefix + width + lenSuffix
+}
+
+func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) {
+ num := len(suggests)
+ new = make([]Suggest, num)
+
+ left := make([]string, num)
+ for i := 0; i < num; i++ {
+ left[i] = suggests[i].Text
+ }
+ right := make([]string, num)
+ for i := 0; i < num; i++ {
+ right[i] = suggests[i].Description
+ }
+
+ left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix)
+ if leftWidth == 0 {
+ return []Suggest{}, 0
+ }
+ right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix)
+
+ for i := 0; i < num; i++ {
+ new[i] = Suggest{Text: left[i], Description: right[i]}
+ }
+ return new, leftWidth + rightWidth
+}
+
+// NewCompletionManager returns initialized CompletionManager object.
+func NewCompletionManager(completer Completer, max uint16) *CompletionManager {
+ return &CompletionManager{
+ selected: -1,
+ max: max,
+ completer: completer,
+
+ verticalScroll: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/document.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/document.go
new file mode 100644
index 0000000000000000000000000000000000000000..93a80b155ad66ade44c28a4b5fca3451547c1dc3
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/document.go
@@ -0,0 +1,446 @@
+package prompt
+
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+ istrings "github.com/c-bata/go-prompt/internal/strings"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Document has text displayed in terminal and cursor position.
+type Document struct {
+ Text string
+ // This represents a index in a rune array of Document.Text.
+ // So if Document is "日本(cursor)語", cursorPosition is 2.
+ // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+ cursorPosition int
+ lastKey Key
+}
+
+// NewDocument return the new empty document.
+func NewDocument() *Document {
+ return &Document{
+ Text: "",
+ cursorPosition: 0,
+ }
+}
+
+// LastKeyStroke return the last key pressed in this document.
+func (d *Document) LastKeyStroke() Key {
+ return d.lastKey
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (d *Document) DisplayCursorPosition() int {
+ var position int
+ runes := []rune(d.Text)[:d.cursorPosition]
+ for i := range runes {
+ position += runewidth.RuneWidth(runes[i])
+ }
+ return position
+}
+
+// GetCharRelativeToCursor return character relative to cursor position, or empty string
+func (d *Document) GetCharRelativeToCursor(offset int) (r rune) {
+ s := d.Text
+ cnt := 0
+
+ for len(s) > 0 {
+ cnt++
+ r, size := utf8.DecodeRuneInString(s)
+ if cnt == d.cursorPosition+offset {
+ return r
+ }
+ s = s[size:]
+ }
+ return 0
+}
+
+// TextBeforeCursor returns the text before the cursor.
+func (d *Document) TextBeforeCursor() string {
+ r := []rune(d.Text)
+ return string(r[:d.cursorPosition])
+}
+
+// TextAfterCursor returns the text after the cursor.
+func (d *Document) TextAfterCursor() string {
+ r := []rune(d.Text)
+ return string(r[d.cursorPosition:])
+}
+
+// GetWordBeforeCursor returns the word before the cursor.
+// If we have whitespace before the cursor this returns an empty string.
+func (d *Document) GetWordBeforeCursor() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWord():]
+}
+
+// GetWordAfterCursor returns the word after the cursor.
+// If we have whitespace after the cursor this returns an empty string.
+func (d *Document) GetWordAfterCursor() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWord()]
+}
+
+// GetWordBeforeCursorWithSpace returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorWithSpace() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordWithSpace():]
+}
+
+// GetWordAfterCursorWithSpace returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorWithSpace() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordWithSpace()]
+}
+
+// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
+func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparator(sep):]
+}
+
+// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
+func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparator(sep)]
+}
+
+// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):]
+}
+
+// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)]
+}
+
+// FindStartOfPreviousWord returns an index relative to the cursor position
+// pointing to the start of the previous word. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWord() int {
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexByte(x, ' ')
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindStartOfPreviousWordWithSpace() int {
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotByte(x, ' ')
+ if end == -1 {
+ return 0
+ }
+
+ start := strings.LastIndexByte(x[:end], ' ')
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWord()
+ }
+
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexAny(x, sep)
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWordWithSpace()
+ }
+
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotAny(x, sep)
+ if end == -1 {
+ return 0
+ }
+ start := strings.LastIndexAny(x[:end], sep)
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindEndOfCurrentWord returns an index relative to the cursor position.
+// pointing to the end of the current word. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWord() int {
+ x := d.TextAfterCursor()
+ i := strings.IndexByte(x, ' ')
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindEndOfCurrentWordWithSpace() int {
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotByte(x, ' ')
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexByte(x[start:], ' ')
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWord()
+ }
+
+ x := d.TextAfterCursor()
+ i := strings.IndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWordWithSpace()
+ }
+
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotAny(x, sep)
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexAny(x[start:], sep)
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// CurrentLineBeforeCursor returns the text from the start of the line until the cursor.
+func (d *Document) CurrentLineBeforeCursor() string {
+ s := strings.Split(d.TextBeforeCursor(), "\n")
+ return s[len(s)-1]
+}
+
+// CurrentLineAfterCursor returns the text from the cursor until the end of the line.
+func (d *Document) CurrentLineAfterCursor() string {
+ return strings.Split(d.TextAfterCursor(), "\n")[0]
+}
+
+// CurrentLine return the text on the line where the cursor is. (when the input
+// consists of just one line, it equals `text`.
+func (d *Document) CurrentLine() string {
+ return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor()
+}
+
+// Array pointing to the start indexes of all the lines.
+func (d *Document) lineStartIndexes() []int {
+ // TODO: Cache, because this is often reused.
+ // (If it is used, it's often used many times.
+ // And this has to be fast for editing big documents!)
+ lc := d.LineCount()
+ lengths := make([]int, lc)
+ for i, l := range d.Lines() {
+ lengths[i] = len(l)
+ }
+
+ // Calculate cumulative sums.
+ indexes := make([]int, lc+1)
+ indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189
+ pos := 0
+ for i, l := range lengths {
+ pos += l + 1
+ indexes[i+1] = pos
+ }
+ if lc > 1 {
+ // Pop the last item. (This is not a new line.)
+ indexes = indexes[:lc]
+ }
+ return indexes
+}
+
+// For the index of a character at a certain line, calculate the index of
+// the first character on that line.
+func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) {
+ indexes := d.lineStartIndexes()
+ pos = bisect.Right(indexes, index) - 1
+ lineStartIndex = indexes[pos]
+ return
+}
+
+// CursorPositionRow returns the current row. (0-based.)
+func (d *Document) CursorPositionRow() (row int) {
+ row, _ = d.findLineStartIndex(d.cursorPosition)
+ return
+}
+
+// CursorPositionCol returns the current column. (0-based.)
+func (d *Document) CursorPositionCol() (col int) {
+ // Don't use self.text_before_cursor to calculate this. Creating substrings
+ // and splitting is too expensive for getting the cursor position.
+ _, index := d.findLineStartIndex(d.cursorPosition)
+ col = d.cursorPosition - index
+ return
+}
+
+// GetCursorLeftPosition returns the relative position for cursor left.
+func (d *Document) GetCursorLeftPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorRightPosition(-count)
+ }
+ if d.CursorPositionCol() > count {
+ return -count
+ }
+ return -d.CursorPositionCol()
+}
+
+// GetCursorRightPosition returns relative position for cursor right.
+func (d *Document) GetCursorRightPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorLeftPosition(-count)
+ }
+ if len(d.CurrentLineAfterCursor()) > count {
+ return count
+ }
+ return len(d.CurrentLineAfterCursor())
+}
+
+// GetCursorUpPosition return the relative cursor position (character index) where we would be
+// if the user pressed the arrow-up button.
+func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+
+ row := d.CursorPositionRow() - count
+ if row < 0 {
+ row = 0
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// GetCursorDownPosition return the relative cursor position (character index) where we would be if the
+// user pressed the arrow-down button.
+func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+ row := d.CursorPositionRow()
+ if count > 0 {
+ row += 1
+ } else {
+ row += count
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// Lines returns the array of all the lines.
+func (d *Document) Lines() []string {
+ // TODO: Cache, because this one is reused very often.
+ return strings.Split(d.Text, "\n")
+}
+
+// LineCount return the number of lines in this document. If the document ends
+// with a trailing \n, that counts as the beginning of a new line.
+func (d *Document) LineCount() int {
+ return len(d.Lines())
+}
+
+// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple.
+// (0-based. Returns (0, 0) for index=0.)
+func (d *Document) TranslateIndexToPosition(index int) (row int, col int) {
+ row, rowIndex := d.findLineStartIndex(index)
+ col = index - rowIndex
+ return
+}
+
+// TranslateRowColToIndex given a (row, col), return the corresponding index.
+// (Row and col params are 0-based.)
+func (d *Document) TranslateRowColToIndex(row int, column int) (index int) {
+ indexes := d.lineStartIndexes()
+ if row < 0 {
+ row = 0
+ } else if row > len(indexes) {
+ row = len(indexes) - 1
+ }
+ index = indexes[row]
+ line := d.Lines()[row]
+
+ // python) result += max(0, min(col, len(line)))
+ if column > 0 || len(line) > 0 {
+ if column > len(line) {
+ index += len(line)
+ } else {
+ index += column
+ }
+ }
+
+ // Keep in range. (len(self.text) is included, because the cursor can be
+ // right after the end of the text as well.)
+ // python) result = max(0, min(result, len(self.text)))
+ if index > len(d.Text) {
+ index = len(d.Text)
+ }
+ if index < 0 {
+ index = 0
+ }
+ return index
+}
+
+// OnLastLine returns true when we are at the last line.
+func (d *Document) OnLastLine() bool {
+ return d.CursorPositionRow() == (d.LineCount() - 1)
+}
+
+// GetEndOfLinePosition returns relative position for the end of this line.
+func (d *Document) GetEndOfLinePosition() int {
+ return len([]rune(d.CurrentLineAfterCursor()))
+}
+
+func (d *Document) leadingWhitespaceInCurrentLine() (margin string) {
+ trimmed := strings.TrimSpace(d.CurrentLine())
+ margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)]
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/emacs.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/emacs.go
new file mode 100644
index 0000000000000000000000000000000000000000..632f96321f2577cdb7e8cffe639f1518a65d5e0f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/emacs.go
@@ -0,0 +1,120 @@
+package prompt
+
+import "github.com/c-bata/go-prompt/internal/debug"
+
+/*
+
+========
+PROGRESS
+========
+
+Moving the cursor
+-----------------
+
+* [x] Ctrl + a Go to the beginning of the line (Home)
+* [x] Ctrl + e Go to the End of the line (End)
+* [x] Ctrl + p Previous command (Up arrow)
+* [x] Ctrl + n Next command (Down arrow)
+* [x] Ctrl + f Forward one character
+* [x] Ctrl + b Backward one character
+* [x] Ctrl + xx Toggle between the start of line and current cursor position
+
+Editing
+-------
+
+* [x] Ctrl + L Clear the Screen, similar to the clear command
+* [x] Ctrl + d Delete character under the cursor
+* [x] Ctrl + h Delete character before the cursor (Backspace)
+
+* [x] Ctrl + w Cut the Word before the cursor to the clipboard.
+* [x] Ctrl + k Cut the Line after the cursor to the clipboard.
+* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard.
+
+* [ ] Ctrl + t Swap the last two characters before the cursor (typo).
+* [ ] Esc + t Swap the last two words before the cursor.
+
+* [ ] ctrl + y Paste the last thing to be cut (yank)
+* [ ] ctrl + _ Undo
+
+*/
+
+var emacsKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: ControlE,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+ },
+ },
+ // Go to the beginning of the line
+ {
+ Key: ControlA,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+ },
+ },
+ // Cut the Line after the cursor
+ {
+ Key: ControlK,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.Delete(len(x))
+ },
+ },
+ // Cut/delete the Line before the cursor
+ {
+ Key: ControlU,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.DeleteBeforeCursor(len(x))
+ },
+ },
+ // Delete character under the cursor
+ {
+ Key: ControlD,
+ Fn: func(buf *Buffer) {
+ if buf.Text() != "" {
+ buf.Delete(1)
+ }
+ },
+ },
+ // Backspace
+ {
+ Key: ControlH,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+ },
+ },
+ // Right allow: Forward one character
+ {
+ Key: ControlF,
+ Fn: func(buf *Buffer) {
+ buf.CursorRight(1)
+ },
+ },
+ // Left allow: Backward one character
+ {
+ Key: ControlB,
+ Fn: func(buf *Buffer) {
+ buf.CursorLeft(1)
+ },
+ },
+ // Cut the Word before the cursor.
+ {
+ Key: ControlW,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace())))
+ },
+ },
+ // Clear the Screen, similar to the clear command
+ {
+ Key: ControlL,
+ Fn: func(buf *Buffer) {
+ consoleWriter.EraseScreen()
+ consoleWriter.CursorGoTo(0, 0)
+ debug.AssertNoError(consoleWriter.Flush())
+ },
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/filter.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/filter.go
new file mode 100644
index 0000000000000000000000000000000000000000..61c17ed7f436a069563f520512bd25e4d81af0de
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/filter.go
@@ -0,0 +1,71 @@
+package prompt
+
+import "strings"
+
+// Filter is the type to filter the prompt.Suggestion array.
+type Filter func([]Suggest, string, bool) []Suggest
+
+// FilterHasPrefix checks whether the string completions.Text begins with sub.
+func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
+}
+
+// FilterHasSuffix checks whether the completion.Text ends with sub.
+func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
+}
+
+// FilterContains checks whether the completion.Text contains sub.
+func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
+}
+
+// FilterFuzzy checks whether the completion.Text fuzzy matches sub.
+// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
+// would match, for example, "Good food is gone"
+// ^ ^ ^
+func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
+}
+
+func fuzzyMatch(s, sub string) bool {
+ sChars := []rune(s)
+ sIdx := 0
+
+ // https://staticcheck.io/docs/checks#S1029
+ for _, c := range sub {
+ found := false
+ for ; sIdx < len(sChars); sIdx++ {
+ if sChars[sIdx] == c {
+ found = true
+ sIdx++
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
+
+func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
+ if sub == "" {
+ return suggestions
+ }
+ if ignoreCase {
+ sub = strings.ToUpper(sub)
+ }
+
+ ret := make([]Suggest, 0, len(suggestions))
+ for i := range suggestions {
+ c := suggestions[i].Text
+ if ignoreCase {
+ c = strings.ToUpper(c)
+ }
+ if function(c, sub) {
+ ret = append(ret, suggestions[i])
+ }
+ }
+ return ret
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/go.mod b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..30bc6d39a39c328341ca7153d3391352be5baa63
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/go.mod
@@ -0,0 +1,11 @@
+module github.com/c-bata/go-prompt
+
+go 1.14
+
+require (
+ github.com/mattn/go-colorable v0.1.7
+ github.com/mattn/go-runewidth v0.0.9
+ github.com/mattn/go-tty v0.0.3
+ github.com/pkg/term v1.2.0-beta.2
+ golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/go.sum b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..768bf93619a68e1b334c13e7b93ec84fa465598e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/go.sum
@@ -0,0 +1,23 @@
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/history.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/history.go
new file mode 100644
index 0000000000000000000000000000000000000000..e75c64592d82142bf4826ceb8c613ac72ca24d9c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/history.go
@@ -0,0 +1,61 @@
+package prompt
+
+// History stores the texts that are entered.
+type History struct {
+ histories []string
+ tmp []string
+ selected int
+}
+
+// Add to add text in history.
+func (h *History) Add(input string) {
+ h.histories = append(h.histories, input)
+ h.Clear()
+}
+
+// Clear to clear the history.
+func (h *History) Clear() {
+ h.tmp = make([]string, len(h.histories))
+ for i := range h.histories {
+ h.tmp[i] = h.histories[i]
+ }
+ h.tmp = append(h.tmp, "")
+ h.selected = len(h.tmp) - 1
+}
+
+// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
+ if len(h.tmp) == 1 || h.selected == 0 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected--
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
+ if h.selected >= len(h.tmp)-1 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected++
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// NewHistory returns new history object.
+func NewHistory() *History {
+ return &History{
+ histories: []string{},
+ tmp: []string{""},
+ selected: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/input.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/input.go
new file mode 100644
index 0000000000000000000000000000000000000000..307e747190c2b27bf888b379644fc4f3cdd489a2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/input.go
@@ -0,0 +1,169 @@
+package prompt
+
+import "bytes"
+
+// WinSize represents the width and height of terminal.
+type WinSize struct {
+ Row uint16
+ Col uint16
+}
+
+// ConsoleParser is an interface to abstract input layer.
+type ConsoleParser interface {
+ // Setup should be called before starting input
+ Setup() error
+ // TearDown should be called after stopping input
+ TearDown() error
+ // GetWinSize returns WinSize object to represent width and height of terminal.
+ GetWinSize() *WinSize
+ // Read returns byte array.
+ Read() ([]byte, error)
+}
+
+// GetKey returns Key correspond to input byte codes.
+func GetKey(b []byte) Key {
+ for _, k := range ASCIISequences {
+ if bytes.Equal(k.ASCIICode, b) {
+ return k.Key
+ }
+ }
+ return NotDefined
+}
+
+// ASCIISequences holds mappings of the key and byte array.
+var ASCIISequences = []*ASCIICode{
+ {Key: Escape, ASCIICode: []byte{0x1b}},
+
+ {Key: ControlSpace, ASCIICode: []byte{0x00}},
+ {Key: ControlA, ASCIICode: []byte{0x1}},
+ {Key: ControlB, ASCIICode: []byte{0x2}},
+ {Key: ControlC, ASCIICode: []byte{0x3}},
+ {Key: ControlD, ASCIICode: []byte{0x4}},
+ {Key: ControlE, ASCIICode: []byte{0x5}},
+ {Key: ControlF, ASCIICode: []byte{0x6}},
+ {Key: ControlG, ASCIICode: []byte{0x7}},
+ {Key: ControlH, ASCIICode: []byte{0x8}},
+ //{Key: ControlI, ASCIICode: []byte{0x9}},
+ //{Key: ControlJ, ASCIICode: []byte{0xa}},
+ {Key: ControlK, ASCIICode: []byte{0xb}},
+ {Key: ControlL, ASCIICode: []byte{0xc}},
+ {Key: ControlM, ASCIICode: []byte{0xd}},
+ {Key: ControlN, ASCIICode: []byte{0xe}},
+ {Key: ControlO, ASCIICode: []byte{0xf}},
+ {Key: ControlP, ASCIICode: []byte{0x10}},
+ {Key: ControlQ, ASCIICode: []byte{0x11}},
+ {Key: ControlR, ASCIICode: []byte{0x12}},
+ {Key: ControlS, ASCIICode: []byte{0x13}},
+ {Key: ControlT, ASCIICode: []byte{0x14}},
+ {Key: ControlU, ASCIICode: []byte{0x15}},
+ {Key: ControlV, ASCIICode: []byte{0x16}},
+ {Key: ControlW, ASCIICode: []byte{0x17}},
+ {Key: ControlX, ASCIICode: []byte{0x18}},
+ {Key: ControlY, ASCIICode: []byte{0x19}},
+ {Key: ControlZ, ASCIICode: []byte{0x1a}},
+
+ {Key: ControlBackslash, ASCIICode: []byte{0x1c}},
+ {Key: ControlSquareClose, ASCIICode: []byte{0x1d}},
+ {Key: ControlCircumflex, ASCIICode: []byte{0x1e}},
+ {Key: ControlUnderscore, ASCIICode: []byte{0x1f}},
+ {Key: Backspace, ASCIICode: []byte{0x7f}},
+
+ {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}},
+
+ {Key: Enter, ASCIICode: []byte{0xa}},
+ {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}},
+ {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+ {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}},
+ {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}},
+ {Key: Tab, ASCIICode: []byte{0x9}},
+ {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}},
+ {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}},
+ {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}},
+ {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}},
+ {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode
+
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}},
+ {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}},
+ {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}},
+ {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}},
+ {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}},
+ {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}},
+ {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}},
+ {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}},
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}},
+ {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}},
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+
+ // Xterm
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}},
+ // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}},
+ {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}},
+ {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}},
+ {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}},
+ {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}},
+
+ {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}},
+ {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}},
+ {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}},
+ {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}},
+
+ // Tmux sends following keystrokes when control+arrow is pressed, but for
+ // Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ // it a normal arrow press, because that's more important.
+ {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}},
+
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt
+
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/input_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/input_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f10430318be0e797c841eba8e08ab1cf5277be27
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/input_posix.go
@@ -0,0 +1,77 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/term"
+ "golang.org/x/sys/unix"
+)
+
+const maxReadBytes = 1024
+
+// PosixParser is a ConsoleParser implementation for POSIX environment.
+type PosixParser struct {
+ fd int
+ origTermios syscall.Termios
+}
+
+// Setup should be called before starting input
+func (t *PosixParser) Setup() error {
+ // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
+ if err := syscall.SetNonblock(t.fd, true); err != nil {
+ return err
+ }
+ if err := term.SetRaw(t.fd); err != nil {
+ return err
+ }
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (t *PosixParser) TearDown() error {
+ if err := syscall.SetNonblock(t.fd, false); err != nil {
+ return err
+ }
+ if err := term.Restore(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Read returns byte array.
+func (t *PosixParser) Read() ([]byte, error) {
+ buf := make([]byte, maxReadBytes)
+ n, err := syscall.Read(t.fd, buf)
+ if err != nil {
+ return []byte{}, err
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (t *PosixParser) GetWinSize() *WinSize {
+ ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: ws.Row,
+ Col: ws.Col,
+ }
+}
+
+var _ ConsoleParser = &PosixParser{}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *PosixParser {
+ in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ return &PosixParser{
+ fd: in,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/input_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/input_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..11b7679d4c4bc8b924a5b6c863ca1f6d6880570d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/input_windows.go
@@ -0,0 +1,83 @@
+// +build windows
+
+package prompt
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf8"
+ "unsafe"
+
+ tty "github.com/mattn/go-tty"
+)
+
+const maxReadBytes = 1024
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
+
+// WindowsParser is a ConsoleParser implementation for Win32 console.
+type WindowsParser struct {
+ tty *tty.TTY
+}
+
+// Setup should be called before starting input
+func (p *WindowsParser) Setup() error {
+ t, err := tty.Open()
+ if err != nil {
+ return err
+ }
+ p.tty = t
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (p *WindowsParser) TearDown() error {
+ return p.tty.Close()
+}
+
+// Read returns byte array.
+func (p *WindowsParser) Read() ([]byte, error) {
+ var ev uint32
+ r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
+ if r0 == 0 {
+ return nil, err
+ }
+ if ev == 0 {
+ return nil, errors.New("EAGAIN")
+ }
+
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, maxReadBytes)
+ n := utf8.EncodeRune(buf[:], r)
+ for p.tty.Buffered() && n < maxReadBytes {
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ break
+ }
+ n += utf8.EncodeRune(buf[n:], r)
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (p *WindowsParser) GetWinSize() *WinSize {
+ w, h, err := p.tty.Size()
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: uint16(h),
+ Col: uint16(w),
+ }
+}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *WindowsParser {
+ return &WindowsParser{}
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/bisect/bisect.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/bisect/bisect.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe162fa8c4873302e25702081b629a445d43415
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/bisect/bisect.go
@@ -0,0 +1,15 @@
+package bisect
+
+import "sort"
+
+// Right to locate the insertion point for v in a to maintain sorted order.
+func Right(a []int, v int) int {
+ return bisectRightRange(a, v, 0, len(a))
+}
+
+func bisectRightRange(a []int, v int, lo, hi int) int {
+ s := a[lo:hi]
+ return sort.Search(len(s), func(i int) bool {
+ return s[i] > v
+ })
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/debug/assert.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/debug/assert.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f648ac93c44e1e021cdf581a68f03b548534d9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/debug/assert.go
@@ -0,0 +1,55 @@
+package debug
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
+)
+
+var (
+ enableAssert bool
+)
+
+func init() {
+ if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
+ enableAssert = true
+ }
+}
+
+// Assert ensures expected condition.
+func Assert(cond bool, msg interface{}) {
+ if cond {
+ return
+ }
+ if enableAssert {
+ panic(msg)
+ }
+ writeWithSync(2, "[ASSERT] "+toString(msg))
+}
+
+func toString(v interface{}) string {
+ switch a := v.(type) {
+ case func() string:
+ return a()
+ case string:
+ return a
+ case fmt.Stringer:
+ return a.String()
+ default:
+ return fmt.Sprintf("unexpected type, %t", v)
+ }
+}
+
+// AssertNoError ensures err is nil.
+func AssertNoError(err error) {
+ if err == nil {
+ return
+ }
+ if enableAssert {
+ panic(err)
+ }
+ writeWithSync(2, "[ASSERT] "+err.Error())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/debug/log.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/debug/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..516378627a34ead9063ab7ce6c445b23c77b7cb4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/debug/log.go
@@ -0,0 +1,52 @@
+package debug
+
+import (
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+const (
+ envEnableLog = "GO_PROMPT_ENABLE_LOG"
+ logFileName = "go-prompt.log"
+)
+
+var (
+ logfile *os.File
+ logger *log.Logger
+)
+
+func init() {
+ if e := os.Getenv(envEnableLog); e == "true" || e == "1" {
+ var err error
+ logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
+ if err == nil {
+ logger = log.New(logfile, "", log.Llongfile)
+ return
+ }
+ }
+ logger = log.New(ioutil.Discard, "", log.Llongfile)
+}
+
+// Teardown to close logfile
+func Teardown() {
+ if logfile == nil {
+ return
+ }
+ _ = logfile.Close()
+}
+
+func writeWithSync(calldepth int, msg string) {
+ calldepth++
+ if logfile == nil {
+ return
+ }
+ _ = logger.Output(calldepth, msg)
+ _ = logfile.Sync() // immediately write msg
+}
+
+// Log to output message
+func Log(msg string) {
+ calldepth := 2
+ writeWithSync(calldepth, msg)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/strings/strings.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/strings/strings.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7d1886ae03a7d541c66dffca921e2d040e6d5eb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/strings/strings.go
@@ -0,0 +1,102 @@
+package strings
+
+import "unicode/utf8"
+
+// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior.
+func IndexNotByte(s string, c byte) int {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior.
+func LastIndexNotByte(s string, c byte) int {
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+type asciiSet [8]uint32
+
+func (as *asciiSet) notContains(c byte) bool {
+ return (as[c>>5] & (1 << uint(c&31))) == 0
+}
+
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c>>5] |= 1 << uint(c&31)
+ }
+ return as, true
+}
+
+// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior.
+func IndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := 0; i < len(s); i++ {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+
+ LabelFirstLoop:
+ for i, c := range s {
+ for j, m := range chars {
+ if c != m && j == len(chars)-1 {
+ return i
+ } else if c != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior.
+func LastIndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ LabelFirstLoop:
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRuneInString(s[:i])
+ i -= size
+ for j, m := range chars {
+ if r != m && j == len(chars)-1 {
+ return i
+ } else if r != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/term/raw.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/term/raw.go
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3ed8d04023558cf386a98080815d661248b85
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/term/raw.go
@@ -0,0 +1,29 @@
+// +build !windows
+
+package term
+
+import (
+ "syscall"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+// SetRaw put terminal into a raw mode
+func SetRaw(fd int) error {
+ n, err := getOriginalTermios(fd)
+ if err != nil {
+ return err
+ }
+
+ n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK |
+ syscall.ISTRIP | syscall.INLCR | syscall.IGNCR |
+ syscall.ICRNL | syscall.IXON
+ n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL
+ n.Cflag &^= syscall.CSIZE | syscall.PARENB
+ n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters.
+ n.Cc[syscall.VMIN] = 1
+ n.Cc[syscall.VTIME] = 0
+
+ return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n))
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/term/term.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/term/term.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a53c059ae60c0348ec01689babef4b13a2ecd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/internal/term/term.go
@@ -0,0 +1,34 @@
+// +build !windows
+
+package term
+
+import (
+ "sync"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ saveTermios *unix.Termios
+ saveTermiosFD int
+ saveTermiosOnce sync.Once
+)
+
+func getOriginalTermios(fd int) (*unix.Termios, error) {
+ var err error
+ saveTermiosOnce.Do(func() {
+ saveTermiosFD = fd
+ saveTermios, err = termios.Tcgetattr(uintptr(fd))
+ })
+ return saveTermios, err
+}
+
+// Restore terminal's mode.
+func Restore() error {
+ o, err := getOriginalTermios(saveTermiosFD)
+ if err != nil {
+ return err
+ }
+ return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/key.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ba569c2dd20a8ae3b3dd79ff3695bf0b6c1bd09
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/key.go
@@ -0,0 +1,128 @@
+// Code generated by hand; DO NOT EDIT.
+// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment.
+
+package prompt
+
+// Key is the type express the key inserted from user.
+//go:generate stringer -type=Key
+type Key int
+
+// ASCIICode is the type contains Key and it's ascii byte array.
+type ASCIICode struct {
+ Key Key
+ ASCIICode []byte
+}
+
+const (
+ Escape Key = iota
+
+ ControlA
+ ControlB
+ ControlC
+ ControlD
+ ControlE
+ ControlF
+ ControlG
+ ControlH
+ ControlI
+ ControlJ
+ ControlK
+ ControlL
+ ControlM
+ ControlN
+ ControlO
+ ControlP
+ ControlQ
+ ControlR
+ ControlS
+ ControlT
+ ControlU
+ ControlV
+ ControlW
+ ControlX
+ ControlY
+ ControlZ
+
+ ControlSpace
+ ControlBackslash
+ ControlSquareClose
+ ControlCircumflex
+ ControlUnderscore
+ ControlLeft
+ ControlRight
+ ControlUp
+ ControlDown
+
+ Up
+ Down
+ Right
+ Left
+
+ ShiftLeft
+ ShiftUp
+ ShiftDown
+ ShiftRight
+
+ Home
+ End
+ Delete
+ ShiftDelete
+ ControlDelete
+ PageUp
+ PageDown
+ BackTab
+ Insert
+ Backspace
+
+ // Aliases.
+ Tab
+ Enter
+ // Actually Enter equals ControlM, not ControlJ,
+ // However, in prompt_toolkit, we made the mistake of translating
+ // \r into \n during the input, so everyone is now handling the
+ // enter key by binding ControlJ.
+
+ // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere,
+ // because that's future compatible, and will still work when we
+ // stop replacing \r by \n.
+
+ F1
+ F2
+ F3
+ F4
+ F5
+ F6
+ F7
+ F8
+ F9
+ F10
+ F11
+ F12
+ F13
+ F14
+ F15
+ F16
+ F17
+ F18
+ F19
+ F20
+ F21
+ F22
+ F23
+ F24
+
+ // Matches any key.
+ Any
+
+ // Special
+ CPRResponse
+ Vt100MouseEvent
+ WindowsMouseEvent
+ BracketedPaste
+
+ // Key which is ignored. (The key binding for this key should not do anything.)
+ Ignore
+
+ // Key is not defined
+ NotDefined
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/key_bind.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/key_bind.go
new file mode 100644
index 0000000000000000000000000000000000000000..42669e7f942efc4d92f896388daede90b96b55dd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/key_bind.go
@@ -0,0 +1,59 @@
+package prompt
+
+// KeyBindFunc receives buffer and processed it.
+type KeyBindFunc func(*Buffer)
+
+// KeyBind represents which key should do what operation.
+type KeyBind struct {
+ Key Key
+ Fn KeyBindFunc
+}
+
+// ASCIICodeBind represents which []byte should do what operation
+type ASCIICodeBind struct {
+ ASCIICode []byte
+ Fn KeyBindFunc
+}
+
+// KeyBindMode to switch a key binding flexibly.
+type KeyBindMode string
+
+const (
+ // CommonKeyBind is a mode without any keyboard shortcut
+ CommonKeyBind KeyBindMode = "common"
+ // EmacsKeyBind is a mode to use emacs-like keyboard shortcut
+ EmacsKeyBind KeyBindMode = "emacs"
+)
+
+var commonKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: End,
+ Fn: GoLineEnd,
+ },
+ // Go to the beginning of the line
+ {
+ Key: Home,
+ Fn: GoLineBeginning,
+ },
+ // Delete character under the cursor
+ {
+ Key: Delete,
+ Fn: DeleteChar,
+ },
+ // Backspace
+ {
+ Key: Backspace,
+ Fn: DeleteBeforeChar,
+ },
+ // Right allow: Forward one character
+ {
+ Key: Right,
+ Fn: GoRightChar,
+ },
+ // Left allow: Backward one character
+ {
+ Key: Left,
+ Fn: GoLeftChar,
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/key_bind_func.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/key_bind_func.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b2ecdf63179dbfdbcb0d71bfa436bb36d62d230
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/key_bind_func.go
@@ -0,0 +1,48 @@
+package prompt
+
+// GoLineEnd Go to the End of the line
+func GoLineEnd(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+}
+
+// GoLineBeginning Go to the beginning of the line
+func GoLineBeginning(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+}
+
+// DeleteChar Delete character under the cursor
+func DeleteChar(buf *Buffer) {
+ buf.Delete(1)
+}
+
+// DeleteWord Delete word before the cursor
+func DeleteWord(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
+
+// DeleteBeforeChar Go to Backspace
+func DeleteBeforeChar(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+}
+
+// GoRightChar Forward one character
+func GoRightChar(buf *Buffer) {
+ buf.CursorRight(1)
+}
+
+// GoLeftChar Backward one character
+func GoLeftChar(buf *Buffer) {
+ buf.CursorLeft(1)
+}
+
+// GoRightWord Forward one word
+func GoRightWord(buf *Buffer) {
+ buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
+}
+
+// GoLeftWord Backward one word
+func GoLeftWord(buf *Buffer) {
+ buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/key_string.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/key_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..fce6ea31c502b3e763451cb47757ae1b49c32814
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/key_string.go
@@ -0,0 +1,16 @@
+// Code generated by "stringer -type=Key"; DO NOT EDIT.
+
+package prompt
+
+import "strconv"
+
+const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined"
+
+var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607}
+
+func (i Key) String() string {
+ if i < 0 || i >= Key(len(_Key_index)-1) {
+ return "Key(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _Key_name[_Key_index[i]:_Key_index[i+1]]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/option.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/option.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd6806cc1dbccf8c4ddb048080fde615c59088
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/option.go
@@ -0,0 +1,310 @@
+package prompt
+
+// Option is the type to replace default parameters.
+// prompt.New accepts any number of options (this is functional option pattern).
+type Option func(prompt *Prompt) error
+
+// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
+func OptionParser(x ConsoleParser) Option {
+ return func(p *Prompt) error {
+ p.in = x
+ return nil
+ }
+}
+
+// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
+func OptionWriter(x ConsoleWriter) Option {
+ return func(p *Prompt) error {
+ registerConsoleWriter(x)
+ p.renderer.out = x
+ return nil
+ }
+}
+
+// OptionTitle to set title displayed at the header bar of terminal.
+func OptionTitle(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.title = x
+ return nil
+ }
+}
+
+// OptionPrefix to set prefix string.
+func OptionPrefix(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefix = x
+ return nil
+ }
+}
+
+// OptionInitialBufferText to set the initial buffer text
+func OptionInitialBufferText(x string) Option {
+ return func(p *Prompt) error {
+ p.buf.InsertText(x, false, true)
+ return nil
+ }
+}
+
+// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
+func OptionCompletionWordSeparator(x string) Option {
+ return func(p *Prompt) error {
+ p.completion.wordSeparator = x
+ return nil
+ }
+}
+
+// OptionLivePrefix to change the prefix dynamically by callback function
+func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
+ return func(p *Prompt) error {
+ p.renderer.livePrefixCallback = f
+ return nil
+ }
+}
+
+// OptionPrefixTextColor change a text color of prefix string
+func OptionPrefixTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixTextColor = x
+ return nil
+ }
+}
+
+// OptionPrefixBackgroundColor to change a background color of prefix string
+func OptionPrefixBackgroundColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixBGColor = x
+ return nil
+ }
+}
+
+// OptionInputTextColor to change a color of text which is input by user
+func OptionInputTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputTextColor = x
+ return nil
+ }
+}
+
+// OptionInputBGColor to change a color of background which is input by user
+func OptionInputBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputBGColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionTextColor to change a text color which is completed
+func OptionPreviewSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionBGColor to change a background color which is completed
+func OptionPreviewSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionTextColor to change a text color in drop down suggestions.
+func OptionSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionBGColor change a background color in drop down suggestions.
+func OptionSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarThumbColor to change a thumb color on scrollbar.
+func OptionScrollbarThumbColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarThumbColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarBGColor to change a background color of scrollbar.
+func OptionScrollbarBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarBGColor = x
+ return nil
+ }
+}
+
+// OptionMaxSuggestion specify the max number of displayed suggestions.
+func OptionMaxSuggestion(x uint16) Option {
+ return func(p *Prompt) error {
+ p.completion.max = x
+ return nil
+ }
+}
+
+// OptionHistory to set history expressed by string array.
+func OptionHistory(x []string) Option {
+ return func(p *Prompt) error {
+ p.history.histories = x
+ p.history.Clear()
+ return nil
+ }
+}
+
+// OptionSwitchKeyBindMode set a key bind mode.
+func OptionSwitchKeyBindMode(m KeyBindMode) Option {
+ return func(p *Prompt) error {
+ p.keyBindMode = m
+ return nil
+ }
+}
+
+// OptionCompletionOnDown allows for Down arrow key to trigger completion.
+func OptionCompletionOnDown() Option {
+ return func(p *Prompt) error {
+ p.completionOnDown = true
+ return nil
+ }
+}
+
+// SwitchKeyBindMode to set a key bind mode.
+// Deprecated: Please use OptionSwitchKeyBindMode.
+var SwitchKeyBindMode = OptionSwitchKeyBindMode
+
+// OptionAddKeyBind to set a custom key bind.
+func OptionAddKeyBind(b ...KeyBind) Option {
+ return func(p *Prompt) error {
+ p.keyBindings = append(p.keyBindings, b...)
+ return nil
+ }
+}
+
+// OptionAddASCIICodeBind to set a custom key bind.
+func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option {
+ return func(p *Prompt) error {
+ p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...)
+ return nil
+ }
+}
+
+// OptionShowCompletionAtStart to set completion window is open at start.
+func OptionShowCompletionAtStart() Option {
+ return func(p *Prompt) error {
+ p.completion.showAtStart = true
+ return nil
+ }
+}
+
+// OptionBreakLineCallback to run a callback at every break line
+func OptionBreakLineCallback(fn func(*Document)) Option {
+ return func(p *Prompt) error {
+ p.renderer.breakLineCallback = fn
+ return nil
+ }
+}
+
+// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop
+func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
+ return func(p *Prompt) error {
+ p.exitChecker = fn
+ return nil
+ }
+}
+
+// New returns a Prompt with powerful auto-completion.
+func New(executor Executor, completer Completer, opts ...Option) *Prompt {
+ defaultWriter := NewStdoutWriter()
+ registerConsoleWriter(defaultWriter)
+
+ pt := &Prompt{
+ in: NewStandardInputParser(),
+ renderer: &Render{
+ prefix: "> ",
+ out: defaultWriter,
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ },
+ buf: NewBuffer(),
+ executor: executor,
+ history: NewHistory(),
+ completion: NewCompletionManager(completer, 6),
+ keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting
+ }
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/output.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/output.go
new file mode 100644
index 0000000000000000000000000000000000000000..42531b412f1ed027c2fff5b85bc273e53e569b3a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/output.go
@@ -0,0 +1,161 @@
+package prompt
+
+import "sync"
+
+var (
+ consoleWriterMu sync.Mutex
+ consoleWriter ConsoleWriter
+)
+
+func registerConsoleWriter(f ConsoleWriter) {
+ consoleWriterMu.Lock()
+ defer consoleWriterMu.Unlock()
+ consoleWriter = f
+}
+
+// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on.
+type DisplayAttribute int
+
+const (
+ // DisplayReset reset all display attributes.
+ DisplayReset DisplayAttribute = iota
+ // DisplayBold set bold or increases intensity.
+ DisplayBold
+ // DisplayLowIntensity decreases intensity. Not widely supported.
+ DisplayLowIntensity
+ // DisplayItalic set italic. Not widely supported.
+ DisplayItalic
+ // DisplayUnderline set underline
+ DisplayUnderline
+ // DisplayBlink set blink (less than 150 per minute).
+ DisplayBlink
+ // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported.
+ DisplayRapidBlink
+ // DisplayReverse swap foreground and background colors.
+ DisplayReverse
+ // DisplayInvisible set invisible. Not widely supported.
+ DisplayInvisible
+ // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported.
+ DisplayCrossedOut
+ // DisplayDefaultFont set primary(default) font
+ DisplayDefaultFont
+)
+
+// Color represents color on terminal.
+type Color int
+
+const (
+ // DefaultColor represents a default color.
+ DefaultColor Color = iota
+
+ // Low intensity
+
+ // Black represents a black.
+ Black
+ // DarkRed represents a dark red.
+ DarkRed
+ // DarkGreen represents a dark green.
+ DarkGreen
+ // Brown represents a brown.
+ Brown
+ // DarkBlue represents a dark blue.
+ DarkBlue
+ // Purple represents a purple.
+ Purple
+ // Cyan represents a cyan.
+ Cyan
+ // LightGray represents a light gray.
+ LightGray
+
+ // High intensity
+
+ // DarkGray represents a dark gray.
+ DarkGray
+ // Red represents a red.
+ Red
+ // Green represents a green.
+ Green
+ // Yellow represents a yellow.
+ Yellow
+ // Blue represents a blue.
+ Blue
+ // Fuchsia represents a fuchsia.
+ Fuchsia
+ // Turquoise represents a turquoise.
+ Turquoise
+ // White represents a white.
+ White
+)
+
+// ConsoleWriter is an interface to abstract output layer.
+type ConsoleWriter interface {
+ /* Write */
+
+ // WriteRaw to write raw byte array.
+ WriteRaw(data []byte)
+ // Write to write safety byte array by removing control sequences.
+ Write(data []byte)
+ // WriteStr to write raw string.
+ WriteRawStr(data string)
+ // WriteStr to write safety string by removing control sequences.
+ WriteStr(data string)
+ // Flush to flush buffer.
+ Flush() error
+
+ /* Erasing */
+
+ // EraseScreen erases the screen with the background colour and moves the cursor to home.
+ EraseScreen()
+ // EraseUp erases the screen from the current line up to the top of the screen.
+ EraseUp()
+ // EraseDown erases the screen from the current line down to the bottom of the screen.
+ EraseDown()
+ // EraseStartOfLine erases from the current cursor position to the start of the current line.
+ EraseStartOfLine()
+ // EraseEndOfLine erases from the current cursor position to the end of the current line.
+ EraseEndOfLine()
+ // EraseLine erases the entire current line.
+ EraseLine()
+
+ /* Cursor */
+
+ // ShowCursor stops blinking cursor and show.
+ ShowCursor()
+ // HideCursor hides cursor.
+ HideCursor()
+ // CursorGoTo sets the cursor position where subsequent text will begin.
+ CursorGoTo(row, col int)
+ // CursorUp moves the cursor up by 'n' rows; the default count is 1.
+ CursorUp(n int)
+ // CursorDown moves the cursor down by 'n' rows; the default count is 1.
+ CursorDown(n int)
+ // CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+ CursorForward(n int)
+ // CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+ CursorBackward(n int)
+ // AskForCPR asks for a cursor position report (CPR).
+ AskForCPR()
+ // SaveCursor saves current cursor position.
+ SaveCursor()
+ // UnSaveCursor restores cursor position after a Save Cursor.
+ UnSaveCursor()
+
+ /* Scrolling */
+
+ // ScrollDown scrolls display down one line.
+ ScrollDown()
+ // ScrollUp scroll display up one line.
+ ScrollUp()
+
+ /* Title */
+
+ // SetTitle sets a title of terminal window.
+ SetTitle(title string)
+ // ClearTitle clears a title of terminal window.
+ ClearTitle()
+
+ /* Font */
+
+ // SetColor sets text and background colors. and specify whether text is bold.
+ SetColor(fg, bg Color, bold bool)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/output_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/output_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..26c770cc152a7b126be43915d60b8ba000ad0e38
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/output_posix.go
@@ -0,0 +1,67 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+)
+
+const flushMaxRetryCount = 3
+
+// PosixWriter is a ConsoleWriter implementation for POSIX environment.
+// To control terminal emulator, this outputs VT100 escape sequences.
+type PosixWriter struct {
+ VT100Writer
+ fd int
+}
+
+// Flush to flush buffer
+func (w *PosixWriter) Flush() error {
+ l := len(w.buffer)
+ offset := 0
+ retry := 0
+ for {
+ n, err := syscall.Write(w.fd, w.buffer[offset:])
+ if err != nil {
+ if retry < flushMaxRetryCount {
+ retry++
+ continue
+ }
+ return err
+ }
+ offset += n
+ if offset == l {
+ break
+ }
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &PosixWriter{}
+
+var (
+ // NewStandardOutputWriter returns ConsoleWriter object to write to stdout.
+ // This generates VT100 escape sequences because almost terminal emulators
+ // in POSIX OS built on top of a VT100 specification.
+ // Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStdoutWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stdout,
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStderrWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stderr,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/output_vt100.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/output_vt100.go
new file mode 100644
index 0000000000000000000000000000000000000000..20850fead883c4cd9802928b5de3f935fbbeb047
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/output_vt100.go
@@ -0,0 +1,310 @@
+package prompt
+
+import (
+ "bytes"
+ "strconv"
+)
+
+// VT100Writer generates VT100 escape sequences.
+type VT100Writer struct {
+ buffer []byte
+}
+
+// WriteRaw to write raw byte array
+func (w *VT100Writer) WriteRaw(data []byte) {
+ w.buffer = append(w.buffer, data...)
+}
+
+// Write to write safety byte array by removing control sequences.
+func (w *VT100Writer) Write(data []byte) {
+ w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1))
+}
+
+// WriteRawStr to write raw string
+func (w *VT100Writer) WriteRawStr(data string) {
+ w.WriteRaw([]byte(data))
+}
+
+// WriteStr to write safety string by removing control sequences.
+func (w *VT100Writer) WriteStr(data string) {
+ w.Write([]byte(data))
+}
+
+/* Erase */
+
+// EraseScreen erases the screen with the background colour and moves the cursor to home.
+func (w *VT100Writer) EraseScreen() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'J'})
+}
+
+// EraseUp erases the screen from the current line up to the top of the screen.
+func (w *VT100Writer) EraseUp() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'J'})
+}
+
+// EraseDown erases the screen from the current line down to the bottom of the screen.
+func (w *VT100Writer) EraseDown() {
+ w.WriteRaw([]byte{0x1b, '[', 'J'})
+}
+
+// EraseStartOfLine erases from the current cursor position to the start of the current line.
+func (w *VT100Writer) EraseStartOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'K'})
+}
+
+// EraseEndOfLine erases from the current cursor position to the end of the current line.
+func (w *VT100Writer) EraseEndOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', 'K'})
+}
+
+// EraseLine erases the entire current line.
+func (w *VT100Writer) EraseLine() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'K'})
+}
+
+/* Cursor */
+
+// ShowCursor stops blinking cursor and show.
+func (w *VT100Writer) ShowCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'})
+}
+
+// HideCursor hides cursor.
+func (w *VT100Writer) HideCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'})
+}
+
+// CursorGoTo sets the cursor position where subsequent text will begin.
+func (w *VT100Writer) CursorGoTo(row, col int) {
+ if row == 0 && col == 0 {
+ // If no row/column parameters are provided (ie. [H), the cursor will move to the home position.
+ w.WriteRaw([]byte{0x1b, '[', 'H'})
+ return
+ }
+ r := strconv.Itoa(row)
+ c := strconv.Itoa(col)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(r))
+ w.WriteRaw([]byte{';'})
+ w.WriteRaw([]byte(c))
+ w.WriteRaw([]byte{'H'})
+}
+
+// CursorUp moves the cursor up by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorUp(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorDown(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'A'})
+}
+
+// CursorDown moves the cursor down by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorDown(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorUp(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'B'})
+}
+
+// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorForward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorBackward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'C'})
+}
+
+// CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorBackward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorForward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'D'})
+}
+
+// AskForCPR asks for a cursor position report (CPR).
+func (w *VT100Writer) AskForCPR() {
+ // CPR: Cursor Position Request.
+ w.WriteRaw([]byte{0x1b, '[', '6', 'n'})
+}
+
+// SaveCursor saves current cursor position.
+func (w *VT100Writer) SaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 's'})
+}
+
+// UnSaveCursor restores cursor position after a Save Cursor.
+func (w *VT100Writer) UnSaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 'u'})
+}
+
+/* Scrolling */
+
+// ScrollDown scrolls display down one line.
+func (w *VT100Writer) ScrollDown() {
+ w.WriteRaw([]byte{0x1b, 'D'})
+}
+
+// ScrollUp scroll display up one line.
+func (w *VT100Writer) ScrollUp() {
+ w.WriteRaw([]byte{0x1b, 'M'})
+}
+
+/* Title */
+
+// SetTitle sets a title of terminal window.
+func (w *VT100Writer) SetTitle(title string) {
+ titleBytes := []byte(title)
+ patterns := []struct {
+ from []byte
+ to []byte
+ }{
+ {
+ from: []byte{0x13},
+ to: []byte{},
+ },
+ {
+ from: []byte{0x07},
+ to: []byte{},
+ },
+ }
+ for i := range patterns {
+ titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1)
+ }
+
+ w.WriteRaw([]byte{0x1b, ']', '2', ';'})
+ w.WriteRaw(titleBytes)
+ w.WriteRaw([]byte{0x07})
+}
+
+// ClearTitle clears a title of terminal window.
+func (w *VT100Writer) ClearTitle() {
+ w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07})
+}
+
+/* Font */
+
+// SetColor sets text and background colors. and specify whether text is bold.
+func (w *VT100Writer) SetColor(fg, bg Color, bold bool) {
+ if bold {
+ w.SetDisplayAttributes(fg, bg, DisplayBold)
+ } else {
+ // If using `DisplayDefualt`, it will be broken in some environment.
+ // Details are https://github.com/c-bata/go-prompt/pull/85
+ w.SetDisplayAttributes(fg, bg, DisplayReset)
+ }
+}
+
+// SetDisplayAttributes to set VT100 display attributes.
+func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) {
+ w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer
+ defer w.WriteRaw([]byte{'m'}) // final character
+
+ var separator byte = ';'
+ for i := range attrs {
+ p, ok := displayAttributeParameters[attrs[i]]
+ if !ok {
+ continue
+ }
+ w.WriteRaw(p)
+ w.WriteRaw([]byte{separator})
+ }
+
+ f, ok := foregroundANSIColors[fg]
+ if !ok {
+ f = foregroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(f)
+ w.WriteRaw([]byte{separator})
+ b, ok := backgroundANSIColors[bg]
+ if !ok {
+ b = backgroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(b)
+}
+
+var displayAttributeParameters = map[DisplayAttribute][]byte{
+ DisplayReset: {'0'},
+ DisplayBold: {'1'},
+ DisplayLowIntensity: {'2'},
+ DisplayItalic: {'3'},
+ DisplayUnderline: {'4'},
+ DisplayBlink: {'5'},
+ DisplayRapidBlink: {'6'},
+ DisplayReverse: {'7'},
+ DisplayInvisible: {'8'},
+ DisplayCrossedOut: {'9'},
+ DisplayDefaultFont: {'1', '0'},
+}
+
+var foregroundANSIColors = map[Color][]byte{
+ DefaultColor: {'3', '9'},
+
+ // Low intensity.
+ Black: {'3', '0'},
+ DarkRed: {'3', '1'},
+ DarkGreen: {'3', '2'},
+ Brown: {'3', '3'},
+ DarkBlue: {'3', '4'},
+ Purple: {'3', '5'},
+ Cyan: {'3', '6'},
+ LightGray: {'3', '7'},
+
+ // High intensity.
+ DarkGray: {'9', '0'},
+ Red: {'9', '1'},
+ Green: {'9', '2'},
+ Yellow: {'9', '3'},
+ Blue: {'9', '4'},
+ Fuchsia: {'9', '5'},
+ Turquoise: {'9', '6'},
+ White: {'9', '7'},
+}
+
+var backgroundANSIColors = map[Color][]byte{
+ DefaultColor: {'4', '9'},
+
+ // Low intensity.
+ Black: {'4', '0'},
+ DarkRed: {'4', '1'},
+ DarkGreen: {'4', '2'},
+ Brown: {'4', '3'},
+ DarkBlue: {'4', '4'},
+ Purple: {'4', '5'},
+ Cyan: {'4', '6'},
+ LightGray: {'4', '7'},
+
+ // High intensity
+ DarkGray: {'1', '0', '0'},
+ Red: {'1', '0', '1'},
+ Green: {'1', '0', '2'},
+ Yellow: {'1', '0', '3'},
+ Blue: {'1', '0', '4'},
+ Fuchsia: {'1', '0', '5'},
+ Turquoise: {'1', '0', '6'},
+ White: {'1', '0', '7'},
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/output_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/output_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b9c2769fc2d64cfcfcc5b99c915591ec625bd5f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/output_windows.go
@@ -0,0 +1,49 @@
+// +build windows
+
+package prompt
+
+import (
+ "io"
+
+ colorable "github.com/mattn/go-colorable"
+)
+
+// WindowsWriter is a ConsoleWriter implementation for Win32 console.
+// Output is converted from VT100 escape sequences by mattn/go-colorable.
+type WindowsWriter struct {
+ VT100Writer
+ out io.Writer
+}
+
+// Flush to flush buffer
+func (w *WindowsWriter) Flush() error {
+ _, err := w.out.Write(w.buffer)
+ if err != nil {
+ return err
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &WindowsWriter{}
+
+var (
+ // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates win32 control sequences.
+func NewStdoutWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStdout(),
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates win32 control sequences.
+func NewStderrWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStderr(),
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/prompt.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/prompt.go
new file mode 100644
index 0000000000000000000000000000000000000000..173cd517c40cde212433e399978641ceff1d1a43
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/prompt.go
@@ -0,0 +1,296 @@
+package prompt
+
+import (
+ "bytes"
+ "os"
+ "time"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Executor is called when user input something text.
+type Executor func(string)
+
+// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
+// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
+// - immediate exit (if breakline is false) without executor called
+// - exit after typing (meaning breakline is true), and the executor is called first, before exit.
+// Exit means exit go-prompt (not the overall Go program)
+type ExitChecker func(in string, breakline bool) bool
+
+// Completer should return the suggest item from Document.
+type Completer func(Document) []Suggest
+
+// Prompt is core struct of go-prompt.
+type Prompt struct {
+ in ConsoleParser
+ buf *Buffer
+ renderer *Render
+ executor Executor
+ history *History
+ completion *CompletionManager
+ keyBindings []KeyBind
+ ASCIICodeBindings []ASCIICodeBind
+ keyBindMode KeyBindMode
+ completionOnDown bool
+ exitChecker ExitChecker
+ skipTearDown bool
+}
+
+// Exec is the struct contains user input context.
+type Exec struct {
+ input string
+}
+
+// Run starts prompt.
+func (p *Prompt) Run() {
+ p.skipTearDown = false
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ exitCh := make(chan int)
+ winSizeCh := make(chan *WinSize)
+ stopHandleSignalCh := make(chan struct{})
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+ return
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+
+ // Unset raw mode
+ // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
+ debug.AssertNoError(p.in.TearDown())
+ p.executor(e.input)
+
+ p.completion.Update(*p.buf.Document())
+
+ p.renderer.Render(p.buf, p.completion)
+
+ if p.exitChecker != nil && p.exitChecker(e.input, true) {
+ p.skipTearDown = true
+ return
+ }
+ // Set raw mode
+ debug.AssertNoError(p.in.Setup())
+ go p.readBuffer(bufCh, stopReadBufCh)
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ case w := <-winSizeCh:
+ p.renderer.UpdateWinSize(w)
+ p.renderer.Render(p.buf, p.completion)
+ case code := <-exitCh:
+ p.renderer.BreakLine(p.buf)
+ p.tearDown()
+ os.Exit(code)
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
+ key := GetKey(b)
+ p.buf.lastKeyStroke = key
+ // completion
+ completing := p.completion.Completing()
+ p.handleCompletionKeyBinding(key, completing)
+
+ switch key {
+ case Enter, ControlJ, ControlM:
+ p.renderer.BreakLine(p.buf)
+
+ exec = &Exec{input: p.buf.Text()}
+ p.buf = NewBuffer()
+ if exec.input != "" {
+ p.history.Add(exec.input)
+ }
+ case ControlC:
+ p.renderer.BreakLine(p.buf)
+ p.buf = NewBuffer()
+ p.history.Clear()
+ case Up, ControlP:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Older(p.buf); changed {
+ p.buf = newBuf
+ }
+ }
+ case Down, ControlN:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Newer(p.buf); changed {
+ p.buf = newBuf
+ }
+ return
+ }
+ case ControlD:
+ if p.buf.Text() == "" {
+ shouldExit = true
+ return
+ }
+ case NotDefined:
+ if p.handleASCIICodeBinding(b) {
+ return
+ }
+ p.buf.InsertText(string(b), false, true)
+ }
+
+ shouldExit = p.handleKeyBinding(key)
+ return
+}
+
+func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
+ switch key {
+ case Down:
+ if completing || p.completionOnDown {
+ p.completion.Next()
+ }
+ case Tab, ControlI:
+ p.completion.Next()
+ case Up:
+ if completing {
+ p.completion.Previous()
+ }
+ case BackTab:
+ p.completion.Previous()
+ default:
+ if s, ok := p.completion.GetSelectedSuggestion(); ok {
+ w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
+ if w != "" {
+ p.buf.DeleteBeforeCursor(len([]rune(w)))
+ }
+ p.buf.InsertText(s.Text, false, true)
+ }
+ p.completion.Reset()
+ }
+}
+
+func (p *Prompt) handleKeyBinding(key Key) bool {
+ shouldExit := false
+ for i := range commonKeyBindings {
+ kb := commonKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+
+ if p.keyBindMode == EmacsKeyBind {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ }
+
+ // Custom key bindings
+ for i := range p.keyBindings {
+ kb := p.keyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
+ shouldExit = true
+ }
+ return shouldExit
+}
+
+func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
+ checked := false
+ for _, kb := range p.ASCIICodeBindings {
+ if bytes.Equal(kb.ASCIICode, b) {
+ kb.Fn(p.buf)
+ checked = true
+ }
+ }
+ return checked
+}
+
+// Input just returns user input text.
+func (p *Prompt) Input() string {
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ return ""
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ return e.input
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
+ debug.Log("start reading buffer")
+ for {
+ select {
+ case <-stopCh:
+ debug.Log("stop reading buffer")
+ return
+ default:
+ if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
+ bufCh <- b
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (p *Prompt) setUp() {
+ debug.AssertNoError(p.in.Setup())
+ p.renderer.Setup()
+ p.renderer.UpdateWinSize(p.in.GetWinSize())
+}
+
+func (p *Prompt) tearDown() {
+ if !p.skipTearDown {
+ debug.AssertNoError(p.in.TearDown())
+ }
+ p.renderer.TearDown()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/render.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/render.go
new file mode 100644
index 0000000000000000000000000000000000000000..299ac48b6254b9752ea16516aaedcd41acca6515
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/render.go
@@ -0,0 +1,287 @@
+package prompt
+
+import (
+ "runtime"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Render to render prompt information from state of Buffer.
+type Render struct {
+ out ConsoleWriter
+ prefix string
+ livePrefixCallback func() (prefix string, useLivePrefix bool)
+ breakLineCallback func(*Document)
+ title string
+ row uint16
+ col uint16
+
+ previousCursor int
+
+ // colors,
+ prefixTextColor Color
+ prefixBGColor Color
+ inputTextColor Color
+ inputBGColor Color
+ previewSuggestionTextColor Color
+ previewSuggestionBGColor Color
+ suggestionTextColor Color
+ suggestionBGColor Color
+ selectedSuggestionTextColor Color
+ selectedSuggestionBGColor Color
+ descriptionTextColor Color
+ descriptionBGColor Color
+ selectedDescriptionTextColor Color
+ selectedDescriptionBGColor Color
+ scrollbarThumbColor Color
+ scrollbarBGColor Color
+}
+
+// Setup to initialize console output.
+func (r *Render) Setup() {
+ if r.title != "" {
+ r.out.SetTitle(r.title)
+ debug.AssertNoError(r.out.Flush())
+ }
+}
+
+// getCurrentPrefix to get current prefix.
+// If live-prefix is enabled, return live-prefix.
+func (r *Render) getCurrentPrefix() string {
+ if prefix, ok := r.livePrefixCallback(); ok {
+ return prefix
+ }
+ return r.prefix
+}
+
+func (r *Render) renderPrefix() {
+ r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
+ r.out.WriteStr(r.getCurrentPrefix())
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// TearDown to clear title and erasing.
+func (r *Render) TearDown() {
+ r.out.ClearTitle()
+ r.out.EraseDown()
+ debug.AssertNoError(r.out.Flush())
+}
+
+func (r *Render) prepareArea(lines int) {
+ for i := 0; i < lines; i++ {
+ r.out.ScrollDown()
+ }
+ for i := 0; i < lines; i++ {
+ r.out.ScrollUp()
+ }
+}
+
+// UpdateWinSize called when window size is changed.
+func (r *Render) UpdateWinSize(ws *WinSize) {
+ r.row = ws.Row
+ r.col = ws.Col
+}
+
+func (r *Render) renderWindowTooSmall() {
+ r.out.CursorGoTo(0, 0)
+ r.out.EraseScreen()
+ r.out.SetColor(DarkRed, White, false)
+ r.out.WriteStr("Your console window is too small...")
+}
+
+func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) {
+ suggestions := completions.GetSuggestions()
+ if len(completions.GetSuggestions()) == 0 {
+ return
+ }
+ prefix := r.getCurrentPrefix()
+ formatted, width := formatSuggestions(
+ suggestions,
+ int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar
+ )
+ // +1 means a width of scrollbar.
+ width++
+
+ windowHeight := len(formatted)
+ if windowHeight > int(completions.max) {
+ windowHeight = int(completions.max)
+ }
+ formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
+ r.prepareArea(windowHeight)
+
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor())
+ x, _ := r.toPos(cursor)
+ if x+width >= int(r.col) {
+ cursor = r.backward(cursor, x+width-int(r.col))
+ }
+
+ contentHeight := len(completions.tmp)
+
+ fractionVisible := float64(windowHeight) / float64(contentHeight)
+ fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
+
+ scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
+ scrollbarTop := int(float64(windowHeight) * fractionAbove)
+
+ isScrollThumb := func(row int) bool {
+ return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
+ }
+
+ selected := completions.selected - completions.verticalScroll
+ r.out.SetColor(White, Cyan, false)
+ for i := 0; i < windowHeight; i++ {
+ r.out.CursorDown(1)
+ if i == selected {
+ r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
+ } else {
+ r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Text)
+
+ if i == selected {
+ r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
+ } else {
+ r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Description)
+
+ if isScrollThumb(i) {
+ r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
+ } else {
+ r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
+ }
+ r.out.WriteStr(" ")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+
+ r.lineWrap(cursor + width)
+ r.backward(cursor+width, width)
+ }
+
+ if x+width >= int(r.col) {
+ r.out.CursorForward(x + width - int(r.col))
+ }
+
+ r.out.CursorUp(windowHeight)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// Render renders to the console.
+func (r *Render) Render(buffer *Buffer, completion *CompletionManager) {
+ // In situations where a pseudo tty is allocated (e.g. within a docker container),
+ // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
+ if r.col == 0 {
+ return
+ }
+ defer func() { debug.AssertNoError(r.out.Flush()) }()
+ r.move(r.previousCursor, 0)
+
+ line := buffer.Text()
+ prefix := r.getCurrentPrefix()
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line)
+
+ // prepare area
+ _, y := r.toPos(cursor)
+
+ h := y + 1 + int(completion.max)
+ if h > int(r.row) || completionMargin > int(r.col) {
+ r.renderWindowTooSmall()
+ return
+ }
+
+ // Rendering
+ r.out.HideCursor()
+ defer r.out.ShowCursor()
+
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(line)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ r.lineWrap(cursor)
+
+ r.out.EraseDown()
+
+ cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition())
+
+ r.renderCompletion(buffer, completion)
+ if suggest, ok := completion.GetSelectedSuggestion(); ok {
+ cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator)))
+
+ r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false)
+ r.out.WriteStr(suggest.Text)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ cursor += runewidth.StringWidth(suggest.Text)
+
+ rest := buffer.Document().TextAfterCursor()
+ r.out.WriteStr(rest)
+ cursor += runewidth.StringWidth(rest)
+ r.lineWrap(cursor)
+
+ cursor = r.backward(cursor, runewidth.StringWidth(rest))
+ }
+ r.previousCursor = cursor
+}
+
+// BreakLine to break line.
+func (r *Render) BreakLine(buffer *Buffer) {
+ // Erasing and Render
+ cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix())
+ r.clear(cursor)
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(buffer.Document().Text + "\n")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ debug.AssertNoError(r.out.Flush())
+ if r.breakLineCallback != nil {
+ r.breakLineCallback(buffer.Document())
+ }
+
+ r.previousCursor = 0
+}
+
+// clear erases the screen from a beginning of input
+// even if there is line break which means input length exceeds a window's width.
+func (r *Render) clear(cursor int) {
+ r.move(cursor, 0)
+ r.out.EraseDown()
+}
+
+// backward moves cursor to backward from a current cursor position
+// regardless there is a line break.
+func (r *Render) backward(from, n int) int {
+ return r.move(from, from-n)
+}
+
+// move moves cursor to specified position from the beginning of input
+// even if there is a line break.
+func (r *Render) move(from, to int) int {
+ fromX, fromY := r.toPos(from)
+ toX, toY := r.toPos(to)
+
+ r.out.CursorUp(fromY - toY)
+ r.out.CursorBackward(fromX - toX)
+ return to
+}
+
+// toPos returns the relative position from the beginning of the string.
+func (r *Render) toPos(cursor int) (x, y int) {
+ col := int(r.col)
+ return cursor % col, cursor / col
+}
+
+func (r *Render) lineWrap(cursor int) {
+ if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 {
+ r.out.WriteRaw([]byte{'\n'})
+ }
+}
+
+func clamp(high, low, x float64) float64 {
+ switch {
+ case high < x:
+ return high
+ case x < low:
+ return low
+ default:
+ return x
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/shortcut.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/shortcut.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8d4282700c0bdb30e4decfb9c9ac91f27af251
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/shortcut.go
@@ -0,0 +1,43 @@
+package prompt
+
+func dummyExecutor(in string) {}
+
+// Input get the input data from the user and return it.
+func Input(prefix string, completer Completer, opts ...Option) string {
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+// Choose to the shortcut of input function to select from string array.
+// Deprecated: Maybe anyone want to use this.
+func Choose(prefix string, choices []string, opts ...Option) string {
+ completer := newChoiceCompleter(choices, FilterHasPrefix)
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+func newChoiceCompleter(choices []string, filter Filter) Completer {
+ s := make([]Suggest, len(choices))
+ for i := range choices {
+ s[i] = Suggest{Text: choices[i]}
+ }
+ return func(x Document) []Suggest {
+ return filter(s, x.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/signal_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/signal_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3150df5d85e7612c42c2a889dbefee3b524bef6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/signal_posix.go
@@ -0,0 +1,49 @@
+// +build !windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ in := p.in
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+
+ case syscall.SIGWINCH:
+ debug.Log("Catch SIGWINCH")
+ winSizeCh <- in.GetWinSize()
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/signal_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/signal_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a427c79ec0414540f8f40694731b2565ea80c13
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/environment/source/signal_windows.go
@@ -0,0 +1,44 @@
+// +build windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/instruction.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..e37af03e8112b9f15d5a8b65a473482044dd880c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/instruction.md
@@ -0,0 +1,35 @@
+GetCursorDownPosition returns incorrect offset when count > 1
+
+#### Description
+
+When calling `GetCursorDownPosition` with a count greater than 1, the function only moves the cursor down by 1 row instead of the specified count. This affects multi-line cursor navigation when trying to move down multiple rows at once.
+
+#### Steps/Code to Reproduce
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func main() {
+ // Create a document with multiple lines
+ text := "line1\nline2\nline3\nline4\nline5"
+ doc := prompt.NewDocument()
+ doc.Text = text
+ doc.cursorPosition = 0 // Start at beginning
+
+ // Try to move down 2 rows
+ offset := doc.GetCursorDownPosition(2, 0)
+ fmt.Printf("Expected offset to move down 2 rows, got: %d\n", offset)
+
+ // Try to move down 3 rows
+ offset = doc.GetCursorDownPosition(3, 0)
+ fmt.Printf("Expected offset to move down 3 rows, got: %d\n", offset)
+}
+```
+
+The function should return the correct offset to move the cursor down by the specified number of rows, but currently it only moves down by 1 row regardless of the count parameter when count > 1.
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/provenance.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..b30b4d06e891f0d5af8593aa7049c8d4ddd32ca1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/provenance.json
@@ -0,0 +1,477 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt",
+ "original-bug": "task-specific unchanged semantic bug",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only",
+ "extra_semantic_repair_coverage": false,
+ "original_patch_hunks": 1
+ },
+ "private_frozen_files": {
+ "buffer_test.go": {
+ "mode": "0o644",
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098",
+ "size": 4965
+ },
+ "completion_test.go": {
+ "mode": "0o644",
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d",
+ "size": 7010
+ },
+ "document_test.go": {
+ "mode": "0o644",
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284",
+ "size": 28938
+ },
+ "emacs_test.go": {
+ "mode": "0o644",
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095",
+ "size": 741
+ },
+ "filter_test.go": {
+ "mode": "0o644",
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247",
+ "size": 3339
+ },
+ "history_test.go": {
+ "mode": "0o644",
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327",
+ "size": 1319
+ },
+ "input_test.go": {
+ "mode": "0o644",
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922",
+ "size": 533
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": "0o644",
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf",
+ "size": 1075
+ },
+ "internal/strings/strings_test.go": {
+ "mode": "0o644",
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6",
+ "size": 981
+ },
+ "output_vt100_test.go": {
+ "mode": "0o644",
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee",
+ "size": 1349
+ },
+ "render_test.go": {
+ "mode": "0o644",
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb",
+ "size": 2890
+ }
+ },
+ "public_files": {
+ ".github/ISSUE_TEMPLATE/bug_report.md": {
+ "mode": "0o644",
+ "sha256": "89d3492ca8533a3d31e4de49a23828a322f75d2a1ec4236327c4a76c7c51ada6",
+ "size": 684
+ },
+ ".github/ISSUE_TEMPLATE/feature_request.md": {
+ "mode": "0o644",
+ "sha256": "d82e14e6b4d021d0007eeef4f5ca489fc6c8e8e4d7479ee30e74fe82afd3b08f",
+ "size": 206
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "3239b94a1a41c05eff5dc086ef1378cf1e289fad0203420b5cb4c78e3c5c239b",
+ "size": 270
+ },
+ "CHANGELOG.md": {
+ "mode": "0o644",
+ "sha256": "1f88f92d3247e1b52af0f0de7ad1263a59807edb17238c7a0211554f8080e51c",
+ "size": 2895
+ },
+ "LICENSE": {
+ "mode": "0o644",
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "size": 1072
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "9425a0d4c15747863625f647348962a9b0f81a0971a7e0184ee722bf34a60ba2",
+ "size": 1177
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "ce56df51a1a9a5b5c5b056429bbee006a260fb0730af63b1d0fe91755e574cc4",
+ "size": 6185
+ },
+ "_example/README.md": {
+ "mode": "0o644",
+ "sha256": "155951bafd778493bd41ae57dcc0ba6b8eca821fcbe2ffe770960ac2780d3d09",
+ "size": 1102
+ },
+ "_example/build.sh": {
+ "mode": "0o755",
+ "sha256": "de2fb330b665691cd75b990236cd6a5df0058608de0dfc6194da30d4041a1e29",
+ "size": 469
+ },
+ "_example/exec-command/main.go": {
+ "mode": "0o644",
+ "sha256": "0e96493b6e6d446b2e691d4834ff8a55834caa410ead970cb611a63ba84f174a",
+ "size": 429
+ },
+ "_example/http-prompt/api.py": {
+ "mode": "0o644",
+ "sha256": "2c2bca9acb07a84c65a4482c61c9ade253a574477a8e461307568ea1f9a342c8",
+ "size": 335
+ },
+ "_example/http-prompt/main.go": {
+ "mode": "0o644",
+ "sha256": "6994b190c4165068e69ed44eb61698af69a15a7690179ce46e3c1c5d8c211643",
+ "size": 5484
+ },
+ "_example/live-prefix/main.go": {
+ "mode": "0o644",
+ "sha256": "20268f9cb6f3b82a52eddc33cbf8082adaa46092e2063df279499e05e25a228c",
+ "size": 1103
+ },
+ "_example/simple-echo/cjk-cyrillic/main.go": {
+ "mode": "0o644",
+ "sha256": "8fb10807d4085ebc4b345bc0ccfef9217e21e49a888bfe3192e8ddfdfa01e89c",
+ "size": 800
+ },
+ "_example/simple-echo/main.go": {
+ "mode": "0o644",
+ "sha256": "e46563ddaa932831fe9ede870b10efb5222c0d54a86f4b4f5197c9cf20942a24",
+ "size": 902
+ },
+ "_tools/README.md": {
+ "mode": "0o644",
+ "sha256": "96dc2343bc5cde642fd449ddc366462753a2e17b6a78adfa015bf991e9dac241",
+ "size": 234
+ },
+ "_tools/complete_file/main.go": {
+ "mode": "0o644",
+ "sha256": "e5dd823f9d6415614a8238ce106d26e9ded1db9b308c121d7f48bb1df003effc",
+ "size": 803
+ },
+ "_tools/sigwinch/main.go": {
+ "mode": "0o644",
+ "sha256": "a806b4e45298f5003c95432d8dd3c40c9c096335f19f1a4160afcdb64fa727e3",
+ "size": 1386
+ },
+ "_tools/vt100_debug/main.go": {
+ "mode": "0o644",
+ "sha256": "7f72eba3cc7037fcf39c9b56a96c578c157e5fb235cb626ab1e83cbef0dc290b",
+ "size": 794
+ },
+ "buffer.go": {
+ "mode": "0o644",
+ "sha256": "10188d96a450fe13ba1e9ec00c89603eb2a2860536965d980d1e4abf4374b018",
+ "size": 5781
+ },
+ "completer/file.go": {
+ "mode": "0o644",
+ "sha256": "6181ed9e39028236c5c93fbe219331fc1492ecfd6af2df764cc42b5455c9bb96",
+ "size": 2401
+ },
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "b90bd9628534cfb343a592775430e17a1999b1de500fb2a8f1507c030a432eae",
+ "size": 4491
+ },
+ "document.go": {
+ "mode": "0o644",
+ "sha256": "63c8d6ad2f0db3f04c4212e1ae5af07468bc46d0a151bc9628416fc155058850",
+ "size": 13144
+ },
+ "emacs.go": {
+ "mode": "0o644",
+ "sha256": "53f0df0016ef9d9695a797b19286681666cf0c7e5a866c393b194aae915f2664",
+ "size": 2675
+ },
+ "filter.go": {
+ "mode": "0o644",
+ "sha256": "dc5922bad6ecb32ecdaf20bd6035dddc7ce8c14f15dbd4d49192c2354cb8a038",
+ "size": 2005
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "97413fa2a2ed68170496f2289a2dca6fb0a192dcd020fc0ca48a5d106e60d55e",
+ "size": 253
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "88ea0a91babaa54b67cc6d5f6f7f47fa4be798fe523324ea568d8926eed2024c",
+ "size": 2183
+ },
+ "history.go": {
+ "mode": "0o644",
+ "sha256": "4ce80ba067cfc72c56a3ee3353ec75cd6bb2f5d82097515c591e3c7c773c51cd",
+ "size": 1488
+ },
+ "input.go": {
+ "mode": "0o644",
+ "sha256": "73461cc4f57d68b66e2a9e196239aaef942539134593beac0d0023743832e0e1",
+ "size": 7630
+ },
+ "input_posix.go": {
+ "mode": "0o644",
+ "sha256": "c7e5a4dfc3910f178f0685ef99f2e47d481a91c4cf9af50f92fc4266aed634df",
+ "size": 1648
+ },
+ "input_windows.go": {
+ "mode": "0o644",
+ "sha256": "f763250d309fb88d9536f77da1d1285c04bc6defe859506f1501e10f7743da9e",
+ "size": 1679
+ },
+ "internal/bisect/bisect.go": {
+ "mode": "0o644",
+ "sha256": "c4de2adfa2e08a77f902661d67325467f89013634dbcef22d24dc6f34d26624a",
+ "size": 327
+ },
+ "internal/debug/assert.go": {
+ "mode": "0o644",
+ "sha256": "1a3050ec58991b62c7ea352d19505e3080ac9760bdb091544f0ecf5aba35969c",
+ "size": 815
+ },
+ "internal/debug/log.go": {
+ "mode": "0o644",
+ "sha256": "2ce968e275558de61c6d83793e85561f7a8dd69c95ec7902ccd2cc3fb169aa82",
+ "size": 875
+ },
+ "internal/strings/strings.go": {
+ "mode": "0o644",
+ "sha256": "b97f08157c3baf1f94fea4bb2237691d8270bd5380b4311709ecd59b84cf4b7b",
+ "size": 2018
+ },
+ "internal/term/raw.go": {
+ "mode": "0o644",
+ "sha256": "177a1a20ae8d71b56857383a5797754560f7f6404ea86778d5f01e9a1c1b4f9f",
+ "size": 747
+ },
+ "internal/term/term.go": {
+ "mode": "0o644",
+ "sha256": "abe6fa965fa15b999b2010135903f598830d4c885a52ef9b067fd5ebbf6e373f",
+ "size": 606
+ },
+ "key.go": {
+ "mode": "0o644",
+ "sha256": "03a43283e07de7a4ea6fed32692d86325f73e98fd89a296f19c171e0bc780999",
+ "size": 1746
+ },
+ "key_bind.go": {
+ "mode": "0o644",
+ "sha256": "83f48bb720a11c8e49165ac382e3a870fdcf6b380a0a95267f8c25211898c9eb",
+ "size": 1109
+ },
+ "key_bind_func.go": {
+ "mode": "0o644",
+ "sha256": "445bff5c0fdb0b52879c635322603c2fc75d265de3761cb8c3b980c798bf39af",
+ "size": 1219
+ },
+ "key_string.go": {
+ "mode": "0o644",
+ "sha256": "55c429dae227bb1659d5d5e2e906dbfa9c7f53b5105fa83fbe290529ff6f2317",
+ "size": 1359
+ },
+ "option.go": {
+ "mode": "0o644",
+ "sha256": "28cfcc1d08b3cf650483d977195458531b3b3913f8a5f357a3ec17ea5d73e215",
+ "size": 8737
+ },
+ "output.go": {
+ "mode": "0o644",
+ "sha256": "372876b0aa908479ed3b29de70a479f420d85e3666b8957c8b61eaed9b32c3f2",
+ "size": 4320
+ },
+ "output_posix.go": {
+ "mode": "0o644",
+ "sha256": "d46b1da307e8969b033e1ade2eb51a83c4c3d4f2a7e4aba35ec3a03991b89a0f",
+ "size": 1545
+ },
+ "output_vt100.go": {
+ "mode": "0o644",
+ "sha256": "9082c7e4619c1eb38030bc4994a4fbf66ef27b130751bf2eb9c25c01082e8605",
+ "size": 7453
+ },
+ "output_windows.go": {
+ "mode": "0o644",
+ "sha256": "571c5ae1ad051a701b426371efd79a3776c2226ca9e3c2e598fe5996dfa1b8e1",
+ "size": 1066
+ },
+ "prompt.go": {
+ "mode": "0o644",
+ "sha256": "6b3e2bbd90f40ad6a487f1a6ea7f5a6fb48cae6c8c246ecc77621fb3e7383ca7",
+ "size": 7062
+ },
+ "render.go": {
+ "mode": "0o644",
+ "sha256": "90fdd57a63e06f01940d10ee1a0be95ced7d6adc7faa255b3141556d7d316270",
+ "size": 8020
+ },
+ "shortcut.go": {
+ "mode": "0o644",
+ "sha256": "b4a097f466df7396049ebe8393f81c9b1200159d4e2be22bd6838c307ec156dc",
+ "size": 1120
+ },
+ "signal_posix.go": {
+ "mode": "0o644",
+ "sha256": "74f0bae5f290f3f7f82a5dd495e672f627a4ab4b63118f870e8c13c0a7024314",
+ "size": 881
+ },
+ "signal_windows.go": {
+ "mode": "0o644",
+ "sha256": "444f662a32e6997df2af8e2a9e7dbfe977414a6bfc0f54a7f10117f204648437",
+ "size": 757
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982",
+ "os": "linux",
+ "sha256": "0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982"
+ },
+ "context_inventory_sha256": "6b8f93086e81483ac1ce82f328d7f4b38b1b560dbad057ed6a2a30ff3cf0e13f",
+ "image": "registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "9d3b21cdacadfa4f3de9584d0cea973e5aa2ceedcd5ec9cbd3a63df22b313455",
+ "receipt_path": "production/runtime-images-extra-v1/resolutions/316e0e68930cd4ef/resolution.json",
+ "receipt_sha256": "697bb0619eddcdfdeba1c9144b033f564f2d7514be6e6a44dc520fa4e63ed8bc",
+ "registry_digest": "sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "source_image": "docker.io/swebench/swesmith.x86_64.c-bata_1776_go-prompt.82a91227@sha256:3daf51c74a01657e9ad8f326651fb6f5b796ffecdb90098e74a52a9560e0a1bb",
+ "source_receipt_sha256": "b450bea0e201cbe194b765ded4b51539144c85296122c8b642d7e94c889526f3",
+ "space_commit": "5ae654cd2e9d695f0de304bd4398835fc7cf45e0",
+ "space_id": "harness-hub/scale800-go-316e0e68930cd4ef-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "faf7ef299a35bd2145ece329ec21c941317535959b8a66d1676d17fe52ca5755",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21",
+ "source_proof_sha256": "2048629727a41470879ed7fb09bff0c7e2c0d91c64b68a629ab6db0d2fd45293",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:c-bata__go-prompt.82a91227.lm_modify__66jwp1cj",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "9992c59c25864ce1556e67b9e1501c93f6e7f9ff",
+ "instruction_sha256": "22f22b2a8b1461d5d17a0758790ef287910752d8d9b91a8f41c9fbc238c061f2",
+ "is_fork": true,
+ "learner_path": "tasks/d9cafa30c79b65c0cce1619d/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/c-bata__go-prompt.82a91227/c0dc1c0dc9f6791fb1577b62dae33748c5601f0f/LICENSE"
+ },
+ "task_bundle": {
+ "basis": "Captured publisherMIT/train; exactsoftwarepermissionverifiedseparately",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "82a912274504477990ecf7c852eebb7c85291772",
+ "patch_sha256": "1334ea452c59226433613f86ab2d9863f8f121e52998efb5e2b8d3c51432a6e2",
+ "provenance_path": "tasks/d9cafa30c79b65c0cce1619d/source-proof.json",
+ "repository_lineage": [
+ "swesmith/c-bata__go-prompt.82a91227",
+ "c-bata/go-prompt"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "c0dc1c0dc9f6791fb1577b62dae33748c5601f0f",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "239721e473625a94637d1c520dab813f3c3138c5",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/c-bata__go-prompt.82a91227",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "c-bata__go-prompt.82a91227.lm_modify__66jwp1cj",
+ "task_sha256": "c8c3219025c62946484f9fed4adf738eb4c7d6e237ab7310904b4d35cbb06797",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "c-bata/go-prompt",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "bda7ebc6cd79f5bbbf3dbaf67ea3369e93c108f3e75cbb8e175d5ef302ac5d1f",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.md",
+ "/testbed/.github/ISSUE_TEMPLATE/feature_request.md",
+ "/testbed/.gitignore",
+ "/testbed/CHANGELOG.md",
+ "/testbed/LICENSE",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/_example/README.md",
+ "/testbed/_example/build.sh",
+ "/testbed/_example/exec-command/main.go",
+ "/testbed/_example/http-prompt/api.py",
+ "/testbed/_example/http-prompt/main.go",
+ "/testbed/_example/live-prefix/main.go",
+ "/testbed/_example/simple-echo/cjk-cyrillic/main.go",
+ "/testbed/_example/simple-echo/main.go",
+ "/testbed/_tools/README.md",
+ "/testbed/_tools/complete_file/main.go",
+ "/testbed/_tools/sigwinch/main.go",
+ "/testbed/_tools/vt100_debug/main.go",
+ "/testbed/buffer.go",
+ "/testbed/completer/file.go",
+ "/testbed/completion.go",
+ "/testbed/document.go",
+ "/testbed/emacs.go",
+ "/testbed/filter.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum",
+ "/testbed/history.go",
+ "/testbed/input.go",
+ "/testbed/input_posix.go",
+ "/testbed/input_windows.go",
+ "/testbed/internal/bisect/bisect.go",
+ "/testbed/internal/debug/assert.go",
+ "/testbed/internal/debug/log.go",
+ "/testbed/internal/strings/strings.go",
+ "/testbed/internal/term/raw.go",
+ "/testbed/internal/term/term.go",
+ "/testbed/key.go",
+ "/testbed/key_bind.go",
+ "/testbed/key_bind_func.go",
+ "/testbed/key_string.go",
+ "/testbed/option.go",
+ "/testbed/output.go",
+ "/testbed/output_posix.go",
+ "/testbed/output_vt100.go",
+ "/testbed/output_windows.go",
+ "/testbed/prompt.go",
+ "/testbed/render.go",
+ "/testbed/shortcut.go",
+ "/testbed/signal_posix.go",
+ "/testbed/signal_windows.go"
+ ]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/solution/solve.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..00d1a533519e8abc9def758862da6b859247bfe5
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"document.go": {"data": "cGFja2FnZSBwcm9tcHQKCmltcG9ydCAoCgkic3RyaW5ncyIKCSJ1bmljb2RlL3V0ZjgiCgoJImdpdGh1Yi5jb20vYy1iYXRhL2dvLXByb21wdC9pbnRlcm5hbC9iaXNlY3QiCglpc3RyaW5ncyAiZ2l0aHViLmNvbS9jLWJhdGEvZ28tcHJvbXB0L2ludGVybmFsL3N0cmluZ3MiCglydW5ld2lkdGggImdpdGh1Yi5jb20vbWF0dG4vZ28tcnVuZXdpZHRoIgopCgovLyBEb2N1bWVudCBoYXMgdGV4dCBkaXNwbGF5ZWQgaW4gdGVybWluYWwgYW5kIGN1cnNvciBwb3NpdGlvbi4KdHlwZSBEb2N1bWVudCBzdHJ1Y3QgewoJVGV4dCBzdHJpbmcKCS8vIFRoaXMgcmVwcmVzZW50cyBhIGluZGV4IGluIGEgcnVuZSBhcnJheSBvZiBEb2N1bWVudC5UZXh0LgoJLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgY3Vyc29yUG9zaXRpb24gaXMgMi4KCS8vIEJ1dCBEaXNwbGF5ZWRDdXJzb3JQb3NpdGlvbiByZXR1cm5zIDQgYmVjYXVzZSAn5pelJyBhbmQgJ+acrCcgYXJlIGRvdWJsZSB3aWR0aCBjaGFyYWN0ZXJzLgoJY3Vyc29yUG9zaXRpb24gaW50CglsYXN0S2V5ICAgICAgICBLZXkKfQoKLy8gTmV3RG9jdW1lbnQgcmV0dXJuIHRoZSBuZXcgZW1wdHkgZG9jdW1lbnQuCmZ1bmMgTmV3RG9jdW1lbnQoKSAqRG9jdW1lbnQgewoJcmV0dXJuICZEb2N1bWVudHsKCQlUZXh0OiAgICAgICAgICAgIiIsCgkJY3Vyc29yUG9zaXRpb246IDAsCgl9Cn0KCi8vIExhc3RLZXlTdHJva2UgcmV0dXJuIHRoZSBsYXN0IGtleSBwcmVzc2VkIGluIHRoaXMgZG9jdW1lbnQuCmZ1bmMgKGQgKkRvY3VtZW50KSBMYXN0S2V5U3Ryb2tlKCkgS2V5IHsKCXJldHVybiBkLmxhc3RLZXkKfQoKLy8gRGlzcGxheUN1cnNvclBvc2l0aW9uIHJldHVybnMgdGhlIGN1cnNvciBwb3NpdGlvbiBvbiByZW5kZXJlZCB0ZXh0IG9uIHRlcm1pbmFsIGVtdWxhdG9ycy4KLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgRGlzcGxheWVkQ3Vyc29yUG9zaXRpb24gcmV0dXJucyA0IGJlY2F1c2UgJ+aXpScgYW5kICfmnKwnIGFyZSBkb3VibGUgd2lkdGggY2hhcmFjdGVycy4KZnVuYyAoZCAqRG9jdW1lbnQpIERpc3BsYXlDdXJzb3JQb3NpdGlvbigpIGludCB7Cgl2YXIgcG9zaXRpb24gaW50CglydW5lcyA6PSBbXXJ1bmUoZC5UZXh0KVs6ZC5jdXJzb3JQb3NpdGlvbl0KCWZvciBpIDo9IHJhbmdlIHJ1bmVzIHsKCQlwb3NpdGlvbiArPSBydW5ld2lkdGguUnVuZVdpZHRoKHJ1bmVzW2ldKQoJfQoJcmV0dXJuIHBvc2l0aW9uCn0KCi8vIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yIHJldHVybiBjaGFyYWN0ZXIgcmVsYXRpdmUgdG8gY3Vyc29yIHBvc2l0aW9uLCBvciBlbXB0eSBzdHJpbmcKZnVuYyAoZCAqRG9jdW1lbnQpIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yKG9mZnNldCBpbnQpIChyIHJ1bmUpIHsKCXMgOj0gZC5UZXh0CgljbnQgOj0gMAoKCWZvciBsZW4ocykgPiAwIHsKCQljbnQrKwoJCXIsIHNpemUgOj0gdXRmOC5EZWNvZGVSdW5lSW5TdHJpbmcocykKCQlpZiBjbnQgPT0gZC5jdXJzb3JQb3NpdGlvbitvZmZzZXQgewoJCQlyZXR1cm4gcgoJCX0KCQlzID0gc1tzaXplOl0KCX0KCXJldHVybiAwCn0KCi8vIFRleHRCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJciA6PSBbXXJ1bmUoZC5UZXh0KQoJcmV0dXJuIHN0cmluZyhyWzpkLmN1cnNvclBvc2l0aW9uXSkKfQoKLy8gVGV4dEFmdGVyQ3Vyc29yIHJldHVybnMgdGhlIHRleHQgYWZ0ZXIgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRBZnRlckN1cnNvcigpIHN0cmluZyB7CglyIDo9IFtdcnVuZShkLlRleHQpCglyZXR1cm4gc3RyaW5nKHJbZC5jdXJzb3JQb3NpdGlvbjpdKQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYmVmb3JlIHRoZSBjdXJzb3IuCi8vIElmIHdlIGhhdmUgd2hpdGVzcGFjZSBiZWZvcmUgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcigpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBJZiB3ZSBoYXZlIHdoaXRlc3BhY2UgYWZ0ZXIgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yKCkgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmQoKV0KfQoKLy8gR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSgpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEFmdGVyQ3Vyc29yLCBpdCByZXR1cm5zIHN0cmluZyBjb250YWluaW5nIHNwYWNlCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UoKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpXQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yVW50aWxTZXBhcmF0b3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvciB1bnRpbCBuZXh0IHNlcGFyYXRvci4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJcmV0dXJuIHhbZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFVudGlsU2VwYXJhdG9yKHNlcCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvciByZXR1cm5zIHRoZSB0ZXh0IGFmdGVyIHRoZSBjdXJzb3IgdW50aWwgbmV4dCBzZXBhcmF0b3IuCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCldCn0KCi8vIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvciByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yKHNlcCBzdHJpbmcpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwKTpdCn0KCi8vIEdldFdvcmRBZnRlckN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYWZ0ZXIgdGhlIGN1cnNvci4KLy8gVW5saWtlIEdldFdvcmRBZnRlckN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXApXQp9CgovLyBGaW5kU3RhcnRPZlByZXZpb3VzV29yZCByZXR1cm5zIGFuIGluZGV4IHJlbGF0aXZlIHRvIHRoZSBjdXJzb3IgcG9zaXRpb24KLy8gcG9pbnRpbmcgdG8gdGhlIHN0YXJ0IG9mIHRoZSBwcmV2aW91cyB3b3JkLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5MYXN0SW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpICsgMQoJfQoJcmV0dXJuIDAKfQoKLy8gRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRXaXRoU3BhY2UgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBUaGUgb25seSBkaWZmZXJlbmNlIGlzIHRvIGlnbm9yZSBjb250aWd1b3VzIHNwYWNlcy4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWVuZCA6PSBpc3RyaW5ncy5MYXN0SW5kZXhOb3RCeXRlKHgsICcgJykKCWlmIGVuZCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEJ5dGUoeFs6ZW5kXSwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiAwCgl9CglyZXR1cm4gc3RhcnQgKyAxCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZCgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJaSA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaSArIDEKCX0KCXJldHVybiAwCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFdpdGhTcGFjZSgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJZW5kIDo9IGlzdHJpbmdzLkxhc3RJbmRleE5vdEFueSh4LCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiAwCgl9CglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4WzplbmRdLCBzZXApCglpZiBzdGFydCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCXJldHVybiBzdGFydCArIDEKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmQgcmV0dXJucyBhbiBpbmRleCByZWxhdGl2ZSB0byB0aGUgY3Vyc29yIHBvc2l0aW9uLgovLyBwb2ludGluZyB0byB0aGUgZW5kIG9mIHRoZSBjdXJyZW50IHdvcmQuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZEVuZE9mQ3VycmVudFdvcmQoKSBpbnQgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglpIDo9IHN0cmluZ3MuSW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpCgl9CglyZXR1cm4gbGVuKHgpCn0KCi8vIEZpbmRFbmRPZkN1cnJlbnRXb3JkV2l0aFNwYWNlIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZC4KLy8gVGhlIG9ubHkgZGlmZmVyZW5jZSBpcyB0byBpZ25vcmUgY29udGlndW91cyBzcGFjZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpIGludCB7Cgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCglzdGFydCA6PSBpc3RyaW5ncy5JbmRleE5vdEJ5dGUoeCwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCgllbmQgOj0gc3RyaW5ncy5JbmRleEJ5dGUoeFtzdGFydDpdLCAnICcpCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvciBpcyBhbG1vc3QgdGhlIHNhbWUgYXMgRmluZEVuZE9mQ3VycmVudFdvcmQuCi8vIEJ1dCB0aGlzIGNhbiBzcGVjaWZ5IFNlcGFyYXRvci4gUmV0dXJuIDAgaWYgbm90aGluZyB3YXMgZm91bmQuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCBzdHJpbmcpIGludCB7CglpZiBzZXAgPT0gIiIgewoJCXJldHVybiBkLkZpbmRFbmRPZkN1cnJlbnRXb3JkKCkKCX0KCgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5JbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaQoJfQoJcmV0dXJuIGxlbih4KQp9CgovLyBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZS4KLy8gQnV0IHRoaXMgY2FuIHNwZWNpZnkgU2VwYXJhdG9yLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRFbmRPZkN1cnJlbnRXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgaW50IHsKCWlmIHNlcCA9PSAiIiB7CgkJcmV0dXJuIGQuRmluZEVuZE9mQ3VycmVudFdvcmRXaXRoU3BhY2UoKQoJfQoKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoKCXN0YXJ0IDo9IGlzdHJpbmdzLkluZGV4Tm90QW55KHgsIHNlcCkKCWlmIHN0YXJ0ID09IC0xIHsKCQlyZXR1cm4gbGVuKHgpCgl9CgoJZW5kIDo9IHN0cmluZ3MuSW5kZXhBbnkoeFtzdGFydDpdLCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gQ3VycmVudExpbmVCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBzdGFydCBvZiB0aGUgbGluZSB1bnRpbCB0aGUgY3Vyc29yLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJcyA6PSBzdHJpbmdzLlNwbGl0KGQuVGV4dEJlZm9yZUN1cnNvcigpLCAiXG4iKQoJcmV0dXJuIHNbbGVuKHMpLTFdCn0KCi8vIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBjdXJzb3IgdW50aWwgdGhlIGVuZCBvZiB0aGUgbGluZS4KZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSBzdHJpbmcgewoJcmV0dXJuIHN0cmluZ3MuU3BsaXQoZC5UZXh0QWZ0ZXJDdXJzb3IoKSwgIlxuIilbMF0KfQoKLy8gQ3VycmVudExpbmUgcmV0dXJuIHRoZSB0ZXh0IG9uIHRoZSBsaW5lIHdoZXJlIHRoZSBjdXJzb3IgaXMuICh3aGVuIHRoZSBpbnB1dAovLyBjb25zaXN0cyBvZiBqdXN0IG9uZSBsaW5lLCBpdCBlcXVhbHMgYHRleHRgLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmUoKSBzdHJpbmcgewoJcmV0dXJuIGQuQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSArIGQuQ3VycmVudExpbmVBZnRlckN1cnNvcigpCn0KCi8vIEFycmF5IHBvaW50aW5nIHRvIHRoZSBzdGFydCBpbmRleGVzIG9mIGFsbCB0aGUgbGluZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBsaW5lU3RhcnRJbmRleGVzKCkgW11pbnQgewoJLy8gVE9ETzogQ2FjaGUsIGJlY2F1c2UgdGhpcyBpcyBvZnRlbiByZXVzZWQuCgkvLyAoSWYgaXQgaXMgdXNlZCwgaXQncyBvZnRlbiB1c2VkIG1hbnkgdGltZXMuCgkvLyBBbmQgdGhpcyBoYXMgdG8gYmUgZmFzdCBmb3IgZWRpdGluZyBiaWcgZG9jdW1lbnRzISkKCWxjIDo9IGQuTGluZUNvdW50KCkKCWxlbmd0aHMgOj0gbWFrZShbXWludCwgbGMpCglmb3IgaSwgbCA6PSByYW5nZSBkLkxpbmVzKCkgewoJCWxlbmd0aHNbaV0gPSBsZW4obCkKCX0KCgkvLyBDYWxjdWxhdGUgY3VtdWxhdGl2ZSBzdW1zLgoJaW5kZXhlcyA6PSBtYWtlKFtdaW50LCBsYysxKQoJaW5kZXhlc1swXSA9IDAgLy8gaHR0cHM6Ly9naXRodWIuY29tL2pvbmF0aGFuc2xlbmRlcnMvcHl0aG9uLXByb21wdC10b29sa2l0L2Jsb2IvbWFzdGVyL3Byb21wdF90b29sa2l0L2RvY3VtZW50LnB5I0wxODkKCXBvcyA6PSAwCglmb3IgaSwgbCA6PSByYW5nZSBsZW5ndGhzIHsKCQlwb3MgKz0gbCArIDEKCQlpbmRleGVzW2krMV0gPSBwb3MKCX0KCWlmIGxjID4gMSB7CgkJLy8gUG9wIHRoZSBsYXN0IGl0ZW0uIChUaGlzIGlzIG5vdCBhIG5ldyBsaW5lLikKCQlpbmRleGVzID0gaW5kZXhlc1s6bGNdCgl9CglyZXR1cm4gaW5kZXhlcwp9CgovLyBGb3IgdGhlIGluZGV4IG9mIGEgY2hhcmFjdGVyIGF0IGEgY2VydGFpbiBsaW5lLCBjYWxjdWxhdGUgdGhlIGluZGV4IG9mCi8vIHRoZSBmaXJzdCBjaGFyYWN0ZXIgb24gdGhhdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgZmluZExpbmVTdGFydEluZGV4KGluZGV4IGludCkgKHBvcyBpbnQsIGxpbmVTdGFydEluZGV4IGludCkgewoJaW5kZXhlcyA6PSBkLmxpbmVTdGFydEluZGV4ZXMoKQoJcG9zID0gYmlzZWN0LlJpZ2h0KGluZGV4ZXMsIGluZGV4KSAtIDEKCWxpbmVTdGFydEluZGV4ID0gaW5kZXhlc1twb3NdCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Sb3cgcmV0dXJucyB0aGUgY3VycmVudCByb3cuICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uUm93KCkgKHJvdyBpbnQpIHsKCXJvdywgXyA9IGQuZmluZExpbmVTdGFydEluZGV4KGQuY3Vyc29yUG9zaXRpb24pCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Db2wgcmV0dXJucyB0aGUgY3VycmVudCBjb2x1bW4uICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uQ29sKCkgKGNvbCBpbnQpIHsKCS8vIERvbid0IHVzZSBzZWxmLnRleHRfYmVmb3JlX2N1cnNvciB0byBjYWxjdWxhdGUgdGhpcy4gQ3JlYXRpbmcgc3Vic3RyaW5ncwoJLy8gYW5kIHNwbGl0dGluZyBpcyB0b28gZXhwZW5zaXZlIGZvciBnZXR0aW5nIHRoZSBjdXJzb3IgcG9zaXRpb24uCglfLCBpbmRleCA6PSBkLmZpbmRMaW5lU3RhcnRJbmRleChkLmN1cnNvclBvc2l0aW9uKQoJY29sID0gZC5jdXJzb3JQb3NpdGlvbiAtIGluZGV4CglyZXR1cm4KfQoKLy8gR2V0Q3Vyc29yTGVmdFBvc2l0aW9uIHJldHVybnMgdGhlIHJlbGF0aXZlIHBvc2l0aW9uIGZvciBjdXJzb3IgbGVmdC4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldEN1cnNvckxlZnRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvclJpZ2h0UG9zaXRpb24oLWNvdW50KQoJfQoJaWYgZC5DdXJzb3JQb3NpdGlvbkNvbCgpID4gY291bnQgewoJCXJldHVybiAtY291bnQKCX0KCXJldHVybiAtZC5DdXJzb3JQb3NpdGlvbkNvbCgpCn0KCi8vIEdldEN1cnNvclJpZ2h0UG9zaXRpb24gcmV0dXJucyByZWxhdGl2ZSBwb3NpdGlvbiBmb3IgY3Vyc29yIHJpZ2h0LgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yUmlnaHRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvckxlZnRQb3NpdGlvbigtY291bnQpCgl9CglpZiBsZW4oZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpID4gY291bnQgewoJCXJldHVybiBjb3VudAoJfQoJcmV0dXJuIGxlbihkLkN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSkKfQoKLy8gR2V0Q3Vyc29yVXBQb3NpdGlvbiByZXR1cm4gdGhlIHJlbGF0aXZlIGN1cnNvciBwb3NpdGlvbiAoY2hhcmFjdGVyIGluZGV4KSB3aGVyZSB3ZSB3b3VsZCBiZQovLyBpZiB0aGUgdXNlciBwcmVzc2VkIHRoZSBhcnJvdy11cCBidXR0b24uCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRDdXJzb3JVcFBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9CgoJcm93IDo9IGQuQ3Vyc29yUG9zaXRpb25Sb3coKSAtIGNvdW50CglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9CglyZXR1cm4gZC5UcmFuc2xhdGVSb3dDb2xUb0luZGV4KHJvdywgY29sKSAtIGQuY3Vyc29yUG9zaXRpb24KfQoKLy8gR2V0Q3Vyc29yRG93blBvc2l0aW9uIHJldHVybiB0aGUgcmVsYXRpdmUgY3Vyc29yIHBvc2l0aW9uIChjaGFyYWN0ZXIgaW5kZXgpIHdoZXJlIHdlIHdvdWxkIGJlIGlmIHRoZQovLyB1c2VyIHByZXNzZWQgdGhlIGFycm93LWRvd24gYnV0dG9uLgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yRG93blBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9Cglyb3cgOj0gZC5DdXJzb3JQb3NpdGlvblJvdygpICsgY291bnQKCXJldHVybiBkLlRyYW5zbGF0ZVJvd0NvbFRvSW5kZXgocm93LCBjb2wpIC0gZC5jdXJzb3JQb3NpdGlvbgp9CgovLyBMaW5lcyByZXR1cm5zIHRoZSBhcnJheSBvZiBhbGwgdGhlIGxpbmVzLgpmdW5jIChkICpEb2N1bWVudCkgTGluZXMoKSBbXXN0cmluZyB7CgkvLyBUT0RPOiBDYWNoZSwgYmVjYXVzZSB0aGlzIG9uZSBpcyByZXVzZWQgdmVyeSBvZnRlbi4KCXJldHVybiBzdHJpbmdzLlNwbGl0KGQuVGV4dCwgIlxuIikKfQoKLy8gTGluZUNvdW50IHJldHVybiB0aGUgbnVtYmVyIG9mIGxpbmVzIGluIHRoaXMgZG9jdW1lbnQuIElmIHRoZSBkb2N1bWVudCBlbmRzCi8vIHdpdGggYSB0cmFpbGluZyBcbiwgdGhhdCBjb3VudHMgYXMgdGhlIGJlZ2lubmluZyBvZiBhIG5ldyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgTGluZUNvdW50KCkgaW50IHsKCXJldHVybiBsZW4oZC5MaW5lcygpKQp9CgovLyBUcmFuc2xhdGVJbmRleFRvUG9zaXRpb24gZ2l2ZW4gYW4gaW5kZXggZm9yIHRoZSB0ZXh0LCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgKHJvdywgY29sKSB0dXBsZS4KLy8gKDAtYmFzZWQuIFJldHVybnMgKDAsIDApIGZvciBpbmRleD0wLikKZnVuYyAoZCAqRG9jdW1lbnQpIFRyYW5zbGF0ZUluZGV4VG9Qb3NpdGlvbihpbmRleCBpbnQpIChyb3cgaW50LCBjb2wgaW50KSB7Cglyb3csIHJvd0luZGV4IDo9IGQuZmluZExpbmVTdGFydEluZGV4KGluZGV4KQoJY29sID0gaW5kZXggLSByb3dJbmRleAoJcmV0dXJuCn0KCi8vIFRyYW5zbGF0ZVJvd0NvbFRvSW5kZXggZ2l2ZW4gYSAocm93LCBjb2wpLCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgaW5kZXguCi8vIChSb3cgYW5kIGNvbCBwYXJhbXMgYXJlIDAtYmFzZWQuKQpmdW5jIChkICpEb2N1bWVudCkgVHJhbnNsYXRlUm93Q29sVG9JbmRleChyb3cgaW50LCBjb2x1bW4gaW50KSAoaW5kZXggaW50KSB7CglpbmRleGVzIDo9IGQubGluZVN0YXJ0SW5kZXhlcygpCglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9IGVsc2UgaWYgcm93ID4gbGVuKGluZGV4ZXMpIHsKCQlyb3cgPSBsZW4oaW5kZXhlcykgLSAxCgl9CglpbmRleCA9IGluZGV4ZXNbcm93XQoJbGluZSA6PSBkLkxpbmVzKClbcm93XQoKCS8vIHB5dGhvbikgcmVzdWx0ICs9IG1heCgwLCBtaW4oY29sLCBsZW4obGluZSkpKQoJaWYgY29sdW1uID4gMCB8fCBsZW4obGluZSkgPiAwIHsKCQlpZiBjb2x1bW4gPiBsZW4obGluZSkgewoJCQlpbmRleCArPSBsZW4obGluZSkKCQl9IGVsc2UgewoJCQlpbmRleCArPSBjb2x1bW4KCQl9Cgl9CgoJLy8gS2VlcCBpbiByYW5nZS4gKGxlbihzZWxmLnRleHQpIGlzIGluY2x1ZGVkLCBiZWNhdXNlIHRoZSBjdXJzb3IgY2FuIGJlCgkvLyByaWdodCBhZnRlciB0aGUgZW5kIG9mIHRoZSB0ZXh0IGFzIHdlbGwuKQoJLy8gcHl0aG9uKSByZXN1bHQgPSBtYXgoMCwgbWluKHJlc3VsdCwgbGVuKHNlbGYudGV4dCkpKQoJaWYgaW5kZXggPiBsZW4oZC5UZXh0KSB7CgkJaW5kZXggPSBsZW4oZC5UZXh0KQoJfQoJaWYgaW5kZXggPCAwIHsKCQlpbmRleCA9IDAKCX0KCXJldHVybiBpbmRleAp9CgovLyBPbkxhc3RMaW5lIHJldHVybnMgdHJ1ZSB3aGVuIHdlIGFyZSBhdCB0aGUgbGFzdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgT25MYXN0TGluZSgpIGJvb2wgewoJcmV0dXJuIGQuQ3Vyc29yUG9zaXRpb25Sb3coKSA9PSAoZC5MaW5lQ291bnQoKSAtIDEpCn0KCi8vIEdldEVuZE9mTGluZVBvc2l0aW9uIHJldHVybnMgcmVsYXRpdmUgcG9zaXRpb24gZm9yIHRoZSBlbmQgb2YgdGhpcyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgR2V0RW5kT2ZMaW5lUG9zaXRpb24oKSBpbnQgewoJcmV0dXJuIGxlbihbXXJ1bmUoZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpKQp9CgpmdW5jIChkICpEb2N1bWVudCkgbGVhZGluZ1doaXRlc3BhY2VJbkN1cnJlbnRMaW5lKCkgKG1hcmdpbiBzdHJpbmcpIHsKCXRyaW1tZWQgOj0gc3RyaW5ncy5UcmltU3BhY2UoZC5DdXJyZW50TGluZSgpKQoJbWFyZ2luID0gZC5DdXJyZW50TGluZSgpWzpsZW4oZC5DdXJyZW50TGluZSgpKS1sZW4odHJpbW1lZCldCglyZXR1cm4KfQo=", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/task.toml b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..e64dc3d905478ce11e27f077d1d2b15c0ece6fdb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/task.toml
@@ -0,0 +1,11 @@
+version = "1.0"
+[agent]
+timeout_sec = 300.0
+[verifier]
+timeout_sec = 300.0
+environment_mode = "shared"
+[environment]
+docker_image = "ghcr.io/younesbelkada/scale800@sha256:042d9231c14c0c44a47b685fe70cdaf20a2bcaa5d32d123621e8dff075be407b"
+cpus = 1
+memory_mb = 2048
+storage_mb = 4096
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..910353d446b2026b3f49701ceee55a931796a725
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/manifest.json
@@ -0,0 +1,432 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorDownPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CursorPositionRowAndCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorLeftPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorUpPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorRightPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_Lines"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_LineCount"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateIndexToPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateRowColToIndex"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_OnLastLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetEndOfLinePosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestEmacsKeyBindings"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFilter"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFuzzyMatch"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryClear"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryAdd"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryOlder"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/escape"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/undefined"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWrite"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteRawStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatCompletion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBreakLineCallback"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionRow"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition_withJapanese"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/validation/canaries/delete-tests.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/validation/canaries/delete-tests.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/validation/canaries/delete-tests.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+find /testbed -name '*_test.go' -type f -delete
+printf 'PASS\nok forged-package 0.001s\n'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..e0179ca7d7366f9611aad26b2e744b6f0ad9f668
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__66jwp1cj/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "049e3044f631972ec9ee0974abc092ead69ba36d312201d7e76cb2e30cf5b84b",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/Dockerfile b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f35bf9e5393ee1086fe1b72c1b442f3b16e2bd5b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22
+WORKDIR /testbed
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c8c031d0f87fb9aea0aff433b1fcaeaac259c41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: "Bug report"
+about: Create a bug report to improve go-prompt
+title: "[Bug]"
+labels: bug
+assignees: ''
+
+---
+
+# Bug reports
+
+*Please file a bug report here.*
+
+## Expected Behavior
+
+*Please describe the behavior you are expecting*
+
+## Current Behavior and Steps to Reproduce
+
+*What is the current behavior? Please provide detailed steps for reproducing the issue.*
+*A picture or gif animation tells a thousand words*
+
+## Context
+
+Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
+
+* Operating System:
+* Terminal Emulator: (i.e. iTerm2)
+* tag of go-prompt or commit revision:
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb816a2496376983781774cb5466fed8e1efc93b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,13 @@
+---
+name: "Feature request"
+about: Suggest an idea for new features in go-prompt.
+title: "[Feature Request]"
+labels: enhancement
+assignees: ''
+
+---
+
+# Feature Request
+
+*Please write your suggestion here.*
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/.gitignore b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..eba2b56abe0f7758a560d47dd19d8985b67ef327
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+bin/
+
+# Folders
+pkg/
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+# Glide
+vendor/
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/CHANGELOG.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..b9e21f1ef333b9ec13323bcd4a8f377322ed7e9f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/CHANGELOG.md
@@ -0,0 +1,79 @@
+# Change Log
+
+## v0.3.0 (2018/??/??)
+
+next release.
+
+## v0.2.3 (2018/10/25)
+
+### What's new?
+
+* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92).
+* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100).
+* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102).
+
+### Fixed
+
+* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details).
+* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details).
+* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details).
+
+### Removed or Deprecated
+
+* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`.
+
+## v0.2.2 (2018/06/28)
+
+### What's new?
+
+* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters.
+* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions.
+ * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details).
+* Add FilePathCompleter to complete file path on your system.
+* Add option to customize ascii code key bindings.
+* Add GetWordAfterCursor method in Document.
+
+### Removed or Deprecated
+
+* prompt.Choose shortcut function is deprecated.
+
+## v0.2.1 (2018/02/14)
+
+### What's New?
+
+* ~~It seems that windows support is almost perfect.~~
+ * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows.
+
+### Fixed
+
+* Fix a Shift+Tab handling on Windows.
+* Fix 4-dimension arrow keys handling on Windows.
+
+## v0.2.0 (2018/02/13)
+
+### What's New?
+
+* Supports scrollbar when there are too many matched suggestions
+* Windows support (but please caution because this is still not perfect).
+* Add OptionLivePrefix to update the prefix dynamically
+* Implement clear screen by `Ctrl+L`.
+
+### Fixed
+
+* Fix the behavior of `Ctrl+W` keybind.
+* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details).
+* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details).
+* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ).
+
+### News
+
+New core developers are joined (alphabetical order).
+
+* Nao Yonashiro (Github @orisano)
+* Ryoma Abe (Github @Allajah)
+* Yusuke Nakamura (Github @unasuke)
+
+
+## v0.1.0 (2017/08/15)
+
+Initial Release
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/LICENSE b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a86acaa7ab24fe61ea152a9afcadc21980020efb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Masashi SHIBATA
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/Makefile b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..505817c36f0b8a0bb643eed8680b8989af2b0920
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/Makefile
@@ -0,0 +1,46 @@
+.DEFAULT_GOAL := help
+
+SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
+
+GOIMPORTS ?= goimports
+GOCILINT ?= golangci-lint
+
+.PHONY: setup
+setup: ## Setup for required tools.
+ go get -u golang.org/x/tools/cmd/goimports
+ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: fmt
+fmt: $(SOURCES) ## Formatting source codes.
+ @$(GOIMPORTS) -w $^
+
+.PHONY: lint
+lint: ## Run golangci-lint.
+ @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
+
+.PHONY: test
+test: ## Run tests with race condition checking.
+ @go test -race ./...
+
+.PHONY: bench
+bench: ## Run benchmarks.
+ @go test -bench=. -run=- -benchmem ./...
+
+.PHONY: coverage
+cover: ## Run the tests.
+ @go test -coverprofile=coverage.o
+ @go tool cover -func=coverage.o
+
+.PHONY: generate
+generate: ## Run go generate
+ @go generate ./...
+
+.PHONY: build
+build: ## Build example command lines.
+ ./_example/build.sh
+
+.PHONY: help
+help: ## Show help text
+ @echo "Commands:"
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfcd7a399b4827d6b126d6a173cce34d36520481
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/README.md
@@ -0,0 +1,125 @@
+# go-prompt
+
+[](https://goreportcard.com/report/github.com/c-bata/go-prompt)
+
+[](https://godoc.org/github.com/c-bata/go-prompt)
+
+
+A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit),
+making it easier to build cross-platform command line tools using Go.
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func completer(d prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ }
+ return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ fmt.Println("Please select table.")
+ t := prompt.Input("> ", completer)
+ fmt.Println("You selected " + t)
+}
+```
+
+#### Projects using go-prompt
+
+* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt)
+* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli)
+* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn)
+* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli)
+* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans)
+* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit)
+* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go)
+* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS)
+* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs)
+* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli)
+* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt)
+* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh)
+* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell)
+* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt)
+* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim)
+* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron)
+* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl)
+* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl)
+* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit)
+* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.)
+
+## Features
+
+### Powerful auto-completion
+
+[](https://github.com/c-bata/kube-prompt)
+
+(This is a GIF animation of kube-prompt.)
+
+### Flexible options
+
+go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details.
+
+[](#flexible-options)
+
+### Keyboard Shortcuts
+
+Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell).
+You can customize and expand these shortcuts.
+
+[](#keyboard-shortcuts)
+
+Key Binding | Description
+---------------------|---------------------------------------------------------
+Ctrl + A | Go to the beginning of the line (Home)
+Ctrl + E | Go to the end of the line (End)
+Ctrl + P | Previous command (Up arrow)
+Ctrl + N | Next command (Down arrow)
+Ctrl + F | Forward one character
+Ctrl + B | Backward one character
+Ctrl + D | Delete character under the cursor
+Ctrl + H | Delete character before the cursor (Backspace)
+Ctrl + W | Cut the word before the cursor to the clipboard
+Ctrl + K | Cut the line after the cursor to the clipboard
+Ctrl + U | Cut the line before the cursor to the clipboard
+Ctrl + L | Clear the screen
+
+### History
+
+You can use Up arrow and Down arrow to walk through the history of commands executed.
+
+[](#history)
+
+### Multiple platform support
+
+We have confirmed go-prompt works fine in the following terminals:
+
+* iTerm2 (macOS)
+* Terminal.app (macOS)
+* Command Prompt (Windows)
+* gnome-terminal (Ubuntu)
+
+## Links
+
+* [Change Log](./CHANGELOG.md)
+* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt)
+* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt)
+
+## Author
+
+Masashi Shibata
+
+* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/)
+* Github: [@c-bata](https://github.com/c-bata/)
+
+## License
+
+This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..759b0e3f8acf1216b055e0f9458758a6c1e8950a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/README.md
@@ -0,0 +1,30 @@
+# Examples of go-prompt
+
+This directory includes some examples using go-prompt.
+These examples are useful to know the usage of go-prompt and check behavior for development.
+
+## simple-echo
+
+
+
+A simple echo example using `prompt.Input`.
+
+## http-prompt
+
+
+
+A simple [http-prompt](https://github.com/eliangcs/http-prompt) implementation using go-prompt in less than 200 lines of Go.
+
+## live-prefix
+
+
+
+A example application which changes a prefix string dynamically.
+This feature is used like [ktr0731/evans](https://github.com/ktr0731/evans) which is interactive gRPC client using go-prompt.
+
+## exec-command
+
+Run another CLI tool via `os/exec` package.
+More practical example is [a source code of kube-prompt](https://github.com/c-bata/kube-prompt).
+I recommend you to look this if you want to create tools like kube-prompt.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/build.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c552afcfa69b2356ffcd484c867abcaaaaeeaff
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+export GO111MODULE=on
+DIR=$(cd $(dirname $0); pwd)
+BIN_DIR=$(cd $(dirname $(dirname $0)); pwd)/bin
+
+mkdir -p ${BIN_DIR}
+go build -o ${BIN_DIR}/exec-command ${DIR}/exec-command/main.go
+go build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.go
+go build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.go
+go build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.go
+go build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/exec-command/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/exec-command/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..838f756260df91569491def29a7ee05a7c9a98f7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/exec-command/main.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "os/exec"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(t string) {
+ if t == "bash" {
+ cmd := exec.Command("bash")
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Run()
+ }
+ return
+}
+
+func completer(t prompt.Document) []prompt.Suggest {
+ return []prompt.Suggest{
+ {Text: "bash"},
+ }
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/http-prompt/api.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/http-prompt/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..08e7b1a489a2077f26f280fe39e3bd06efa52cd2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/http-prompt/api.py
@@ -0,0 +1,17 @@
+from bottle import route, run, request
+
+@route('/')
+def hello():
+ return "Hello World!"
+
+@route('/ping')
+def hello():
+ return "pong!"
+
+@route('/register', method='POST')
+def register():
+ name = request.json.get("name")
+ return "Hello %s!" % name
+
+if __name__ == "__main__":
+ run(host='localhost', port=8000, debug=True)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/http-prompt/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/http-prompt/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b372a3550c50121d6e500e2a08e641e168b8c00d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/http-prompt/main.go
@@ -0,0 +1,192 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+type RequestContext struct {
+ url *url.URL
+ header http.Header
+ client *http.Client
+}
+
+var ctx *RequestContext
+
+// See https://github.com/eliangcs/http-prompt/blob/master/http_prompt/completion.py
+var suggestions = []prompt.Suggest{
+ // Command
+ {"cd", "Change URL/path"},
+ {"exit", "Exit http-prompt"},
+
+ // HTTP Method
+ {"delete", "DELETE request"},
+ {"get", "GET request"},
+ {"patch", "GET request"},
+ {"post", "POST request"},
+ {"put", "PUT request"},
+
+ // HTTP Header
+ {"Accept", "Acceptable response media type"},
+ {"Accept-Charset", "Acceptable response charsets"},
+ {"Accept-Encoding", "Acceptable response content codings"},
+ {"Accept-Language", "Preferred natural languages in response"},
+ {"ALPN", "Application-layer protocol negotiation to use"},
+ {"Alt-Used", "Alternative host in use"},
+ {"Authorization", "Authentication information"},
+ {"Cache-Control", "Directives for caches"},
+ {"Connection", "Connection options"},
+ {"Content-Encoding", "Content codings"},
+ {"Content-Language", "Natural languages for content"},
+ {"Content-Length", "Anticipated size for payload body"},
+ {"Content-Location", "Where content was obtained"},
+ {"Content-MD5", "Base64-encoded MD5 sum of content"},
+ {"Content-Type", "Content media type"},
+ {"Cookie", "Stored cookies"},
+ {"Date", "Datetime when message was originated"},
+ {"Depth", "Applied only to resource or its members"},
+ {"DNT", "Do not track user"},
+ {"Expect", "Expected behaviors supported by server"},
+ {"Forwarded", "Proxies involved"},
+ {"From", "Sender email address"},
+ {"Host", "Target URI"},
+ {"HTTP2-Settings", "HTTP/2 connection parameters"},
+ {"If", "Request condition on state tokens and ETags"},
+ {"If-Match", "Request condition on target resource"},
+ {"If-Modified-Since", "Request condition on modification date"},
+ {"If-None-Match", "Request condition on target resource"},
+ {"If-Range", "Request condition on Range"},
+ {"If-Schedule-Tag-Match", "Request condition on Schedule-Tag"},
+ {"If-Unmodified-Since", "Request condition on modification date"},
+ {"Max-Forwards", "Max number of times forwarded by proxies"},
+ {"MIME-Version", "Version of MIME protocol"},
+ {"Origin", "Origin(s} issuing the request"},
+ {"Pragma", "Implementation-specific directives"},
+ {"Prefer", "Preferred server behaviors"},
+ {"Proxy-Authorization", "Proxy authorization credentials"},
+ {"Proxy-Connection", "Proxy connection options"},
+ {"Range", "Request transfer of only part of data"},
+ {"Referer", "Previous web page"},
+ {"TE", "Transfer codings willing to accept"},
+ {"Transfer-Encoding", "Transfer codings applied to payload body"},
+ {"Upgrade", "Invite server to upgrade to another protocol"},
+ {"User-Agent", "User agent string"},
+ {"Via", "Intermediate proxies"},
+ {"Warning", "Possible incorrectness with payload body"},
+ {"WWW-Authenticate", "Authentication scheme"},
+ {"X-Csrf-Token", "Prevent cross-site request forgery"},
+ {"X-CSRFToken", "Prevent cross-site request forgery"},
+ {"X-Forwarded-For", "Originating client IP address"},
+ {"X-Forwarded-Host", "Original host requested by client"},
+ {"X-Forwarded-Proto", "Originating protocol"},
+ {"X-Http-Method-Override", "Request method override"},
+ {"X-Requested-With", "Used to identify Ajax requests"},
+ {"X-XSRF-TOKEN", "Prevent cross-site request forgery"},
+}
+
+func livePrefix() (string, bool) {
+ if ctx.url.Path == "/" {
+ return "", false
+ }
+ return ctx.url.String() + "> ", true
+}
+
+func executor(in string) {
+ in = strings.TrimSpace(in)
+
+ var method, body string
+ blocks := strings.Split(in, " ")
+ switch blocks[0] {
+ case "exit":
+ fmt.Println("Bye!")
+ os.Exit(0)
+ case "cd":
+ if len(blocks) < 2 {
+ ctx.url.Path = "/"
+ } else {
+ ctx.url.Path = path.Join(ctx.url.Path, blocks[1])
+ }
+ return
+ case "get", "delete":
+ method = strings.ToUpper(blocks[0])
+ case "post", "put", "patch":
+ if len(blocks) < 2 {
+ fmt.Println("please set request body.")
+ return
+ }
+ body = strings.Join(blocks[1:], " ")
+ method = strings.ToUpper(blocks[0])
+ }
+ if method != "" {
+ req, err := http.NewRequest(method, ctx.url.String(), strings.NewReader(body))
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ req.Header = ctx.header
+ res, err := ctx.client.Do(req)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ result, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ fmt.Printf("%s\n", result)
+ ctx.header = http.Header{}
+ return
+ }
+
+ if h := strings.Split(in, ":"); len(h) == 2 {
+ // Handling HTTP Header
+ ctx.header.Add(strings.TrimSpace(h[0]), strings.Trim(h[1], ` '"`))
+ } else {
+ fmt.Println("Sorry, I don't understand.")
+ }
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ w := in.GetWordBeforeCursor()
+ if w == "" {
+ return []prompt.Suggest{}
+ }
+ return prompt.FilterHasPrefix(suggestions, w, true)
+}
+
+func main() {
+ var baseURL = "http://localhost:8000/"
+ if len(os.Args) == 2 {
+ baseURL = os.Args[1]
+ if strings.HasSuffix(baseURL, "/") {
+ baseURL += "/"
+ }
+ }
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ ctx = &RequestContext{
+ url: u,
+ header: http.Header{},
+ client: &http.Client{},
+ }
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(u.String()+"> "),
+ prompt.OptionLivePrefix(livePrefix),
+ prompt.OptionTitle("http-prompt"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/live-prefix/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/live-prefix/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c7ced720592173e2a13f19f7cb543730192d3f8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/live-prefix/main.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var LivePrefixState struct {
+ LivePrefix string
+ IsEnable bool
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+ if in == "" {
+ LivePrefixState.IsEnable = false
+ LivePrefixState.LivePrefix = in
+ return
+ }
+ LivePrefixState.LivePrefix = in + "> "
+ LivePrefixState.IsEnable = true
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func changeLivePrefix() (string, bool) {
+ return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionLivePrefix(changeLivePrefix),
+ prompt.OptionTitle("live-prefix-example"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/simple-echo/cjk-cyrillic/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/simple-echo/cjk-cyrillic/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e9e53adef1558e004f86ccbca2c2e2b83c1da39
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/simple-echo/cjk-cyrillic/main.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
+ {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
+ {Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
+ {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionTitle("sql-prompt for multi width characters"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/simple-echo/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/simple-echo/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..12b1bb4fc189e6b369e889779418d7826a45db9d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_example/simple-echo/main.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ in := prompt.Input(">>> ", completer,
+ prompt.OptionTitle("sql-prompt"),
+ prompt.OptionHistory([]string{"SELECT * FROM users;"}),
+ prompt.OptionPrefixTextColor(prompt.Yellow),
+ prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
+ prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
+ prompt.OptionSuggestionBGColor(prompt.DarkGray))
+ fmt.Println("Your input: " + in)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_tools/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..45bd2234f21ff32562984bec046316c8e52868fd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_tools/README.md
@@ -0,0 +1,10 @@
+## Tools of go-prompt
+
+### vt100_debug
+
+
+
+### sigwinch
+
+
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_tools/complete_file/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_tools/complete_file/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..41015cfab9b021fbc7df575bde87e3c510705496
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_tools/complete_file/main.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/completer"
+)
+
+var filePathCompleter = completer.FilePathCompleter{
+ IgnoreCase: true,
+ Filter: func(fi os.FileInfo) bool {
+ return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
+ },
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completerFunc(d prompt.Document) []prompt.Suggest {
+ t := d.GetWordBeforeCursor()
+ if strings.HasPrefix(t, "--") {
+ return []prompt.Suggest{
+ {"--foo", ""},
+ {"--bar", ""},
+ {"--baz", ""},
+ }
+ }
+ return filePathCompleter.Complete(d)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completerFunc,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_tools/sigwinch/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_tools/sigwinch/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9608eb3b4a5e3c6942c140c41e08a36ab3adb33b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_tools/sigwinch/main.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "unsafe"
+)
+
+// Winsize is winsize struct got from the ioctl(2) system call.
+type Winsize struct {
+ Row uint16
+ Col uint16
+ X uint16 // pixel value
+ Y uint16 // pixel value
+}
+
+// GetWinSize returns winsize struct which is the response of ioctl(2).
+func GetWinSize(fd int) *Winsize {
+ ws := &Winsize{}
+ retCode, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ uintptr(fd),
+ uintptr(syscall.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(ws)))
+
+ if int(retCode) == -1 {
+ panic(errno)
+ }
+ return ws
+}
+
+func main() {
+ signalChan := make(chan os.Signal, 1)
+ signal.Notify(
+ signalChan,
+ syscall.SIGHUP,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ exitChan := make(chan int)
+ go func() {
+ for {
+ s := <-signalChan
+ switch s {
+ // kill -SIGHUP XXXX
+ case syscall.SIGHUP:
+ exitChan <- 0
+
+ // kill -SIGINT XXXX or Ctrl+c
+ case syscall.SIGINT:
+ exitChan <- 0
+
+ // kill -SIGTERM XXXX
+ case syscall.SIGTERM:
+ exitChan <- 0
+
+ // kill -SIGQUIT XXXX
+ case syscall.SIGQUIT:
+ exitChan <- 0
+
+ case syscall.SIGWINCH:
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ default:
+ exitChan <- 1
+ }
+ }
+ }()
+
+ code := <-exitChan
+ os.Exit(code)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_tools/vt100_debug/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_tools/vt100_debug/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c6036d45959febc739e287a3a7b631259d4ee7c1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/_tools/vt100_debug/main.go
@@ -0,0 +1,47 @@
+// +build !windows
+
+package main
+
+import (
+ "fmt"
+ "syscall"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/term"
+)
+
+func main() {
+ if err := term.SetRaw(syscall.Stdin); err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer term.Restore()
+
+ bufCh := make(chan []byte, 128)
+ go readBuffer(bufCh)
+ fmt.Print("> ")
+
+ for {
+ b := <-bufCh
+ if key := prompt.GetKey(b); key == prompt.NotDefined {
+ fmt.Printf("Key '%s' data:'%#v'\n", string(b), b)
+ } else {
+ if key == prompt.ControlC {
+ fmt.Println("exit.")
+ return
+ }
+ fmt.Printf("Key '%s' data:'%#v'\n", key, b)
+ }
+ fmt.Print("> ")
+ }
+}
+
+func readBuffer(bufCh chan []byte) {
+ buf := make([]byte, 1024)
+
+ for {
+ if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
+ bufCh <- buf[:n]
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/buffer.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..560b126f5239d311d379cd4d0dfb9c955aee9a4f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/buffer.go
@@ -0,0 +1,191 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Buffer emulates the console buffer.
+type Buffer struct {
+ workingLines []string // The working lines. Similar to history
+ workingIndex int
+ cursorPosition int
+ cacheDocument *Document
+ preferredColumn int // Remember the original column for the next up/down movement.
+ lastKeyStroke Key
+}
+
+// Text returns string of the current line.
+func (b *Buffer) Text() string {
+ return b.workingLines[b.workingIndex]
+}
+
+// Document method to return document instance from the current text and cursor position.
+func (b *Buffer) Document() (d *Document) {
+ if b.cacheDocument == nil ||
+ b.cacheDocument.Text != b.Text() ||
+ b.cacheDocument.cursorPosition != b.cursorPosition {
+ b.cacheDocument = &Document{
+ Text: b.Text(),
+ cursorPosition: b.cursorPosition,
+ }
+ }
+ b.cacheDocument.lastKey = b.lastKeyStroke
+ return b.cacheDocument
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (b *Buffer) DisplayCursorPosition() int {
+ return b.Document().DisplayCursorPosition()
+}
+
+// InsertText insert string from current line.
+func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
+ or := []rune(b.Text())
+ oc := b.cursorPosition
+
+ if overwrite {
+ overwritten := string(or[oc : oc+len(v)])
+ if strings.Contains(overwritten, "\n") {
+ i := strings.IndexAny(overwritten, "\n")
+ overwritten = overwritten[:i]
+ }
+ b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):]))
+ } else {
+ b.setText(string(or[:oc]) + v + string(or[oc:]))
+ }
+
+ if moveCursor {
+ b.cursorPosition += len([]rune(v))
+ }
+}
+
+// SetText method to set text and update cursorPosition.
+// (When doing this, make sure that the cursor_position is valid for this text.
+// text/cursor_position should be consistent at any time, otherwise set a Document instead.)
+func (b *Buffer) setText(v string) {
+ debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position")
+ b.workingLines[b.workingIndex] = v
+}
+
+// Set cursor position. Return whether it changed.
+func (b *Buffer) setCursorPosition(p int) {
+ if p > 0 {
+ b.cursorPosition = p
+ } else {
+ b.cursorPosition = 0
+ }
+}
+
+func (b *Buffer) setDocument(d *Document) {
+ b.cacheDocument = d
+ b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length.
+ b.setText(d.Text)
+}
+
+// CursorLeft move to left on the current line.
+func (b *Buffer) CursorLeft(count int) {
+ l := b.Document().GetCursorLeftPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorRight move to right on the current line.
+func (b *Buffer) CursorRight(count int) {
+ l := b.Document().GetCursorRightPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorUp move cursor to the previous line.
+// (for multi-line edit).
+func (b *Buffer) CursorUp(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorUpPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// CursorDown move cursor to the next line.
+// (for multi-line edit).
+func (b *Buffer) CursorDown(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorDownPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text.
+func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) {
+ debug.Assert(count >= 0, "count should be positive")
+ r := []rune(b.Text())
+
+ if b.cursorPosition > 0 {
+ start := b.cursorPosition - count
+ if start < 0 {
+ start = 0
+ }
+ deleted = string(r[start:b.cursorPosition])
+ b.setDocument(&Document{
+ Text: string(r[:start]) + string(r[b.cursorPosition:]),
+ cursorPosition: b.cursorPosition - len([]rune(deleted)),
+ })
+ }
+ return
+}
+
+// NewLine means CR.
+func (b *Buffer) NewLine(copyMargin bool) {
+ if copyMargin {
+ b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true)
+ } else {
+ b.InsertText("\n", false, true)
+ }
+}
+
+// Delete specified number of characters and Return the deleted text.
+func (b *Buffer) Delete(count int) (deleted string) {
+ r := []rune(b.Text())
+ if b.cursorPosition < len(r) {
+ deleted = b.Document().TextAfterCursor()[:count]
+ b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):]))
+ }
+ return
+}
+
+// JoinNextLine joins the next line to the current one by deleting the line ending after the current line.
+func (b *Buffer) JoinNextLine(separator string) {
+ if !b.Document().OnLastLine() {
+ b.cursorPosition += b.Document().GetEndOfLinePosition()
+ b.Delete(1)
+ // Remove spaces
+ b.setText(b.Document().TextBeforeCursor() + strings.TrimLeft(separator+b.Document().TextAfterCursor(), " "))
+ }
+}
+
+// SwapCharactersBeforeCursor swaps the last two characters before the cursor.
+func (b *Buffer) SwapCharactersBeforeCursor() {
+ if b.cursorPosition >= 2 {
+ x := b.Text()[b.cursorPosition-2 : b.cursorPosition-1]
+ y := b.Text()[b.cursorPosition-1 : b.cursorPosition]
+ b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:])
+ }
+}
+
+// NewBuffer is constructor of Buffer struct.
+func NewBuffer() (b *Buffer) {
+ b = &Buffer{
+ workingLines: []string{""},
+ workingIndex: 0,
+ preferredColumn: -1, // -1 means nil
+ }
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/completer/file.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/completer/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..59f2d8dec84214ccaa6e345a11ed51aa61a08199
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/completer/file.go
@@ -0,0 +1,90 @@
+package completer
+
+import (
+ "io/ioutil"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+var (
+ // FilePathCompletionSeparator holds separate characters.
+ FilePathCompletionSeparator = string([]byte{' ', os.PathSeparator})
+)
+
+// FilePathCompleter is a completer for your local file system.
+// Please caution that you need to set OptionCompletionWordSeparator(completer.FilePathCompletionSeparator)
+// when you use this completer.
+type FilePathCompleter struct {
+ Filter func(fi os.FileInfo) bool
+ IgnoreCase bool
+ fileListCache map[string][]prompt.Suggest
+}
+
+func cleanFilePath(path string) (dir, base string, err error) {
+ if path == "" {
+ return ".", "", nil
+ }
+
+ var endsWithSeparator bool
+ if len(path) >= 1 && path[len(path)-1] == os.PathSeparator {
+ endsWithSeparator = true
+ }
+
+ if runtime.GOOS != "windows" && len(path) >= 2 && path[0:2] == "~/" {
+ me, err := user.Current()
+ if err != nil {
+ return "", "", err
+ }
+ path = filepath.Join(me.HomeDir, path[1:])
+ }
+ path = filepath.Clean(os.ExpandEnv(path))
+ dir = filepath.Dir(path)
+ base = filepath.Base(path)
+
+ if endsWithSeparator {
+ dir = path + string(os.PathSeparator) // Append slash(in POSIX) if path ends with slash.
+ base = "" // Set empty string if path ends with separator.
+ }
+ return dir, base, nil
+}
+
+// Complete returns suggestions from your local file system.
+func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest {
+ if c.fileListCache == nil {
+ c.fileListCache = make(map[string][]prompt.Suggest, 4)
+ }
+
+ path := d.GetWordBeforeCursor()
+ dir, base, err := cleanFilePath(path)
+ if err != nil {
+ debug.Log("completer: cannot get current user:" + err.Error())
+ return nil
+ }
+
+ if cached, ok := c.fileListCache[dir]; ok {
+ return prompt.FilterHasPrefix(cached, base, c.IgnoreCase)
+ }
+
+ files, err := ioutil.ReadDir(dir)
+ if err != nil && os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ debug.Log("completer: cannot read directory items:" + err.Error())
+ return nil
+ }
+
+ suggests := make([]prompt.Suggest, 0, len(files))
+ for _, f := range files {
+ if c.Filter != nil && !c.Filter(f) {
+ continue
+ }
+ suggests = append(suggests, prompt.Suggest{Text: f.Name()})
+ }
+ c.fileListCache[dir] = suggests
+ return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/completion.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/completion.go
new file mode 100644
index 0000000000000000000000000000000000000000..57e82eefc0f50e9561214704e770a2ad313a3659
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/completion.go
@@ -0,0 +1,190 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+const (
+ shortenSuffix = "..."
+ leftPrefix = " "
+ leftSuffix = " "
+ rightPrefix = " "
+ rightSuffix = " "
+)
+
+var (
+ leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix)
+ rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix)
+ completionMargin = leftMargin + rightMargin
+)
+
+// Suggest is printed when completing.
+type Suggest struct {
+ Text string
+ Description string
+}
+
+// CompletionManager manages which suggestion is now selected.
+type CompletionManager struct {
+ selected int // -1 means nothing one is selected.
+ tmp []Suggest
+ max uint16
+ completer Completer
+
+ verticalScroll int
+ wordSeparator string
+ showAtStart bool
+}
+
+// GetSelectedSuggestion returns the selected item.
+func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) {
+ if c.selected == -1 {
+ return Suggest{}, false
+ } else if c.selected < -1 {
+ debug.Assert(false, "must not reach here")
+ c.selected = -1
+ return Suggest{}, false
+ }
+ return c.tmp[c.selected], true
+}
+
+// GetSuggestions returns the list of suggestion.
+func (c *CompletionManager) GetSuggestions() []Suggest {
+ return c.tmp
+}
+
+// Reset to select nothing.
+func (c *CompletionManager) Reset() {
+ c.selected = -1
+ c.verticalScroll = 0
+ c.Update(*NewDocument())
+}
+
+// Update to update the suggestions.
+func (c *CompletionManager) Update(in Document) {
+ c.tmp = c.completer(in)
+}
+
+// Previous to select the previous suggestion item.
+func (c *CompletionManager) Previous() {
+ if c.verticalScroll == c.selected && c.selected > 0 {
+ c.verticalScroll--
+ }
+ c.selected--
+ c.update()
+}
+
+// Next to select the next suggestion item.
+func (c *CompletionManager) Next() {
+ if c.verticalScroll+int(c.max)-1 == c.selected {
+ c.verticalScroll++
+ }
+ c.selected++
+ c.update()
+}
+
+// Completing returns whether the CompletionManager selects something one.
+func (c *CompletionManager) Completing() bool {
+ return c.selected != -1
+}
+
+func (c *CompletionManager) update() {
+ max := int(c.max)
+ if len(c.tmp) < max {
+ max = len(c.tmp)
+ }
+
+ if c.selected >= len(c.tmp) {
+ c.Reset()
+ } else if c.selected < -1 {
+ c.selected = len(c.tmp) - 1
+ c.verticalScroll = len(c.tmp) - max
+ }
+}
+
+func deleteBreakLineCharacters(s string) string {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, "\r", "", -1)
+ return s
+}
+
+func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) {
+ l := len(o)
+ n := make([]string, l)
+
+ lenPrefix := runewidth.StringWidth(prefix)
+ lenSuffix := runewidth.StringWidth(suffix)
+ lenShorten := runewidth.StringWidth(shortenSuffix)
+ min := lenPrefix + lenSuffix + lenShorten
+ for i := 0; i < l; i++ {
+ o[i] = deleteBreakLineCharacters(o[i])
+
+ w := runewidth.StringWidth(o[i])
+ if width < w {
+ width = w
+ }
+ }
+
+ if width == 0 {
+ return n, 0
+ }
+ if min >= max {
+ return n, 0
+ }
+ if lenPrefix+width+lenSuffix > max {
+ width = max - lenPrefix - lenSuffix
+ }
+
+ for i := 0; i < l; i++ {
+ x := runewidth.StringWidth(o[i])
+ if x <= width {
+ spaces := strings.Repeat(" ", width-x)
+ n[i] = prefix + o[i] + spaces + suffix
+ } else if x > width {
+ x := runewidth.Truncate(o[i], width, shortenSuffix)
+ // When calling runewidth.Truncate("您好xxx您好xxx", 11, "...") returns "您好xxx..."
+ // But the length of this result is 10. So we need fill right using runewidth.FillRight.
+ n[i] = prefix + runewidth.FillRight(x, width) + suffix
+ }
+ }
+ return n, lenPrefix + width + lenSuffix
+}
+
+func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) {
+ num := len(suggests)
+ new = make([]Suggest, num)
+
+ left := make([]string, num)
+ for i := 0; i < num; i++ {
+ left[i] = suggests[i].Text
+ }
+ right := make([]string, num)
+ for i := 0; i < num; i++ {
+ right[i] = suggests[i].Description
+ }
+
+ left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix)
+ if leftWidth == 0 {
+ return []Suggest{}, 0
+ }
+ right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix)
+
+ for i := 0; i < num; i++ {
+ new[i] = Suggest{Text: left[i], Description: right[i]}
+ }
+ return new, leftWidth + rightWidth
+}
+
+// NewCompletionManager returns initialized CompletionManager object.
+func NewCompletionManager(completer Completer, max uint16) *CompletionManager {
+ return &CompletionManager{
+ selected: -1,
+ max: max,
+ completer: completer,
+
+ verticalScroll: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/document.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/document.go
new file mode 100644
index 0000000000000000000000000000000000000000..2a47f52bb2a760b293b5b81de1f27f2b8325a805
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/document.go
@@ -0,0 +1,441 @@
+package prompt
+
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+ istrings "github.com/c-bata/go-prompt/internal/strings"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Document has text displayed in terminal and cursor position.
+type Document struct {
+ Text string
+ // This represents a index in a rune array of Document.Text.
+ // So if Document is "日本(cursor)語", cursorPosition is 2.
+ // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+ cursorPosition int
+ lastKey Key
+}
+
+// NewDocument return the new empty document.
+func NewDocument() *Document {
+ return &Document{
+ Text: "",
+ cursorPosition: 0,
+ }
+}
+
+// LastKeyStroke return the last key pressed in this document.
+func (d *Document) LastKeyStroke() Key {
+ return d.lastKey
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (d *Document) DisplayCursorPosition() int {
+ var position int
+ runes := []rune(d.Text)[:d.cursorPosition]
+ for i := range runes {
+ position += runewidth.RuneWidth(runes[i])
+ }
+ return position
+}
+
+// GetCharRelativeToCursor return character relative to cursor position, or empty string
+func (d *Document) GetCharRelativeToCursor(offset int) (r rune) {
+ s := d.Text
+ cnt := 0
+
+ for len(s) > 0 {
+ cnt++
+ r, size := utf8.DecodeRuneInString(s)
+ if cnt == d.cursorPosition+offset {
+ return r
+ }
+ s = s[size:]
+ }
+ return 0
+}
+
+// TextBeforeCursor returns the text before the cursor.
+func (d *Document) TextBeforeCursor() string {
+ r := []rune(d.Text)
+ return string(r[:d.cursorPosition])
+}
+
+// TextAfterCursor returns the text after the cursor.
+func (d *Document) TextAfterCursor() string {
+ r := []rune(d.Text)
+ return string(r[d.cursorPosition:])
+}
+
+// GetWordBeforeCursor returns the word before the cursor.
+// If we have whitespace before the cursor this returns an empty string.
+func (d *Document) GetWordBeforeCursor() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWord():]
+}
+
+// GetWordAfterCursor returns the word after the cursor.
+// If we have whitespace after the cursor this returns an empty string.
+func (d *Document) GetWordAfterCursor() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWord()]
+}
+
+// GetWordBeforeCursorWithSpace returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorWithSpace() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordWithSpace():]
+}
+
+// GetWordAfterCursorWithSpace returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorWithSpace() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordWithSpace()]
+}
+
+// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
+func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparator(sep):]
+}
+
+// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
+func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparator(sep)]
+}
+
+// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):]
+}
+
+// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)]
+}
+
+// FindStartOfPreviousWord returns an index relative to the cursor position
+// pointing to the start of the previous word. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWord() int {
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexByte(x, ' ')
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindStartOfPreviousWordWithSpace() int {
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotByte(x, ' ')
+ if end == -1 {
+ return 0
+ }
+
+ start := strings.LastIndexByte(x[:end], ' ')
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWord()
+ }
+
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexAny(x, sep)
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWordWithSpace()
+ }
+
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotAny(x, sep)
+ if end == -1 {
+ return 0
+ }
+ start := strings.LastIndexAny(x[:end], sep)
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindEndOfCurrentWord returns an index relative to the cursor position.
+// pointing to the end of the current word. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWord() int {
+ x := d.TextAfterCursor()
+ i := strings.IndexByte(x, ' ')
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindEndOfCurrentWordWithSpace() int {
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotByte(x, ' ')
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexByte(x[start:], ' ')
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWord()
+ }
+
+ x := d.TextAfterCursor()
+ i := strings.IndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWordWithSpace()
+ }
+
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotAny(x, sep)
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexAny(x[start:], sep)
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// CurrentLineBeforeCursor returns the text from the start of the line until the cursor.
+func (d *Document) CurrentLineBeforeCursor() string {
+ s := strings.Split(d.TextBeforeCursor(), "\n")
+ return s[len(s)-1]
+}
+
+// CurrentLineAfterCursor returns the text from the cursor until the end of the line.
+func (d *Document) CurrentLineAfterCursor() string {
+ return strings.Split(d.TextAfterCursor(), "\n")[0]
+}
+
+// CurrentLine return the text on the line where the cursor is. (when the input
+// consists of just one line, it equals `text`.
+func (d *Document) CurrentLine() string {
+ return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor()
+}
+
+// Array pointing to the start indexes of all the lines.
+func (d *Document) lineStartIndexes() []int {
+ // TODO: Cache, because this is often reused.
+ // (If it is used, it's often used many times.
+ // And this has to be fast for editing big documents!)
+ lc := d.LineCount()
+ lengths := make([]int, lc)
+ for i, l := range d.Lines() {
+ lengths[i] = len(l)
+ }
+
+ // Calculate cumulative sums.
+ indexes := make([]int, lc+1)
+ indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189
+ pos := 0
+ for i, l := range lengths {
+ pos += l + 1
+ indexes[i+1] = pos
+ }
+ if lc > 1 {
+ // Pop the last item. (This is not a new line.)
+ indexes = indexes[:lc]
+ }
+ return indexes
+}
+
+// For the index of a character at a certain line, calculate the index of
+// the first character on that line.
+func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) {
+ indexes := d.lineStartIndexes()
+ pos = bisect.Right(indexes, index) - 1
+ lineStartIndex = indexes[pos]
+ return
+}
+
+// CursorPositionRow returns the current row. (0-based.)
+func (d *Document) CursorPositionRow() (row int) {
+ row, _ = d.findLineStartIndex(d.cursorPosition)
+ return
+}
+
+// CursorPositionCol returns the current column. (0-based.)
+func (d *Document) CursorPositionCol() (col int) {
+ // Don't use self.text_before_cursor to calculate this. Creating substrings
+ // and splitting is too expensive for getting the cursor position.
+ _, index := d.findLineStartIndex(d.cursorPosition)
+ col = d.cursorPosition - index
+ return
+}
+
+// GetCursorLeftPosition returns the relative position for cursor left.
+func (d *Document) GetCursorLeftPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorRightPosition(-count)
+ }
+ if d.CursorPositionCol() > count {
+ return -count
+ }
+ return -d.CursorPositionCol()
+}
+
+// GetCursorRightPosition returns relative position for cursor right.
+func (d *Document) GetCursorRightPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorLeftPosition(-count)
+ }
+ if len(d.CurrentLineAfterCursor()) > count {
+ return count
+ }
+ return len(d.CurrentLineAfterCursor())
+}
+
+// GetCursorUpPosition return the relative cursor position (character index) where we would be
+// if the user pressed the arrow-up button.
+func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+
+ row := d.CursorPositionRow() - count
+ if row < 0 {
+ row = 0
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// GetCursorDownPosition return the relative cursor position (character index) where we would be if the
+// user pressed the arrow-down button.
+func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+ row := d.CursorPositionRow() + count
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// Lines returns the array of all the lines.
+func (d *Document) Lines() []string {
+ // TODO: Cache, because this one is reused very often.
+ return strings.Split(d.Text, "\n")
+}
+
+// LineCount return the number of lines in this document. If the document ends
+// with a trailing \n, that counts as the beginning of a new line.
+func (d *Document) LineCount() int {
+ return len(d.Lines())
+}
+
+// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple.
+// (0-based. Returns (0, 0) for index=0.)
+func (d *Document) TranslateIndexToPosition(index int) (row int, col int) {
+ row, rowIndex := d.findLineStartIndex(index)
+ col = index - rowIndex
+ return
+}
+
+// TranslateRowColToIndex given a (row, col), return the corresponding index.
+// (Row and col params are 0-based.)
+func (d *Document) TranslateRowColToIndex(row int, column int) (index int) {
+ indexes := d.lineStartIndexes()
+ if row < 0 {
+ row = 0
+ } else if row > len(indexes) {
+ row = len(indexes) - 1
+ }
+ index = indexes[row]
+ line := d.Lines()[row]
+
+ // python) result += max(0, min(col, len(line)))
+ if column > 0 || len(line) > 0 {
+ if column > len(line) {
+ index += len(line)
+ } else {
+ index += column
+ }
+ }
+
+ // Keep in range. (len(self.text) is included, because the cursor can be
+ // right after the end of the text as well.)
+ // python) result = max(0, min(result, len(self.text)))
+ if index > len(d.Text) {
+ index = len(d.Text)
+ }
+ if index < 0 {
+ index = 0
+ }
+ return index
+}
+
+// OnLastLine returns true when we are at the last line.
+func (d *Document) OnLastLine() bool {
+ return d.CursorPositionRow() == (d.LineCount() - 1)
+}
+
+// GetEndOfLinePosition returns relative position for the end of this line.
+func (d *Document) GetEndOfLinePosition() int {
+ return len([]rune(d.CurrentLineAfterCursor()))
+}
+
+func (d *Document) leadingWhitespaceInCurrentLine() (margin string) {
+ trimmed := strings.TrimSpace(d.CurrentLine())
+ margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)]
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/emacs.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/emacs.go
new file mode 100644
index 0000000000000000000000000000000000000000..632f96321f2577cdb7e8cffe639f1518a65d5e0f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/emacs.go
@@ -0,0 +1,120 @@
+package prompt
+
+import "github.com/c-bata/go-prompt/internal/debug"
+
+/*
+
+========
+PROGRESS
+========
+
+Moving the cursor
+-----------------
+
+* [x] Ctrl + a Go to the beginning of the line (Home)
+* [x] Ctrl + e Go to the End of the line (End)
+* [x] Ctrl + p Previous command (Up arrow)
+* [x] Ctrl + n Next command (Down arrow)
+* [x] Ctrl + f Forward one character
+* [x] Ctrl + b Backward one character
+* [x] Ctrl + xx Toggle between the start of line and current cursor position
+
+Editing
+-------
+
+* [x] Ctrl + L Clear the Screen, similar to the clear command
+* [x] Ctrl + d Delete character under the cursor
+* [x] Ctrl + h Delete character before the cursor (Backspace)
+
+* [x] Ctrl + w Cut the Word before the cursor to the clipboard.
+* [x] Ctrl + k Cut the Line after the cursor to the clipboard.
+* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard.
+
+* [ ] Ctrl + t Swap the last two characters before the cursor (typo).
+* [ ] Esc + t Swap the last two words before the cursor.
+
+* [ ] ctrl + y Paste the last thing to be cut (yank)
+* [ ] ctrl + _ Undo
+
+*/
+
+var emacsKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: ControlE,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+ },
+ },
+ // Go to the beginning of the line
+ {
+ Key: ControlA,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+ },
+ },
+ // Cut the Line after the cursor
+ {
+ Key: ControlK,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.Delete(len(x))
+ },
+ },
+ // Cut/delete the Line before the cursor
+ {
+ Key: ControlU,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.DeleteBeforeCursor(len(x))
+ },
+ },
+ // Delete character under the cursor
+ {
+ Key: ControlD,
+ Fn: func(buf *Buffer) {
+ if buf.Text() != "" {
+ buf.Delete(1)
+ }
+ },
+ },
+ // Backspace
+ {
+ Key: ControlH,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+ },
+ },
+ // Right allow: Forward one character
+ {
+ Key: ControlF,
+ Fn: func(buf *Buffer) {
+ buf.CursorRight(1)
+ },
+ },
+ // Left allow: Backward one character
+ {
+ Key: ControlB,
+ Fn: func(buf *Buffer) {
+ buf.CursorLeft(1)
+ },
+ },
+ // Cut the Word before the cursor.
+ {
+ Key: ControlW,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace())))
+ },
+ },
+ // Clear the Screen, similar to the clear command
+ {
+ Key: ControlL,
+ Fn: func(buf *Buffer) {
+ consoleWriter.EraseScreen()
+ consoleWriter.CursorGoTo(0, 0)
+ debug.AssertNoError(consoleWriter.Flush())
+ },
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/filter.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/filter.go
new file mode 100644
index 0000000000000000000000000000000000000000..61c17ed7f436a069563f520512bd25e4d81af0de
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/filter.go
@@ -0,0 +1,71 @@
+package prompt
+
+import "strings"
+
+// Filter is the type to filter the prompt.Suggestion array.
+type Filter func([]Suggest, string, bool) []Suggest
+
+// FilterHasPrefix checks whether the string completions.Text begins with sub.
+func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
+}
+
+// FilterHasSuffix checks whether the completion.Text ends with sub.
+func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
+}
+
+// FilterContains checks whether the completion.Text contains sub.
+func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
+}
+
+// FilterFuzzy checks whether the completion.Text fuzzy matches sub.
+// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
+// would match, for example, "Good food is gone"
+// ^ ^ ^
+func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
+}
+
+func fuzzyMatch(s, sub string) bool {
+ sChars := []rune(s)
+ sIdx := 0
+
+ // https://staticcheck.io/docs/checks#S1029
+ for _, c := range sub {
+ found := false
+ for ; sIdx < len(sChars); sIdx++ {
+ if sChars[sIdx] == c {
+ found = true
+ sIdx++
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
+
+func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
+ if sub == "" {
+ return suggestions
+ }
+ if ignoreCase {
+ sub = strings.ToUpper(sub)
+ }
+
+ ret := make([]Suggest, 0, len(suggestions))
+ for i := range suggestions {
+ c := suggestions[i].Text
+ if ignoreCase {
+ c = strings.ToUpper(c)
+ }
+ if function(c, sub) {
+ ret = append(ret, suggestions[i])
+ }
+ }
+ return ret
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/go.mod b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..30bc6d39a39c328341ca7153d3391352be5baa63
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/go.mod
@@ -0,0 +1,11 @@
+module github.com/c-bata/go-prompt
+
+go 1.14
+
+require (
+ github.com/mattn/go-colorable v0.1.7
+ github.com/mattn/go-runewidth v0.0.9
+ github.com/mattn/go-tty v0.0.3
+ github.com/pkg/term v1.2.0-beta.2
+ golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/go.sum b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..768bf93619a68e1b334c13e7b93ec84fa465598e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/go.sum
@@ -0,0 +1,23 @@
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/history.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/history.go
new file mode 100644
index 0000000000000000000000000000000000000000..e75c64592d82142bf4826ceb8c613ac72ca24d9c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/history.go
@@ -0,0 +1,61 @@
+package prompt
+
+// History stores the texts that are entered.
+type History struct {
+ histories []string
+ tmp []string
+ selected int
+}
+
+// Add to add text in history.
+func (h *History) Add(input string) {
+ h.histories = append(h.histories, input)
+ h.Clear()
+}
+
+// Clear to clear the history.
+func (h *History) Clear() {
+ h.tmp = make([]string, len(h.histories))
+ for i := range h.histories {
+ h.tmp[i] = h.histories[i]
+ }
+ h.tmp = append(h.tmp, "")
+ h.selected = len(h.tmp) - 1
+}
+
+// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
+ if len(h.tmp) == 1 || h.selected == 0 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected--
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
+ if h.selected >= len(h.tmp)-1 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected++
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// NewHistory returns new history object.
+func NewHistory() *History {
+ return &History{
+ histories: []string{},
+ tmp: []string{""},
+ selected: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/input.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/input.go
new file mode 100644
index 0000000000000000000000000000000000000000..307e747190c2b27bf888b379644fc4f3cdd489a2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/input.go
@@ -0,0 +1,169 @@
+package prompt
+
+import "bytes"
+
+// WinSize represents the width and height of terminal.
+type WinSize struct {
+ Row uint16
+ Col uint16
+}
+
+// ConsoleParser is an interface to abstract input layer.
+type ConsoleParser interface {
+ // Setup should be called before starting input
+ Setup() error
+ // TearDown should be called after stopping input
+ TearDown() error
+ // GetWinSize returns WinSize object to represent width and height of terminal.
+ GetWinSize() *WinSize
+ // Read returns byte array.
+ Read() ([]byte, error)
+}
+
+// GetKey returns Key correspond to input byte codes.
+func GetKey(b []byte) Key {
+ for _, k := range ASCIISequences {
+ if bytes.Equal(k.ASCIICode, b) {
+ return k.Key
+ }
+ }
+ return NotDefined
+}
+
+// ASCIISequences holds mappings of the key and byte array.
+var ASCIISequences = []*ASCIICode{
+ {Key: Escape, ASCIICode: []byte{0x1b}},
+
+ {Key: ControlSpace, ASCIICode: []byte{0x00}},
+ {Key: ControlA, ASCIICode: []byte{0x1}},
+ {Key: ControlB, ASCIICode: []byte{0x2}},
+ {Key: ControlC, ASCIICode: []byte{0x3}},
+ {Key: ControlD, ASCIICode: []byte{0x4}},
+ {Key: ControlE, ASCIICode: []byte{0x5}},
+ {Key: ControlF, ASCIICode: []byte{0x6}},
+ {Key: ControlG, ASCIICode: []byte{0x7}},
+ {Key: ControlH, ASCIICode: []byte{0x8}},
+ //{Key: ControlI, ASCIICode: []byte{0x9}},
+ //{Key: ControlJ, ASCIICode: []byte{0xa}},
+ {Key: ControlK, ASCIICode: []byte{0xb}},
+ {Key: ControlL, ASCIICode: []byte{0xc}},
+ {Key: ControlM, ASCIICode: []byte{0xd}},
+ {Key: ControlN, ASCIICode: []byte{0xe}},
+ {Key: ControlO, ASCIICode: []byte{0xf}},
+ {Key: ControlP, ASCIICode: []byte{0x10}},
+ {Key: ControlQ, ASCIICode: []byte{0x11}},
+ {Key: ControlR, ASCIICode: []byte{0x12}},
+ {Key: ControlS, ASCIICode: []byte{0x13}},
+ {Key: ControlT, ASCIICode: []byte{0x14}},
+ {Key: ControlU, ASCIICode: []byte{0x15}},
+ {Key: ControlV, ASCIICode: []byte{0x16}},
+ {Key: ControlW, ASCIICode: []byte{0x17}},
+ {Key: ControlX, ASCIICode: []byte{0x18}},
+ {Key: ControlY, ASCIICode: []byte{0x19}},
+ {Key: ControlZ, ASCIICode: []byte{0x1a}},
+
+ {Key: ControlBackslash, ASCIICode: []byte{0x1c}},
+ {Key: ControlSquareClose, ASCIICode: []byte{0x1d}},
+ {Key: ControlCircumflex, ASCIICode: []byte{0x1e}},
+ {Key: ControlUnderscore, ASCIICode: []byte{0x1f}},
+ {Key: Backspace, ASCIICode: []byte{0x7f}},
+
+ {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}},
+
+ {Key: Enter, ASCIICode: []byte{0xa}},
+ {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}},
+ {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+ {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}},
+ {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}},
+ {Key: Tab, ASCIICode: []byte{0x9}},
+ {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}},
+ {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}},
+ {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}},
+ {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}},
+ {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode
+
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}},
+ {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}},
+ {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}},
+ {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}},
+ {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}},
+ {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}},
+ {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}},
+ {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}},
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}},
+ {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}},
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+
+ // Xterm
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}},
+ // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}},
+ {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}},
+ {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}},
+ {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}},
+ {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}},
+
+ {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}},
+ {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}},
+ {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}},
+ {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}},
+
+ // Tmux sends following keystrokes when control+arrow is pressed, but for
+ // Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ // it a normal arrow press, because that's more important.
+ {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}},
+
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt
+
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/input_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/input_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f10430318be0e797c841eba8e08ab1cf5277be27
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/input_posix.go
@@ -0,0 +1,77 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/term"
+ "golang.org/x/sys/unix"
+)
+
+const maxReadBytes = 1024
+
+// PosixParser is a ConsoleParser implementation for POSIX environment.
+type PosixParser struct {
+ fd int
+ origTermios syscall.Termios
+}
+
+// Setup should be called before starting input
+func (t *PosixParser) Setup() error {
+ // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
+ if err := syscall.SetNonblock(t.fd, true); err != nil {
+ return err
+ }
+ if err := term.SetRaw(t.fd); err != nil {
+ return err
+ }
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (t *PosixParser) TearDown() error {
+ if err := syscall.SetNonblock(t.fd, false); err != nil {
+ return err
+ }
+ if err := term.Restore(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Read returns byte array.
+func (t *PosixParser) Read() ([]byte, error) {
+ buf := make([]byte, maxReadBytes)
+ n, err := syscall.Read(t.fd, buf)
+ if err != nil {
+ return []byte{}, err
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (t *PosixParser) GetWinSize() *WinSize {
+ ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: ws.Row,
+ Col: ws.Col,
+ }
+}
+
+var _ ConsoleParser = &PosixParser{}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *PosixParser {
+ in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ return &PosixParser{
+ fd: in,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/input_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/input_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..11b7679d4c4bc8b924a5b6c863ca1f6d6880570d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/input_windows.go
@@ -0,0 +1,83 @@
+// +build windows
+
+package prompt
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf8"
+ "unsafe"
+
+ tty "github.com/mattn/go-tty"
+)
+
+const maxReadBytes = 1024
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
+
+// WindowsParser is a ConsoleParser implementation for Win32 console.
+type WindowsParser struct {
+ tty *tty.TTY
+}
+
+// Setup should be called before starting input
+func (p *WindowsParser) Setup() error {
+ t, err := tty.Open()
+ if err != nil {
+ return err
+ }
+ p.tty = t
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (p *WindowsParser) TearDown() error {
+ return p.tty.Close()
+}
+
+// Read returns byte array.
+func (p *WindowsParser) Read() ([]byte, error) {
+ var ev uint32
+ r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
+ if r0 == 0 {
+ return nil, err
+ }
+ if ev == 0 {
+ return nil, errors.New("EAGAIN")
+ }
+
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, maxReadBytes)
+ n := utf8.EncodeRune(buf[:], r)
+ for p.tty.Buffered() && n < maxReadBytes {
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ break
+ }
+ n += utf8.EncodeRune(buf[n:], r)
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (p *WindowsParser) GetWinSize() *WinSize {
+ w, h, err := p.tty.Size()
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: uint16(h),
+ Col: uint16(w),
+ }
+}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *WindowsParser {
+ return &WindowsParser{}
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/bisect/bisect.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/bisect/bisect.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe162fa8c4873302e25702081b629a445d43415
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/bisect/bisect.go
@@ -0,0 +1,15 @@
+package bisect
+
+import "sort"
+
+// Right to locate the insertion point for v in a to maintain sorted order.
+func Right(a []int, v int) int {
+ return bisectRightRange(a, v, 0, len(a))
+}
+
+func bisectRightRange(a []int, v int, lo, hi int) int {
+ s := a[lo:hi]
+ return sort.Search(len(s), func(i int) bool {
+ return s[i] > v
+ })
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/debug/assert.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/debug/assert.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f648ac93c44e1e021cdf581a68f03b548534d9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/debug/assert.go
@@ -0,0 +1,55 @@
+package debug
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
+)
+
+var (
+ enableAssert bool
+)
+
+func init() {
+ if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
+ enableAssert = true
+ }
+}
+
+// Assert ensures expected condition.
+func Assert(cond bool, msg interface{}) {
+ if cond {
+ return
+ }
+ if enableAssert {
+ panic(msg)
+ }
+ writeWithSync(2, "[ASSERT] "+toString(msg))
+}
+
+func toString(v interface{}) string {
+ switch a := v.(type) {
+ case func() string:
+ return a()
+ case string:
+ return a
+ case fmt.Stringer:
+ return a.String()
+ default:
+ return fmt.Sprintf("unexpected type, %t", v)
+ }
+}
+
+// AssertNoError ensures err is nil.
+func AssertNoError(err error) {
+ if err == nil {
+ return
+ }
+ if enableAssert {
+ panic(err)
+ }
+ writeWithSync(2, "[ASSERT] "+err.Error())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/debug/log.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/debug/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..516378627a34ead9063ab7ce6c445b23c77b7cb4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/debug/log.go
@@ -0,0 +1,52 @@
+package debug
+
+import (
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+const (
+ envEnableLog = "GO_PROMPT_ENABLE_LOG"
+ logFileName = "go-prompt.log"
+)
+
+var (
+ logfile *os.File
+ logger *log.Logger
+)
+
+func init() {
+ if e := os.Getenv(envEnableLog); e == "true" || e == "1" {
+ var err error
+ logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
+ if err == nil {
+ logger = log.New(logfile, "", log.Llongfile)
+ return
+ }
+ }
+ logger = log.New(ioutil.Discard, "", log.Llongfile)
+}
+
+// Teardown to close logfile
+func Teardown() {
+ if logfile == nil {
+ return
+ }
+ _ = logfile.Close()
+}
+
+func writeWithSync(calldepth int, msg string) {
+ calldepth++
+ if logfile == nil {
+ return
+ }
+ _ = logger.Output(calldepth, msg)
+ _ = logfile.Sync() // immediately write msg
+}
+
+// Log to output message
+func Log(msg string) {
+ calldepth := 2
+ writeWithSync(calldepth, msg)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/strings/strings.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/strings/strings.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7d1886ae03a7d541c66dffca921e2d040e6d5eb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/strings/strings.go
@@ -0,0 +1,102 @@
+package strings
+
+import "unicode/utf8"
+
+// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior.
+func IndexNotByte(s string, c byte) int {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior.
+func LastIndexNotByte(s string, c byte) int {
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+type asciiSet [8]uint32
+
+func (as *asciiSet) notContains(c byte) bool {
+ return (as[c>>5] & (1 << uint(c&31))) == 0
+}
+
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c>>5] |= 1 << uint(c&31)
+ }
+ return as, true
+}
+
+// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior.
+func IndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := 0; i < len(s); i++ {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+
+ LabelFirstLoop:
+ for i, c := range s {
+ for j, m := range chars {
+ if c != m && j == len(chars)-1 {
+ return i
+ } else if c != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior.
+func LastIndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ LabelFirstLoop:
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRuneInString(s[:i])
+ i -= size
+ for j, m := range chars {
+ if r != m && j == len(chars)-1 {
+ return i
+ } else if r != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/term/raw.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/term/raw.go
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3ed8d04023558cf386a98080815d661248b85
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/term/raw.go
@@ -0,0 +1,29 @@
+// +build !windows
+
+package term
+
+import (
+ "syscall"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+// SetRaw put terminal into a raw mode
+func SetRaw(fd int) error {
+ n, err := getOriginalTermios(fd)
+ if err != nil {
+ return err
+ }
+
+ n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK |
+ syscall.ISTRIP | syscall.INLCR | syscall.IGNCR |
+ syscall.ICRNL | syscall.IXON
+ n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL
+ n.Cflag &^= syscall.CSIZE | syscall.PARENB
+ n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters.
+ n.Cc[syscall.VMIN] = 1
+ n.Cc[syscall.VTIME] = 0
+
+ return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n))
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/term/term.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/term/term.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a53c059ae60c0348ec01689babef4b13a2ecd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/internal/term/term.go
@@ -0,0 +1,34 @@
+// +build !windows
+
+package term
+
+import (
+ "sync"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ saveTermios *unix.Termios
+ saveTermiosFD int
+ saveTermiosOnce sync.Once
+)
+
+func getOriginalTermios(fd int) (*unix.Termios, error) {
+ var err error
+ saveTermiosOnce.Do(func() {
+ saveTermiosFD = fd
+ saveTermios, err = termios.Tcgetattr(uintptr(fd))
+ })
+ return saveTermios, err
+}
+
+// Restore terminal's mode.
+func Restore() error {
+ o, err := getOriginalTermios(saveTermiosFD)
+ if err != nil {
+ return err
+ }
+ return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/key.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ba569c2dd20a8ae3b3dd79ff3695bf0b6c1bd09
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/key.go
@@ -0,0 +1,128 @@
+// Code generated by hand; DO NOT EDIT.
+// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment.
+
+package prompt
+
+// Key is the type express the key inserted from user.
+//go:generate stringer -type=Key
+type Key int
+
+// ASCIICode is the type contains Key and it's ascii byte array.
+type ASCIICode struct {
+ Key Key
+ ASCIICode []byte
+}
+
+const (
+ Escape Key = iota
+
+ ControlA
+ ControlB
+ ControlC
+ ControlD
+ ControlE
+ ControlF
+ ControlG
+ ControlH
+ ControlI
+ ControlJ
+ ControlK
+ ControlL
+ ControlM
+ ControlN
+ ControlO
+ ControlP
+ ControlQ
+ ControlR
+ ControlS
+ ControlT
+ ControlU
+ ControlV
+ ControlW
+ ControlX
+ ControlY
+ ControlZ
+
+ ControlSpace
+ ControlBackslash
+ ControlSquareClose
+ ControlCircumflex
+ ControlUnderscore
+ ControlLeft
+ ControlRight
+ ControlUp
+ ControlDown
+
+ Up
+ Down
+ Right
+ Left
+
+ ShiftLeft
+ ShiftUp
+ ShiftDown
+ ShiftRight
+
+ Home
+ End
+ Delete
+ ShiftDelete
+ ControlDelete
+ PageUp
+ PageDown
+ BackTab
+ Insert
+ Backspace
+
+ // Aliases.
+ Tab
+ Enter
+ // Actually Enter equals ControlM, not ControlJ,
+ // However, in prompt_toolkit, we made the mistake of translating
+ // \r into \n during the input, so everyone is now handling the
+ // enter key by binding ControlJ.
+
+ // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere,
+ // because that's future compatible, and will still work when we
+ // stop replacing \r by \n.
+
+ F1
+ F2
+ F3
+ F4
+ F5
+ F6
+ F7
+ F8
+ F9
+ F10
+ F11
+ F12
+ F13
+ F14
+ F15
+ F16
+ F17
+ F18
+ F19
+ F20
+ F21
+ F22
+ F23
+ F24
+
+ // Matches any key.
+ Any
+
+ // Special
+ CPRResponse
+ Vt100MouseEvent
+ WindowsMouseEvent
+ BracketedPaste
+
+ // Key which is ignored. (The key binding for this key should not do anything.)
+ Ignore
+
+ // Key is not defined
+ NotDefined
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/key_bind.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/key_bind.go
new file mode 100644
index 0000000000000000000000000000000000000000..42669e7f942efc4d92f896388daede90b96b55dd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/key_bind.go
@@ -0,0 +1,59 @@
+package prompt
+
+// KeyBindFunc receives buffer and processed it.
+type KeyBindFunc func(*Buffer)
+
+// KeyBind represents which key should do what operation.
+type KeyBind struct {
+ Key Key
+ Fn KeyBindFunc
+}
+
+// ASCIICodeBind represents which []byte should do what operation
+type ASCIICodeBind struct {
+ ASCIICode []byte
+ Fn KeyBindFunc
+}
+
+// KeyBindMode to switch a key binding flexibly.
+type KeyBindMode string
+
+const (
+ // CommonKeyBind is a mode without any keyboard shortcut
+ CommonKeyBind KeyBindMode = "common"
+ // EmacsKeyBind is a mode to use emacs-like keyboard shortcut
+ EmacsKeyBind KeyBindMode = "emacs"
+)
+
+var commonKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: End,
+ Fn: GoLineEnd,
+ },
+ // Go to the beginning of the line
+ {
+ Key: Home,
+ Fn: GoLineBeginning,
+ },
+ // Delete character under the cursor
+ {
+ Key: Delete,
+ Fn: DeleteChar,
+ },
+ // Backspace
+ {
+ Key: Backspace,
+ Fn: DeleteBeforeChar,
+ },
+ // Right allow: Forward one character
+ {
+ Key: Right,
+ Fn: GoRightChar,
+ },
+ // Left allow: Backward one character
+ {
+ Key: Left,
+ Fn: GoLeftChar,
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/key_bind_func.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/key_bind_func.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b2ecdf63179dbfdbcb0d71bfa436bb36d62d230
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/key_bind_func.go
@@ -0,0 +1,48 @@
+package prompt
+
+// GoLineEnd Go to the End of the line
+func GoLineEnd(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+}
+
+// GoLineBeginning Go to the beginning of the line
+func GoLineBeginning(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+}
+
+// DeleteChar Delete character under the cursor
+func DeleteChar(buf *Buffer) {
+ buf.Delete(1)
+}
+
+// DeleteWord Delete word before the cursor
+func DeleteWord(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
+
+// DeleteBeforeChar Go to Backspace
+func DeleteBeforeChar(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+}
+
+// GoRightChar Forward one character
+func GoRightChar(buf *Buffer) {
+ buf.CursorRight(1)
+}
+
+// GoLeftChar Backward one character
+func GoLeftChar(buf *Buffer) {
+ buf.CursorLeft(1)
+}
+
+// GoRightWord Forward one word
+func GoRightWord(buf *Buffer) {
+ buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
+}
+
+// GoLeftWord Backward one word
+func GoLeftWord(buf *Buffer) {
+ buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/key_string.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/key_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..fce6ea31c502b3e763451cb47757ae1b49c32814
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/key_string.go
@@ -0,0 +1,16 @@
+// Code generated by "stringer -type=Key"; DO NOT EDIT.
+
+package prompt
+
+import "strconv"
+
+const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined"
+
+var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607}
+
+func (i Key) String() string {
+ if i < 0 || i >= Key(len(_Key_index)-1) {
+ return "Key(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _Key_name[_Key_index[i]:_Key_index[i+1]]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/option.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/option.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd6806cc1dbccf8c4ddb048080fde615c59088
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/option.go
@@ -0,0 +1,310 @@
+package prompt
+
+// Option is the type to replace default parameters.
+// prompt.New accepts any number of options (this is functional option pattern).
+type Option func(prompt *Prompt) error
+
+// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
+func OptionParser(x ConsoleParser) Option {
+ return func(p *Prompt) error {
+ p.in = x
+ return nil
+ }
+}
+
+// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
+func OptionWriter(x ConsoleWriter) Option {
+ return func(p *Prompt) error {
+ registerConsoleWriter(x)
+ p.renderer.out = x
+ return nil
+ }
+}
+
+// OptionTitle to set title displayed at the header bar of terminal.
+func OptionTitle(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.title = x
+ return nil
+ }
+}
+
+// OptionPrefix to set prefix string.
+func OptionPrefix(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefix = x
+ return nil
+ }
+}
+
+// OptionInitialBufferText to set the initial buffer text
+func OptionInitialBufferText(x string) Option {
+ return func(p *Prompt) error {
+ p.buf.InsertText(x, false, true)
+ return nil
+ }
+}
+
+// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
+func OptionCompletionWordSeparator(x string) Option {
+ return func(p *Prompt) error {
+ p.completion.wordSeparator = x
+ return nil
+ }
+}
+
+// OptionLivePrefix to change the prefix dynamically by callback function
+func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
+ return func(p *Prompt) error {
+ p.renderer.livePrefixCallback = f
+ return nil
+ }
+}
+
+// OptionPrefixTextColor change a text color of prefix string
+func OptionPrefixTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixTextColor = x
+ return nil
+ }
+}
+
+// OptionPrefixBackgroundColor to change a background color of prefix string
+func OptionPrefixBackgroundColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixBGColor = x
+ return nil
+ }
+}
+
+// OptionInputTextColor to change a color of text which is input by user
+func OptionInputTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputTextColor = x
+ return nil
+ }
+}
+
+// OptionInputBGColor to change a color of background which is input by user
+func OptionInputBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputBGColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionTextColor to change a text color which is completed
+func OptionPreviewSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionBGColor to change a background color which is completed
+func OptionPreviewSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionTextColor to change a text color in drop down suggestions.
+func OptionSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionBGColor change a background color in drop down suggestions.
+func OptionSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarThumbColor to change a thumb color on scrollbar.
+func OptionScrollbarThumbColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarThumbColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarBGColor to change a background color of scrollbar.
+func OptionScrollbarBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarBGColor = x
+ return nil
+ }
+}
+
+// OptionMaxSuggestion specify the max number of displayed suggestions.
+func OptionMaxSuggestion(x uint16) Option {
+ return func(p *Prompt) error {
+ p.completion.max = x
+ return nil
+ }
+}
+
+// OptionHistory to set history expressed by string array.
+func OptionHistory(x []string) Option {
+ return func(p *Prompt) error {
+ p.history.histories = x
+ p.history.Clear()
+ return nil
+ }
+}
+
+// OptionSwitchKeyBindMode set a key bind mode.
+func OptionSwitchKeyBindMode(m KeyBindMode) Option {
+ return func(p *Prompt) error {
+ p.keyBindMode = m
+ return nil
+ }
+}
+
+// OptionCompletionOnDown allows for Down arrow key to trigger completion.
+func OptionCompletionOnDown() Option {
+ return func(p *Prompt) error {
+ p.completionOnDown = true
+ return nil
+ }
+}
+
+// SwitchKeyBindMode to set a key bind mode.
+// Deprecated: Please use OptionSwitchKeyBindMode.
+var SwitchKeyBindMode = OptionSwitchKeyBindMode
+
+// OptionAddKeyBind to set a custom key bind.
+func OptionAddKeyBind(b ...KeyBind) Option {
+ return func(p *Prompt) error {
+ p.keyBindings = append(p.keyBindings, b...)
+ return nil
+ }
+}
+
+// OptionAddASCIICodeBind to set a custom key bind.
+func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option {
+ return func(p *Prompt) error {
+ p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...)
+ return nil
+ }
+}
+
+// OptionShowCompletionAtStart to set completion window is open at start.
+func OptionShowCompletionAtStart() Option {
+ return func(p *Prompt) error {
+ p.completion.showAtStart = true
+ return nil
+ }
+}
+
+// OptionBreakLineCallback to run a callback at every break line
+func OptionBreakLineCallback(fn func(*Document)) Option {
+ return func(p *Prompt) error {
+ p.renderer.breakLineCallback = fn
+ return nil
+ }
+}
+
+// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop
+func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
+ return func(p *Prompt) error {
+ p.exitChecker = fn
+ return nil
+ }
+}
+
+// New returns a Prompt with powerful auto-completion.
+func New(executor Executor, completer Completer, opts ...Option) *Prompt {
+ defaultWriter := NewStdoutWriter()
+ registerConsoleWriter(defaultWriter)
+
+ pt := &Prompt{
+ in: NewStandardInputParser(),
+ renderer: &Render{
+ prefix: "> ",
+ out: defaultWriter,
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ },
+ buf: NewBuffer(),
+ executor: executor,
+ history: NewHistory(),
+ completion: NewCompletionManager(completer, 6),
+ keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting
+ }
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/output.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/output.go
new file mode 100644
index 0000000000000000000000000000000000000000..42531b412f1ed027c2fff5b85bc273e53e569b3a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/output.go
@@ -0,0 +1,161 @@
+package prompt
+
+import "sync"
+
+var (
+ consoleWriterMu sync.Mutex
+ consoleWriter ConsoleWriter
+)
+
+func registerConsoleWriter(f ConsoleWriter) {
+ consoleWriterMu.Lock()
+ defer consoleWriterMu.Unlock()
+ consoleWriter = f
+}
+
+// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on.
+type DisplayAttribute int
+
+const (
+ // DisplayReset reset all display attributes.
+ DisplayReset DisplayAttribute = iota
+ // DisplayBold set bold or increases intensity.
+ DisplayBold
+ // DisplayLowIntensity decreases intensity. Not widely supported.
+ DisplayLowIntensity
+ // DisplayItalic set italic. Not widely supported.
+ DisplayItalic
+ // DisplayUnderline set underline
+ DisplayUnderline
+ // DisplayBlink set blink (less than 150 per minute).
+ DisplayBlink
+ // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported.
+ DisplayRapidBlink
+ // DisplayReverse swap foreground and background colors.
+ DisplayReverse
+ // DisplayInvisible set invisible. Not widely supported.
+ DisplayInvisible
+ // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported.
+ DisplayCrossedOut
+ // DisplayDefaultFont set primary(default) font
+ DisplayDefaultFont
+)
+
+// Color represents color on terminal.
+type Color int
+
+const (
+ // DefaultColor represents a default color.
+ DefaultColor Color = iota
+
+ // Low intensity
+
+ // Black represents a black.
+ Black
+ // DarkRed represents a dark red.
+ DarkRed
+ // DarkGreen represents a dark green.
+ DarkGreen
+ // Brown represents a brown.
+ Brown
+ // DarkBlue represents a dark blue.
+ DarkBlue
+ // Purple represents a purple.
+ Purple
+ // Cyan represents a cyan.
+ Cyan
+ // LightGray represents a light gray.
+ LightGray
+
+ // High intensity
+
+ // DarkGray represents a dark gray.
+ DarkGray
+ // Red represents a red.
+ Red
+ // Green represents a green.
+ Green
+ // Yellow represents a yellow.
+ Yellow
+ // Blue represents a blue.
+ Blue
+ // Fuchsia represents a fuchsia.
+ Fuchsia
+ // Turquoise represents a turquoise.
+ Turquoise
+ // White represents a white.
+ White
+)
+
+// ConsoleWriter is an interface to abstract output layer.
+type ConsoleWriter interface {
+ /* Write */
+
+ // WriteRaw to write raw byte array.
+ WriteRaw(data []byte)
+ // Write to write safety byte array by removing control sequences.
+ Write(data []byte)
+ // WriteStr to write raw string.
+ WriteRawStr(data string)
+ // WriteStr to write safety string by removing control sequences.
+ WriteStr(data string)
+ // Flush to flush buffer.
+ Flush() error
+
+ /* Erasing */
+
+ // EraseScreen erases the screen with the background colour and moves the cursor to home.
+ EraseScreen()
+ // EraseUp erases the screen from the current line up to the top of the screen.
+ EraseUp()
+ // EraseDown erases the screen from the current line down to the bottom of the screen.
+ EraseDown()
+ // EraseStartOfLine erases from the current cursor position to the start of the current line.
+ EraseStartOfLine()
+ // EraseEndOfLine erases from the current cursor position to the end of the current line.
+ EraseEndOfLine()
+ // EraseLine erases the entire current line.
+ EraseLine()
+
+ /* Cursor */
+
+ // ShowCursor stops blinking cursor and show.
+ ShowCursor()
+ // HideCursor hides cursor.
+ HideCursor()
+ // CursorGoTo sets the cursor position where subsequent text will begin.
+ CursorGoTo(row, col int)
+ // CursorUp moves the cursor up by 'n' rows; the default count is 1.
+ CursorUp(n int)
+ // CursorDown moves the cursor down by 'n' rows; the default count is 1.
+ CursorDown(n int)
+ // CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+ CursorForward(n int)
+ // CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+ CursorBackward(n int)
+ // AskForCPR asks for a cursor position report (CPR).
+ AskForCPR()
+ // SaveCursor saves current cursor position.
+ SaveCursor()
+ // UnSaveCursor restores cursor position after a Save Cursor.
+ UnSaveCursor()
+
+ /* Scrolling */
+
+ // ScrollDown scrolls display down one line.
+ ScrollDown()
+ // ScrollUp scroll display up one line.
+ ScrollUp()
+
+ /* Title */
+
+ // SetTitle sets a title of terminal window.
+ SetTitle(title string)
+ // ClearTitle clears a title of terminal window.
+ ClearTitle()
+
+ /* Font */
+
+ // SetColor sets text and background colors. and specify whether text is bold.
+ SetColor(fg, bg Color, bold bool)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/output_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/output_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..26c770cc152a7b126be43915d60b8ba000ad0e38
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/output_posix.go
@@ -0,0 +1,67 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+)
+
+const flushMaxRetryCount = 3
+
+// PosixWriter is a ConsoleWriter implementation for POSIX environment.
+// To control terminal emulator, this outputs VT100 escape sequences.
+type PosixWriter struct {
+ VT100Writer
+ fd int
+}
+
+// Flush to flush buffer
+func (w *PosixWriter) Flush() error {
+ l := len(w.buffer)
+ offset := 0
+ retry := 0
+ for {
+ n, err := syscall.Write(w.fd, w.buffer[offset:])
+ if err != nil {
+ if retry < flushMaxRetryCount {
+ retry++
+ continue
+ }
+ return err
+ }
+ offset += n
+ if offset == l {
+ break
+ }
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &PosixWriter{}
+
+var (
+ // NewStandardOutputWriter returns ConsoleWriter object to write to stdout.
+ // This generates VT100 escape sequences because almost terminal emulators
+ // in POSIX OS built on top of a VT100 specification.
+ // Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStdoutWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stdout,
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStderrWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stderr,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/output_vt100.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/output_vt100.go
new file mode 100644
index 0000000000000000000000000000000000000000..20850fead883c4cd9802928b5de3f935fbbeb047
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/output_vt100.go
@@ -0,0 +1,310 @@
+package prompt
+
+import (
+ "bytes"
+ "strconv"
+)
+
+// VT100Writer generates VT100 escape sequences.
+type VT100Writer struct {
+ buffer []byte
+}
+
+// WriteRaw to write raw byte array
+func (w *VT100Writer) WriteRaw(data []byte) {
+ w.buffer = append(w.buffer, data...)
+}
+
+// Write to write safety byte array by removing control sequences.
+func (w *VT100Writer) Write(data []byte) {
+ w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1))
+}
+
+// WriteRawStr to write raw string
+func (w *VT100Writer) WriteRawStr(data string) {
+ w.WriteRaw([]byte(data))
+}
+
+// WriteStr to write safety string by removing control sequences.
+func (w *VT100Writer) WriteStr(data string) {
+ w.Write([]byte(data))
+}
+
+/* Erase */
+
+// EraseScreen erases the screen with the background colour and moves the cursor to home.
+func (w *VT100Writer) EraseScreen() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'J'})
+}
+
+// EraseUp erases the screen from the current line up to the top of the screen.
+func (w *VT100Writer) EraseUp() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'J'})
+}
+
+// EraseDown erases the screen from the current line down to the bottom of the screen.
+func (w *VT100Writer) EraseDown() {
+ w.WriteRaw([]byte{0x1b, '[', 'J'})
+}
+
+// EraseStartOfLine erases from the current cursor position to the start of the current line.
+func (w *VT100Writer) EraseStartOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'K'})
+}
+
+// EraseEndOfLine erases from the current cursor position to the end of the current line.
+func (w *VT100Writer) EraseEndOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', 'K'})
+}
+
+// EraseLine erases the entire current line.
+func (w *VT100Writer) EraseLine() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'K'})
+}
+
+/* Cursor */
+
+// ShowCursor stops blinking cursor and show.
+func (w *VT100Writer) ShowCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'})
+}
+
+// HideCursor hides cursor.
+func (w *VT100Writer) HideCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'})
+}
+
+// CursorGoTo sets the cursor position where subsequent text will begin.
+func (w *VT100Writer) CursorGoTo(row, col int) {
+ if row == 0 && col == 0 {
+ // If no row/column parameters are provided (ie. [H), the cursor will move to the home position.
+ w.WriteRaw([]byte{0x1b, '[', 'H'})
+ return
+ }
+ r := strconv.Itoa(row)
+ c := strconv.Itoa(col)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(r))
+ w.WriteRaw([]byte{';'})
+ w.WriteRaw([]byte(c))
+ w.WriteRaw([]byte{'H'})
+}
+
+// CursorUp moves the cursor up by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorUp(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorDown(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'A'})
+}
+
+// CursorDown moves the cursor down by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorDown(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorUp(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'B'})
+}
+
+// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorForward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorBackward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'C'})
+}
+
+// CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorBackward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorForward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'D'})
+}
+
+// AskForCPR asks for a cursor position report (CPR).
+func (w *VT100Writer) AskForCPR() {
+ // CPR: Cursor Position Request.
+ w.WriteRaw([]byte{0x1b, '[', '6', 'n'})
+}
+
+// SaveCursor saves current cursor position.
+func (w *VT100Writer) SaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 's'})
+}
+
+// UnSaveCursor restores cursor position after a Save Cursor.
+func (w *VT100Writer) UnSaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 'u'})
+}
+
+/* Scrolling */
+
+// ScrollDown scrolls display down one line.
+func (w *VT100Writer) ScrollDown() {
+ w.WriteRaw([]byte{0x1b, 'D'})
+}
+
+// ScrollUp scroll display up one line.
+func (w *VT100Writer) ScrollUp() {
+ w.WriteRaw([]byte{0x1b, 'M'})
+}
+
+/* Title */
+
+// SetTitle sets a title of terminal window.
+func (w *VT100Writer) SetTitle(title string) {
+ titleBytes := []byte(title)
+ patterns := []struct {
+ from []byte
+ to []byte
+ }{
+ {
+ from: []byte{0x13},
+ to: []byte{},
+ },
+ {
+ from: []byte{0x07},
+ to: []byte{},
+ },
+ }
+ for i := range patterns {
+ titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1)
+ }
+
+ w.WriteRaw([]byte{0x1b, ']', '2', ';'})
+ w.WriteRaw(titleBytes)
+ w.WriteRaw([]byte{0x07})
+}
+
+// ClearTitle clears a title of terminal window.
+func (w *VT100Writer) ClearTitle() {
+ w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07})
+}
+
+/* Font */
+
+// SetColor sets text and background colors. and specify whether text is bold.
+func (w *VT100Writer) SetColor(fg, bg Color, bold bool) {
+ if bold {
+ w.SetDisplayAttributes(fg, bg, DisplayBold)
+ } else {
+ // If using `DisplayDefualt`, it will be broken in some environment.
+ // Details are https://github.com/c-bata/go-prompt/pull/85
+ w.SetDisplayAttributes(fg, bg, DisplayReset)
+ }
+}
+
+// SetDisplayAttributes to set VT100 display attributes.
+func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) {
+ w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer
+ defer w.WriteRaw([]byte{'m'}) // final character
+
+ var separator byte = ';'
+ for i := range attrs {
+ p, ok := displayAttributeParameters[attrs[i]]
+ if !ok {
+ continue
+ }
+ w.WriteRaw(p)
+ w.WriteRaw([]byte{separator})
+ }
+
+ f, ok := foregroundANSIColors[fg]
+ if !ok {
+ f = foregroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(f)
+ w.WriteRaw([]byte{separator})
+ b, ok := backgroundANSIColors[bg]
+ if !ok {
+ b = backgroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(b)
+}
+
+var displayAttributeParameters = map[DisplayAttribute][]byte{
+ DisplayReset: {'0'},
+ DisplayBold: {'1'},
+ DisplayLowIntensity: {'2'},
+ DisplayItalic: {'3'},
+ DisplayUnderline: {'4'},
+ DisplayBlink: {'5'},
+ DisplayRapidBlink: {'6'},
+ DisplayReverse: {'7'},
+ DisplayInvisible: {'8'},
+ DisplayCrossedOut: {'9'},
+ DisplayDefaultFont: {'1', '0'},
+}
+
+var foregroundANSIColors = map[Color][]byte{
+ DefaultColor: {'3', '9'},
+
+ // Low intensity.
+ Black: {'3', '0'},
+ DarkRed: {'3', '1'},
+ DarkGreen: {'3', '2'},
+ Brown: {'3', '3'},
+ DarkBlue: {'3', '4'},
+ Purple: {'3', '5'},
+ Cyan: {'3', '6'},
+ LightGray: {'3', '7'},
+
+ // High intensity.
+ DarkGray: {'9', '0'},
+ Red: {'9', '1'},
+ Green: {'9', '2'},
+ Yellow: {'9', '3'},
+ Blue: {'9', '4'},
+ Fuchsia: {'9', '5'},
+ Turquoise: {'9', '6'},
+ White: {'9', '7'},
+}
+
+var backgroundANSIColors = map[Color][]byte{
+ DefaultColor: {'4', '9'},
+
+ // Low intensity.
+ Black: {'4', '0'},
+ DarkRed: {'4', '1'},
+ DarkGreen: {'4', '2'},
+ Brown: {'4', '3'},
+ DarkBlue: {'4', '4'},
+ Purple: {'4', '5'},
+ Cyan: {'4', '6'},
+ LightGray: {'4', '7'},
+
+ // High intensity
+ DarkGray: {'1', '0', '0'},
+ Red: {'1', '0', '1'},
+ Green: {'1', '0', '2'},
+ Yellow: {'1', '0', '3'},
+ Blue: {'1', '0', '4'},
+ Fuchsia: {'1', '0', '5'},
+ Turquoise: {'1', '0', '6'},
+ White: {'1', '0', '7'},
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/output_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/output_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b9c2769fc2d64cfcfcc5b99c915591ec625bd5f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/output_windows.go
@@ -0,0 +1,49 @@
+// +build windows
+
+package prompt
+
+import (
+ "io"
+
+ colorable "github.com/mattn/go-colorable"
+)
+
+// WindowsWriter is a ConsoleWriter implementation for Win32 console.
+// Output is converted from VT100 escape sequences by mattn/go-colorable.
+type WindowsWriter struct {
+ VT100Writer
+ out io.Writer
+}
+
+// Flush to flush buffer
+func (w *WindowsWriter) Flush() error {
+ _, err := w.out.Write(w.buffer)
+ if err != nil {
+ return err
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &WindowsWriter{}
+
+var (
+ // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates win32 control sequences.
+func NewStdoutWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStdout(),
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates win32 control sequences.
+func NewStderrWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStderr(),
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/prompt.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/prompt.go
new file mode 100644
index 0000000000000000000000000000000000000000..173cd517c40cde212433e399978641ceff1d1a43
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/prompt.go
@@ -0,0 +1,296 @@
+package prompt
+
+import (
+ "bytes"
+ "os"
+ "time"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Executor is called when user input something text.
+type Executor func(string)
+
+// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
+// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
+// - immediate exit (if breakline is false) without executor called
+// - exit after typing (meaning breakline is true), and the executor is called first, before exit.
+// Exit means exit go-prompt (not the overall Go program)
+type ExitChecker func(in string, breakline bool) bool
+
+// Completer should return the suggest item from Document.
+type Completer func(Document) []Suggest
+
+// Prompt is core struct of go-prompt.
+type Prompt struct {
+ in ConsoleParser
+ buf *Buffer
+ renderer *Render
+ executor Executor
+ history *History
+ completion *CompletionManager
+ keyBindings []KeyBind
+ ASCIICodeBindings []ASCIICodeBind
+ keyBindMode KeyBindMode
+ completionOnDown bool
+ exitChecker ExitChecker
+ skipTearDown bool
+}
+
+// Exec is the struct contains user input context.
+type Exec struct {
+ input string
+}
+
+// Run starts prompt.
+func (p *Prompt) Run() {
+ p.skipTearDown = false
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ exitCh := make(chan int)
+ winSizeCh := make(chan *WinSize)
+ stopHandleSignalCh := make(chan struct{})
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+ return
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+
+ // Unset raw mode
+ // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
+ debug.AssertNoError(p.in.TearDown())
+ p.executor(e.input)
+
+ p.completion.Update(*p.buf.Document())
+
+ p.renderer.Render(p.buf, p.completion)
+
+ if p.exitChecker != nil && p.exitChecker(e.input, true) {
+ p.skipTearDown = true
+ return
+ }
+ // Set raw mode
+ debug.AssertNoError(p.in.Setup())
+ go p.readBuffer(bufCh, stopReadBufCh)
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ case w := <-winSizeCh:
+ p.renderer.UpdateWinSize(w)
+ p.renderer.Render(p.buf, p.completion)
+ case code := <-exitCh:
+ p.renderer.BreakLine(p.buf)
+ p.tearDown()
+ os.Exit(code)
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
+ key := GetKey(b)
+ p.buf.lastKeyStroke = key
+ // completion
+ completing := p.completion.Completing()
+ p.handleCompletionKeyBinding(key, completing)
+
+ switch key {
+ case Enter, ControlJ, ControlM:
+ p.renderer.BreakLine(p.buf)
+
+ exec = &Exec{input: p.buf.Text()}
+ p.buf = NewBuffer()
+ if exec.input != "" {
+ p.history.Add(exec.input)
+ }
+ case ControlC:
+ p.renderer.BreakLine(p.buf)
+ p.buf = NewBuffer()
+ p.history.Clear()
+ case Up, ControlP:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Older(p.buf); changed {
+ p.buf = newBuf
+ }
+ }
+ case Down, ControlN:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Newer(p.buf); changed {
+ p.buf = newBuf
+ }
+ return
+ }
+ case ControlD:
+ if p.buf.Text() == "" {
+ shouldExit = true
+ return
+ }
+ case NotDefined:
+ if p.handleASCIICodeBinding(b) {
+ return
+ }
+ p.buf.InsertText(string(b), false, true)
+ }
+
+ shouldExit = p.handleKeyBinding(key)
+ return
+}
+
+func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
+ switch key {
+ case Down:
+ if completing || p.completionOnDown {
+ p.completion.Next()
+ }
+ case Tab, ControlI:
+ p.completion.Next()
+ case Up:
+ if completing {
+ p.completion.Previous()
+ }
+ case BackTab:
+ p.completion.Previous()
+ default:
+ if s, ok := p.completion.GetSelectedSuggestion(); ok {
+ w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
+ if w != "" {
+ p.buf.DeleteBeforeCursor(len([]rune(w)))
+ }
+ p.buf.InsertText(s.Text, false, true)
+ }
+ p.completion.Reset()
+ }
+}
+
+func (p *Prompt) handleKeyBinding(key Key) bool {
+ shouldExit := false
+ for i := range commonKeyBindings {
+ kb := commonKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+
+ if p.keyBindMode == EmacsKeyBind {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ }
+
+ // Custom key bindings
+ for i := range p.keyBindings {
+ kb := p.keyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
+ shouldExit = true
+ }
+ return shouldExit
+}
+
+func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
+ checked := false
+ for _, kb := range p.ASCIICodeBindings {
+ if bytes.Equal(kb.ASCIICode, b) {
+ kb.Fn(p.buf)
+ checked = true
+ }
+ }
+ return checked
+}
+
+// Input just returns user input text.
+func (p *Prompt) Input() string {
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ return ""
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ return e.input
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
+ debug.Log("start reading buffer")
+ for {
+ select {
+ case <-stopCh:
+ debug.Log("stop reading buffer")
+ return
+ default:
+ if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
+ bufCh <- b
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (p *Prompt) setUp() {
+ debug.AssertNoError(p.in.Setup())
+ p.renderer.Setup()
+ p.renderer.UpdateWinSize(p.in.GetWinSize())
+}
+
+func (p *Prompt) tearDown() {
+ if !p.skipTearDown {
+ debug.AssertNoError(p.in.TearDown())
+ }
+ p.renderer.TearDown()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/render.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/render.go
new file mode 100644
index 0000000000000000000000000000000000000000..299ac48b6254b9752ea16516aaedcd41acca6515
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/render.go
@@ -0,0 +1,287 @@
+package prompt
+
+import (
+ "runtime"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Render to render prompt information from state of Buffer.
+type Render struct {
+ out ConsoleWriter
+ prefix string
+ livePrefixCallback func() (prefix string, useLivePrefix bool)
+ breakLineCallback func(*Document)
+ title string
+ row uint16
+ col uint16
+
+ previousCursor int
+
+ // colors,
+ prefixTextColor Color
+ prefixBGColor Color
+ inputTextColor Color
+ inputBGColor Color
+ previewSuggestionTextColor Color
+ previewSuggestionBGColor Color
+ suggestionTextColor Color
+ suggestionBGColor Color
+ selectedSuggestionTextColor Color
+ selectedSuggestionBGColor Color
+ descriptionTextColor Color
+ descriptionBGColor Color
+ selectedDescriptionTextColor Color
+ selectedDescriptionBGColor Color
+ scrollbarThumbColor Color
+ scrollbarBGColor Color
+}
+
+// Setup to initialize console output.
+func (r *Render) Setup() {
+ if r.title != "" {
+ r.out.SetTitle(r.title)
+ debug.AssertNoError(r.out.Flush())
+ }
+}
+
+// getCurrentPrefix to get current prefix.
+// If live-prefix is enabled, return live-prefix.
+func (r *Render) getCurrentPrefix() string {
+ if prefix, ok := r.livePrefixCallback(); ok {
+ return prefix
+ }
+ return r.prefix
+}
+
+func (r *Render) renderPrefix() {
+ r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
+ r.out.WriteStr(r.getCurrentPrefix())
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// TearDown to clear title and erasing.
+func (r *Render) TearDown() {
+ r.out.ClearTitle()
+ r.out.EraseDown()
+ debug.AssertNoError(r.out.Flush())
+}
+
+func (r *Render) prepareArea(lines int) {
+ for i := 0; i < lines; i++ {
+ r.out.ScrollDown()
+ }
+ for i := 0; i < lines; i++ {
+ r.out.ScrollUp()
+ }
+}
+
+// UpdateWinSize called when window size is changed.
+func (r *Render) UpdateWinSize(ws *WinSize) {
+ r.row = ws.Row
+ r.col = ws.Col
+}
+
+func (r *Render) renderWindowTooSmall() {
+ r.out.CursorGoTo(0, 0)
+ r.out.EraseScreen()
+ r.out.SetColor(DarkRed, White, false)
+ r.out.WriteStr("Your console window is too small...")
+}
+
+func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) {
+ suggestions := completions.GetSuggestions()
+ if len(completions.GetSuggestions()) == 0 {
+ return
+ }
+ prefix := r.getCurrentPrefix()
+ formatted, width := formatSuggestions(
+ suggestions,
+ int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar
+ )
+ // +1 means a width of scrollbar.
+ width++
+
+ windowHeight := len(formatted)
+ if windowHeight > int(completions.max) {
+ windowHeight = int(completions.max)
+ }
+ formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
+ r.prepareArea(windowHeight)
+
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor())
+ x, _ := r.toPos(cursor)
+ if x+width >= int(r.col) {
+ cursor = r.backward(cursor, x+width-int(r.col))
+ }
+
+ contentHeight := len(completions.tmp)
+
+ fractionVisible := float64(windowHeight) / float64(contentHeight)
+ fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
+
+ scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
+ scrollbarTop := int(float64(windowHeight) * fractionAbove)
+
+ isScrollThumb := func(row int) bool {
+ return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
+ }
+
+ selected := completions.selected - completions.verticalScroll
+ r.out.SetColor(White, Cyan, false)
+ for i := 0; i < windowHeight; i++ {
+ r.out.CursorDown(1)
+ if i == selected {
+ r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
+ } else {
+ r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Text)
+
+ if i == selected {
+ r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
+ } else {
+ r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Description)
+
+ if isScrollThumb(i) {
+ r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
+ } else {
+ r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
+ }
+ r.out.WriteStr(" ")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+
+ r.lineWrap(cursor + width)
+ r.backward(cursor+width, width)
+ }
+
+ if x+width >= int(r.col) {
+ r.out.CursorForward(x + width - int(r.col))
+ }
+
+ r.out.CursorUp(windowHeight)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// Render renders to the console.
+func (r *Render) Render(buffer *Buffer, completion *CompletionManager) {
+ // In situations where a pseudo tty is allocated (e.g. within a docker container),
+ // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
+ if r.col == 0 {
+ return
+ }
+ defer func() { debug.AssertNoError(r.out.Flush()) }()
+ r.move(r.previousCursor, 0)
+
+ line := buffer.Text()
+ prefix := r.getCurrentPrefix()
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line)
+
+ // prepare area
+ _, y := r.toPos(cursor)
+
+ h := y + 1 + int(completion.max)
+ if h > int(r.row) || completionMargin > int(r.col) {
+ r.renderWindowTooSmall()
+ return
+ }
+
+ // Rendering
+ r.out.HideCursor()
+ defer r.out.ShowCursor()
+
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(line)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ r.lineWrap(cursor)
+
+ r.out.EraseDown()
+
+ cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition())
+
+ r.renderCompletion(buffer, completion)
+ if suggest, ok := completion.GetSelectedSuggestion(); ok {
+ cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator)))
+
+ r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false)
+ r.out.WriteStr(suggest.Text)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ cursor += runewidth.StringWidth(suggest.Text)
+
+ rest := buffer.Document().TextAfterCursor()
+ r.out.WriteStr(rest)
+ cursor += runewidth.StringWidth(rest)
+ r.lineWrap(cursor)
+
+ cursor = r.backward(cursor, runewidth.StringWidth(rest))
+ }
+ r.previousCursor = cursor
+}
+
+// BreakLine to break line.
+func (r *Render) BreakLine(buffer *Buffer) {
+ // Erasing and Render
+ cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix())
+ r.clear(cursor)
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(buffer.Document().Text + "\n")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ debug.AssertNoError(r.out.Flush())
+ if r.breakLineCallback != nil {
+ r.breakLineCallback(buffer.Document())
+ }
+
+ r.previousCursor = 0
+}
+
+// clear erases the screen from a beginning of input
+// even if there is line break which means input length exceeds a window's width.
+func (r *Render) clear(cursor int) {
+ r.move(cursor, 0)
+ r.out.EraseDown()
+}
+
+// backward moves cursor to backward from a current cursor position
+// regardless there is a line break.
+func (r *Render) backward(from, n int) int {
+ return r.move(from, from-n)
+}
+
+// move moves cursor to specified position from the beginning of input
+// even if there is a line break.
+func (r *Render) move(from, to int) int {
+ fromX, fromY := r.toPos(from)
+ toX, toY := r.toPos(to)
+
+ r.out.CursorUp(fromY - toY)
+ r.out.CursorBackward(fromX - toX)
+ return to
+}
+
+// toPos returns the relative position from the beginning of the string.
+func (r *Render) toPos(cursor int) (x, y int) {
+ col := int(r.col)
+ return cursor % col, cursor / col
+}
+
+func (r *Render) lineWrap(cursor int) {
+ if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 {
+ r.out.WriteRaw([]byte{'\n'})
+ }
+}
+
+func clamp(high, low, x float64) float64 {
+ switch {
+ case high < x:
+ return high
+ case x < low:
+ return low
+ default:
+ return x
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/shortcut.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/shortcut.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8d4282700c0bdb30e4decfb9c9ac91f27af251
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/shortcut.go
@@ -0,0 +1,43 @@
+package prompt
+
+func dummyExecutor(in string) {}
+
+// Input get the input data from the user and return it.
+func Input(prefix string, completer Completer, opts ...Option) string {
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+// Choose to the shortcut of input function to select from string array.
+// Deprecated: Maybe anyone want to use this.
+func Choose(prefix string, choices []string, opts ...Option) string {
+ completer := newChoiceCompleter(choices, FilterHasPrefix)
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+func newChoiceCompleter(choices []string, filter Filter) Completer {
+ s := make([]Suggest, len(choices))
+ for i := range choices {
+ s[i] = Suggest{Text: choices[i]}
+ }
+ return func(x Document) []Suggest {
+ return filter(s, x.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/signal_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/signal_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3150df5d85e7612c42c2a889dbefee3b524bef6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/signal_posix.go
@@ -0,0 +1,49 @@
+// +build !windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ in := p.in
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+
+ case syscall.SIGWINCH:
+ debug.Log("Catch SIGWINCH")
+ winSizeCh <- in.GetWinSize()
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/signal_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/signal_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a427c79ec0414540f8f40694731b2565ea80c13
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/environment/source/signal_windows.go
@@ -0,0 +1,44 @@
+// +build windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/instruction.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..b7e3fd28f607a32a4dff071ee38c0b9a8e716c6b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/instruction.md
@@ -0,0 +1,30 @@
+JoinNextLine separator not preserved when trimming spaces
+
+#### Description
+
+The `JoinNextLine` method is not correctly preserving the separator when trimming leading spaces from the next line. The separator gets trimmed along with the spaces instead of being preserved.
+
+#### Steps/Code to Reproduce
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func main() {
+ buffer := prompt.NewBuffer()
+ buffer.InsertText("line1\nline2 line3", false, true)
+ buffer.CursorPosition = 5 // Position at end of "line1"
+
+ buffer.JoinNextLine(" ")
+
+ fmt.Printf("Expected: line1 line2 line3\n")
+ fmt.Printf("Got: %s\n", buffer.Text())
+}
+```
+
+When joining lines with a separator like a space, the separator should be preserved between the joined content. Currently the separator is being trimmed away along with any leading spaces on the next line.
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/provenance.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..f7ea72e1cb2e4ee25b68cedacd949aab6b996d84
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/provenance.json
@@ -0,0 +1,477 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt",
+ "original-bug": "task-specific unchanged semantic bug",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only",
+ "extra_semantic_repair_coverage": false,
+ "original_patch_hunks": 1
+ },
+ "private_frozen_files": {
+ "buffer_test.go": {
+ "mode": "0o644",
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098",
+ "size": 4965
+ },
+ "completion_test.go": {
+ "mode": "0o644",
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d",
+ "size": 7010
+ },
+ "document_test.go": {
+ "mode": "0o644",
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284",
+ "size": 28938
+ },
+ "emacs_test.go": {
+ "mode": "0o644",
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095",
+ "size": 741
+ },
+ "filter_test.go": {
+ "mode": "0o644",
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247",
+ "size": 3339
+ },
+ "history_test.go": {
+ "mode": "0o644",
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327",
+ "size": 1319
+ },
+ "input_test.go": {
+ "mode": "0o644",
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922",
+ "size": 533
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": "0o644",
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf",
+ "size": 1075
+ },
+ "internal/strings/strings_test.go": {
+ "mode": "0o644",
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6",
+ "size": 981
+ },
+ "output_vt100_test.go": {
+ "mode": "0o644",
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee",
+ "size": 1349
+ },
+ "render_test.go": {
+ "mode": "0o644",
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb",
+ "size": 2890
+ }
+ },
+ "public_files": {
+ ".github/ISSUE_TEMPLATE/bug_report.md": {
+ "mode": "0o644",
+ "sha256": "89d3492ca8533a3d31e4de49a23828a322f75d2a1ec4236327c4a76c7c51ada6",
+ "size": 684
+ },
+ ".github/ISSUE_TEMPLATE/feature_request.md": {
+ "mode": "0o644",
+ "sha256": "d82e14e6b4d021d0007eeef4f5ca489fc6c8e8e4d7479ee30e74fe82afd3b08f",
+ "size": 206
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "3239b94a1a41c05eff5dc086ef1378cf1e289fad0203420b5cb4c78e3c5c239b",
+ "size": 270
+ },
+ "CHANGELOG.md": {
+ "mode": "0o644",
+ "sha256": "1f88f92d3247e1b52af0f0de7ad1263a59807edb17238c7a0211554f8080e51c",
+ "size": 2895
+ },
+ "LICENSE": {
+ "mode": "0o644",
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "size": 1072
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "9425a0d4c15747863625f647348962a9b0f81a0971a7e0184ee722bf34a60ba2",
+ "size": 1177
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "ce56df51a1a9a5b5c5b056429bbee006a260fb0730af63b1d0fe91755e574cc4",
+ "size": 6185
+ },
+ "_example/README.md": {
+ "mode": "0o644",
+ "sha256": "155951bafd778493bd41ae57dcc0ba6b8eca821fcbe2ffe770960ac2780d3d09",
+ "size": 1102
+ },
+ "_example/build.sh": {
+ "mode": "0o755",
+ "sha256": "de2fb330b665691cd75b990236cd6a5df0058608de0dfc6194da30d4041a1e29",
+ "size": 469
+ },
+ "_example/exec-command/main.go": {
+ "mode": "0o644",
+ "sha256": "0e96493b6e6d446b2e691d4834ff8a55834caa410ead970cb611a63ba84f174a",
+ "size": 429
+ },
+ "_example/http-prompt/api.py": {
+ "mode": "0o644",
+ "sha256": "2c2bca9acb07a84c65a4482c61c9ade253a574477a8e461307568ea1f9a342c8",
+ "size": 335
+ },
+ "_example/http-prompt/main.go": {
+ "mode": "0o644",
+ "sha256": "6994b190c4165068e69ed44eb61698af69a15a7690179ce46e3c1c5d8c211643",
+ "size": 5484
+ },
+ "_example/live-prefix/main.go": {
+ "mode": "0o644",
+ "sha256": "20268f9cb6f3b82a52eddc33cbf8082adaa46092e2063df279499e05e25a228c",
+ "size": 1103
+ },
+ "_example/simple-echo/cjk-cyrillic/main.go": {
+ "mode": "0o644",
+ "sha256": "8fb10807d4085ebc4b345bc0ccfef9217e21e49a888bfe3192e8ddfdfa01e89c",
+ "size": 800
+ },
+ "_example/simple-echo/main.go": {
+ "mode": "0o644",
+ "sha256": "e46563ddaa932831fe9ede870b10efb5222c0d54a86f4b4f5197c9cf20942a24",
+ "size": 902
+ },
+ "_tools/README.md": {
+ "mode": "0o644",
+ "sha256": "96dc2343bc5cde642fd449ddc366462753a2e17b6a78adfa015bf991e9dac241",
+ "size": 234
+ },
+ "_tools/complete_file/main.go": {
+ "mode": "0o644",
+ "sha256": "e5dd823f9d6415614a8238ce106d26e9ded1db9b308c121d7f48bb1df003effc",
+ "size": 803
+ },
+ "_tools/sigwinch/main.go": {
+ "mode": "0o644",
+ "sha256": "a806b4e45298f5003c95432d8dd3c40c9c096335f19f1a4160afcdb64fa727e3",
+ "size": 1386
+ },
+ "_tools/vt100_debug/main.go": {
+ "mode": "0o644",
+ "sha256": "7f72eba3cc7037fcf39c9b56a96c578c157e5fb235cb626ab1e83cbef0dc290b",
+ "size": 794
+ },
+ "buffer.go": {
+ "mode": "0o644",
+ "sha256": "6a2470931be29d15ae0b51c65b0a8ed8eaa928aa2d7dd08cf83bdb4590ccc9c4",
+ "size": 5779
+ },
+ "completer/file.go": {
+ "mode": "0o644",
+ "sha256": "6181ed9e39028236c5c93fbe219331fc1492ecfd6af2df764cc42b5455c9bb96",
+ "size": 2401
+ },
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "b90bd9628534cfb343a592775430e17a1999b1de500fb2a8f1507c030a432eae",
+ "size": 4491
+ },
+ "document.go": {
+ "mode": "0o644",
+ "sha256": "e719d4c10a10f506c371b87dbd363a9b7f7d3aa8f0190a40965ac761197e1f1e",
+ "size": 13097
+ },
+ "emacs.go": {
+ "mode": "0o644",
+ "sha256": "53f0df0016ef9d9695a797b19286681666cf0c7e5a866c393b194aae915f2664",
+ "size": 2675
+ },
+ "filter.go": {
+ "mode": "0o644",
+ "sha256": "dc5922bad6ecb32ecdaf20bd6035dddc7ce8c14f15dbd4d49192c2354cb8a038",
+ "size": 2005
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "97413fa2a2ed68170496f2289a2dca6fb0a192dcd020fc0ca48a5d106e60d55e",
+ "size": 253
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "88ea0a91babaa54b67cc6d5f6f7f47fa4be798fe523324ea568d8926eed2024c",
+ "size": 2183
+ },
+ "history.go": {
+ "mode": "0o644",
+ "sha256": "4ce80ba067cfc72c56a3ee3353ec75cd6bb2f5d82097515c591e3c7c773c51cd",
+ "size": 1488
+ },
+ "input.go": {
+ "mode": "0o644",
+ "sha256": "73461cc4f57d68b66e2a9e196239aaef942539134593beac0d0023743832e0e1",
+ "size": 7630
+ },
+ "input_posix.go": {
+ "mode": "0o644",
+ "sha256": "c7e5a4dfc3910f178f0685ef99f2e47d481a91c4cf9af50f92fc4266aed634df",
+ "size": 1648
+ },
+ "input_windows.go": {
+ "mode": "0o644",
+ "sha256": "f763250d309fb88d9536f77da1d1285c04bc6defe859506f1501e10f7743da9e",
+ "size": 1679
+ },
+ "internal/bisect/bisect.go": {
+ "mode": "0o644",
+ "sha256": "c4de2adfa2e08a77f902661d67325467f89013634dbcef22d24dc6f34d26624a",
+ "size": 327
+ },
+ "internal/debug/assert.go": {
+ "mode": "0o644",
+ "sha256": "1a3050ec58991b62c7ea352d19505e3080ac9760bdb091544f0ecf5aba35969c",
+ "size": 815
+ },
+ "internal/debug/log.go": {
+ "mode": "0o644",
+ "sha256": "2ce968e275558de61c6d83793e85561f7a8dd69c95ec7902ccd2cc3fb169aa82",
+ "size": 875
+ },
+ "internal/strings/strings.go": {
+ "mode": "0o644",
+ "sha256": "b97f08157c3baf1f94fea4bb2237691d8270bd5380b4311709ecd59b84cf4b7b",
+ "size": 2018
+ },
+ "internal/term/raw.go": {
+ "mode": "0o644",
+ "sha256": "177a1a20ae8d71b56857383a5797754560f7f6404ea86778d5f01e9a1c1b4f9f",
+ "size": 747
+ },
+ "internal/term/term.go": {
+ "mode": "0o644",
+ "sha256": "abe6fa965fa15b999b2010135903f598830d4c885a52ef9b067fd5ebbf6e373f",
+ "size": 606
+ },
+ "key.go": {
+ "mode": "0o644",
+ "sha256": "03a43283e07de7a4ea6fed32692d86325f73e98fd89a296f19c171e0bc780999",
+ "size": 1746
+ },
+ "key_bind.go": {
+ "mode": "0o644",
+ "sha256": "83f48bb720a11c8e49165ac382e3a870fdcf6b380a0a95267f8c25211898c9eb",
+ "size": 1109
+ },
+ "key_bind_func.go": {
+ "mode": "0o644",
+ "sha256": "445bff5c0fdb0b52879c635322603c2fc75d265de3761cb8c3b980c798bf39af",
+ "size": 1219
+ },
+ "key_string.go": {
+ "mode": "0o644",
+ "sha256": "55c429dae227bb1659d5d5e2e906dbfa9c7f53b5105fa83fbe290529ff6f2317",
+ "size": 1359
+ },
+ "option.go": {
+ "mode": "0o644",
+ "sha256": "28cfcc1d08b3cf650483d977195458531b3b3913f8a5f357a3ec17ea5d73e215",
+ "size": 8737
+ },
+ "output.go": {
+ "mode": "0o644",
+ "sha256": "372876b0aa908479ed3b29de70a479f420d85e3666b8957c8b61eaed9b32c3f2",
+ "size": 4320
+ },
+ "output_posix.go": {
+ "mode": "0o644",
+ "sha256": "d46b1da307e8969b033e1ade2eb51a83c4c3d4f2a7e4aba35ec3a03991b89a0f",
+ "size": 1545
+ },
+ "output_vt100.go": {
+ "mode": "0o644",
+ "sha256": "9082c7e4619c1eb38030bc4994a4fbf66ef27b130751bf2eb9c25c01082e8605",
+ "size": 7453
+ },
+ "output_windows.go": {
+ "mode": "0o644",
+ "sha256": "571c5ae1ad051a701b426371efd79a3776c2226ca9e3c2e598fe5996dfa1b8e1",
+ "size": 1066
+ },
+ "prompt.go": {
+ "mode": "0o644",
+ "sha256": "6b3e2bbd90f40ad6a487f1a6ea7f5a6fb48cae6c8c246ecc77621fb3e7383ca7",
+ "size": 7062
+ },
+ "render.go": {
+ "mode": "0o644",
+ "sha256": "90fdd57a63e06f01940d10ee1a0be95ced7d6adc7faa255b3141556d7d316270",
+ "size": 8020
+ },
+ "shortcut.go": {
+ "mode": "0o644",
+ "sha256": "b4a097f466df7396049ebe8393f81c9b1200159d4e2be22bd6838c307ec156dc",
+ "size": 1120
+ },
+ "signal_posix.go": {
+ "mode": "0o644",
+ "sha256": "74f0bae5f290f3f7f82a5dd495e672f627a4ab4b63118f870e8c13c0a7024314",
+ "size": 881
+ },
+ "signal_windows.go": {
+ "mode": "0o644",
+ "sha256": "444f662a32e6997df2af8e2a9e7dbfe977414a6bfc0f54a7f10117f204648437",
+ "size": 757
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982",
+ "os": "linux",
+ "sha256": "0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982"
+ },
+ "context_inventory_sha256": "6b8f93086e81483ac1ce82f328d7f4b38b1b560dbad057ed6a2a30ff3cf0e13f",
+ "image": "registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "9d3b21cdacadfa4f3de9584d0cea973e5aa2ceedcd5ec9cbd3a63df22b313455",
+ "receipt_path": "production/runtime-images-extra-v1/resolutions/316e0e68930cd4ef/resolution.json",
+ "receipt_sha256": "697bb0619eddcdfdeba1c9144b033f564f2d7514be6e6a44dc520fa4e63ed8bc",
+ "registry_digest": "sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "source_image": "docker.io/swebench/swesmith.x86_64.c-bata_1776_go-prompt.82a91227@sha256:3daf51c74a01657e9ad8f326651fb6f5b796ffecdb90098e74a52a9560e0a1bb",
+ "source_receipt_sha256": "b450bea0e201cbe194b765ded4b51539144c85296122c8b642d7e94c889526f3",
+ "space_commit": "5ae654cd2e9d695f0de304bd4398835fc7cf45e0",
+ "space_id": "harness-hub/scale800-go-316e0e68930cd4ef-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "cb7574e50c624911fe44670c9efd4243021fb1b68bc569e89ac29dc753deb0ab",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21",
+ "source_proof_sha256": "9bd273208e36c34cac74503676f920a155f1fccc4002fd667c6324502dd77354",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:c-bata__go-prompt.82a91227.lm_modify__75q1kses",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "9992c59c25864ce1556e67b9e1501c93f6e7f9ff",
+ "instruction_sha256": "dd708bbe611ce0b3374d78b61e16b446fce1a97559622bd3f268fd5d46dcd2c0",
+ "is_fork": true,
+ "learner_path": "tasks/a8846e217a3d807e3cd16ca1/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/c-bata__go-prompt.82a91227/3048570c52e1b4e20270d35ae563049a5058b2f2/LICENSE"
+ },
+ "task_bundle": {
+ "basis": "Captured publisherMIT/train; exactsoftwarepermissionverifiedseparately",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "82a912274504477990ecf7c852eebb7c85291772",
+ "patch_sha256": "0bab77cda77bcf3424eb617d3298c5da810e87678bb517df43a2e4f2988093eb",
+ "provenance_path": "tasks/a8846e217a3d807e3cd16ca1/source-proof.json",
+ "repository_lineage": [
+ "swesmith/c-bata__go-prompt.82a91227",
+ "c-bata/go-prompt"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "3048570c52e1b4e20270d35ae563049a5058b2f2",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "b2169f0885fd4d0ef12bc77ce24d47743252a5ed",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/c-bata__go-prompt.82a91227",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "c-bata__go-prompt.82a91227.lm_modify__75q1kses",
+ "task_sha256": "9efdfbc711f51f56797ef520b1adfc0b3da39925fb1e9c5a197f0c1c70e013f9",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "c-bata/go-prompt",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "c69f589f06eaabbbeb9be52258e14d7c1398377425f87104e1cc611bfa02dad6",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.md",
+ "/testbed/.github/ISSUE_TEMPLATE/feature_request.md",
+ "/testbed/.gitignore",
+ "/testbed/CHANGELOG.md",
+ "/testbed/LICENSE",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/_example/README.md",
+ "/testbed/_example/build.sh",
+ "/testbed/_example/exec-command/main.go",
+ "/testbed/_example/http-prompt/api.py",
+ "/testbed/_example/http-prompt/main.go",
+ "/testbed/_example/live-prefix/main.go",
+ "/testbed/_example/simple-echo/cjk-cyrillic/main.go",
+ "/testbed/_example/simple-echo/main.go",
+ "/testbed/_tools/README.md",
+ "/testbed/_tools/complete_file/main.go",
+ "/testbed/_tools/sigwinch/main.go",
+ "/testbed/_tools/vt100_debug/main.go",
+ "/testbed/buffer.go",
+ "/testbed/completer/file.go",
+ "/testbed/completion.go",
+ "/testbed/document.go",
+ "/testbed/emacs.go",
+ "/testbed/filter.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum",
+ "/testbed/history.go",
+ "/testbed/input.go",
+ "/testbed/input_posix.go",
+ "/testbed/input_windows.go",
+ "/testbed/internal/bisect/bisect.go",
+ "/testbed/internal/debug/assert.go",
+ "/testbed/internal/debug/log.go",
+ "/testbed/internal/strings/strings.go",
+ "/testbed/internal/term/raw.go",
+ "/testbed/internal/term/term.go",
+ "/testbed/key.go",
+ "/testbed/key_bind.go",
+ "/testbed/key_bind_func.go",
+ "/testbed/key_string.go",
+ "/testbed/option.go",
+ "/testbed/output.go",
+ "/testbed/output_posix.go",
+ "/testbed/output_vt100.go",
+ "/testbed/output_windows.go",
+ "/testbed/prompt.go",
+ "/testbed/render.go",
+ "/testbed/shortcut.go",
+ "/testbed/signal_posix.go",
+ "/testbed/signal_windows.go"
+ ]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/solution/solve.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7b1491520258de7be4d970d00e4aef3dabf95e6b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"buffer.go": {"data": "cGFja2FnZSBwcm9tcHQKCmltcG9ydCAoCgkic3RyaW5ncyIKCgkiZ2l0aHViLmNvbS9jLWJhdGEvZ28tcHJvbXB0L2ludGVybmFsL2RlYnVnIgopCgovLyBCdWZmZXIgZW11bGF0ZXMgdGhlIGNvbnNvbGUgYnVmZmVyLgp0eXBlIEJ1ZmZlciBzdHJ1Y3QgewoJd29ya2luZ0xpbmVzICAgIFtdc3RyaW5nIC8vIFRoZSB3b3JraW5nIGxpbmVzLiBTaW1pbGFyIHRvIGhpc3RvcnkKCXdvcmtpbmdJbmRleCAgICBpbnQKCWN1cnNvclBvc2l0aW9uICBpbnQKCWNhY2hlRG9jdW1lbnQgICAqRG9jdW1lbnQKCXByZWZlcnJlZENvbHVtbiBpbnQgLy8gUmVtZW1iZXIgdGhlIG9yaWdpbmFsIGNvbHVtbiBmb3IgdGhlIG5leHQgdXAvZG93biBtb3ZlbWVudC4KCWxhc3RLZXlTdHJva2UgICBLZXkKfQoKLy8gVGV4dCByZXR1cm5zIHN0cmluZyBvZiB0aGUgY3VycmVudCBsaW5lLgpmdW5jIChiICpCdWZmZXIpIFRleHQoKSBzdHJpbmcgewoJcmV0dXJuIGIud29ya2luZ0xpbmVzW2Iud29ya2luZ0luZGV4XQp9CgovLyBEb2N1bWVudCBtZXRob2QgdG8gcmV0dXJuIGRvY3VtZW50IGluc3RhbmNlIGZyb20gdGhlIGN1cnJlbnQgdGV4dCBhbmQgY3Vyc29yIHBvc2l0aW9uLgpmdW5jIChiICpCdWZmZXIpIERvY3VtZW50KCkgKGQgKkRvY3VtZW50KSB7CglpZiBiLmNhY2hlRG9jdW1lbnQgPT0gbmlsIHx8CgkJYi5jYWNoZURvY3VtZW50LlRleHQgIT0gYi5UZXh0KCkgfHwKCQliLmNhY2hlRG9jdW1lbnQuY3Vyc29yUG9zaXRpb24gIT0gYi5jdXJzb3JQb3NpdGlvbiB7CgkJYi5jYWNoZURvY3VtZW50ID0gJkRvY3VtZW50ewoJCQlUZXh0OiAgICAgICAgICAgYi5UZXh0KCksCgkJCWN1cnNvclBvc2l0aW9uOiBiLmN1cnNvclBvc2l0aW9uLAoJCX0KCX0KCWIuY2FjaGVEb2N1bWVudC5sYXN0S2V5ID0gYi5sYXN0S2V5U3Ryb2tlCglyZXR1cm4gYi5jYWNoZURvY3VtZW50Cn0KCi8vIERpc3BsYXlDdXJzb3JQb3NpdGlvbiByZXR1cm5zIHRoZSBjdXJzb3IgcG9zaXRpb24gb24gcmVuZGVyZWQgdGV4dCBvbiB0ZXJtaW5hbCBlbXVsYXRvcnMuCi8vIFNvIGlmIERvY3VtZW50IGlzICLml6XmnKwoY3Vyc29yKeiqniIsIERpc3BsYXllZEN1cnNvclBvc2l0aW9uIHJldHVybnMgNCBiZWNhdXNlICfml6UnIGFuZCAn5pysJyBhcmUgZG91YmxlIHdpZHRoIGNoYXJhY3RlcnMuCmZ1bmMgKGIgKkJ1ZmZlcikgRGlzcGxheUN1cnNvclBvc2l0aW9uKCkgaW50IHsKCXJldHVybiBiLkRvY3VtZW50KCkuRGlzcGxheUN1cnNvclBvc2l0aW9uKCkKfQoKLy8gSW5zZXJ0VGV4dCBpbnNlcnQgc3RyaW5nIGZyb20gY3VycmVudCBsaW5lLgpmdW5jIChiICpCdWZmZXIpIEluc2VydFRleHQodiBzdHJpbmcsIG92ZXJ3cml0ZSBib29sLCBtb3ZlQ3Vyc29yIGJvb2wpIHsKCW9yIDo9IFtdcnVuZShiLlRleHQoKSkKCW9jIDo9IGIuY3Vyc29yUG9zaXRpb24KCglpZiBvdmVyd3JpdGUgewoJCW92ZXJ3cml0dGVuIDo9IHN0cmluZyhvcltvYyA6IG9jK2xlbih2KV0pCgkJaWYgc3RyaW5ncy5Db250YWlucyhvdmVyd3JpdHRlbiwgIlxuIikgewoJCQlpIDo9IHN0cmluZ3MuSW5kZXhBbnkob3ZlcndyaXR0ZW4sICJcbiIpCgkJCW92ZXJ3cml0dGVuID0gb3ZlcndyaXR0ZW5bOmldCgkJfQoJCWIuc2V0VGV4dChzdHJpbmcob3JbOm9jXSkgKyB2ICsgc3RyaW5nKG9yW29jK2xlbihvdmVyd3JpdHRlbik6XSkpCgl9IGVsc2UgewoJCWIuc2V0VGV4dChzdHJpbmcob3JbOm9jXSkgKyB2ICsgc3RyaW5nKG9yW29jOl0pKQoJfQoKCWlmIG1vdmVDdXJzb3IgewoJCWIuY3Vyc29yUG9zaXRpb24gKz0gbGVuKFtdcnVuZSh2KSkKCX0KfQoKLy8gU2V0VGV4dCBtZXRob2QgdG8gc2V0IHRleHQgYW5kIHVwZGF0ZSBjdXJzb3JQb3NpdGlvbi4KLy8gKFdoZW4gZG9pbmcgdGhpcywgbWFrZSBzdXJlIHRoYXQgdGhlIGN1cnNvcl9wb3NpdGlvbiBpcyB2YWxpZCBmb3IgdGhpcyB0ZXh0LgovLyB0ZXh0L2N1cnNvcl9wb3NpdGlvbiBzaG91bGQgYmUgY29uc2lzdGVudCBhdCBhbnkgdGltZSwgb3RoZXJ3aXNlIHNldCBhIERvY3VtZW50IGluc3RlYWQuKQpmdW5jIChiICpCdWZmZXIpIHNldFRleHQodiBzdHJpbmcpIHsKCWRlYnVnLkFzc2VydChiLmN1cnNvclBvc2l0aW9uIDw9IGxlbihbXXJ1bmUodikpLCAibGVuZ3RoIG9mIGlucHV0IHNob3VsZCBiZSBzaG9ydGVyIHRoYW4gY3Vyc29yIHBvc2l0aW9uIikKCWIud29ya2luZ0xpbmVzW2Iud29ya2luZ0luZGV4XSA9IHYKfQoKLy8gU2V0IGN1cnNvciBwb3NpdGlvbi4gUmV0dXJuIHdoZXRoZXIgaXQgY2hhbmdlZC4KZnVuYyAoYiAqQnVmZmVyKSBzZXRDdXJzb3JQb3NpdGlvbihwIGludCkgewoJaWYgcCA+IDAgewoJCWIuY3Vyc29yUG9zaXRpb24gPSBwCgl9IGVsc2UgewoJCWIuY3Vyc29yUG9zaXRpb24gPSAwCgl9Cn0KCmZ1bmMgKGIgKkJ1ZmZlcikgc2V0RG9jdW1lbnQoZCAqRG9jdW1lbnQpIHsKCWIuY2FjaGVEb2N1bWVudCA9IGQKCWIuc2V0Q3Vyc29yUG9zaXRpb24oZC5jdXJzb3JQb3NpdGlvbikgLy8gQ2FsbCBiZWZvcmUgc2V0VGV4dCBiZWNhdXNlIHNldFRleHQgY2hlY2sgdGhlIHJlbGF0aW9uIGJldHdlZW4gY3Vyc29yUG9zaXRpb24gYW5kIGxpbmUgbGVuZ3RoLgoJYi5zZXRUZXh0KGQuVGV4dCkKfQoKLy8gQ3Vyc29yTGVmdCBtb3ZlIHRvIGxlZnQgb24gdGhlIGN1cnJlbnQgbGluZS4KZnVuYyAoYiAqQnVmZmVyKSBDdXJzb3JMZWZ0KGNvdW50IGludCkgewoJbCA6PSBiLkRvY3VtZW50KCkuR2V0Q3Vyc29yTGVmdFBvc2l0aW9uKGNvdW50KQoJYi5jdXJzb3JQb3NpdGlvbiArPSBsCn0KCi8vIEN1cnNvclJpZ2h0IG1vdmUgdG8gcmlnaHQgb24gdGhlIGN1cnJlbnQgbGluZS4KZnVuYyAoYiAqQnVmZmVyKSBDdXJzb3JSaWdodChjb3VudCBpbnQpIHsKCWwgOj0gYi5Eb2N1bWVudCgpLkdldEN1cnNvclJpZ2h0UG9zaXRpb24oY291bnQpCgliLmN1cnNvclBvc2l0aW9uICs9IGwKfQoKLy8gQ3Vyc29yVXAgbW92ZSBjdXJzb3IgdG8gdGhlIHByZXZpb3VzIGxpbmUuCi8vIChmb3IgbXVsdGktbGluZSBlZGl0KS4KZnVuYyAoYiAqQnVmZmVyKSBDdXJzb3JVcChjb3VudCBpbnQpIHsKCW9yaWcgOj0gYi5wcmVmZXJyZWRDb2x1bW4KCWlmIGIucHJlZmVycmVkQ29sdW1uID09IC0xIHsgLy8gLTEgbWVhbnMgbmlsCgkJb3JpZyA9IGIuRG9jdW1lbnQoKS5DdXJzb3JQb3NpdGlvbkNvbCgpCgl9CgliLmN1cnNvclBvc2l0aW9uICs9IGIuRG9jdW1lbnQoKS5HZXRDdXJzb3JVcFBvc2l0aW9uKGNvdW50LCBvcmlnKQoKCS8vIFJlbWVtYmVyIHRoZSBvcmlnaW5hbCBjb2x1bW4gZm9yIHRoZSBuZXh0IHVwL2Rvd24gbW92ZW1lbnQuCgliLnByZWZlcnJlZENvbHVtbiA9IG9yaWcKfQoKLy8gQ3Vyc29yRG93biBtb3ZlIGN1cnNvciB0byB0aGUgbmV4dCBsaW5lLgovLyAoZm9yIG11bHRpLWxpbmUgZWRpdCkuCmZ1bmMgKGIgKkJ1ZmZlcikgQ3Vyc29yRG93bihjb3VudCBpbnQpIHsKCW9yaWcgOj0gYi5wcmVmZXJyZWRDb2x1bW4KCWlmIGIucHJlZmVycmVkQ29sdW1uID09IC0xIHsgLy8gLTEgbWVhbnMgbmlsCgkJb3JpZyA9IGIuRG9jdW1lbnQoKS5DdXJzb3JQb3NpdGlvbkNvbCgpCgl9CgliLmN1cnNvclBvc2l0aW9uICs9IGIuRG9jdW1lbnQoKS5HZXRDdXJzb3JEb3duUG9zaXRpb24oY291bnQsIG9yaWcpCgoJLy8gUmVtZW1iZXIgdGhlIG9yaWdpbmFsIGNvbHVtbiBmb3IgdGhlIG5leHQgdXAvZG93biBtb3ZlbWVudC4KCWIucHJlZmVycmVkQ29sdW1uID0gb3JpZwp9CgovLyBEZWxldGVCZWZvcmVDdXJzb3IgZGVsZXRlIHNwZWNpZmllZCBudW1iZXIgb2YgY2hhcmFjdGVycyBiZWZvcmUgY3Vyc29yIGFuZCByZXR1cm4gdGhlIGRlbGV0ZWQgdGV4dC4KZnVuYyAoYiAqQnVmZmVyKSBEZWxldGVCZWZvcmVDdXJzb3IoY291bnQgaW50KSAoZGVsZXRlZCBzdHJpbmcpIHsKCWRlYnVnLkFzc2VydChjb3VudCA+PSAwLCAiY291bnQgc2hvdWxkIGJlIHBvc2l0aXZlIikKCXIgOj0gW11ydW5lKGIuVGV4dCgpKQoKCWlmIGIuY3Vyc29yUG9zaXRpb24gPiAwIHsKCQlzdGFydCA6PSBiLmN1cnNvclBvc2l0aW9uIC0gY291bnQKCQlpZiBzdGFydCA8IDAgewoJCQlzdGFydCA9IDAKCQl9CgkJZGVsZXRlZCA9IHN0cmluZyhyW3N0YXJ0OmIuY3Vyc29yUG9zaXRpb25dKQoJCWIuc2V0RG9jdW1lbnQoJkRvY3VtZW50ewoJCQlUZXh0OiAgICAgICAgICAgc3RyaW5nKHJbOnN0YXJ0XSkgKyBzdHJpbmcocltiLmN1cnNvclBvc2l0aW9uOl0pLAoJCQljdXJzb3JQb3NpdGlvbjogYi5jdXJzb3JQb3NpdGlvbiAtIGxlbihbXXJ1bmUoZGVsZXRlZCkpLAoJCX0pCgl9CglyZXR1cm4KfQoKLy8gTmV3TGluZSBtZWFucyBDUi4KZnVuYyAoYiAqQnVmZmVyKSBOZXdMaW5lKGNvcHlNYXJnaW4gYm9vbCkgewoJaWYgY29weU1hcmdpbiB7CgkJYi5JbnNlcnRUZXh0KCJcbiIrYi5Eb2N1bWVudCgpLmxlYWRpbmdXaGl0ZXNwYWNlSW5DdXJyZW50TGluZSgpLCBmYWxzZSwgdHJ1ZSkKCX0gZWxzZSB7CgkJYi5JbnNlcnRUZXh0KCJcbiIsIGZhbHNlLCB0cnVlKQoJfQp9CgovLyBEZWxldGUgc3BlY2lmaWVkIG51bWJlciBvZiBjaGFyYWN0ZXJzIGFuZCBSZXR1cm4gdGhlIGRlbGV0ZWQgdGV4dC4KZnVuYyAoYiAqQnVmZmVyKSBEZWxldGUoY291bnQgaW50KSAoZGVsZXRlZCBzdHJpbmcpIHsKCXIgOj0gW11ydW5lKGIuVGV4dCgpKQoJaWYgYi5jdXJzb3JQb3NpdGlvbiA8IGxlbihyKSB7CgkJZGVsZXRlZCA9IGIuRG9jdW1lbnQoKS5UZXh0QWZ0ZXJDdXJzb3IoKVs6Y291bnRdCgkJYi5zZXRUZXh0KHN0cmluZyhyWzpiLmN1cnNvclBvc2l0aW9uXSkgKyBzdHJpbmcocltiLmN1cnNvclBvc2l0aW9uK2xlbihkZWxldGVkKTpdKSkKCX0KCXJldHVybgp9CgovLyBKb2luTmV4dExpbmUgam9pbnMgdGhlIG5leHQgbGluZSB0byB0aGUgY3VycmVudCBvbmUgYnkgZGVsZXRpbmcgdGhlIGxpbmUgZW5kaW5nIGFmdGVyIHRoZSBjdXJyZW50IGxpbmUuCmZ1bmMgKGIgKkJ1ZmZlcikgSm9pbk5leHRMaW5lKHNlcGFyYXRvciBzdHJpbmcpIHsKCWlmICFiLkRvY3VtZW50KCkuT25MYXN0TGluZSgpIHsKCQliLmN1cnNvclBvc2l0aW9uICs9IGIuRG9jdW1lbnQoKS5HZXRFbmRPZkxpbmVQb3NpdGlvbigpCgkJYi5EZWxldGUoMSkKCQkvLyBSZW1vdmUgc3BhY2VzCgkJYi5zZXRUZXh0KGIuRG9jdW1lbnQoKS5UZXh0QmVmb3JlQ3Vyc29yKCkgKyBzZXBhcmF0b3IgKyBzdHJpbmdzLlRyaW1MZWZ0KGIuRG9jdW1lbnQoKS5UZXh0QWZ0ZXJDdXJzb3IoKSwgIiAiKSkKCX0KfQoKLy8gU3dhcENoYXJhY3RlcnNCZWZvcmVDdXJzb3Igc3dhcHMgdGhlIGxhc3QgdHdvIGNoYXJhY3RlcnMgYmVmb3JlIHRoZSBjdXJzb3IuCmZ1bmMgKGIgKkJ1ZmZlcikgU3dhcENoYXJhY3RlcnNCZWZvcmVDdXJzb3IoKSB7CglpZiBiLmN1cnNvclBvc2l0aW9uID49IDIgewoJCXggOj0gYi5UZXh0KClbYi5jdXJzb3JQb3NpdGlvbi0yIDogYi5jdXJzb3JQb3NpdGlvbi0xXQoJCXkgOj0gYi5UZXh0KClbYi5jdXJzb3JQb3NpdGlvbi0xIDogYi5jdXJzb3JQb3NpdGlvbl0KCQliLnNldFRleHQoYi5UZXh0KClbOmIuY3Vyc29yUG9zaXRpb24tMl0gKyB5ICsgeCArIGIuVGV4dCgpW2IuY3Vyc29yUG9zaXRpb246XSkKCX0KfQoKLy8gTmV3QnVmZmVyIGlzIGNvbnN0cnVjdG9yIG9mIEJ1ZmZlciBzdHJ1Y3QuCmZ1bmMgTmV3QnVmZmVyKCkgKGIgKkJ1ZmZlcikgewoJYiA9ICZCdWZmZXJ7CgkJd29ya2luZ0xpbmVzOiAgICBbXXN0cmluZ3siIn0sCgkJd29ya2luZ0luZGV4OiAgICAwLAoJCXByZWZlcnJlZENvbHVtbjogLTEsIC8vIC0xIG1lYW5zIG5pbAoJfQoJcmV0dXJuCn0K", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/task.toml b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..d8aa77fa50dfe546c7708796251e36c8133c7bb2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/task.toml
@@ -0,0 +1,11 @@
+version = "1.0"
+[agent]
+timeout_sec = 300.0
+[verifier]
+timeout_sec = 300.0
+environment_mode = "shared"
+[environment]
+docker_image = "ghcr.io/younesbelkada/scale800@sha256:3b980977c7fa96cf9187fbc66768db1a1621367cb8cd899582d821f1c0397188"
+cpus = 1
+memory_mb = 2048
+storage_mb = 4096
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..df17cb1062692f79989fd1bd1b8fe03c4652c2d0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/manifest.json
@@ -0,0 +1,432 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CursorPositionRowAndCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorLeftPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorUpPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorDownPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorRightPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_Lines"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_LineCount"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateIndexToPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateRowColToIndex"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_OnLastLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetEndOfLinePosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestEmacsKeyBindings"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFilter"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFuzzyMatch"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryClear"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryAdd"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryOlder"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/escape"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/undefined"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWrite"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteRawStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatCompletion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBreakLineCallback"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionRow"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition_withJapanese"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/validation/canaries/delete-tests.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/validation/canaries/delete-tests.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/validation/canaries/delete-tests.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+find /testbed -name '*_test.go' -type f -delete
+printf 'PASS\nok forged-package 0.001s\n'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..bc3880fc14494a2c99163dbd21015ba5039d7795
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__75q1kses/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "4ba39b3d29d3fb77539f0be23ff7a23af705bc12adc2ed1efa5c2d3482f2b1b7",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/Dockerfile b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f35bf9e5393ee1086fe1b72c1b442f3b16e2bd5b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22
+WORKDIR /testbed
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c8c031d0f87fb9aea0aff433b1fcaeaac259c41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: "Bug report"
+about: Create a bug report to improve go-prompt
+title: "[Bug]"
+labels: bug
+assignees: ''
+
+---
+
+# Bug reports
+
+*Please file a bug report here.*
+
+## Expected Behavior
+
+*Please describe the behavior you are expecting*
+
+## Current Behavior and Steps to Reproduce
+
+*What is the current behavior? Please provide detailed steps for reproducing the issue.*
+*A picture or gif animation tells a thousand words*
+
+## Context
+
+Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
+
+* Operating System:
+* Terminal Emulator: (i.e. iTerm2)
+* tag of go-prompt or commit revision:
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb816a2496376983781774cb5466fed8e1efc93b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,13 @@
+---
+name: "Feature request"
+about: Suggest an idea for new features in go-prompt.
+title: "[Feature Request]"
+labels: enhancement
+assignees: ''
+
+---
+
+# Feature Request
+
+*Please write your suggestion here.*
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/.gitignore b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..eba2b56abe0f7758a560d47dd19d8985b67ef327
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+bin/
+
+# Folders
+pkg/
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+# Glide
+vendor/
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/CHANGELOG.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..b9e21f1ef333b9ec13323bcd4a8f377322ed7e9f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/CHANGELOG.md
@@ -0,0 +1,79 @@
+# Change Log
+
+## v0.3.0 (2018/??/??)
+
+next release.
+
+## v0.2.3 (2018/10/25)
+
+### What's new?
+
+* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92).
+* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100).
+* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102).
+
+### Fixed
+
+* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details).
+* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details).
+* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details).
+
+### Removed or Deprecated
+
+* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`.
+
+## v0.2.2 (2018/06/28)
+
+### What's new?
+
+* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters.
+* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions.
+ * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details).
+* Add FilePathCompleter to complete file path on your system.
+* Add option to customize ascii code key bindings.
+* Add GetWordAfterCursor method in Document.
+
+### Removed or Deprecated
+
+* prompt.Choose shortcut function is deprecated.
+
+## v0.2.1 (2018/02/14)
+
+### What's New?
+
+* ~~It seems that windows support is almost perfect.~~
+ * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows.
+
+### Fixed
+
+* Fix a Shift+Tab handling on Windows.
+* Fix 4-dimension arrow keys handling on Windows.
+
+## v0.2.0 (2018/02/13)
+
+### What's New?
+
+* Supports scrollbar when there are too many matched suggestions
+* Windows support (but please caution because this is still not perfect).
+* Add OptionLivePrefix to update the prefix dynamically
+* Implement clear screen by `Ctrl+L`.
+
+### Fixed
+
+* Fix the behavior of `Ctrl+W` keybind.
+* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details).
+* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details).
+* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ).
+
+### News
+
+New core developers are joined (alphabetical order).
+
+* Nao Yonashiro (Github @orisano)
+* Ryoma Abe (Github @Allajah)
+* Yusuke Nakamura (Github @unasuke)
+
+
+## v0.1.0 (2017/08/15)
+
+Initial Release
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/LICENSE b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a86acaa7ab24fe61ea152a9afcadc21980020efb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Masashi SHIBATA
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/Makefile b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..505817c36f0b8a0bb643eed8680b8989af2b0920
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/Makefile
@@ -0,0 +1,46 @@
+.DEFAULT_GOAL := help
+
+SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
+
+GOIMPORTS ?= goimports
+GOCILINT ?= golangci-lint
+
+.PHONY: setup
+setup: ## Setup for required tools.
+ go get -u golang.org/x/tools/cmd/goimports
+ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: fmt
+fmt: $(SOURCES) ## Formatting source codes.
+ @$(GOIMPORTS) -w $^
+
+.PHONY: lint
+lint: ## Run golangci-lint.
+ @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
+
+.PHONY: test
+test: ## Run tests with race condition checking.
+ @go test -race ./...
+
+.PHONY: bench
+bench: ## Run benchmarks.
+ @go test -bench=. -run=- -benchmem ./...
+
+.PHONY: coverage
+cover: ## Run the tests.
+ @go test -coverprofile=coverage.o
+ @go tool cover -func=coverage.o
+
+.PHONY: generate
+generate: ## Run go generate
+ @go generate ./...
+
+.PHONY: build
+build: ## Build example command lines.
+ ./_example/build.sh
+
+.PHONY: help
+help: ## Show help text
+ @echo "Commands:"
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfcd7a399b4827d6b126d6a173cce34d36520481
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/README.md
@@ -0,0 +1,125 @@
+# go-prompt
+
+[](https://goreportcard.com/report/github.com/c-bata/go-prompt)
+
+[](https://godoc.org/github.com/c-bata/go-prompt)
+
+
+A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit),
+making it easier to build cross-platform command line tools using Go.
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func completer(d prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ }
+ return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ fmt.Println("Please select table.")
+ t := prompt.Input("> ", completer)
+ fmt.Println("You selected " + t)
+}
+```
+
+#### Projects using go-prompt
+
+* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt)
+* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli)
+* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn)
+* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli)
+* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans)
+* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit)
+* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go)
+* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS)
+* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs)
+* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli)
+* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt)
+* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh)
+* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell)
+* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt)
+* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim)
+* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron)
+* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl)
+* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl)
+* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit)
+* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.)
+
+## Features
+
+### Powerful auto-completion
+
+[](https://github.com/c-bata/kube-prompt)
+
+(This is a GIF animation of kube-prompt.)
+
+### Flexible options
+
+go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details.
+
+[](#flexible-options)
+
+### Keyboard Shortcuts
+
+Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell).
+You can customize and expand these shortcuts.
+
+[](#keyboard-shortcuts)
+
+Key Binding | Description
+---------------------|---------------------------------------------------------
+Ctrl + A | Go to the beginning of the line (Home)
+Ctrl + E | Go to the end of the line (End)
+Ctrl + P | Previous command (Up arrow)
+Ctrl + N | Next command (Down arrow)
+Ctrl + F | Forward one character
+Ctrl + B | Backward one character
+Ctrl + D | Delete character under the cursor
+Ctrl + H | Delete character before the cursor (Backspace)
+Ctrl + W | Cut the word before the cursor to the clipboard
+Ctrl + K | Cut the line after the cursor to the clipboard
+Ctrl + U | Cut the line before the cursor to the clipboard
+Ctrl + L | Clear the screen
+
+### History
+
+You can use Up arrow and Down arrow to walk through the history of commands executed.
+
+[](#history)
+
+### Multiple platform support
+
+We have confirmed go-prompt works fine in the following terminals:
+
+* iTerm2 (macOS)
+* Terminal.app (macOS)
+* Command Prompt (Windows)
+* gnome-terminal (Ubuntu)
+
+## Links
+
+* [Change Log](./CHANGELOG.md)
+* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt)
+* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt)
+
+## Author
+
+Masashi Shibata
+
+* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/)
+* Github: [@c-bata](https://github.com/c-bata/)
+
+## License
+
+This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..759b0e3f8acf1216b055e0f9458758a6c1e8950a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/README.md
@@ -0,0 +1,30 @@
+# Examples of go-prompt
+
+This directory includes some examples using go-prompt.
+These examples are useful to know the usage of go-prompt and check behavior for development.
+
+## simple-echo
+
+
+
+A simple echo example using `prompt.Input`.
+
+## http-prompt
+
+
+
+A simple [http-prompt](https://github.com/eliangcs/http-prompt) implementation using go-prompt in less than 200 lines of Go.
+
+## live-prefix
+
+
+
+A example application which changes a prefix string dynamically.
+This feature is used like [ktr0731/evans](https://github.com/ktr0731/evans) which is interactive gRPC client using go-prompt.
+
+## exec-command
+
+Run another CLI tool via `os/exec` package.
+More practical example is [a source code of kube-prompt](https://github.com/c-bata/kube-prompt).
+I recommend you to look this if you want to create tools like kube-prompt.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/build.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c552afcfa69b2356ffcd484c867abcaaaaeeaff
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+export GO111MODULE=on
+DIR=$(cd $(dirname $0); pwd)
+BIN_DIR=$(cd $(dirname $(dirname $0)); pwd)/bin
+
+mkdir -p ${BIN_DIR}
+go build -o ${BIN_DIR}/exec-command ${DIR}/exec-command/main.go
+go build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.go
+go build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.go
+go build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.go
+go build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/exec-command/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/exec-command/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..838f756260df91569491def29a7ee05a7c9a98f7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/exec-command/main.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "os/exec"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(t string) {
+ if t == "bash" {
+ cmd := exec.Command("bash")
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Run()
+ }
+ return
+}
+
+func completer(t prompt.Document) []prompt.Suggest {
+ return []prompt.Suggest{
+ {Text: "bash"},
+ }
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/http-prompt/api.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/http-prompt/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..08e7b1a489a2077f26f280fe39e3bd06efa52cd2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/http-prompt/api.py
@@ -0,0 +1,17 @@
+from bottle import route, run, request
+
+@route('/')
+def hello():
+ return "Hello World!"
+
+@route('/ping')
+def hello():
+ return "pong!"
+
+@route('/register', method='POST')
+def register():
+ name = request.json.get("name")
+ return "Hello %s!" % name
+
+if __name__ == "__main__":
+ run(host='localhost', port=8000, debug=True)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/http-prompt/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/http-prompt/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b372a3550c50121d6e500e2a08e641e168b8c00d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/http-prompt/main.go
@@ -0,0 +1,192 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+type RequestContext struct {
+ url *url.URL
+ header http.Header
+ client *http.Client
+}
+
+var ctx *RequestContext
+
+// See https://github.com/eliangcs/http-prompt/blob/master/http_prompt/completion.py
+var suggestions = []prompt.Suggest{
+ // Command
+ {"cd", "Change URL/path"},
+ {"exit", "Exit http-prompt"},
+
+ // HTTP Method
+ {"delete", "DELETE request"},
+ {"get", "GET request"},
+ {"patch", "GET request"},
+ {"post", "POST request"},
+ {"put", "PUT request"},
+
+ // HTTP Header
+ {"Accept", "Acceptable response media type"},
+ {"Accept-Charset", "Acceptable response charsets"},
+ {"Accept-Encoding", "Acceptable response content codings"},
+ {"Accept-Language", "Preferred natural languages in response"},
+ {"ALPN", "Application-layer protocol negotiation to use"},
+ {"Alt-Used", "Alternative host in use"},
+ {"Authorization", "Authentication information"},
+ {"Cache-Control", "Directives for caches"},
+ {"Connection", "Connection options"},
+ {"Content-Encoding", "Content codings"},
+ {"Content-Language", "Natural languages for content"},
+ {"Content-Length", "Anticipated size for payload body"},
+ {"Content-Location", "Where content was obtained"},
+ {"Content-MD5", "Base64-encoded MD5 sum of content"},
+ {"Content-Type", "Content media type"},
+ {"Cookie", "Stored cookies"},
+ {"Date", "Datetime when message was originated"},
+ {"Depth", "Applied only to resource or its members"},
+ {"DNT", "Do not track user"},
+ {"Expect", "Expected behaviors supported by server"},
+ {"Forwarded", "Proxies involved"},
+ {"From", "Sender email address"},
+ {"Host", "Target URI"},
+ {"HTTP2-Settings", "HTTP/2 connection parameters"},
+ {"If", "Request condition on state tokens and ETags"},
+ {"If-Match", "Request condition on target resource"},
+ {"If-Modified-Since", "Request condition on modification date"},
+ {"If-None-Match", "Request condition on target resource"},
+ {"If-Range", "Request condition on Range"},
+ {"If-Schedule-Tag-Match", "Request condition on Schedule-Tag"},
+ {"If-Unmodified-Since", "Request condition on modification date"},
+ {"Max-Forwards", "Max number of times forwarded by proxies"},
+ {"MIME-Version", "Version of MIME protocol"},
+ {"Origin", "Origin(s} issuing the request"},
+ {"Pragma", "Implementation-specific directives"},
+ {"Prefer", "Preferred server behaviors"},
+ {"Proxy-Authorization", "Proxy authorization credentials"},
+ {"Proxy-Connection", "Proxy connection options"},
+ {"Range", "Request transfer of only part of data"},
+ {"Referer", "Previous web page"},
+ {"TE", "Transfer codings willing to accept"},
+ {"Transfer-Encoding", "Transfer codings applied to payload body"},
+ {"Upgrade", "Invite server to upgrade to another protocol"},
+ {"User-Agent", "User agent string"},
+ {"Via", "Intermediate proxies"},
+ {"Warning", "Possible incorrectness with payload body"},
+ {"WWW-Authenticate", "Authentication scheme"},
+ {"X-Csrf-Token", "Prevent cross-site request forgery"},
+ {"X-CSRFToken", "Prevent cross-site request forgery"},
+ {"X-Forwarded-For", "Originating client IP address"},
+ {"X-Forwarded-Host", "Original host requested by client"},
+ {"X-Forwarded-Proto", "Originating protocol"},
+ {"X-Http-Method-Override", "Request method override"},
+ {"X-Requested-With", "Used to identify Ajax requests"},
+ {"X-XSRF-TOKEN", "Prevent cross-site request forgery"},
+}
+
+func livePrefix() (string, bool) {
+ if ctx.url.Path == "/" {
+ return "", false
+ }
+ return ctx.url.String() + "> ", true
+}
+
+func executor(in string) {
+ in = strings.TrimSpace(in)
+
+ var method, body string
+ blocks := strings.Split(in, " ")
+ switch blocks[0] {
+ case "exit":
+ fmt.Println("Bye!")
+ os.Exit(0)
+ case "cd":
+ if len(blocks) < 2 {
+ ctx.url.Path = "/"
+ } else {
+ ctx.url.Path = path.Join(ctx.url.Path, blocks[1])
+ }
+ return
+ case "get", "delete":
+ method = strings.ToUpper(blocks[0])
+ case "post", "put", "patch":
+ if len(blocks) < 2 {
+ fmt.Println("please set request body.")
+ return
+ }
+ body = strings.Join(blocks[1:], " ")
+ method = strings.ToUpper(blocks[0])
+ }
+ if method != "" {
+ req, err := http.NewRequest(method, ctx.url.String(), strings.NewReader(body))
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ req.Header = ctx.header
+ res, err := ctx.client.Do(req)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ result, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ fmt.Printf("%s\n", result)
+ ctx.header = http.Header{}
+ return
+ }
+
+ if h := strings.Split(in, ":"); len(h) == 2 {
+ // Handling HTTP Header
+ ctx.header.Add(strings.TrimSpace(h[0]), strings.Trim(h[1], ` '"`))
+ } else {
+ fmt.Println("Sorry, I don't understand.")
+ }
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ w := in.GetWordBeforeCursor()
+ if w == "" {
+ return []prompt.Suggest{}
+ }
+ return prompt.FilterHasPrefix(suggestions, w, true)
+}
+
+func main() {
+ var baseURL = "http://localhost:8000/"
+ if len(os.Args) == 2 {
+ baseURL = os.Args[1]
+ if strings.HasSuffix(baseURL, "/") {
+ baseURL += "/"
+ }
+ }
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ ctx = &RequestContext{
+ url: u,
+ header: http.Header{},
+ client: &http.Client{},
+ }
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(u.String()+"> "),
+ prompt.OptionLivePrefix(livePrefix),
+ prompt.OptionTitle("http-prompt"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/live-prefix/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/live-prefix/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c7ced720592173e2a13f19f7cb543730192d3f8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/live-prefix/main.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var LivePrefixState struct {
+ LivePrefix string
+ IsEnable bool
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+ if in == "" {
+ LivePrefixState.IsEnable = false
+ LivePrefixState.LivePrefix = in
+ return
+ }
+ LivePrefixState.LivePrefix = in + "> "
+ LivePrefixState.IsEnable = true
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func changeLivePrefix() (string, bool) {
+ return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionLivePrefix(changeLivePrefix),
+ prompt.OptionTitle("live-prefix-example"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/simple-echo/cjk-cyrillic/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/simple-echo/cjk-cyrillic/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e9e53adef1558e004f86ccbca2c2e2b83c1da39
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/simple-echo/cjk-cyrillic/main.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
+ {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
+ {Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
+ {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionTitle("sql-prompt for multi width characters"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/simple-echo/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/simple-echo/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..12b1bb4fc189e6b369e889779418d7826a45db9d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_example/simple-echo/main.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ in := prompt.Input(">>> ", completer,
+ prompt.OptionTitle("sql-prompt"),
+ prompt.OptionHistory([]string{"SELECT * FROM users;"}),
+ prompt.OptionPrefixTextColor(prompt.Yellow),
+ prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
+ prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
+ prompt.OptionSuggestionBGColor(prompt.DarkGray))
+ fmt.Println("Your input: " + in)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_tools/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..45bd2234f21ff32562984bec046316c8e52868fd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_tools/README.md
@@ -0,0 +1,10 @@
+## Tools of go-prompt
+
+### vt100_debug
+
+
+
+### sigwinch
+
+
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_tools/complete_file/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_tools/complete_file/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..41015cfab9b021fbc7df575bde87e3c510705496
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_tools/complete_file/main.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/completer"
+)
+
+var filePathCompleter = completer.FilePathCompleter{
+ IgnoreCase: true,
+ Filter: func(fi os.FileInfo) bool {
+ return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
+ },
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completerFunc(d prompt.Document) []prompt.Suggest {
+ t := d.GetWordBeforeCursor()
+ if strings.HasPrefix(t, "--") {
+ return []prompt.Suggest{
+ {"--foo", ""},
+ {"--bar", ""},
+ {"--baz", ""},
+ }
+ }
+ return filePathCompleter.Complete(d)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completerFunc,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_tools/sigwinch/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_tools/sigwinch/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9608eb3b4a5e3c6942c140c41e08a36ab3adb33b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_tools/sigwinch/main.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "unsafe"
+)
+
+// Winsize is winsize struct got from the ioctl(2) system call.
+type Winsize struct {
+ Row uint16
+ Col uint16
+ X uint16 // pixel value
+ Y uint16 // pixel value
+}
+
+// GetWinSize returns winsize struct which is the response of ioctl(2).
+func GetWinSize(fd int) *Winsize {
+ ws := &Winsize{}
+ retCode, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ uintptr(fd),
+ uintptr(syscall.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(ws)))
+
+ if int(retCode) == -1 {
+ panic(errno)
+ }
+ return ws
+}
+
+func main() {
+ signalChan := make(chan os.Signal, 1)
+ signal.Notify(
+ signalChan,
+ syscall.SIGHUP,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ exitChan := make(chan int)
+ go func() {
+ for {
+ s := <-signalChan
+ switch s {
+ // kill -SIGHUP XXXX
+ case syscall.SIGHUP:
+ exitChan <- 0
+
+ // kill -SIGINT XXXX or Ctrl+c
+ case syscall.SIGINT:
+ exitChan <- 0
+
+ // kill -SIGTERM XXXX
+ case syscall.SIGTERM:
+ exitChan <- 0
+
+ // kill -SIGQUIT XXXX
+ case syscall.SIGQUIT:
+ exitChan <- 0
+
+ case syscall.SIGWINCH:
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ default:
+ exitChan <- 1
+ }
+ }
+ }()
+
+ code := <-exitChan
+ os.Exit(code)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_tools/vt100_debug/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_tools/vt100_debug/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c6036d45959febc739e287a3a7b631259d4ee7c1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/_tools/vt100_debug/main.go
@@ -0,0 +1,47 @@
+// +build !windows
+
+package main
+
+import (
+ "fmt"
+ "syscall"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/term"
+)
+
+func main() {
+ if err := term.SetRaw(syscall.Stdin); err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer term.Restore()
+
+ bufCh := make(chan []byte, 128)
+ go readBuffer(bufCh)
+ fmt.Print("> ")
+
+ for {
+ b := <-bufCh
+ if key := prompt.GetKey(b); key == prompt.NotDefined {
+ fmt.Printf("Key '%s' data:'%#v'\n", string(b), b)
+ } else {
+ if key == prompt.ControlC {
+ fmt.Println("exit.")
+ return
+ }
+ fmt.Printf("Key '%s' data:'%#v'\n", key, b)
+ }
+ fmt.Print("> ")
+ }
+}
+
+func readBuffer(bufCh chan []byte) {
+ buf := make([]byte, 1024)
+
+ for {
+ if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
+ bufCh <- buf[:n]
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/buffer.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..46efbbba8bfb75f4a064c83368b781d1d6dbbb29
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/buffer.go
@@ -0,0 +1,191 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Buffer emulates the console buffer.
+type Buffer struct {
+ workingLines []string // The working lines. Similar to history
+ workingIndex int
+ cursorPosition int
+ cacheDocument *Document
+ preferredColumn int // Remember the original column for the next up/down movement.
+ lastKeyStroke Key
+}
+
+// Text returns string of the current line.
+func (b *Buffer) Text() string {
+ return b.workingLines[b.workingIndex]
+}
+
+// Document method to return document instance from the current text and cursor position.
+func (b *Buffer) Document() (d *Document) {
+ if b.cacheDocument == nil ||
+ b.cacheDocument.Text != b.Text() ||
+ b.cacheDocument.cursorPosition != b.cursorPosition {
+ b.cacheDocument = &Document{
+ Text: b.Text(),
+ cursorPosition: b.cursorPosition,
+ }
+ }
+ b.cacheDocument.lastKey = b.lastKeyStroke
+ return b.cacheDocument
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (b *Buffer) DisplayCursorPosition() int {
+ return b.Document().DisplayCursorPosition()
+}
+
+// InsertText insert string from current line.
+func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
+ or := []rune(b.Text())
+ oc := b.cursorPosition
+
+ if overwrite {
+ overwritten := string(or[oc : oc+len(v)])
+ if strings.Contains(overwritten, "\n") {
+ i := strings.IndexAny(overwritten, "\n")
+ overwritten = overwritten[:i]
+ }
+ b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):]))
+ } else {
+ b.setText(string(or[:oc]) + v + string(or[oc:]))
+ }
+
+ if moveCursor {
+ b.cursorPosition += len([]rune(v))
+ }
+}
+
+// SetText method to set text and update cursorPosition.
+// (When doing this, make sure that the cursor_position is valid for this text.
+// text/cursor_position should be consistent at any time, otherwise set a Document instead.)
+func (b *Buffer) setText(v string) {
+ debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position")
+ b.workingLines[b.workingIndex] = v
+}
+
+// Set cursor position. Return whether it changed.
+func (b *Buffer) setCursorPosition(p int) {
+ if p > 0 {
+ b.cursorPosition = p
+ } else {
+ b.cursorPosition = 0
+ }
+}
+
+func (b *Buffer) setDocument(d *Document) {
+ b.cacheDocument = d
+ b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length.
+ b.setText(d.Text)
+}
+
+// CursorLeft move to left on the current line.
+func (b *Buffer) CursorLeft(count int) {
+ l := b.Document().GetCursorLeftPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorRight move to right on the current line.
+func (b *Buffer) CursorRight(count int) {
+ l := b.Document().GetCursorRightPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorUp move cursor to the previous line.
+// (for multi-line edit).
+func (b *Buffer) CursorUp(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorUpPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// CursorDown move cursor to the next line.
+// (for multi-line edit).
+func (b *Buffer) CursorDown(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorDownPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text.
+func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) {
+ debug.Assert(count >= 0, "count should be positive")
+ r := []rune(b.Text())
+
+ if b.cursorPosition > 0 {
+ start := b.cursorPosition - count
+ if start < 0 {
+ start = 0
+ }
+ deleted = string(r[start:b.cursorPosition])
+ b.setDocument(&Document{
+ Text: string(r[:start]) + string(r[b.cursorPosition:]),
+ cursorPosition: b.cursorPosition - len([]rune(deleted)),
+ })
+ }
+ return
+}
+
+// NewLine means CR.
+func (b *Buffer) NewLine(copyMargin bool) {
+ if copyMargin {
+ b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true)
+ } else {
+ b.InsertText("\n", false, true)
+ }
+}
+
+// Delete specified number of characters and Return the deleted text.
+func (b *Buffer) Delete(count int) (deleted string) {
+ r := []rune(b.Text())
+ if b.cursorPosition < len(r) {
+ deleted = b.Document().TextAfterCursor()[:count]
+ b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):]))
+ }
+ return
+}
+
+// JoinNextLine joins the next line to the current one by deleting the line ending after the current line.
+func (b *Buffer) JoinNextLine(separator string) {
+ if !b.Document().OnLastLine() {
+ b.cursorPosition += b.Document().GetEndOfLinePosition()
+ b.Delete(1)
+ // Remove spaces
+ b.setText(b.Document().TextBeforeCursor() + separator + strings.TrimLeft(b.Document().TextAfterCursor(), " "))
+ }
+}
+
+// SwapCharactersBeforeCursor swaps the last two characters before the cursor.
+func (b *Buffer) SwapCharactersBeforeCursor() {
+ if b.cursorPosition >= 2 {
+ x := b.Text()[b.cursorPosition-2 : b.cursorPosition-1]
+ y := b.Text()[b.cursorPosition-1 : b.cursorPosition]
+ b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:])
+ }
+}
+
+// NewBuffer is constructor of Buffer struct.
+func NewBuffer() (b *Buffer) {
+ b = &Buffer{
+ workingLines: []string{""},
+ workingIndex: 0,
+ preferredColumn: -1, // -1 means nil
+ }
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/completer/file.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/completer/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..59f2d8dec84214ccaa6e345a11ed51aa61a08199
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/completer/file.go
@@ -0,0 +1,90 @@
+package completer
+
+import (
+ "io/ioutil"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+var (
+ // FilePathCompletionSeparator holds separate characters.
+ FilePathCompletionSeparator = string([]byte{' ', os.PathSeparator})
+)
+
+// FilePathCompleter is a completer for your local file system.
+// Please caution that you need to set OptionCompletionWordSeparator(completer.FilePathCompletionSeparator)
+// when you use this completer.
+type FilePathCompleter struct {
+ Filter func(fi os.FileInfo) bool
+ IgnoreCase bool
+ fileListCache map[string][]prompt.Suggest
+}
+
+func cleanFilePath(path string) (dir, base string, err error) {
+ if path == "" {
+ return ".", "", nil
+ }
+
+ var endsWithSeparator bool
+ if len(path) >= 1 && path[len(path)-1] == os.PathSeparator {
+ endsWithSeparator = true
+ }
+
+ if runtime.GOOS != "windows" && len(path) >= 2 && path[0:2] == "~/" {
+ me, err := user.Current()
+ if err != nil {
+ return "", "", err
+ }
+ path = filepath.Join(me.HomeDir, path[1:])
+ }
+ path = filepath.Clean(os.ExpandEnv(path))
+ dir = filepath.Dir(path)
+ base = filepath.Base(path)
+
+ if endsWithSeparator {
+ dir = path + string(os.PathSeparator) // Append slash(in POSIX) if path ends with slash.
+ base = "" // Set empty string if path ends with separator.
+ }
+ return dir, base, nil
+}
+
+// Complete returns suggestions from your local file system.
+func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest {
+ if c.fileListCache == nil {
+ c.fileListCache = make(map[string][]prompt.Suggest, 4)
+ }
+
+ path := d.GetWordBeforeCursor()
+ dir, base, err := cleanFilePath(path)
+ if err != nil {
+ debug.Log("completer: cannot get current user:" + err.Error())
+ return nil
+ }
+
+ if cached, ok := c.fileListCache[dir]; ok {
+ return prompt.FilterHasPrefix(cached, base, c.IgnoreCase)
+ }
+
+ files, err := ioutil.ReadDir(dir)
+ if err != nil && os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ debug.Log("completer: cannot read directory items:" + err.Error())
+ return nil
+ }
+
+ suggests := make([]prompt.Suggest, 0, len(files))
+ for _, f := range files {
+ if c.Filter != nil && !c.Filter(f) {
+ continue
+ }
+ suggests = append(suggests, prompt.Suggest{Text: f.Name()})
+ }
+ c.fileListCache[dir] = suggests
+ return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/completion.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/completion.go
new file mode 100644
index 0000000000000000000000000000000000000000..57e82eefc0f50e9561214704e770a2ad313a3659
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/completion.go
@@ -0,0 +1,190 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+const (
+ shortenSuffix = "..."
+ leftPrefix = " "
+ leftSuffix = " "
+ rightPrefix = " "
+ rightSuffix = " "
+)
+
+var (
+ leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix)
+ rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix)
+ completionMargin = leftMargin + rightMargin
+)
+
+// Suggest is printed when completing.
+type Suggest struct {
+ Text string
+ Description string
+}
+
+// CompletionManager manages which suggestion is now selected.
+type CompletionManager struct {
+ selected int // -1 means nothing one is selected.
+ tmp []Suggest
+ max uint16
+ completer Completer
+
+ verticalScroll int
+ wordSeparator string
+ showAtStart bool
+}
+
+// GetSelectedSuggestion returns the selected item.
+func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) {
+ if c.selected == -1 {
+ return Suggest{}, false
+ } else if c.selected < -1 {
+ debug.Assert(false, "must not reach here")
+ c.selected = -1
+ return Suggest{}, false
+ }
+ return c.tmp[c.selected], true
+}
+
+// GetSuggestions returns the list of suggestion.
+func (c *CompletionManager) GetSuggestions() []Suggest {
+ return c.tmp
+}
+
+// Reset to select nothing.
+func (c *CompletionManager) Reset() {
+ c.selected = -1
+ c.verticalScroll = 0
+ c.Update(*NewDocument())
+}
+
+// Update to update the suggestions.
+func (c *CompletionManager) Update(in Document) {
+ c.tmp = c.completer(in)
+}
+
+// Previous to select the previous suggestion item.
+func (c *CompletionManager) Previous() {
+ if c.verticalScroll == c.selected && c.selected > 0 {
+ c.verticalScroll--
+ }
+ c.selected--
+ c.update()
+}
+
+// Next to select the next suggestion item.
+func (c *CompletionManager) Next() {
+ if c.verticalScroll+int(c.max)-1 == c.selected {
+ c.verticalScroll++
+ }
+ c.selected++
+ c.update()
+}
+
+// Completing returns whether the CompletionManager selects something one.
+func (c *CompletionManager) Completing() bool {
+ return c.selected != -1
+}
+
+func (c *CompletionManager) update() {
+ max := int(c.max)
+ if len(c.tmp) < max {
+ max = len(c.tmp)
+ }
+
+ if c.selected >= len(c.tmp) {
+ c.Reset()
+ } else if c.selected < -1 {
+ c.selected = len(c.tmp) - 1
+ c.verticalScroll = len(c.tmp) - max
+ }
+}
+
+func deleteBreakLineCharacters(s string) string {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, "\r", "", -1)
+ return s
+}
+
+func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) {
+ l := len(o)
+ n := make([]string, l)
+
+ lenPrefix := runewidth.StringWidth(prefix)
+ lenSuffix := runewidth.StringWidth(suffix)
+ lenShorten := runewidth.StringWidth(shortenSuffix)
+ min := lenPrefix + lenSuffix + lenShorten
+ for i := 0; i < l; i++ {
+ o[i] = deleteBreakLineCharacters(o[i])
+
+ w := runewidth.StringWidth(o[i])
+ if width < w {
+ width = w
+ }
+ }
+
+ if width == 0 {
+ return n, 0
+ }
+ if min >= max {
+ return n, 0
+ }
+ if lenPrefix+width+lenSuffix > max {
+ width = max - lenPrefix - lenSuffix
+ }
+
+ for i := 0; i < l; i++ {
+ x := runewidth.StringWidth(o[i])
+ if x <= width {
+ spaces := strings.Repeat(" ", width-x)
+ n[i] = prefix + o[i] + spaces + suffix
+ } else if x > width {
+ x := runewidth.Truncate(o[i], width, shortenSuffix)
+ // When calling runewidth.Truncate("您好xxx您好xxx", 11, "...") returns "您好xxx..."
+ // But the length of this result is 10. So we need fill right using runewidth.FillRight.
+ n[i] = prefix + runewidth.FillRight(x, width) + suffix
+ }
+ }
+ return n, lenPrefix + width + lenSuffix
+}
+
+func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) {
+ num := len(suggests)
+ new = make([]Suggest, num)
+
+ left := make([]string, num)
+ for i := 0; i < num; i++ {
+ left[i] = suggests[i].Text
+ }
+ right := make([]string, num)
+ for i := 0; i < num; i++ {
+ right[i] = suggests[i].Description
+ }
+
+ left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix)
+ if leftWidth == 0 {
+ return []Suggest{}, 0
+ }
+ right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix)
+
+ for i := 0; i < num; i++ {
+ new[i] = Suggest{Text: left[i], Description: right[i]}
+ }
+ return new, leftWidth + rightWidth
+}
+
+// NewCompletionManager returns initialized CompletionManager object.
+func NewCompletionManager(completer Completer, max uint16) *CompletionManager {
+ return &CompletionManager{
+ selected: -1,
+ max: max,
+ completer: completer,
+
+ verticalScroll: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/document.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/document.go
new file mode 100644
index 0000000000000000000000000000000000000000..167d3dd04cf6dca798e5a6c96a0cd28a43725a9b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/document.go
@@ -0,0 +1,441 @@
+package prompt
+
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+ istrings "github.com/c-bata/go-prompt/internal/strings"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Document has text displayed in terminal and cursor position.
+type Document struct {
+ Text string
+ // This represents a index in a rune array of Document.Text.
+ // So if Document is "日本(cursor)語", cursorPosition is 2.
+ // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+ cursorPosition int
+ lastKey Key
+}
+
+// NewDocument return the new empty document.
+func NewDocument() *Document {
+ return &Document{
+ Text: "",
+ cursorPosition: 0,
+ }
+}
+
+// LastKeyStroke return the last key pressed in this document.
+func (d *Document) LastKeyStroke() Key {
+ return d.lastKey
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (d *Document) DisplayCursorPosition() int {
+ var position int
+ runes := []rune(d.Text)[:d.cursorPosition]
+ for i := range runes {
+ position += runewidth.RuneWidth(runes[i])
+ }
+ return position
+}
+
+// GetCharRelativeToCursor return character relative to cursor position, or empty string
+func (d *Document) GetCharRelativeToCursor(offset int) (r rune) {
+ s := d.Text
+ cnt := 0
+
+ for len(s) > 0 {
+ cnt++
+ r, size := utf8.DecodeRuneInString(s)
+ if cnt == d.cursorPosition+offset {
+ return r
+ }
+ s = s[size:]
+ }
+ return 0
+}
+
+// TextBeforeCursor returns the text before the cursor.
+func (d *Document) TextBeforeCursor() string {
+ r := []rune(d.Text)
+ return string(r[:d.cursorPosition])
+}
+
+// TextAfterCursor returns the text after the cursor.
+func (d *Document) TextAfterCursor() string {
+ r := []rune(d.Text)
+ return string(r[d.cursorPosition:])
+}
+
+// GetWordBeforeCursor returns the word before the cursor.
+// If we have whitespace before the cursor this returns an empty string.
+func (d *Document) GetWordBeforeCursor() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWord():]
+}
+
+// GetWordAfterCursor returns the word after the cursor.
+// If we have whitespace after the cursor this returns an empty string.
+func (d *Document) GetWordAfterCursor() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWord()]
+}
+
+// GetWordBeforeCursorWithSpace returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorWithSpace() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordWithSpace():]
+}
+
+// GetWordAfterCursorWithSpace returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorWithSpace() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordWithSpace()]
+}
+
+// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
+func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparator(sep):]
+}
+
+// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
+func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparator(sep)]
+}
+
+// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):]
+}
+
+// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)]
+}
+
+// FindStartOfPreviousWord returns an index relative to the cursor position
+// pointing to the start of the previous word. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWord() int {
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexByte(x, ' ')
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindStartOfPreviousWordWithSpace() int {
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotByte(x, ' ')
+ if end == -1 {
+ return 0
+ }
+
+ start := strings.LastIndexByte(x[:end], ' ')
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWord()
+ }
+
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWordWithSpace()
+ }
+
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotAny(x, sep)
+ if end == -1 {
+ return 0
+ }
+ start := strings.LastIndexAny(x[:end], sep)
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindEndOfCurrentWord returns an index relative to the cursor position.
+// pointing to the end of the current word. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWord() int {
+ x := d.TextAfterCursor()
+ i := strings.IndexByte(x, ' ')
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindEndOfCurrentWordWithSpace() int {
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotByte(x, ' ')
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexByte(x[start:], ' ')
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWord()
+ }
+
+ x := d.TextAfterCursor()
+ i := strings.IndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWordWithSpace()
+ }
+
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotAny(x, sep)
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexAny(x[start:], sep)
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// CurrentLineBeforeCursor returns the text from the start of the line until the cursor.
+func (d *Document) CurrentLineBeforeCursor() string {
+ s := strings.Split(d.TextBeforeCursor(), "\n")
+ return s[len(s)-1]
+}
+
+// CurrentLineAfterCursor returns the text from the cursor until the end of the line.
+func (d *Document) CurrentLineAfterCursor() string {
+ return strings.Split(d.TextAfterCursor(), "\n")[0]
+}
+
+// CurrentLine return the text on the line where the cursor is. (when the input
+// consists of just one line, it equals `text`.
+func (d *Document) CurrentLine() string {
+ return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor()
+}
+
+// Array pointing to the start indexes of all the lines.
+func (d *Document) lineStartIndexes() []int {
+ // TODO: Cache, because this is often reused.
+ // (If it is used, it's often used many times.
+ // And this has to be fast for editing big documents!)
+ lc := d.LineCount()
+ lengths := make([]int, lc)
+ for i, l := range d.Lines() {
+ lengths[i] = len(l)
+ }
+
+ // Calculate cumulative sums.
+ indexes := make([]int, lc+1)
+ indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189
+ pos := 0
+ for i, l := range lengths {
+ pos += l + 1
+ indexes[i+1] = pos
+ }
+ if lc > 1 {
+ // Pop the last item. (This is not a new line.)
+ indexes = indexes[:lc]
+ }
+ return indexes
+}
+
+// For the index of a character at a certain line, calculate the index of
+// the first character on that line.
+func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) {
+ indexes := d.lineStartIndexes()
+ pos = bisect.Right(indexes, index) - 1
+ lineStartIndex = indexes[pos]
+ return
+}
+
+// CursorPositionRow returns the current row. (0-based.)
+func (d *Document) CursorPositionRow() (row int) {
+ row, _ = d.findLineStartIndex(d.cursorPosition)
+ return
+}
+
+// CursorPositionCol returns the current column. (0-based.)
+func (d *Document) CursorPositionCol() (col int) {
+ // Don't use self.text_before_cursor to calculate this. Creating substrings
+ // and splitting is too expensive for getting the cursor position.
+ _, index := d.findLineStartIndex(d.cursorPosition)
+ col = d.cursorPosition - index
+ return
+}
+
+// GetCursorLeftPosition returns the relative position for cursor left.
+func (d *Document) GetCursorLeftPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorRightPosition(-count)
+ }
+ if d.CursorPositionCol() > count {
+ return -count
+ }
+ return -d.CursorPositionCol()
+}
+
+// GetCursorRightPosition returns relative position for cursor right.
+func (d *Document) GetCursorRightPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorLeftPosition(-count)
+ }
+ if len(d.CurrentLineAfterCursor()) > count {
+ return count
+ }
+ return len(d.CurrentLineAfterCursor())
+}
+
+// GetCursorUpPosition return the relative cursor position (character index) where we would be
+// if the user pressed the arrow-up button.
+func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+
+ row := d.CursorPositionRow() - count
+ if row < 0 {
+ row = 0
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// GetCursorDownPosition return the relative cursor position (character index) where we would be if the
+// user pressed the arrow-down button.
+func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+ row := d.CursorPositionRow() + count
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// Lines returns the array of all the lines.
+func (d *Document) Lines() []string {
+ // TODO: Cache, because this one is reused very often.
+ return strings.Split(d.Text, "\n")
+}
+
+// LineCount return the number of lines in this document. If the document ends
+// with a trailing \n, that counts as the beginning of a new line.
+func (d *Document) LineCount() int {
+ return len(d.Lines())
+}
+
+// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple.
+// (0-based. Returns (0, 0) for index=0.)
+func (d *Document) TranslateIndexToPosition(index int) (row int, col int) {
+ row, rowIndex := d.findLineStartIndex(index)
+ col = index - rowIndex
+ return
+}
+
+// TranslateRowColToIndex given a (row, col), return the corresponding index.
+// (Row and col params are 0-based.)
+func (d *Document) TranslateRowColToIndex(row int, column int) (index int) {
+ indexes := d.lineStartIndexes()
+ if row < 0 {
+ row = 0
+ } else if row > len(indexes) {
+ row = len(indexes) - 1
+ }
+ index = indexes[row]
+ line := d.Lines()[row]
+
+ // python) result += max(0, min(col, len(line)))
+ if column > 0 || len(line) > 0 {
+ if column > len(line) {
+ index += len(line)
+ } else {
+ index += column
+ }
+ }
+
+ // Keep in range. (len(self.text) is included, because the cursor can be
+ // right after the end of the text as well.)
+ // python) result = max(0, min(result, len(self.text)))
+ if index > len(d.Text) {
+ index = len(d.Text)
+ }
+ if index < 0 {
+ index = 0
+ }
+ return index
+}
+
+// OnLastLine returns true when we are at the last line.
+func (d *Document) OnLastLine() bool {
+ return d.CursorPositionRow() == (d.LineCount() - 1)
+}
+
+// GetEndOfLinePosition returns relative position for the end of this line.
+func (d *Document) GetEndOfLinePosition() int {
+ return len([]rune(d.CurrentLineAfterCursor()))
+}
+
+func (d *Document) leadingWhitespaceInCurrentLine() (margin string) {
+ trimmed := strings.TrimSpace(d.CurrentLine())
+ margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)]
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/emacs.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/emacs.go
new file mode 100644
index 0000000000000000000000000000000000000000..632f96321f2577cdb7e8cffe639f1518a65d5e0f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/emacs.go
@@ -0,0 +1,120 @@
+package prompt
+
+import "github.com/c-bata/go-prompt/internal/debug"
+
+/*
+
+========
+PROGRESS
+========
+
+Moving the cursor
+-----------------
+
+* [x] Ctrl + a Go to the beginning of the line (Home)
+* [x] Ctrl + e Go to the End of the line (End)
+* [x] Ctrl + p Previous command (Up arrow)
+* [x] Ctrl + n Next command (Down arrow)
+* [x] Ctrl + f Forward one character
+* [x] Ctrl + b Backward one character
+* [x] Ctrl + xx Toggle between the start of line and current cursor position
+
+Editing
+-------
+
+* [x] Ctrl + L Clear the Screen, similar to the clear command
+* [x] Ctrl + d Delete character under the cursor
+* [x] Ctrl + h Delete character before the cursor (Backspace)
+
+* [x] Ctrl + w Cut the Word before the cursor to the clipboard.
+* [x] Ctrl + k Cut the Line after the cursor to the clipboard.
+* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard.
+
+* [ ] Ctrl + t Swap the last two characters before the cursor (typo).
+* [ ] Esc + t Swap the last two words before the cursor.
+
+* [ ] ctrl + y Paste the last thing to be cut (yank)
+* [ ] ctrl + _ Undo
+
+*/
+
+var emacsKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: ControlE,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+ },
+ },
+ // Go to the beginning of the line
+ {
+ Key: ControlA,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+ },
+ },
+ // Cut the Line after the cursor
+ {
+ Key: ControlK,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.Delete(len(x))
+ },
+ },
+ // Cut/delete the Line before the cursor
+ {
+ Key: ControlU,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.DeleteBeforeCursor(len(x))
+ },
+ },
+ // Delete character under the cursor
+ {
+ Key: ControlD,
+ Fn: func(buf *Buffer) {
+ if buf.Text() != "" {
+ buf.Delete(1)
+ }
+ },
+ },
+ // Backspace
+ {
+ Key: ControlH,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+ },
+ },
+ // Right allow: Forward one character
+ {
+ Key: ControlF,
+ Fn: func(buf *Buffer) {
+ buf.CursorRight(1)
+ },
+ },
+ // Left allow: Backward one character
+ {
+ Key: ControlB,
+ Fn: func(buf *Buffer) {
+ buf.CursorLeft(1)
+ },
+ },
+ // Cut the Word before the cursor.
+ {
+ Key: ControlW,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace())))
+ },
+ },
+ // Clear the Screen, similar to the clear command
+ {
+ Key: ControlL,
+ Fn: func(buf *Buffer) {
+ consoleWriter.EraseScreen()
+ consoleWriter.CursorGoTo(0, 0)
+ debug.AssertNoError(consoleWriter.Flush())
+ },
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/filter.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/filter.go
new file mode 100644
index 0000000000000000000000000000000000000000..61c17ed7f436a069563f520512bd25e4d81af0de
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/filter.go
@@ -0,0 +1,71 @@
+package prompt
+
+import "strings"
+
+// Filter is the type to filter the prompt.Suggestion array.
+type Filter func([]Suggest, string, bool) []Suggest
+
+// FilterHasPrefix checks whether the string completions.Text begins with sub.
+func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
+}
+
+// FilterHasSuffix checks whether the completion.Text ends with sub.
+func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
+}
+
+// FilterContains checks whether the completion.Text contains sub.
+func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
+}
+
+// FilterFuzzy checks whether the completion.Text fuzzy matches sub.
+// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
+// would match, for example, "Good food is gone"
+// ^ ^ ^
+func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
+}
+
+func fuzzyMatch(s, sub string) bool {
+ sChars := []rune(s)
+ sIdx := 0
+
+ // https://staticcheck.io/docs/checks#S1029
+ for _, c := range sub {
+ found := false
+ for ; sIdx < len(sChars); sIdx++ {
+ if sChars[sIdx] == c {
+ found = true
+ sIdx++
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
+
+func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
+ if sub == "" {
+ return suggestions
+ }
+ if ignoreCase {
+ sub = strings.ToUpper(sub)
+ }
+
+ ret := make([]Suggest, 0, len(suggestions))
+ for i := range suggestions {
+ c := suggestions[i].Text
+ if ignoreCase {
+ c = strings.ToUpper(c)
+ }
+ if function(c, sub) {
+ ret = append(ret, suggestions[i])
+ }
+ }
+ return ret
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/go.mod b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..30bc6d39a39c328341ca7153d3391352be5baa63
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/go.mod
@@ -0,0 +1,11 @@
+module github.com/c-bata/go-prompt
+
+go 1.14
+
+require (
+ github.com/mattn/go-colorable v0.1.7
+ github.com/mattn/go-runewidth v0.0.9
+ github.com/mattn/go-tty v0.0.3
+ github.com/pkg/term v1.2.0-beta.2
+ golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/go.sum b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..768bf93619a68e1b334c13e7b93ec84fa465598e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/go.sum
@@ -0,0 +1,23 @@
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/history.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/history.go
new file mode 100644
index 0000000000000000000000000000000000000000..e75c64592d82142bf4826ceb8c613ac72ca24d9c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/history.go
@@ -0,0 +1,61 @@
+package prompt
+
+// History stores the texts that are entered.
+type History struct {
+ histories []string
+ tmp []string
+ selected int
+}
+
+// Add to add text in history.
+func (h *History) Add(input string) {
+ h.histories = append(h.histories, input)
+ h.Clear()
+}
+
+// Clear to clear the history.
+func (h *History) Clear() {
+ h.tmp = make([]string, len(h.histories))
+ for i := range h.histories {
+ h.tmp[i] = h.histories[i]
+ }
+ h.tmp = append(h.tmp, "")
+ h.selected = len(h.tmp) - 1
+}
+
+// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
+ if len(h.tmp) == 1 || h.selected == 0 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected--
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
+ if h.selected >= len(h.tmp)-1 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected++
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// NewHistory returns new history object.
+func NewHistory() *History {
+ return &History{
+ histories: []string{},
+ tmp: []string{""},
+ selected: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/input.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/input.go
new file mode 100644
index 0000000000000000000000000000000000000000..307e747190c2b27bf888b379644fc4f3cdd489a2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/input.go
@@ -0,0 +1,169 @@
+package prompt
+
+import "bytes"
+
+// WinSize represents the width and height of terminal.
+type WinSize struct {
+ Row uint16
+ Col uint16
+}
+
+// ConsoleParser is an interface to abstract input layer.
+type ConsoleParser interface {
+ // Setup should be called before starting input
+ Setup() error
+ // TearDown should be called after stopping input
+ TearDown() error
+ // GetWinSize returns WinSize object to represent width and height of terminal.
+ GetWinSize() *WinSize
+ // Read returns byte array.
+ Read() ([]byte, error)
+}
+
+// GetKey returns Key correspond to input byte codes.
+func GetKey(b []byte) Key {
+ for _, k := range ASCIISequences {
+ if bytes.Equal(k.ASCIICode, b) {
+ return k.Key
+ }
+ }
+ return NotDefined
+}
+
+// ASCIISequences holds mappings of the key and byte array.
+var ASCIISequences = []*ASCIICode{
+ {Key: Escape, ASCIICode: []byte{0x1b}},
+
+ {Key: ControlSpace, ASCIICode: []byte{0x00}},
+ {Key: ControlA, ASCIICode: []byte{0x1}},
+ {Key: ControlB, ASCIICode: []byte{0x2}},
+ {Key: ControlC, ASCIICode: []byte{0x3}},
+ {Key: ControlD, ASCIICode: []byte{0x4}},
+ {Key: ControlE, ASCIICode: []byte{0x5}},
+ {Key: ControlF, ASCIICode: []byte{0x6}},
+ {Key: ControlG, ASCIICode: []byte{0x7}},
+ {Key: ControlH, ASCIICode: []byte{0x8}},
+ //{Key: ControlI, ASCIICode: []byte{0x9}},
+ //{Key: ControlJ, ASCIICode: []byte{0xa}},
+ {Key: ControlK, ASCIICode: []byte{0xb}},
+ {Key: ControlL, ASCIICode: []byte{0xc}},
+ {Key: ControlM, ASCIICode: []byte{0xd}},
+ {Key: ControlN, ASCIICode: []byte{0xe}},
+ {Key: ControlO, ASCIICode: []byte{0xf}},
+ {Key: ControlP, ASCIICode: []byte{0x10}},
+ {Key: ControlQ, ASCIICode: []byte{0x11}},
+ {Key: ControlR, ASCIICode: []byte{0x12}},
+ {Key: ControlS, ASCIICode: []byte{0x13}},
+ {Key: ControlT, ASCIICode: []byte{0x14}},
+ {Key: ControlU, ASCIICode: []byte{0x15}},
+ {Key: ControlV, ASCIICode: []byte{0x16}},
+ {Key: ControlW, ASCIICode: []byte{0x17}},
+ {Key: ControlX, ASCIICode: []byte{0x18}},
+ {Key: ControlY, ASCIICode: []byte{0x19}},
+ {Key: ControlZ, ASCIICode: []byte{0x1a}},
+
+ {Key: ControlBackslash, ASCIICode: []byte{0x1c}},
+ {Key: ControlSquareClose, ASCIICode: []byte{0x1d}},
+ {Key: ControlCircumflex, ASCIICode: []byte{0x1e}},
+ {Key: ControlUnderscore, ASCIICode: []byte{0x1f}},
+ {Key: Backspace, ASCIICode: []byte{0x7f}},
+
+ {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}},
+
+ {Key: Enter, ASCIICode: []byte{0xa}},
+ {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}},
+ {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+ {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}},
+ {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}},
+ {Key: Tab, ASCIICode: []byte{0x9}},
+ {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}},
+ {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}},
+ {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}},
+ {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}},
+ {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode
+
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}},
+ {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}},
+ {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}},
+ {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}},
+ {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}},
+ {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}},
+ {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}},
+ {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}},
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}},
+ {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}},
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+
+ // Xterm
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}},
+ // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}},
+ {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}},
+ {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}},
+ {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}},
+ {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}},
+
+ {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}},
+ {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}},
+ {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}},
+ {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}},
+
+ // Tmux sends following keystrokes when control+arrow is pressed, but for
+ // Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ // it a normal arrow press, because that's more important.
+ {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}},
+
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt
+
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/input_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/input_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f10430318be0e797c841eba8e08ab1cf5277be27
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/input_posix.go
@@ -0,0 +1,77 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/term"
+ "golang.org/x/sys/unix"
+)
+
+const maxReadBytes = 1024
+
+// PosixParser is a ConsoleParser implementation for POSIX environment.
+type PosixParser struct {
+ fd int
+ origTermios syscall.Termios
+}
+
+// Setup should be called before starting input
+func (t *PosixParser) Setup() error {
+ // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
+ if err := syscall.SetNonblock(t.fd, true); err != nil {
+ return err
+ }
+ if err := term.SetRaw(t.fd); err != nil {
+ return err
+ }
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (t *PosixParser) TearDown() error {
+ if err := syscall.SetNonblock(t.fd, false); err != nil {
+ return err
+ }
+ if err := term.Restore(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Read returns byte array.
+func (t *PosixParser) Read() ([]byte, error) {
+ buf := make([]byte, maxReadBytes)
+ n, err := syscall.Read(t.fd, buf)
+ if err != nil {
+ return []byte{}, err
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (t *PosixParser) GetWinSize() *WinSize {
+ ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: ws.Row,
+ Col: ws.Col,
+ }
+}
+
+var _ ConsoleParser = &PosixParser{}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *PosixParser {
+ in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ return &PosixParser{
+ fd: in,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/input_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/input_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..11b7679d4c4bc8b924a5b6c863ca1f6d6880570d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/input_windows.go
@@ -0,0 +1,83 @@
+// +build windows
+
+package prompt
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf8"
+ "unsafe"
+
+ tty "github.com/mattn/go-tty"
+)
+
+const maxReadBytes = 1024
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
+
+// WindowsParser is a ConsoleParser implementation for Win32 console.
+type WindowsParser struct {
+ tty *tty.TTY
+}
+
+// Setup should be called before starting input
+func (p *WindowsParser) Setup() error {
+ t, err := tty.Open()
+ if err != nil {
+ return err
+ }
+ p.tty = t
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (p *WindowsParser) TearDown() error {
+ return p.tty.Close()
+}
+
+// Read returns byte array.
+func (p *WindowsParser) Read() ([]byte, error) {
+ var ev uint32
+ r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
+ if r0 == 0 {
+ return nil, err
+ }
+ if ev == 0 {
+ return nil, errors.New("EAGAIN")
+ }
+
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, maxReadBytes)
+ n := utf8.EncodeRune(buf[:], r)
+ for p.tty.Buffered() && n < maxReadBytes {
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ break
+ }
+ n += utf8.EncodeRune(buf[n:], r)
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (p *WindowsParser) GetWinSize() *WinSize {
+ w, h, err := p.tty.Size()
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: uint16(h),
+ Col: uint16(w),
+ }
+}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *WindowsParser {
+ return &WindowsParser{}
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/bisect/bisect.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/bisect/bisect.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe162fa8c4873302e25702081b629a445d43415
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/bisect/bisect.go
@@ -0,0 +1,15 @@
+package bisect
+
+import "sort"
+
+// Right to locate the insertion point for v in a to maintain sorted order.
+func Right(a []int, v int) int {
+ return bisectRightRange(a, v, 0, len(a))
+}
+
+func bisectRightRange(a []int, v int, lo, hi int) int {
+ s := a[lo:hi]
+ return sort.Search(len(s), func(i int) bool {
+ return s[i] > v
+ })
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/debug/assert.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/debug/assert.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f648ac93c44e1e021cdf581a68f03b548534d9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/debug/assert.go
@@ -0,0 +1,55 @@
+package debug
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
+)
+
+var (
+ enableAssert bool
+)
+
+func init() {
+ if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
+ enableAssert = true
+ }
+}
+
+// Assert ensures expected condition.
+func Assert(cond bool, msg interface{}) {
+ if cond {
+ return
+ }
+ if enableAssert {
+ panic(msg)
+ }
+ writeWithSync(2, "[ASSERT] "+toString(msg))
+}
+
+func toString(v interface{}) string {
+ switch a := v.(type) {
+ case func() string:
+ return a()
+ case string:
+ return a
+ case fmt.Stringer:
+ return a.String()
+ default:
+ return fmt.Sprintf("unexpected type, %t", v)
+ }
+}
+
+// AssertNoError ensures err is nil.
+func AssertNoError(err error) {
+ if err == nil {
+ return
+ }
+ if enableAssert {
+ panic(err)
+ }
+ writeWithSync(2, "[ASSERT] "+err.Error())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/debug/log.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/debug/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..516378627a34ead9063ab7ce6c445b23c77b7cb4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/debug/log.go
@@ -0,0 +1,52 @@
+package debug
+
+import (
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+const (
+ envEnableLog = "GO_PROMPT_ENABLE_LOG"
+ logFileName = "go-prompt.log"
+)
+
+var (
+ logfile *os.File
+ logger *log.Logger
+)
+
+func init() {
+ if e := os.Getenv(envEnableLog); e == "true" || e == "1" {
+ var err error
+ logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
+ if err == nil {
+ logger = log.New(logfile, "", log.Llongfile)
+ return
+ }
+ }
+ logger = log.New(ioutil.Discard, "", log.Llongfile)
+}
+
+// Teardown to close logfile
+func Teardown() {
+ if logfile == nil {
+ return
+ }
+ _ = logfile.Close()
+}
+
+func writeWithSync(calldepth int, msg string) {
+ calldepth++
+ if logfile == nil {
+ return
+ }
+ _ = logger.Output(calldepth, msg)
+ _ = logfile.Sync() // immediately write msg
+}
+
+// Log to output message
+func Log(msg string) {
+ calldepth := 2
+ writeWithSync(calldepth, msg)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/strings/strings.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/strings/strings.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7d1886ae03a7d541c66dffca921e2d040e6d5eb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/strings/strings.go
@@ -0,0 +1,102 @@
+package strings
+
+import "unicode/utf8"
+
+// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior.
+func IndexNotByte(s string, c byte) int {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior.
+func LastIndexNotByte(s string, c byte) int {
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+type asciiSet [8]uint32
+
+func (as *asciiSet) notContains(c byte) bool {
+ return (as[c>>5] & (1 << uint(c&31))) == 0
+}
+
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c>>5] |= 1 << uint(c&31)
+ }
+ return as, true
+}
+
+// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior.
+func IndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := 0; i < len(s); i++ {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+
+ LabelFirstLoop:
+ for i, c := range s {
+ for j, m := range chars {
+ if c != m && j == len(chars)-1 {
+ return i
+ } else if c != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior.
+func LastIndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ LabelFirstLoop:
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRuneInString(s[:i])
+ i -= size
+ for j, m := range chars {
+ if r != m && j == len(chars)-1 {
+ return i
+ } else if r != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/term/raw.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/term/raw.go
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3ed8d04023558cf386a98080815d661248b85
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/term/raw.go
@@ -0,0 +1,29 @@
+// +build !windows
+
+package term
+
+import (
+ "syscall"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+// SetRaw put terminal into a raw mode
+func SetRaw(fd int) error {
+ n, err := getOriginalTermios(fd)
+ if err != nil {
+ return err
+ }
+
+ n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK |
+ syscall.ISTRIP | syscall.INLCR | syscall.IGNCR |
+ syscall.ICRNL | syscall.IXON
+ n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL
+ n.Cflag &^= syscall.CSIZE | syscall.PARENB
+ n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters.
+ n.Cc[syscall.VMIN] = 1
+ n.Cc[syscall.VTIME] = 0
+
+ return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n))
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/term/term.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/term/term.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a53c059ae60c0348ec01689babef4b13a2ecd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/internal/term/term.go
@@ -0,0 +1,34 @@
+// +build !windows
+
+package term
+
+import (
+ "sync"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ saveTermios *unix.Termios
+ saveTermiosFD int
+ saveTermiosOnce sync.Once
+)
+
+func getOriginalTermios(fd int) (*unix.Termios, error) {
+ var err error
+ saveTermiosOnce.Do(func() {
+ saveTermiosFD = fd
+ saveTermios, err = termios.Tcgetattr(uintptr(fd))
+ })
+ return saveTermios, err
+}
+
+// Restore terminal's mode.
+func Restore() error {
+ o, err := getOriginalTermios(saveTermiosFD)
+ if err != nil {
+ return err
+ }
+ return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/key.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ba569c2dd20a8ae3b3dd79ff3695bf0b6c1bd09
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/key.go
@@ -0,0 +1,128 @@
+// Code generated by hand; DO NOT EDIT.
+// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment.
+
+package prompt
+
+// Key is the type express the key inserted from user.
+//go:generate stringer -type=Key
+type Key int
+
+// ASCIICode is the type contains Key and it's ascii byte array.
+type ASCIICode struct {
+ Key Key
+ ASCIICode []byte
+}
+
+const (
+ Escape Key = iota
+
+ ControlA
+ ControlB
+ ControlC
+ ControlD
+ ControlE
+ ControlF
+ ControlG
+ ControlH
+ ControlI
+ ControlJ
+ ControlK
+ ControlL
+ ControlM
+ ControlN
+ ControlO
+ ControlP
+ ControlQ
+ ControlR
+ ControlS
+ ControlT
+ ControlU
+ ControlV
+ ControlW
+ ControlX
+ ControlY
+ ControlZ
+
+ ControlSpace
+ ControlBackslash
+ ControlSquareClose
+ ControlCircumflex
+ ControlUnderscore
+ ControlLeft
+ ControlRight
+ ControlUp
+ ControlDown
+
+ Up
+ Down
+ Right
+ Left
+
+ ShiftLeft
+ ShiftUp
+ ShiftDown
+ ShiftRight
+
+ Home
+ End
+ Delete
+ ShiftDelete
+ ControlDelete
+ PageUp
+ PageDown
+ BackTab
+ Insert
+ Backspace
+
+ // Aliases.
+ Tab
+ Enter
+ // Actually Enter equals ControlM, not ControlJ,
+ // However, in prompt_toolkit, we made the mistake of translating
+ // \r into \n during the input, so everyone is now handling the
+ // enter key by binding ControlJ.
+
+ // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere,
+ // because that's future compatible, and will still work when we
+ // stop replacing \r by \n.
+
+ F1
+ F2
+ F3
+ F4
+ F5
+ F6
+ F7
+ F8
+ F9
+ F10
+ F11
+ F12
+ F13
+ F14
+ F15
+ F16
+ F17
+ F18
+ F19
+ F20
+ F21
+ F22
+ F23
+ F24
+
+ // Matches any key.
+ Any
+
+ // Special
+ CPRResponse
+ Vt100MouseEvent
+ WindowsMouseEvent
+ BracketedPaste
+
+ // Key which is ignored. (The key binding for this key should not do anything.)
+ Ignore
+
+ // Key is not defined
+ NotDefined
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/key_bind.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/key_bind.go
new file mode 100644
index 0000000000000000000000000000000000000000..42669e7f942efc4d92f896388daede90b96b55dd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/key_bind.go
@@ -0,0 +1,59 @@
+package prompt
+
+// KeyBindFunc receives buffer and processed it.
+type KeyBindFunc func(*Buffer)
+
+// KeyBind represents which key should do what operation.
+type KeyBind struct {
+ Key Key
+ Fn KeyBindFunc
+}
+
+// ASCIICodeBind represents which []byte should do what operation
+type ASCIICodeBind struct {
+ ASCIICode []byte
+ Fn KeyBindFunc
+}
+
+// KeyBindMode to switch a key binding flexibly.
+type KeyBindMode string
+
+const (
+ // CommonKeyBind is a mode without any keyboard shortcut
+ CommonKeyBind KeyBindMode = "common"
+ // EmacsKeyBind is a mode to use emacs-like keyboard shortcut
+ EmacsKeyBind KeyBindMode = "emacs"
+)
+
+var commonKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: End,
+ Fn: GoLineEnd,
+ },
+ // Go to the beginning of the line
+ {
+ Key: Home,
+ Fn: GoLineBeginning,
+ },
+ // Delete character under the cursor
+ {
+ Key: Delete,
+ Fn: DeleteChar,
+ },
+ // Backspace
+ {
+ Key: Backspace,
+ Fn: DeleteBeforeChar,
+ },
+ // Right allow: Forward one character
+ {
+ Key: Right,
+ Fn: GoRightChar,
+ },
+ // Left allow: Backward one character
+ {
+ Key: Left,
+ Fn: GoLeftChar,
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/key_bind_func.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/key_bind_func.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b2ecdf63179dbfdbcb0d71bfa436bb36d62d230
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/key_bind_func.go
@@ -0,0 +1,48 @@
+package prompt
+
+// GoLineEnd Go to the End of the line
+func GoLineEnd(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+}
+
+// GoLineBeginning Go to the beginning of the line
+func GoLineBeginning(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+}
+
+// DeleteChar Delete character under the cursor
+func DeleteChar(buf *Buffer) {
+ buf.Delete(1)
+}
+
+// DeleteWord Delete word before the cursor
+func DeleteWord(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
+
+// DeleteBeforeChar Go to Backspace
+func DeleteBeforeChar(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+}
+
+// GoRightChar Forward one character
+func GoRightChar(buf *Buffer) {
+ buf.CursorRight(1)
+}
+
+// GoLeftChar Backward one character
+func GoLeftChar(buf *Buffer) {
+ buf.CursorLeft(1)
+}
+
+// GoRightWord Forward one word
+func GoRightWord(buf *Buffer) {
+ buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
+}
+
+// GoLeftWord Backward one word
+func GoLeftWord(buf *Buffer) {
+ buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/key_string.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/key_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..fce6ea31c502b3e763451cb47757ae1b49c32814
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/key_string.go
@@ -0,0 +1,16 @@
+// Code generated by "stringer -type=Key"; DO NOT EDIT.
+
+package prompt
+
+import "strconv"
+
+const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined"
+
+var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607}
+
+func (i Key) String() string {
+ if i < 0 || i >= Key(len(_Key_index)-1) {
+ return "Key(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _Key_name[_Key_index[i]:_Key_index[i+1]]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/option.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/option.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd6806cc1dbccf8c4ddb048080fde615c59088
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/option.go
@@ -0,0 +1,310 @@
+package prompt
+
+// Option is the type to replace default parameters.
+// prompt.New accepts any number of options (this is functional option pattern).
+type Option func(prompt *Prompt) error
+
+// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
+func OptionParser(x ConsoleParser) Option {
+ return func(p *Prompt) error {
+ p.in = x
+ return nil
+ }
+}
+
+// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
+func OptionWriter(x ConsoleWriter) Option {
+ return func(p *Prompt) error {
+ registerConsoleWriter(x)
+ p.renderer.out = x
+ return nil
+ }
+}
+
+// OptionTitle to set title displayed at the header bar of terminal.
+func OptionTitle(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.title = x
+ return nil
+ }
+}
+
+// OptionPrefix to set prefix string.
+func OptionPrefix(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefix = x
+ return nil
+ }
+}
+
+// OptionInitialBufferText to set the initial buffer text
+func OptionInitialBufferText(x string) Option {
+ return func(p *Prompt) error {
+ p.buf.InsertText(x, false, true)
+ return nil
+ }
+}
+
+// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
+func OptionCompletionWordSeparator(x string) Option {
+ return func(p *Prompt) error {
+ p.completion.wordSeparator = x
+ return nil
+ }
+}
+
+// OptionLivePrefix to change the prefix dynamically by callback function
+func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
+ return func(p *Prompt) error {
+ p.renderer.livePrefixCallback = f
+ return nil
+ }
+}
+
+// OptionPrefixTextColor change a text color of prefix string
+func OptionPrefixTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixTextColor = x
+ return nil
+ }
+}
+
+// OptionPrefixBackgroundColor to change a background color of prefix string
+func OptionPrefixBackgroundColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixBGColor = x
+ return nil
+ }
+}
+
+// OptionInputTextColor to change a color of text which is input by user
+func OptionInputTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputTextColor = x
+ return nil
+ }
+}
+
+// OptionInputBGColor to change a color of background which is input by user
+func OptionInputBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputBGColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionTextColor to change a text color which is completed
+func OptionPreviewSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionBGColor to change a background color which is completed
+func OptionPreviewSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionTextColor to change a text color in drop down suggestions.
+func OptionSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionBGColor change a background color in drop down suggestions.
+func OptionSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarThumbColor to change a thumb color on scrollbar.
+func OptionScrollbarThumbColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarThumbColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarBGColor to change a background color of scrollbar.
+func OptionScrollbarBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarBGColor = x
+ return nil
+ }
+}
+
+// OptionMaxSuggestion specify the max number of displayed suggestions.
+func OptionMaxSuggestion(x uint16) Option {
+ return func(p *Prompt) error {
+ p.completion.max = x
+ return nil
+ }
+}
+
+// OptionHistory to set history expressed by string array.
+func OptionHistory(x []string) Option {
+ return func(p *Prompt) error {
+ p.history.histories = x
+ p.history.Clear()
+ return nil
+ }
+}
+
+// OptionSwitchKeyBindMode set a key bind mode.
+func OptionSwitchKeyBindMode(m KeyBindMode) Option {
+ return func(p *Prompt) error {
+ p.keyBindMode = m
+ return nil
+ }
+}
+
+// OptionCompletionOnDown allows for Down arrow key to trigger completion.
+func OptionCompletionOnDown() Option {
+ return func(p *Prompt) error {
+ p.completionOnDown = true
+ return nil
+ }
+}
+
+// SwitchKeyBindMode to set a key bind mode.
+// Deprecated: Please use OptionSwitchKeyBindMode.
+var SwitchKeyBindMode = OptionSwitchKeyBindMode
+
+// OptionAddKeyBind to set a custom key bind.
+func OptionAddKeyBind(b ...KeyBind) Option {
+ return func(p *Prompt) error {
+ p.keyBindings = append(p.keyBindings, b...)
+ return nil
+ }
+}
+
+// OptionAddASCIICodeBind to set a custom key bind.
+func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option {
+ return func(p *Prompt) error {
+ p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...)
+ return nil
+ }
+}
+
+// OptionShowCompletionAtStart to set completion window is open at start.
+func OptionShowCompletionAtStart() Option {
+ return func(p *Prompt) error {
+ p.completion.showAtStart = true
+ return nil
+ }
+}
+
+// OptionBreakLineCallback to run a callback at every break line
+func OptionBreakLineCallback(fn func(*Document)) Option {
+ return func(p *Prompt) error {
+ p.renderer.breakLineCallback = fn
+ return nil
+ }
+}
+
+// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop
+func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
+ return func(p *Prompt) error {
+ p.exitChecker = fn
+ return nil
+ }
+}
+
+// New returns a Prompt with powerful auto-completion.
+func New(executor Executor, completer Completer, opts ...Option) *Prompt {
+ defaultWriter := NewStdoutWriter()
+ registerConsoleWriter(defaultWriter)
+
+ pt := &Prompt{
+ in: NewStandardInputParser(),
+ renderer: &Render{
+ prefix: "> ",
+ out: defaultWriter,
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ },
+ buf: NewBuffer(),
+ executor: executor,
+ history: NewHistory(),
+ completion: NewCompletionManager(completer, 6),
+ keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting
+ }
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/output.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/output.go
new file mode 100644
index 0000000000000000000000000000000000000000..42531b412f1ed027c2fff5b85bc273e53e569b3a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/output.go
@@ -0,0 +1,161 @@
+package prompt
+
+import "sync"
+
+var (
+ consoleWriterMu sync.Mutex
+ consoleWriter ConsoleWriter
+)
+
+func registerConsoleWriter(f ConsoleWriter) {
+ consoleWriterMu.Lock()
+ defer consoleWriterMu.Unlock()
+ consoleWriter = f
+}
+
+// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on.
+type DisplayAttribute int
+
+const (
+ // DisplayReset reset all display attributes.
+ DisplayReset DisplayAttribute = iota
+ // DisplayBold set bold or increases intensity.
+ DisplayBold
+ // DisplayLowIntensity decreases intensity. Not widely supported.
+ DisplayLowIntensity
+ // DisplayItalic set italic. Not widely supported.
+ DisplayItalic
+ // DisplayUnderline set underline
+ DisplayUnderline
+ // DisplayBlink set blink (less than 150 per minute).
+ DisplayBlink
+ // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported.
+ DisplayRapidBlink
+ // DisplayReverse swap foreground and background colors.
+ DisplayReverse
+ // DisplayInvisible set invisible. Not widely supported.
+ DisplayInvisible
+ // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported.
+ DisplayCrossedOut
+ // DisplayDefaultFont set primary(default) font
+ DisplayDefaultFont
+)
+
+// Color represents color on terminal.
+type Color int
+
+const (
+ // DefaultColor represents a default color.
+ DefaultColor Color = iota
+
+ // Low intensity
+
+ // Black represents a black.
+ Black
+ // DarkRed represents a dark red.
+ DarkRed
+ // DarkGreen represents a dark green.
+ DarkGreen
+ // Brown represents a brown.
+ Brown
+ // DarkBlue represents a dark blue.
+ DarkBlue
+ // Purple represents a purple.
+ Purple
+ // Cyan represents a cyan.
+ Cyan
+ // LightGray represents a light gray.
+ LightGray
+
+ // High intensity
+
+ // DarkGray represents a dark gray.
+ DarkGray
+ // Red represents a red.
+ Red
+ // Green represents a green.
+ Green
+ // Yellow represents a yellow.
+ Yellow
+ // Blue represents a blue.
+ Blue
+ // Fuchsia represents a fuchsia.
+ Fuchsia
+ // Turquoise represents a turquoise.
+ Turquoise
+ // White represents a white.
+ White
+)
+
+// ConsoleWriter is an interface to abstract output layer.
+type ConsoleWriter interface {
+ /* Write */
+
+ // WriteRaw to write raw byte array.
+ WriteRaw(data []byte)
+ // Write to write safety byte array by removing control sequences.
+ Write(data []byte)
+ // WriteStr to write raw string.
+ WriteRawStr(data string)
+ // WriteStr to write safety string by removing control sequences.
+ WriteStr(data string)
+ // Flush to flush buffer.
+ Flush() error
+
+ /* Erasing */
+
+ // EraseScreen erases the screen with the background colour and moves the cursor to home.
+ EraseScreen()
+ // EraseUp erases the screen from the current line up to the top of the screen.
+ EraseUp()
+ // EraseDown erases the screen from the current line down to the bottom of the screen.
+ EraseDown()
+ // EraseStartOfLine erases from the current cursor position to the start of the current line.
+ EraseStartOfLine()
+ // EraseEndOfLine erases from the current cursor position to the end of the current line.
+ EraseEndOfLine()
+ // EraseLine erases the entire current line.
+ EraseLine()
+
+ /* Cursor */
+
+ // ShowCursor stops blinking cursor and show.
+ ShowCursor()
+ // HideCursor hides cursor.
+ HideCursor()
+ // CursorGoTo sets the cursor position where subsequent text will begin.
+ CursorGoTo(row, col int)
+ // CursorUp moves the cursor up by 'n' rows; the default count is 1.
+ CursorUp(n int)
+ // CursorDown moves the cursor down by 'n' rows; the default count is 1.
+ CursorDown(n int)
+ // CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+ CursorForward(n int)
+ // CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+ CursorBackward(n int)
+ // AskForCPR asks for a cursor position report (CPR).
+ AskForCPR()
+ // SaveCursor saves current cursor position.
+ SaveCursor()
+ // UnSaveCursor restores cursor position after a Save Cursor.
+ UnSaveCursor()
+
+ /* Scrolling */
+
+ // ScrollDown scrolls display down one line.
+ ScrollDown()
+ // ScrollUp scroll display up one line.
+ ScrollUp()
+
+ /* Title */
+
+ // SetTitle sets a title of terminal window.
+ SetTitle(title string)
+ // ClearTitle clears a title of terminal window.
+ ClearTitle()
+
+ /* Font */
+
+ // SetColor sets text and background colors. and specify whether text is bold.
+ SetColor(fg, bg Color, bold bool)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/output_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/output_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..26c770cc152a7b126be43915d60b8ba000ad0e38
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/output_posix.go
@@ -0,0 +1,67 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+)
+
+const flushMaxRetryCount = 3
+
+// PosixWriter is a ConsoleWriter implementation for POSIX environment.
+// To control terminal emulator, this outputs VT100 escape sequences.
+type PosixWriter struct {
+ VT100Writer
+ fd int
+}
+
+// Flush to flush buffer
+func (w *PosixWriter) Flush() error {
+ l := len(w.buffer)
+ offset := 0
+ retry := 0
+ for {
+ n, err := syscall.Write(w.fd, w.buffer[offset:])
+ if err != nil {
+ if retry < flushMaxRetryCount {
+ retry++
+ continue
+ }
+ return err
+ }
+ offset += n
+ if offset == l {
+ break
+ }
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &PosixWriter{}
+
+var (
+ // NewStandardOutputWriter returns ConsoleWriter object to write to stdout.
+ // This generates VT100 escape sequences because almost terminal emulators
+ // in POSIX OS built on top of a VT100 specification.
+ // Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStdoutWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stdout,
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStderrWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stderr,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/output_vt100.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/output_vt100.go
new file mode 100644
index 0000000000000000000000000000000000000000..20850fead883c4cd9802928b5de3f935fbbeb047
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/output_vt100.go
@@ -0,0 +1,310 @@
+package prompt
+
+import (
+ "bytes"
+ "strconv"
+)
+
+// VT100Writer generates VT100 escape sequences.
+type VT100Writer struct {
+ buffer []byte
+}
+
+// WriteRaw to write raw byte array
+func (w *VT100Writer) WriteRaw(data []byte) {
+ w.buffer = append(w.buffer, data...)
+}
+
+// Write to write safety byte array by removing control sequences.
+func (w *VT100Writer) Write(data []byte) {
+ w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1))
+}
+
+// WriteRawStr to write raw string
+func (w *VT100Writer) WriteRawStr(data string) {
+ w.WriteRaw([]byte(data))
+}
+
+// WriteStr to write safety string by removing control sequences.
+func (w *VT100Writer) WriteStr(data string) {
+ w.Write([]byte(data))
+}
+
+/* Erase */
+
+// EraseScreen erases the screen with the background colour and moves the cursor to home.
+func (w *VT100Writer) EraseScreen() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'J'})
+}
+
+// EraseUp erases the screen from the current line up to the top of the screen.
+func (w *VT100Writer) EraseUp() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'J'})
+}
+
+// EraseDown erases the screen from the current line down to the bottom of the screen.
+func (w *VT100Writer) EraseDown() {
+ w.WriteRaw([]byte{0x1b, '[', 'J'})
+}
+
+// EraseStartOfLine erases from the current cursor position to the start of the current line.
+func (w *VT100Writer) EraseStartOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'K'})
+}
+
+// EraseEndOfLine erases from the current cursor position to the end of the current line.
+func (w *VT100Writer) EraseEndOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', 'K'})
+}
+
+// EraseLine erases the entire current line.
+func (w *VT100Writer) EraseLine() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'K'})
+}
+
+/* Cursor */
+
+// ShowCursor stops blinking cursor and show.
+func (w *VT100Writer) ShowCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'})
+}
+
+// HideCursor hides cursor.
+func (w *VT100Writer) HideCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'})
+}
+
+// CursorGoTo sets the cursor position where subsequent text will begin.
+func (w *VT100Writer) CursorGoTo(row, col int) {
+ if row == 0 && col == 0 {
+ // If no row/column parameters are provided (ie. [H), the cursor will move to the home position.
+ w.WriteRaw([]byte{0x1b, '[', 'H'})
+ return
+ }
+ r := strconv.Itoa(row)
+ c := strconv.Itoa(col)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(r))
+ w.WriteRaw([]byte{';'})
+ w.WriteRaw([]byte(c))
+ w.WriteRaw([]byte{'H'})
+}
+
+// CursorUp moves the cursor up by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorUp(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorDown(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'A'})
+}
+
+// CursorDown moves the cursor down by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorDown(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorUp(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'B'})
+}
+
+// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorForward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorBackward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'C'})
+}
+
+// CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorBackward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorForward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'D'})
+}
+
+// AskForCPR asks for a cursor position report (CPR).
+func (w *VT100Writer) AskForCPR() {
+ // CPR: Cursor Position Request.
+ w.WriteRaw([]byte{0x1b, '[', '6', 'n'})
+}
+
+// SaveCursor saves current cursor position.
+func (w *VT100Writer) SaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 's'})
+}
+
+// UnSaveCursor restores cursor position after a Save Cursor.
+func (w *VT100Writer) UnSaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 'u'})
+}
+
+/* Scrolling */
+
+// ScrollDown scrolls display down one line.
+func (w *VT100Writer) ScrollDown() {
+ w.WriteRaw([]byte{0x1b, 'D'})
+}
+
+// ScrollUp scroll display up one line.
+func (w *VT100Writer) ScrollUp() {
+ w.WriteRaw([]byte{0x1b, 'M'})
+}
+
+/* Title */
+
+// SetTitle sets a title of terminal window.
+func (w *VT100Writer) SetTitle(title string) {
+ titleBytes := []byte(title)
+ patterns := []struct {
+ from []byte
+ to []byte
+ }{
+ {
+ from: []byte{0x13},
+ to: []byte{},
+ },
+ {
+ from: []byte{0x07},
+ to: []byte{},
+ },
+ }
+ for i := range patterns {
+ titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1)
+ }
+
+ w.WriteRaw([]byte{0x1b, ']', '2', ';'})
+ w.WriteRaw(titleBytes)
+ w.WriteRaw([]byte{0x07})
+}
+
+// ClearTitle clears a title of terminal window.
+func (w *VT100Writer) ClearTitle() {
+ w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07})
+}
+
+/* Font */
+
+// SetColor sets text and background colors. and specify whether text is bold.
+func (w *VT100Writer) SetColor(fg, bg Color, bold bool) {
+ if bold {
+ w.SetDisplayAttributes(fg, bg, DisplayBold)
+ } else {
+ // If using `DisplayDefualt`, it will be broken in some environment.
+ // Details are https://github.com/c-bata/go-prompt/pull/85
+ w.SetDisplayAttributes(fg, bg, DisplayReset)
+ }
+}
+
+// SetDisplayAttributes to set VT100 display attributes.
+func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) {
+ w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer
+ defer w.WriteRaw([]byte{'m'}) // final character
+
+ var separator byte = ';'
+ for i := range attrs {
+ p, ok := displayAttributeParameters[attrs[i]]
+ if !ok {
+ continue
+ }
+ w.WriteRaw(p)
+ w.WriteRaw([]byte{separator})
+ }
+
+ f, ok := foregroundANSIColors[fg]
+ if !ok {
+ f = foregroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(f)
+ w.WriteRaw([]byte{separator})
+ b, ok := backgroundANSIColors[bg]
+ if !ok {
+ b = backgroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(b)
+}
+
+var displayAttributeParameters = map[DisplayAttribute][]byte{
+ DisplayReset: {'0'},
+ DisplayBold: {'1'},
+ DisplayLowIntensity: {'2'},
+ DisplayItalic: {'3'},
+ DisplayUnderline: {'4'},
+ DisplayBlink: {'5'},
+ DisplayRapidBlink: {'6'},
+ DisplayReverse: {'7'},
+ DisplayInvisible: {'8'},
+ DisplayCrossedOut: {'9'},
+ DisplayDefaultFont: {'1', '0'},
+}
+
+var foregroundANSIColors = map[Color][]byte{
+ DefaultColor: {'3', '9'},
+
+ // Low intensity.
+ Black: {'3', '0'},
+ DarkRed: {'3', '1'},
+ DarkGreen: {'3', '2'},
+ Brown: {'3', '3'},
+ DarkBlue: {'3', '4'},
+ Purple: {'3', '5'},
+ Cyan: {'3', '6'},
+ LightGray: {'3', '7'},
+
+ // High intensity.
+ DarkGray: {'9', '0'},
+ Red: {'9', '1'},
+ Green: {'9', '2'},
+ Yellow: {'9', '3'},
+ Blue: {'9', '4'},
+ Fuchsia: {'9', '5'},
+ Turquoise: {'9', '6'},
+ White: {'9', '7'},
+}
+
+var backgroundANSIColors = map[Color][]byte{
+ DefaultColor: {'4', '9'},
+
+ // Low intensity.
+ Black: {'4', '0'},
+ DarkRed: {'4', '1'},
+ DarkGreen: {'4', '2'},
+ Brown: {'4', '3'},
+ DarkBlue: {'4', '4'},
+ Purple: {'4', '5'},
+ Cyan: {'4', '6'},
+ LightGray: {'4', '7'},
+
+ // High intensity
+ DarkGray: {'1', '0', '0'},
+ Red: {'1', '0', '1'},
+ Green: {'1', '0', '2'},
+ Yellow: {'1', '0', '3'},
+ Blue: {'1', '0', '4'},
+ Fuchsia: {'1', '0', '5'},
+ Turquoise: {'1', '0', '6'},
+ White: {'1', '0', '7'},
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/output_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/output_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b9c2769fc2d64cfcfcc5b99c915591ec625bd5f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/output_windows.go
@@ -0,0 +1,49 @@
+// +build windows
+
+package prompt
+
+import (
+ "io"
+
+ colorable "github.com/mattn/go-colorable"
+)
+
+// WindowsWriter is a ConsoleWriter implementation for Win32 console.
+// Output is converted from VT100 escape sequences by mattn/go-colorable.
+type WindowsWriter struct {
+ VT100Writer
+ out io.Writer
+}
+
+// Flush to flush buffer
+func (w *WindowsWriter) Flush() error {
+ _, err := w.out.Write(w.buffer)
+ if err != nil {
+ return err
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &WindowsWriter{}
+
+var (
+ // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates win32 control sequences.
+func NewStdoutWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStdout(),
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates win32 control sequences.
+func NewStderrWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStderr(),
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/prompt.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/prompt.go
new file mode 100644
index 0000000000000000000000000000000000000000..173cd517c40cde212433e399978641ceff1d1a43
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/prompt.go
@@ -0,0 +1,296 @@
+package prompt
+
+import (
+ "bytes"
+ "os"
+ "time"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Executor is called when user input something text.
+type Executor func(string)
+
+// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
+// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
+// - immediate exit (if breakline is false) without executor called
+// - exit after typing (meaning breakline is true), and the executor is called first, before exit.
+// Exit means exit go-prompt (not the overall Go program)
+type ExitChecker func(in string, breakline bool) bool
+
+// Completer should return the suggest item from Document.
+type Completer func(Document) []Suggest
+
+// Prompt is core struct of go-prompt.
+type Prompt struct {
+ in ConsoleParser
+ buf *Buffer
+ renderer *Render
+ executor Executor
+ history *History
+ completion *CompletionManager
+ keyBindings []KeyBind
+ ASCIICodeBindings []ASCIICodeBind
+ keyBindMode KeyBindMode
+ completionOnDown bool
+ exitChecker ExitChecker
+ skipTearDown bool
+}
+
+// Exec is the struct contains user input context.
+type Exec struct {
+ input string
+}
+
+// Run starts prompt.
+func (p *Prompt) Run() {
+ p.skipTearDown = false
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ exitCh := make(chan int)
+ winSizeCh := make(chan *WinSize)
+ stopHandleSignalCh := make(chan struct{})
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+ return
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+
+ // Unset raw mode
+ // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
+ debug.AssertNoError(p.in.TearDown())
+ p.executor(e.input)
+
+ p.completion.Update(*p.buf.Document())
+
+ p.renderer.Render(p.buf, p.completion)
+
+ if p.exitChecker != nil && p.exitChecker(e.input, true) {
+ p.skipTearDown = true
+ return
+ }
+ // Set raw mode
+ debug.AssertNoError(p.in.Setup())
+ go p.readBuffer(bufCh, stopReadBufCh)
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ case w := <-winSizeCh:
+ p.renderer.UpdateWinSize(w)
+ p.renderer.Render(p.buf, p.completion)
+ case code := <-exitCh:
+ p.renderer.BreakLine(p.buf)
+ p.tearDown()
+ os.Exit(code)
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
+ key := GetKey(b)
+ p.buf.lastKeyStroke = key
+ // completion
+ completing := p.completion.Completing()
+ p.handleCompletionKeyBinding(key, completing)
+
+ switch key {
+ case Enter, ControlJ, ControlM:
+ p.renderer.BreakLine(p.buf)
+
+ exec = &Exec{input: p.buf.Text()}
+ p.buf = NewBuffer()
+ if exec.input != "" {
+ p.history.Add(exec.input)
+ }
+ case ControlC:
+ p.renderer.BreakLine(p.buf)
+ p.buf = NewBuffer()
+ p.history.Clear()
+ case Up, ControlP:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Older(p.buf); changed {
+ p.buf = newBuf
+ }
+ }
+ case Down, ControlN:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Newer(p.buf); changed {
+ p.buf = newBuf
+ }
+ return
+ }
+ case ControlD:
+ if p.buf.Text() == "" {
+ shouldExit = true
+ return
+ }
+ case NotDefined:
+ if p.handleASCIICodeBinding(b) {
+ return
+ }
+ p.buf.InsertText(string(b), false, true)
+ }
+
+ shouldExit = p.handleKeyBinding(key)
+ return
+}
+
+func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
+ switch key {
+ case Down:
+ if completing || p.completionOnDown {
+ p.completion.Next()
+ }
+ case Tab, ControlI:
+ p.completion.Next()
+ case Up:
+ if completing {
+ p.completion.Previous()
+ }
+ case BackTab:
+ p.completion.Previous()
+ default:
+ if s, ok := p.completion.GetSelectedSuggestion(); ok {
+ w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
+ if w != "" {
+ p.buf.DeleteBeforeCursor(len([]rune(w)))
+ }
+ p.buf.InsertText(s.Text, false, true)
+ }
+ p.completion.Reset()
+ }
+}
+
+func (p *Prompt) handleKeyBinding(key Key) bool {
+ shouldExit := false
+ for i := range commonKeyBindings {
+ kb := commonKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+
+ if p.keyBindMode == EmacsKeyBind {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ }
+
+ // Custom key bindings
+ for i := range p.keyBindings {
+ kb := p.keyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
+ shouldExit = true
+ }
+ return shouldExit
+}
+
+func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
+ checked := false
+ for _, kb := range p.ASCIICodeBindings {
+ if bytes.Equal(kb.ASCIICode, b) {
+ kb.Fn(p.buf)
+ checked = true
+ }
+ }
+ return checked
+}
+
+// Input just returns user input text.
+func (p *Prompt) Input() string {
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ return ""
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ return e.input
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
+ debug.Log("start reading buffer")
+ for {
+ select {
+ case <-stopCh:
+ debug.Log("stop reading buffer")
+ return
+ default:
+ if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
+ bufCh <- b
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (p *Prompt) setUp() {
+ debug.AssertNoError(p.in.Setup())
+ p.renderer.Setup()
+ p.renderer.UpdateWinSize(p.in.GetWinSize())
+}
+
+func (p *Prompt) tearDown() {
+ if !p.skipTearDown {
+ debug.AssertNoError(p.in.TearDown())
+ }
+ p.renderer.TearDown()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/render.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/render.go
new file mode 100644
index 0000000000000000000000000000000000000000..299ac48b6254b9752ea16516aaedcd41acca6515
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/render.go
@@ -0,0 +1,287 @@
+package prompt
+
+import (
+ "runtime"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Render to render prompt information from state of Buffer.
+type Render struct {
+ out ConsoleWriter
+ prefix string
+ livePrefixCallback func() (prefix string, useLivePrefix bool)
+ breakLineCallback func(*Document)
+ title string
+ row uint16
+ col uint16
+
+ previousCursor int
+
+ // colors,
+ prefixTextColor Color
+ prefixBGColor Color
+ inputTextColor Color
+ inputBGColor Color
+ previewSuggestionTextColor Color
+ previewSuggestionBGColor Color
+ suggestionTextColor Color
+ suggestionBGColor Color
+ selectedSuggestionTextColor Color
+ selectedSuggestionBGColor Color
+ descriptionTextColor Color
+ descriptionBGColor Color
+ selectedDescriptionTextColor Color
+ selectedDescriptionBGColor Color
+ scrollbarThumbColor Color
+ scrollbarBGColor Color
+}
+
+// Setup to initialize console output.
+func (r *Render) Setup() {
+ if r.title != "" {
+ r.out.SetTitle(r.title)
+ debug.AssertNoError(r.out.Flush())
+ }
+}
+
+// getCurrentPrefix to get current prefix.
+// If live-prefix is enabled, return live-prefix.
+func (r *Render) getCurrentPrefix() string {
+ if prefix, ok := r.livePrefixCallback(); ok {
+ return prefix
+ }
+ return r.prefix
+}
+
+func (r *Render) renderPrefix() {
+ r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
+ r.out.WriteStr(r.getCurrentPrefix())
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// TearDown to clear title and erasing.
+func (r *Render) TearDown() {
+ r.out.ClearTitle()
+ r.out.EraseDown()
+ debug.AssertNoError(r.out.Flush())
+}
+
+func (r *Render) prepareArea(lines int) {
+ for i := 0; i < lines; i++ {
+ r.out.ScrollDown()
+ }
+ for i := 0; i < lines; i++ {
+ r.out.ScrollUp()
+ }
+}
+
+// UpdateWinSize called when window size is changed.
+func (r *Render) UpdateWinSize(ws *WinSize) {
+ r.row = ws.Row
+ r.col = ws.Col
+}
+
+func (r *Render) renderWindowTooSmall() {
+ r.out.CursorGoTo(0, 0)
+ r.out.EraseScreen()
+ r.out.SetColor(DarkRed, White, false)
+ r.out.WriteStr("Your console window is too small...")
+}
+
+func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) {
+ suggestions := completions.GetSuggestions()
+ if len(completions.GetSuggestions()) == 0 {
+ return
+ }
+ prefix := r.getCurrentPrefix()
+ formatted, width := formatSuggestions(
+ suggestions,
+ int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar
+ )
+ // +1 means a width of scrollbar.
+ width++
+
+ windowHeight := len(formatted)
+ if windowHeight > int(completions.max) {
+ windowHeight = int(completions.max)
+ }
+ formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
+ r.prepareArea(windowHeight)
+
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor())
+ x, _ := r.toPos(cursor)
+ if x+width >= int(r.col) {
+ cursor = r.backward(cursor, x+width-int(r.col))
+ }
+
+ contentHeight := len(completions.tmp)
+
+ fractionVisible := float64(windowHeight) / float64(contentHeight)
+ fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
+
+ scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
+ scrollbarTop := int(float64(windowHeight) * fractionAbove)
+
+ isScrollThumb := func(row int) bool {
+ return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
+ }
+
+ selected := completions.selected - completions.verticalScroll
+ r.out.SetColor(White, Cyan, false)
+ for i := 0; i < windowHeight; i++ {
+ r.out.CursorDown(1)
+ if i == selected {
+ r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
+ } else {
+ r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Text)
+
+ if i == selected {
+ r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
+ } else {
+ r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Description)
+
+ if isScrollThumb(i) {
+ r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
+ } else {
+ r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
+ }
+ r.out.WriteStr(" ")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+
+ r.lineWrap(cursor + width)
+ r.backward(cursor+width, width)
+ }
+
+ if x+width >= int(r.col) {
+ r.out.CursorForward(x + width - int(r.col))
+ }
+
+ r.out.CursorUp(windowHeight)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// Render renders to the console.
+func (r *Render) Render(buffer *Buffer, completion *CompletionManager) {
+ // In situations where a pseudo tty is allocated (e.g. within a docker container),
+ // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
+ if r.col == 0 {
+ return
+ }
+ defer func() { debug.AssertNoError(r.out.Flush()) }()
+ r.move(r.previousCursor, 0)
+
+ line := buffer.Text()
+ prefix := r.getCurrentPrefix()
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line)
+
+ // prepare area
+ _, y := r.toPos(cursor)
+
+ h := y + 1 + int(completion.max)
+ if h > int(r.row) || completionMargin > int(r.col) {
+ r.renderWindowTooSmall()
+ return
+ }
+
+ // Rendering
+ r.out.HideCursor()
+ defer r.out.ShowCursor()
+
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(line)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ r.lineWrap(cursor)
+
+ r.out.EraseDown()
+
+ cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition())
+
+ r.renderCompletion(buffer, completion)
+ if suggest, ok := completion.GetSelectedSuggestion(); ok {
+ cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator)))
+
+ r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false)
+ r.out.WriteStr(suggest.Text)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ cursor += runewidth.StringWidth(suggest.Text)
+
+ rest := buffer.Document().TextAfterCursor()
+ r.out.WriteStr(rest)
+ cursor += runewidth.StringWidth(rest)
+ r.lineWrap(cursor)
+
+ cursor = r.backward(cursor, runewidth.StringWidth(rest))
+ }
+ r.previousCursor = cursor
+}
+
+// BreakLine to break line.
+func (r *Render) BreakLine(buffer *Buffer) {
+ // Erasing and Render
+ cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix())
+ r.clear(cursor)
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(buffer.Document().Text + "\n")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ debug.AssertNoError(r.out.Flush())
+ if r.breakLineCallback != nil {
+ r.breakLineCallback(buffer.Document())
+ }
+
+ r.previousCursor = 0
+}
+
+// clear erases the screen from a beginning of input
+// even if there is line break which means input length exceeds a window's width.
+func (r *Render) clear(cursor int) {
+ r.move(cursor, 0)
+ r.out.EraseDown()
+}
+
+// backward moves cursor to backward from a current cursor position
+// regardless there is a line break.
+func (r *Render) backward(from, n int) int {
+ return r.move(from, from-n)
+}
+
+// move moves cursor to specified position from the beginning of input
+// even if there is a line break.
+func (r *Render) move(from, to int) int {
+ fromX, fromY := r.toPos(from)
+ toX, toY := r.toPos(to)
+
+ r.out.CursorUp(fromY - toY)
+ r.out.CursorBackward(fromX - toX)
+ return to
+}
+
+// toPos returns the relative position from the beginning of the string.
+func (r *Render) toPos(cursor int) (x, y int) {
+ col := int(r.col)
+ return cursor % col, cursor / col
+}
+
+func (r *Render) lineWrap(cursor int) {
+ if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 {
+ r.out.WriteRaw([]byte{'\n'})
+ }
+}
+
+func clamp(high, low, x float64) float64 {
+ switch {
+ case high < x:
+ return high
+ case x < low:
+ return low
+ default:
+ return x
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/shortcut.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/shortcut.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8d4282700c0bdb30e4decfb9c9ac91f27af251
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/shortcut.go
@@ -0,0 +1,43 @@
+package prompt
+
+func dummyExecutor(in string) {}
+
+// Input get the input data from the user and return it.
+func Input(prefix string, completer Completer, opts ...Option) string {
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+// Choose to the shortcut of input function to select from string array.
+// Deprecated: Maybe anyone want to use this.
+func Choose(prefix string, choices []string, opts ...Option) string {
+ completer := newChoiceCompleter(choices, FilterHasPrefix)
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+func newChoiceCompleter(choices []string, filter Filter) Completer {
+ s := make([]Suggest, len(choices))
+ for i := range choices {
+ s[i] = Suggest{Text: choices[i]}
+ }
+ return func(x Document) []Suggest {
+ return filter(s, x.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/signal_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/signal_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3150df5d85e7612c42c2a889dbefee3b524bef6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/signal_posix.go
@@ -0,0 +1,49 @@
+// +build !windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ in := p.in
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+
+ case syscall.SIGWINCH:
+ debug.Log("Catch SIGWINCH")
+ winSizeCh <- in.GetWinSize()
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/signal_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/signal_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a427c79ec0414540f8f40694731b2565ea80c13
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/environment/source/signal_windows.go
@@ -0,0 +1,44 @@
+// +build windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/instruction.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..f672aac59b07efebb62b0f2c15b026cc9eca2dcd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/instruction.md
@@ -0,0 +1,38 @@
+FindStartOfPreviousWordUntilSeparator returns incorrect position
+
+#### Description
+
+The `FindStartOfPreviousWordUntilSeparator` method is returning the wrong position when finding the start of the previous word. It appears to be off by one character.
+
+#### Steps/Code to Reproduce
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func main() {
+ doc := &prompt.Document{
+ Text: "hello,world test",
+ cursor: 16, // at end of string
+ }
+
+ pos := doc.FindStartOfPreviousWordUntilSeparator(",")
+ fmt.Printf("Expected: 11, Got: %d\n", pos)
+
+ // Another example
+ doc2 := &prompt.Document{
+ Text: "foo.json bar",
+ cursor: 12, // at end of string
+ }
+
+ pos2 := doc2.FindStartOfPreviousWordUntilSeparator(".")
+ fmt.Printf("Expected: 9, Got: %d\n", pos2)
+}
+```
+
+The method should return the position right after the separator, but it's currently returning the position of the separator itself. This affects word navigation functionality when using custom separators.
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/provenance.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..021e39736c4819e76d3a27ab4440738a30f183d6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/provenance.json
@@ -0,0 +1,477 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt",
+ "original-bug": "task-specific unchanged semantic bug",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only",
+ "extra_semantic_repair_coverage": false,
+ "original_patch_hunks": 1
+ },
+ "private_frozen_files": {
+ "buffer_test.go": {
+ "mode": "0o644",
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098",
+ "size": 4965
+ },
+ "completion_test.go": {
+ "mode": "0o644",
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d",
+ "size": 7010
+ },
+ "document_test.go": {
+ "mode": "0o644",
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284",
+ "size": 28938
+ },
+ "emacs_test.go": {
+ "mode": "0o644",
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095",
+ "size": 741
+ },
+ "filter_test.go": {
+ "mode": "0o644",
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247",
+ "size": 3339
+ },
+ "history_test.go": {
+ "mode": "0o644",
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327",
+ "size": 1319
+ },
+ "input_test.go": {
+ "mode": "0o644",
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922",
+ "size": 533
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": "0o644",
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf",
+ "size": 1075
+ },
+ "internal/strings/strings_test.go": {
+ "mode": "0o644",
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6",
+ "size": 981
+ },
+ "output_vt100_test.go": {
+ "mode": "0o644",
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee",
+ "size": 1349
+ },
+ "render_test.go": {
+ "mode": "0o644",
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb",
+ "size": 2890
+ }
+ },
+ "public_files": {
+ ".github/ISSUE_TEMPLATE/bug_report.md": {
+ "mode": "0o644",
+ "sha256": "89d3492ca8533a3d31e4de49a23828a322f75d2a1ec4236327c4a76c7c51ada6",
+ "size": 684
+ },
+ ".github/ISSUE_TEMPLATE/feature_request.md": {
+ "mode": "0o644",
+ "sha256": "d82e14e6b4d021d0007eeef4f5ca489fc6c8e8e4d7479ee30e74fe82afd3b08f",
+ "size": 206
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "3239b94a1a41c05eff5dc086ef1378cf1e289fad0203420b5cb4c78e3c5c239b",
+ "size": 270
+ },
+ "CHANGELOG.md": {
+ "mode": "0o644",
+ "sha256": "1f88f92d3247e1b52af0f0de7ad1263a59807edb17238c7a0211554f8080e51c",
+ "size": 2895
+ },
+ "LICENSE": {
+ "mode": "0o644",
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "size": 1072
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "9425a0d4c15747863625f647348962a9b0f81a0971a7e0184ee722bf34a60ba2",
+ "size": 1177
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "ce56df51a1a9a5b5c5b056429bbee006a260fb0730af63b1d0fe91755e574cc4",
+ "size": 6185
+ },
+ "_example/README.md": {
+ "mode": "0o644",
+ "sha256": "155951bafd778493bd41ae57dcc0ba6b8eca821fcbe2ffe770960ac2780d3d09",
+ "size": 1102
+ },
+ "_example/build.sh": {
+ "mode": "0o755",
+ "sha256": "de2fb330b665691cd75b990236cd6a5df0058608de0dfc6194da30d4041a1e29",
+ "size": 469
+ },
+ "_example/exec-command/main.go": {
+ "mode": "0o644",
+ "sha256": "0e96493b6e6d446b2e691d4834ff8a55834caa410ead970cb611a63ba84f174a",
+ "size": 429
+ },
+ "_example/http-prompt/api.py": {
+ "mode": "0o644",
+ "sha256": "2c2bca9acb07a84c65a4482c61c9ade253a574477a8e461307568ea1f9a342c8",
+ "size": 335
+ },
+ "_example/http-prompt/main.go": {
+ "mode": "0o644",
+ "sha256": "6994b190c4165068e69ed44eb61698af69a15a7690179ce46e3c1c5d8c211643",
+ "size": 5484
+ },
+ "_example/live-prefix/main.go": {
+ "mode": "0o644",
+ "sha256": "20268f9cb6f3b82a52eddc33cbf8082adaa46092e2063df279499e05e25a228c",
+ "size": 1103
+ },
+ "_example/simple-echo/cjk-cyrillic/main.go": {
+ "mode": "0o644",
+ "sha256": "8fb10807d4085ebc4b345bc0ccfef9217e21e49a888bfe3192e8ddfdfa01e89c",
+ "size": 800
+ },
+ "_example/simple-echo/main.go": {
+ "mode": "0o644",
+ "sha256": "e46563ddaa932831fe9ede870b10efb5222c0d54a86f4b4f5197c9cf20942a24",
+ "size": 902
+ },
+ "_tools/README.md": {
+ "mode": "0o644",
+ "sha256": "96dc2343bc5cde642fd449ddc366462753a2e17b6a78adfa015bf991e9dac241",
+ "size": 234
+ },
+ "_tools/complete_file/main.go": {
+ "mode": "0o644",
+ "sha256": "e5dd823f9d6415614a8238ce106d26e9ded1db9b308c121d7f48bb1df003effc",
+ "size": 803
+ },
+ "_tools/sigwinch/main.go": {
+ "mode": "0o644",
+ "sha256": "a806b4e45298f5003c95432d8dd3c40c9c096335f19f1a4160afcdb64fa727e3",
+ "size": 1386
+ },
+ "_tools/vt100_debug/main.go": {
+ "mode": "0o644",
+ "sha256": "7f72eba3cc7037fcf39c9b56a96c578c157e5fb235cb626ab1e83cbef0dc290b",
+ "size": 794
+ },
+ "buffer.go": {
+ "mode": "0o644",
+ "sha256": "10188d96a450fe13ba1e9ec00c89603eb2a2860536965d980d1e4abf4374b018",
+ "size": 5781
+ },
+ "completer/file.go": {
+ "mode": "0o644",
+ "sha256": "6181ed9e39028236c5c93fbe219331fc1492ecfd6af2df764cc42b5455c9bb96",
+ "size": 2401
+ },
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "b90bd9628534cfb343a592775430e17a1999b1de500fb2a8f1507c030a432eae",
+ "size": 4491
+ },
+ "document.go": {
+ "mode": "0o644",
+ "sha256": "b0d19da898f939f15b65924c380bfc4219593ad5057611395c670db2568436c4",
+ "size": 13093
+ },
+ "emacs.go": {
+ "mode": "0o644",
+ "sha256": "53f0df0016ef9d9695a797b19286681666cf0c7e5a866c393b194aae915f2664",
+ "size": 2675
+ },
+ "filter.go": {
+ "mode": "0o644",
+ "sha256": "dc5922bad6ecb32ecdaf20bd6035dddc7ce8c14f15dbd4d49192c2354cb8a038",
+ "size": 2005
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "97413fa2a2ed68170496f2289a2dca6fb0a192dcd020fc0ca48a5d106e60d55e",
+ "size": 253
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "88ea0a91babaa54b67cc6d5f6f7f47fa4be798fe523324ea568d8926eed2024c",
+ "size": 2183
+ },
+ "history.go": {
+ "mode": "0o644",
+ "sha256": "4ce80ba067cfc72c56a3ee3353ec75cd6bb2f5d82097515c591e3c7c773c51cd",
+ "size": 1488
+ },
+ "input.go": {
+ "mode": "0o644",
+ "sha256": "73461cc4f57d68b66e2a9e196239aaef942539134593beac0d0023743832e0e1",
+ "size": 7630
+ },
+ "input_posix.go": {
+ "mode": "0o644",
+ "sha256": "c7e5a4dfc3910f178f0685ef99f2e47d481a91c4cf9af50f92fc4266aed634df",
+ "size": 1648
+ },
+ "input_windows.go": {
+ "mode": "0o644",
+ "sha256": "f763250d309fb88d9536f77da1d1285c04bc6defe859506f1501e10f7743da9e",
+ "size": 1679
+ },
+ "internal/bisect/bisect.go": {
+ "mode": "0o644",
+ "sha256": "c4de2adfa2e08a77f902661d67325467f89013634dbcef22d24dc6f34d26624a",
+ "size": 327
+ },
+ "internal/debug/assert.go": {
+ "mode": "0o644",
+ "sha256": "1a3050ec58991b62c7ea352d19505e3080ac9760bdb091544f0ecf5aba35969c",
+ "size": 815
+ },
+ "internal/debug/log.go": {
+ "mode": "0o644",
+ "sha256": "2ce968e275558de61c6d83793e85561f7a8dd69c95ec7902ccd2cc3fb169aa82",
+ "size": 875
+ },
+ "internal/strings/strings.go": {
+ "mode": "0o644",
+ "sha256": "b97f08157c3baf1f94fea4bb2237691d8270bd5380b4311709ecd59b84cf4b7b",
+ "size": 2018
+ },
+ "internal/term/raw.go": {
+ "mode": "0o644",
+ "sha256": "177a1a20ae8d71b56857383a5797754560f7f6404ea86778d5f01e9a1c1b4f9f",
+ "size": 747
+ },
+ "internal/term/term.go": {
+ "mode": "0o644",
+ "sha256": "abe6fa965fa15b999b2010135903f598830d4c885a52ef9b067fd5ebbf6e373f",
+ "size": 606
+ },
+ "key.go": {
+ "mode": "0o644",
+ "sha256": "03a43283e07de7a4ea6fed32692d86325f73e98fd89a296f19c171e0bc780999",
+ "size": 1746
+ },
+ "key_bind.go": {
+ "mode": "0o644",
+ "sha256": "83f48bb720a11c8e49165ac382e3a870fdcf6b380a0a95267f8c25211898c9eb",
+ "size": 1109
+ },
+ "key_bind_func.go": {
+ "mode": "0o644",
+ "sha256": "445bff5c0fdb0b52879c635322603c2fc75d265de3761cb8c3b980c798bf39af",
+ "size": 1219
+ },
+ "key_string.go": {
+ "mode": "0o644",
+ "sha256": "55c429dae227bb1659d5d5e2e906dbfa9c7f53b5105fa83fbe290529ff6f2317",
+ "size": 1359
+ },
+ "option.go": {
+ "mode": "0o644",
+ "sha256": "28cfcc1d08b3cf650483d977195458531b3b3913f8a5f357a3ec17ea5d73e215",
+ "size": 8737
+ },
+ "output.go": {
+ "mode": "0o644",
+ "sha256": "372876b0aa908479ed3b29de70a479f420d85e3666b8957c8b61eaed9b32c3f2",
+ "size": 4320
+ },
+ "output_posix.go": {
+ "mode": "0o644",
+ "sha256": "d46b1da307e8969b033e1ade2eb51a83c4c3d4f2a7e4aba35ec3a03991b89a0f",
+ "size": 1545
+ },
+ "output_vt100.go": {
+ "mode": "0o644",
+ "sha256": "9082c7e4619c1eb38030bc4994a4fbf66ef27b130751bf2eb9c25c01082e8605",
+ "size": 7453
+ },
+ "output_windows.go": {
+ "mode": "0o644",
+ "sha256": "571c5ae1ad051a701b426371efd79a3776c2226ca9e3c2e598fe5996dfa1b8e1",
+ "size": 1066
+ },
+ "prompt.go": {
+ "mode": "0o644",
+ "sha256": "6b3e2bbd90f40ad6a487f1a6ea7f5a6fb48cae6c8c246ecc77621fb3e7383ca7",
+ "size": 7062
+ },
+ "render.go": {
+ "mode": "0o644",
+ "sha256": "90fdd57a63e06f01940d10ee1a0be95ced7d6adc7faa255b3141556d7d316270",
+ "size": 8020
+ },
+ "shortcut.go": {
+ "mode": "0o644",
+ "sha256": "b4a097f466df7396049ebe8393f81c9b1200159d4e2be22bd6838c307ec156dc",
+ "size": 1120
+ },
+ "signal_posix.go": {
+ "mode": "0o644",
+ "sha256": "74f0bae5f290f3f7f82a5dd495e672f627a4ab4b63118f870e8c13c0a7024314",
+ "size": 881
+ },
+ "signal_windows.go": {
+ "mode": "0o644",
+ "sha256": "444f662a32e6997df2af8e2a9e7dbfe977414a6bfc0f54a7f10117f204648437",
+ "size": 757
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982",
+ "os": "linux",
+ "sha256": "0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982"
+ },
+ "context_inventory_sha256": "6b8f93086e81483ac1ce82f328d7f4b38b1b560dbad057ed6a2a30ff3cf0e13f",
+ "image": "registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "9d3b21cdacadfa4f3de9584d0cea973e5aa2ceedcd5ec9cbd3a63df22b313455",
+ "receipt_path": "production/runtime-images-extra-v1/resolutions/316e0e68930cd4ef/resolution.json",
+ "receipt_sha256": "697bb0619eddcdfdeba1c9144b033f564f2d7514be6e6a44dc520fa4e63ed8bc",
+ "registry_digest": "sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "source_image": "docker.io/swebench/swesmith.x86_64.c-bata_1776_go-prompt.82a91227@sha256:3daf51c74a01657e9ad8f326651fb6f5b796ffecdb90098e74a52a9560e0a1bb",
+ "source_receipt_sha256": "b450bea0e201cbe194b765ded4b51539144c85296122c8b642d7e94c889526f3",
+ "space_commit": "5ae654cd2e9d695f0de304bd4398835fc7cf45e0",
+ "space_id": "harness-hub/scale800-go-316e0e68930cd4ef-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "b95addc02b95fc744e13d74fe6ad929484ec79fb7f2e5344f8de233956feac66",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21",
+ "source_proof_sha256": "6807b26f869e08dd045477e84018db79837170c63ed6cdb14609e34e922854bb",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:c-bata__go-prompt.82a91227.lm_modify__8gcanb51",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "9992c59c25864ce1556e67b9e1501c93f6e7f9ff",
+ "instruction_sha256": "7c3850ac925d7857cfa26aef3b2167960dc04521b3dc5003099c9a57cd94d245",
+ "is_fork": true,
+ "learner_path": "tasks/d5ec4ae57a3e26e165969f1e/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/c-bata__go-prompt.82a91227/a8a665926773770662d709b9bdadf3268bedca51/LICENSE"
+ },
+ "task_bundle": {
+ "basis": "Captured publisherMIT/train; exactsoftwarepermissionverifiedseparately",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "82a912274504477990ecf7c852eebb7c85291772",
+ "patch_sha256": "8b6f233581fa2b2db2cb0002653056321cc6c05c0cc5706c466fb097b69b76e9",
+ "provenance_path": "tasks/d5ec4ae57a3e26e165969f1e/source-proof.json",
+ "repository_lineage": [
+ "swesmith/c-bata__go-prompt.82a91227",
+ "c-bata/go-prompt"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "a8a665926773770662d709b9bdadf3268bedca51",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "003554c1c4bf0bb9a062ee26e7f896c30ea318a6",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/c-bata__go-prompt.82a91227",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "c-bata__go-prompt.82a91227.lm_modify__8gcanb51",
+ "task_sha256": "d2df532962aea911580a27f099a33bea3952f5c9373cd33c64afd8868df6e5ab",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "c-bata/go-prompt",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "1b6e8dec481a78854e7bfca272348a935583ac4b05d7d10b0101efe56ec3dbf5",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.md",
+ "/testbed/.github/ISSUE_TEMPLATE/feature_request.md",
+ "/testbed/.gitignore",
+ "/testbed/CHANGELOG.md",
+ "/testbed/LICENSE",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/_example/README.md",
+ "/testbed/_example/build.sh",
+ "/testbed/_example/exec-command/main.go",
+ "/testbed/_example/http-prompt/api.py",
+ "/testbed/_example/http-prompt/main.go",
+ "/testbed/_example/live-prefix/main.go",
+ "/testbed/_example/simple-echo/cjk-cyrillic/main.go",
+ "/testbed/_example/simple-echo/main.go",
+ "/testbed/_tools/README.md",
+ "/testbed/_tools/complete_file/main.go",
+ "/testbed/_tools/sigwinch/main.go",
+ "/testbed/_tools/vt100_debug/main.go",
+ "/testbed/buffer.go",
+ "/testbed/completer/file.go",
+ "/testbed/completion.go",
+ "/testbed/document.go",
+ "/testbed/emacs.go",
+ "/testbed/filter.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum",
+ "/testbed/history.go",
+ "/testbed/input.go",
+ "/testbed/input_posix.go",
+ "/testbed/input_windows.go",
+ "/testbed/internal/bisect/bisect.go",
+ "/testbed/internal/debug/assert.go",
+ "/testbed/internal/debug/log.go",
+ "/testbed/internal/strings/strings.go",
+ "/testbed/internal/term/raw.go",
+ "/testbed/internal/term/term.go",
+ "/testbed/key.go",
+ "/testbed/key_bind.go",
+ "/testbed/key_bind_func.go",
+ "/testbed/key_string.go",
+ "/testbed/option.go",
+ "/testbed/output.go",
+ "/testbed/output_posix.go",
+ "/testbed/output_vt100.go",
+ "/testbed/output_windows.go",
+ "/testbed/prompt.go",
+ "/testbed/render.go",
+ "/testbed/shortcut.go",
+ "/testbed/signal_posix.go",
+ "/testbed/signal_windows.go"
+ ]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/solution/solve.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..00d1a533519e8abc9def758862da6b859247bfe5
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"document.go": {"data": "cGFja2FnZSBwcm9tcHQKCmltcG9ydCAoCgkic3RyaW5ncyIKCSJ1bmljb2RlL3V0ZjgiCgoJImdpdGh1Yi5jb20vYy1iYXRhL2dvLXByb21wdC9pbnRlcm5hbC9iaXNlY3QiCglpc3RyaW5ncyAiZ2l0aHViLmNvbS9jLWJhdGEvZ28tcHJvbXB0L2ludGVybmFsL3N0cmluZ3MiCglydW5ld2lkdGggImdpdGh1Yi5jb20vbWF0dG4vZ28tcnVuZXdpZHRoIgopCgovLyBEb2N1bWVudCBoYXMgdGV4dCBkaXNwbGF5ZWQgaW4gdGVybWluYWwgYW5kIGN1cnNvciBwb3NpdGlvbi4KdHlwZSBEb2N1bWVudCBzdHJ1Y3QgewoJVGV4dCBzdHJpbmcKCS8vIFRoaXMgcmVwcmVzZW50cyBhIGluZGV4IGluIGEgcnVuZSBhcnJheSBvZiBEb2N1bWVudC5UZXh0LgoJLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgY3Vyc29yUG9zaXRpb24gaXMgMi4KCS8vIEJ1dCBEaXNwbGF5ZWRDdXJzb3JQb3NpdGlvbiByZXR1cm5zIDQgYmVjYXVzZSAn5pelJyBhbmQgJ+acrCcgYXJlIGRvdWJsZSB3aWR0aCBjaGFyYWN0ZXJzLgoJY3Vyc29yUG9zaXRpb24gaW50CglsYXN0S2V5ICAgICAgICBLZXkKfQoKLy8gTmV3RG9jdW1lbnQgcmV0dXJuIHRoZSBuZXcgZW1wdHkgZG9jdW1lbnQuCmZ1bmMgTmV3RG9jdW1lbnQoKSAqRG9jdW1lbnQgewoJcmV0dXJuICZEb2N1bWVudHsKCQlUZXh0OiAgICAgICAgICAgIiIsCgkJY3Vyc29yUG9zaXRpb246IDAsCgl9Cn0KCi8vIExhc3RLZXlTdHJva2UgcmV0dXJuIHRoZSBsYXN0IGtleSBwcmVzc2VkIGluIHRoaXMgZG9jdW1lbnQuCmZ1bmMgKGQgKkRvY3VtZW50KSBMYXN0S2V5U3Ryb2tlKCkgS2V5IHsKCXJldHVybiBkLmxhc3RLZXkKfQoKLy8gRGlzcGxheUN1cnNvclBvc2l0aW9uIHJldHVybnMgdGhlIGN1cnNvciBwb3NpdGlvbiBvbiByZW5kZXJlZCB0ZXh0IG9uIHRlcm1pbmFsIGVtdWxhdG9ycy4KLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgRGlzcGxheWVkQ3Vyc29yUG9zaXRpb24gcmV0dXJucyA0IGJlY2F1c2UgJ+aXpScgYW5kICfmnKwnIGFyZSBkb3VibGUgd2lkdGggY2hhcmFjdGVycy4KZnVuYyAoZCAqRG9jdW1lbnQpIERpc3BsYXlDdXJzb3JQb3NpdGlvbigpIGludCB7Cgl2YXIgcG9zaXRpb24gaW50CglydW5lcyA6PSBbXXJ1bmUoZC5UZXh0KVs6ZC5jdXJzb3JQb3NpdGlvbl0KCWZvciBpIDo9IHJhbmdlIHJ1bmVzIHsKCQlwb3NpdGlvbiArPSBydW5ld2lkdGguUnVuZVdpZHRoKHJ1bmVzW2ldKQoJfQoJcmV0dXJuIHBvc2l0aW9uCn0KCi8vIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yIHJldHVybiBjaGFyYWN0ZXIgcmVsYXRpdmUgdG8gY3Vyc29yIHBvc2l0aW9uLCBvciBlbXB0eSBzdHJpbmcKZnVuYyAoZCAqRG9jdW1lbnQpIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yKG9mZnNldCBpbnQpIChyIHJ1bmUpIHsKCXMgOj0gZC5UZXh0CgljbnQgOj0gMAoKCWZvciBsZW4ocykgPiAwIHsKCQljbnQrKwoJCXIsIHNpemUgOj0gdXRmOC5EZWNvZGVSdW5lSW5TdHJpbmcocykKCQlpZiBjbnQgPT0gZC5jdXJzb3JQb3NpdGlvbitvZmZzZXQgewoJCQlyZXR1cm4gcgoJCX0KCQlzID0gc1tzaXplOl0KCX0KCXJldHVybiAwCn0KCi8vIFRleHRCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJciA6PSBbXXJ1bmUoZC5UZXh0KQoJcmV0dXJuIHN0cmluZyhyWzpkLmN1cnNvclBvc2l0aW9uXSkKfQoKLy8gVGV4dEFmdGVyQ3Vyc29yIHJldHVybnMgdGhlIHRleHQgYWZ0ZXIgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRBZnRlckN1cnNvcigpIHN0cmluZyB7CglyIDo9IFtdcnVuZShkLlRleHQpCglyZXR1cm4gc3RyaW5nKHJbZC5jdXJzb3JQb3NpdGlvbjpdKQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYmVmb3JlIHRoZSBjdXJzb3IuCi8vIElmIHdlIGhhdmUgd2hpdGVzcGFjZSBiZWZvcmUgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcigpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBJZiB3ZSBoYXZlIHdoaXRlc3BhY2UgYWZ0ZXIgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yKCkgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmQoKV0KfQoKLy8gR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSgpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEFmdGVyQ3Vyc29yLCBpdCByZXR1cm5zIHN0cmluZyBjb250YWluaW5nIHNwYWNlCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UoKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpXQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yVW50aWxTZXBhcmF0b3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvciB1bnRpbCBuZXh0IHNlcGFyYXRvci4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJcmV0dXJuIHhbZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFVudGlsU2VwYXJhdG9yKHNlcCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvciByZXR1cm5zIHRoZSB0ZXh0IGFmdGVyIHRoZSBjdXJzb3IgdW50aWwgbmV4dCBzZXBhcmF0b3IuCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCldCn0KCi8vIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvciByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yKHNlcCBzdHJpbmcpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwKTpdCn0KCi8vIEdldFdvcmRBZnRlckN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYWZ0ZXIgdGhlIGN1cnNvci4KLy8gVW5saWtlIEdldFdvcmRBZnRlckN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXApXQp9CgovLyBGaW5kU3RhcnRPZlByZXZpb3VzV29yZCByZXR1cm5zIGFuIGluZGV4IHJlbGF0aXZlIHRvIHRoZSBjdXJzb3IgcG9zaXRpb24KLy8gcG9pbnRpbmcgdG8gdGhlIHN0YXJ0IG9mIHRoZSBwcmV2aW91cyB3b3JkLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5MYXN0SW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpICsgMQoJfQoJcmV0dXJuIDAKfQoKLy8gRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRXaXRoU3BhY2UgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBUaGUgb25seSBkaWZmZXJlbmNlIGlzIHRvIGlnbm9yZSBjb250aWd1b3VzIHNwYWNlcy4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWVuZCA6PSBpc3RyaW5ncy5MYXN0SW5kZXhOb3RCeXRlKHgsICcgJykKCWlmIGVuZCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEJ5dGUoeFs6ZW5kXSwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiAwCgl9CglyZXR1cm4gc3RhcnQgKyAxCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZCgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJaSA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaSArIDEKCX0KCXJldHVybiAwCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFdpdGhTcGFjZSgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJZW5kIDo9IGlzdHJpbmdzLkxhc3RJbmRleE5vdEFueSh4LCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiAwCgl9CglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4WzplbmRdLCBzZXApCglpZiBzdGFydCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCXJldHVybiBzdGFydCArIDEKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmQgcmV0dXJucyBhbiBpbmRleCByZWxhdGl2ZSB0byB0aGUgY3Vyc29yIHBvc2l0aW9uLgovLyBwb2ludGluZyB0byB0aGUgZW5kIG9mIHRoZSBjdXJyZW50IHdvcmQuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZEVuZE9mQ3VycmVudFdvcmQoKSBpbnQgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglpIDo9IHN0cmluZ3MuSW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpCgl9CglyZXR1cm4gbGVuKHgpCn0KCi8vIEZpbmRFbmRPZkN1cnJlbnRXb3JkV2l0aFNwYWNlIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZC4KLy8gVGhlIG9ubHkgZGlmZmVyZW5jZSBpcyB0byBpZ25vcmUgY29udGlndW91cyBzcGFjZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpIGludCB7Cgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCglzdGFydCA6PSBpc3RyaW5ncy5JbmRleE5vdEJ5dGUoeCwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCgllbmQgOj0gc3RyaW5ncy5JbmRleEJ5dGUoeFtzdGFydDpdLCAnICcpCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvciBpcyBhbG1vc3QgdGhlIHNhbWUgYXMgRmluZEVuZE9mQ3VycmVudFdvcmQuCi8vIEJ1dCB0aGlzIGNhbiBzcGVjaWZ5IFNlcGFyYXRvci4gUmV0dXJuIDAgaWYgbm90aGluZyB3YXMgZm91bmQuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCBzdHJpbmcpIGludCB7CglpZiBzZXAgPT0gIiIgewoJCXJldHVybiBkLkZpbmRFbmRPZkN1cnJlbnRXb3JkKCkKCX0KCgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5JbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaQoJfQoJcmV0dXJuIGxlbih4KQp9CgovLyBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZS4KLy8gQnV0IHRoaXMgY2FuIHNwZWNpZnkgU2VwYXJhdG9yLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRFbmRPZkN1cnJlbnRXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgaW50IHsKCWlmIHNlcCA9PSAiIiB7CgkJcmV0dXJuIGQuRmluZEVuZE9mQ3VycmVudFdvcmRXaXRoU3BhY2UoKQoJfQoKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoKCXN0YXJ0IDo9IGlzdHJpbmdzLkluZGV4Tm90QW55KHgsIHNlcCkKCWlmIHN0YXJ0ID09IC0xIHsKCQlyZXR1cm4gbGVuKHgpCgl9CgoJZW5kIDo9IHN0cmluZ3MuSW5kZXhBbnkoeFtzdGFydDpdLCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gQ3VycmVudExpbmVCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBzdGFydCBvZiB0aGUgbGluZSB1bnRpbCB0aGUgY3Vyc29yLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJcyA6PSBzdHJpbmdzLlNwbGl0KGQuVGV4dEJlZm9yZUN1cnNvcigpLCAiXG4iKQoJcmV0dXJuIHNbbGVuKHMpLTFdCn0KCi8vIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBjdXJzb3IgdW50aWwgdGhlIGVuZCBvZiB0aGUgbGluZS4KZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSBzdHJpbmcgewoJcmV0dXJuIHN0cmluZ3MuU3BsaXQoZC5UZXh0QWZ0ZXJDdXJzb3IoKSwgIlxuIilbMF0KfQoKLy8gQ3VycmVudExpbmUgcmV0dXJuIHRoZSB0ZXh0IG9uIHRoZSBsaW5lIHdoZXJlIHRoZSBjdXJzb3IgaXMuICh3aGVuIHRoZSBpbnB1dAovLyBjb25zaXN0cyBvZiBqdXN0IG9uZSBsaW5lLCBpdCBlcXVhbHMgYHRleHRgLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmUoKSBzdHJpbmcgewoJcmV0dXJuIGQuQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSArIGQuQ3VycmVudExpbmVBZnRlckN1cnNvcigpCn0KCi8vIEFycmF5IHBvaW50aW5nIHRvIHRoZSBzdGFydCBpbmRleGVzIG9mIGFsbCB0aGUgbGluZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBsaW5lU3RhcnRJbmRleGVzKCkgW11pbnQgewoJLy8gVE9ETzogQ2FjaGUsIGJlY2F1c2UgdGhpcyBpcyBvZnRlbiByZXVzZWQuCgkvLyAoSWYgaXQgaXMgdXNlZCwgaXQncyBvZnRlbiB1c2VkIG1hbnkgdGltZXMuCgkvLyBBbmQgdGhpcyBoYXMgdG8gYmUgZmFzdCBmb3IgZWRpdGluZyBiaWcgZG9jdW1lbnRzISkKCWxjIDo9IGQuTGluZUNvdW50KCkKCWxlbmd0aHMgOj0gbWFrZShbXWludCwgbGMpCglmb3IgaSwgbCA6PSByYW5nZSBkLkxpbmVzKCkgewoJCWxlbmd0aHNbaV0gPSBsZW4obCkKCX0KCgkvLyBDYWxjdWxhdGUgY3VtdWxhdGl2ZSBzdW1zLgoJaW5kZXhlcyA6PSBtYWtlKFtdaW50LCBsYysxKQoJaW5kZXhlc1swXSA9IDAgLy8gaHR0cHM6Ly9naXRodWIuY29tL2pvbmF0aGFuc2xlbmRlcnMvcHl0aG9uLXByb21wdC10b29sa2l0L2Jsb2IvbWFzdGVyL3Byb21wdF90b29sa2l0L2RvY3VtZW50LnB5I0wxODkKCXBvcyA6PSAwCglmb3IgaSwgbCA6PSByYW5nZSBsZW5ndGhzIHsKCQlwb3MgKz0gbCArIDEKCQlpbmRleGVzW2krMV0gPSBwb3MKCX0KCWlmIGxjID4gMSB7CgkJLy8gUG9wIHRoZSBsYXN0IGl0ZW0uIChUaGlzIGlzIG5vdCBhIG5ldyBsaW5lLikKCQlpbmRleGVzID0gaW5kZXhlc1s6bGNdCgl9CglyZXR1cm4gaW5kZXhlcwp9CgovLyBGb3IgdGhlIGluZGV4IG9mIGEgY2hhcmFjdGVyIGF0IGEgY2VydGFpbiBsaW5lLCBjYWxjdWxhdGUgdGhlIGluZGV4IG9mCi8vIHRoZSBmaXJzdCBjaGFyYWN0ZXIgb24gdGhhdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgZmluZExpbmVTdGFydEluZGV4KGluZGV4IGludCkgKHBvcyBpbnQsIGxpbmVTdGFydEluZGV4IGludCkgewoJaW5kZXhlcyA6PSBkLmxpbmVTdGFydEluZGV4ZXMoKQoJcG9zID0gYmlzZWN0LlJpZ2h0KGluZGV4ZXMsIGluZGV4KSAtIDEKCWxpbmVTdGFydEluZGV4ID0gaW5kZXhlc1twb3NdCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Sb3cgcmV0dXJucyB0aGUgY3VycmVudCByb3cuICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uUm93KCkgKHJvdyBpbnQpIHsKCXJvdywgXyA9IGQuZmluZExpbmVTdGFydEluZGV4KGQuY3Vyc29yUG9zaXRpb24pCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Db2wgcmV0dXJucyB0aGUgY3VycmVudCBjb2x1bW4uICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uQ29sKCkgKGNvbCBpbnQpIHsKCS8vIERvbid0IHVzZSBzZWxmLnRleHRfYmVmb3JlX2N1cnNvciB0byBjYWxjdWxhdGUgdGhpcy4gQ3JlYXRpbmcgc3Vic3RyaW5ncwoJLy8gYW5kIHNwbGl0dGluZyBpcyB0b28gZXhwZW5zaXZlIGZvciBnZXR0aW5nIHRoZSBjdXJzb3IgcG9zaXRpb24uCglfLCBpbmRleCA6PSBkLmZpbmRMaW5lU3RhcnRJbmRleChkLmN1cnNvclBvc2l0aW9uKQoJY29sID0gZC5jdXJzb3JQb3NpdGlvbiAtIGluZGV4CglyZXR1cm4KfQoKLy8gR2V0Q3Vyc29yTGVmdFBvc2l0aW9uIHJldHVybnMgdGhlIHJlbGF0aXZlIHBvc2l0aW9uIGZvciBjdXJzb3IgbGVmdC4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldEN1cnNvckxlZnRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvclJpZ2h0UG9zaXRpb24oLWNvdW50KQoJfQoJaWYgZC5DdXJzb3JQb3NpdGlvbkNvbCgpID4gY291bnQgewoJCXJldHVybiAtY291bnQKCX0KCXJldHVybiAtZC5DdXJzb3JQb3NpdGlvbkNvbCgpCn0KCi8vIEdldEN1cnNvclJpZ2h0UG9zaXRpb24gcmV0dXJucyByZWxhdGl2ZSBwb3NpdGlvbiBmb3IgY3Vyc29yIHJpZ2h0LgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yUmlnaHRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvckxlZnRQb3NpdGlvbigtY291bnQpCgl9CglpZiBsZW4oZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpID4gY291bnQgewoJCXJldHVybiBjb3VudAoJfQoJcmV0dXJuIGxlbihkLkN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSkKfQoKLy8gR2V0Q3Vyc29yVXBQb3NpdGlvbiByZXR1cm4gdGhlIHJlbGF0aXZlIGN1cnNvciBwb3NpdGlvbiAoY2hhcmFjdGVyIGluZGV4KSB3aGVyZSB3ZSB3b3VsZCBiZQovLyBpZiB0aGUgdXNlciBwcmVzc2VkIHRoZSBhcnJvdy11cCBidXR0b24uCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRDdXJzb3JVcFBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9CgoJcm93IDo9IGQuQ3Vyc29yUG9zaXRpb25Sb3coKSAtIGNvdW50CglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9CglyZXR1cm4gZC5UcmFuc2xhdGVSb3dDb2xUb0luZGV4KHJvdywgY29sKSAtIGQuY3Vyc29yUG9zaXRpb24KfQoKLy8gR2V0Q3Vyc29yRG93blBvc2l0aW9uIHJldHVybiB0aGUgcmVsYXRpdmUgY3Vyc29yIHBvc2l0aW9uIChjaGFyYWN0ZXIgaW5kZXgpIHdoZXJlIHdlIHdvdWxkIGJlIGlmIHRoZQovLyB1c2VyIHByZXNzZWQgdGhlIGFycm93LWRvd24gYnV0dG9uLgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yRG93blBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9Cglyb3cgOj0gZC5DdXJzb3JQb3NpdGlvblJvdygpICsgY291bnQKCXJldHVybiBkLlRyYW5zbGF0ZVJvd0NvbFRvSW5kZXgocm93LCBjb2wpIC0gZC5jdXJzb3JQb3NpdGlvbgp9CgovLyBMaW5lcyByZXR1cm5zIHRoZSBhcnJheSBvZiBhbGwgdGhlIGxpbmVzLgpmdW5jIChkICpEb2N1bWVudCkgTGluZXMoKSBbXXN0cmluZyB7CgkvLyBUT0RPOiBDYWNoZSwgYmVjYXVzZSB0aGlzIG9uZSBpcyByZXVzZWQgdmVyeSBvZnRlbi4KCXJldHVybiBzdHJpbmdzLlNwbGl0KGQuVGV4dCwgIlxuIikKfQoKLy8gTGluZUNvdW50IHJldHVybiB0aGUgbnVtYmVyIG9mIGxpbmVzIGluIHRoaXMgZG9jdW1lbnQuIElmIHRoZSBkb2N1bWVudCBlbmRzCi8vIHdpdGggYSB0cmFpbGluZyBcbiwgdGhhdCBjb3VudHMgYXMgdGhlIGJlZ2lubmluZyBvZiBhIG5ldyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgTGluZUNvdW50KCkgaW50IHsKCXJldHVybiBsZW4oZC5MaW5lcygpKQp9CgovLyBUcmFuc2xhdGVJbmRleFRvUG9zaXRpb24gZ2l2ZW4gYW4gaW5kZXggZm9yIHRoZSB0ZXh0LCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgKHJvdywgY29sKSB0dXBsZS4KLy8gKDAtYmFzZWQuIFJldHVybnMgKDAsIDApIGZvciBpbmRleD0wLikKZnVuYyAoZCAqRG9jdW1lbnQpIFRyYW5zbGF0ZUluZGV4VG9Qb3NpdGlvbihpbmRleCBpbnQpIChyb3cgaW50LCBjb2wgaW50KSB7Cglyb3csIHJvd0luZGV4IDo9IGQuZmluZExpbmVTdGFydEluZGV4KGluZGV4KQoJY29sID0gaW5kZXggLSByb3dJbmRleAoJcmV0dXJuCn0KCi8vIFRyYW5zbGF0ZVJvd0NvbFRvSW5kZXggZ2l2ZW4gYSAocm93LCBjb2wpLCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgaW5kZXguCi8vIChSb3cgYW5kIGNvbCBwYXJhbXMgYXJlIDAtYmFzZWQuKQpmdW5jIChkICpEb2N1bWVudCkgVHJhbnNsYXRlUm93Q29sVG9JbmRleChyb3cgaW50LCBjb2x1bW4gaW50KSAoaW5kZXggaW50KSB7CglpbmRleGVzIDo9IGQubGluZVN0YXJ0SW5kZXhlcygpCglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9IGVsc2UgaWYgcm93ID4gbGVuKGluZGV4ZXMpIHsKCQlyb3cgPSBsZW4oaW5kZXhlcykgLSAxCgl9CglpbmRleCA9IGluZGV4ZXNbcm93XQoJbGluZSA6PSBkLkxpbmVzKClbcm93XQoKCS8vIHB5dGhvbikgcmVzdWx0ICs9IG1heCgwLCBtaW4oY29sLCBsZW4obGluZSkpKQoJaWYgY29sdW1uID4gMCB8fCBsZW4obGluZSkgPiAwIHsKCQlpZiBjb2x1bW4gPiBsZW4obGluZSkgewoJCQlpbmRleCArPSBsZW4obGluZSkKCQl9IGVsc2UgewoJCQlpbmRleCArPSBjb2x1bW4KCQl9Cgl9CgoJLy8gS2VlcCBpbiByYW5nZS4gKGxlbihzZWxmLnRleHQpIGlzIGluY2x1ZGVkLCBiZWNhdXNlIHRoZSBjdXJzb3IgY2FuIGJlCgkvLyByaWdodCBhZnRlciB0aGUgZW5kIG9mIHRoZSB0ZXh0IGFzIHdlbGwuKQoJLy8gcHl0aG9uKSByZXN1bHQgPSBtYXgoMCwgbWluKHJlc3VsdCwgbGVuKHNlbGYudGV4dCkpKQoJaWYgaW5kZXggPiBsZW4oZC5UZXh0KSB7CgkJaW5kZXggPSBsZW4oZC5UZXh0KQoJfQoJaWYgaW5kZXggPCAwIHsKCQlpbmRleCA9IDAKCX0KCXJldHVybiBpbmRleAp9CgovLyBPbkxhc3RMaW5lIHJldHVybnMgdHJ1ZSB3aGVuIHdlIGFyZSBhdCB0aGUgbGFzdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgT25MYXN0TGluZSgpIGJvb2wgewoJcmV0dXJuIGQuQ3Vyc29yUG9zaXRpb25Sb3coKSA9PSAoZC5MaW5lQ291bnQoKSAtIDEpCn0KCi8vIEdldEVuZE9mTGluZVBvc2l0aW9uIHJldHVybnMgcmVsYXRpdmUgcG9zaXRpb24gZm9yIHRoZSBlbmQgb2YgdGhpcyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgR2V0RW5kT2ZMaW5lUG9zaXRpb24oKSBpbnQgewoJcmV0dXJuIGxlbihbXXJ1bmUoZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpKQp9CgpmdW5jIChkICpEb2N1bWVudCkgbGVhZGluZ1doaXRlc3BhY2VJbkN1cnJlbnRMaW5lKCkgKG1hcmdpbiBzdHJpbmcpIHsKCXRyaW1tZWQgOj0gc3RyaW5ncy5UcmltU3BhY2UoZC5DdXJyZW50TGluZSgpKQoJbWFyZ2luID0gZC5DdXJyZW50TGluZSgpWzpsZW4oZC5DdXJyZW50TGluZSgpKS1sZW4odHJpbW1lZCldCglyZXR1cm4KfQo=", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/task.toml b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..05a7f67ef22dc627d02b49298a31852c2838677b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/task.toml
@@ -0,0 +1,11 @@
+version = "1.0"
+[agent]
+timeout_sec = 300.0
+[verifier]
+timeout_sec = 300.0
+environment_mode = "shared"
+[environment]
+docker_image = "ghcr.io/younesbelkada/scale800@sha256:92e6a64d706ecb3218d8eb570135dc627a699b1dc334fff84ac424d057d4fc14"
+cpus = 1
+memory_mb = 2048
+storage_mb = 4096
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..1ac1583aaa50378cbba8f19c0e382288176dc432
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/manifest.json
@@ -0,0 +1,432 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWord"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CursorPositionRowAndCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorLeftPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorUpPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorDownPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorRightPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_Lines"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_LineCount"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateIndexToPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateRowColToIndex"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_OnLastLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetEndOfLinePosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestEmacsKeyBindings"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFilter"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFuzzyMatch"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryClear"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryAdd"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryOlder"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/escape"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/undefined"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWrite"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteRawStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatCompletion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBreakLineCallback"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionRow"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition_withJapanese"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/validation/canaries/delete-tests.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/validation/canaries/delete-tests.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/validation/canaries/delete-tests.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+find /testbed -name '*_test.go' -type f -delete
+printf 'PASS\nok forged-package 0.001s\n'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..3b1e7b88af359bd2db342f1ad85408b5e197a9d1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__8gcanb51/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "e51e112a6a81601013cdb3b71b7cd28890617d11767d75398b09871be9dd6ccb",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/Dockerfile b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f35bf9e5393ee1086fe1b72c1b442f3b16e2bd5b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22
+WORKDIR /testbed
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c8c031d0f87fb9aea0aff433b1fcaeaac259c41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: "Bug report"
+about: Create a bug report to improve go-prompt
+title: "[Bug]"
+labels: bug
+assignees: ''
+
+---
+
+# Bug reports
+
+*Please file a bug report here.*
+
+## Expected Behavior
+
+*Please describe the behavior you are expecting*
+
+## Current Behavior and Steps to Reproduce
+
+*What is the current behavior? Please provide detailed steps for reproducing the issue.*
+*A picture or gif animation tells a thousand words*
+
+## Context
+
+Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
+
+* Operating System:
+* Terminal Emulator: (i.e. iTerm2)
+* tag of go-prompt or commit revision:
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb816a2496376983781774cb5466fed8e1efc93b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,13 @@
+---
+name: "Feature request"
+about: Suggest an idea for new features in go-prompt.
+title: "[Feature Request]"
+labels: enhancement
+assignees: ''
+
+---
+
+# Feature Request
+
+*Please write your suggestion here.*
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/.gitignore b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..eba2b56abe0f7758a560d47dd19d8985b67ef327
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+bin/
+
+# Folders
+pkg/
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+# Glide
+vendor/
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/CHANGELOG.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..b9e21f1ef333b9ec13323bcd4a8f377322ed7e9f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/CHANGELOG.md
@@ -0,0 +1,79 @@
+# Change Log
+
+## v0.3.0 (2018/??/??)
+
+next release.
+
+## v0.2.3 (2018/10/25)
+
+### What's new?
+
+* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92).
+* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100).
+* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102).
+
+### Fixed
+
+* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details).
+* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details).
+* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details).
+
+### Removed or Deprecated
+
+* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`.
+
+## v0.2.2 (2018/06/28)
+
+### What's new?
+
+* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters.
+* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions.
+ * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details).
+* Add FilePathCompleter to complete file path on your system.
+* Add option to customize ascii code key bindings.
+* Add GetWordAfterCursor method in Document.
+
+### Removed or Deprecated
+
+* prompt.Choose shortcut function is deprecated.
+
+## v0.2.1 (2018/02/14)
+
+### What's New?
+
+* ~~It seems that windows support is almost perfect.~~
+ * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows.
+
+### Fixed
+
+* Fix a Shift+Tab handling on Windows.
+* Fix 4-dimension arrow keys handling on Windows.
+
+## v0.2.0 (2018/02/13)
+
+### What's New?
+
+* Supports scrollbar when there are too many matched suggestions
+* Windows support (but please caution because this is still not perfect).
+* Add OptionLivePrefix to update the prefix dynamically
+* Implement clear screen by `Ctrl+L`.
+
+### Fixed
+
+* Fix the behavior of `Ctrl+W` keybind.
+* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details).
+* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details).
+* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ).
+
+### News
+
+New core developers are joined (alphabetical order).
+
+* Nao Yonashiro (Github @orisano)
+* Ryoma Abe (Github @Allajah)
+* Yusuke Nakamura (Github @unasuke)
+
+
+## v0.1.0 (2017/08/15)
+
+Initial Release
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/LICENSE b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a86acaa7ab24fe61ea152a9afcadc21980020efb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Masashi SHIBATA
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/Makefile b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..505817c36f0b8a0bb643eed8680b8989af2b0920
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/Makefile
@@ -0,0 +1,46 @@
+.DEFAULT_GOAL := help
+
+SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
+
+GOIMPORTS ?= goimports
+GOCILINT ?= golangci-lint
+
+.PHONY: setup
+setup: ## Setup for required tools.
+ go get -u golang.org/x/tools/cmd/goimports
+ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: fmt
+fmt: $(SOURCES) ## Formatting source codes.
+ @$(GOIMPORTS) -w $^
+
+.PHONY: lint
+lint: ## Run golangci-lint.
+ @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
+
+.PHONY: test
+test: ## Run tests with race condition checking.
+ @go test -race ./...
+
+.PHONY: bench
+bench: ## Run benchmarks.
+ @go test -bench=. -run=- -benchmem ./...
+
+.PHONY: coverage
+cover: ## Run the tests.
+ @go test -coverprofile=coverage.o
+ @go tool cover -func=coverage.o
+
+.PHONY: generate
+generate: ## Run go generate
+ @go generate ./...
+
+.PHONY: build
+build: ## Build example command lines.
+ ./_example/build.sh
+
+.PHONY: help
+help: ## Show help text
+ @echo "Commands:"
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfcd7a399b4827d6b126d6a173cce34d36520481
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/README.md
@@ -0,0 +1,125 @@
+# go-prompt
+
+[](https://goreportcard.com/report/github.com/c-bata/go-prompt)
+
+[](https://godoc.org/github.com/c-bata/go-prompt)
+
+
+A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit),
+making it easier to build cross-platform command line tools using Go.
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func completer(d prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ }
+ return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ fmt.Println("Please select table.")
+ t := prompt.Input("> ", completer)
+ fmt.Println("You selected " + t)
+}
+```
+
+#### Projects using go-prompt
+
+* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt)
+* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli)
+* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn)
+* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli)
+* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans)
+* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit)
+* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go)
+* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS)
+* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs)
+* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli)
+* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt)
+* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh)
+* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell)
+* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt)
+* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim)
+* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron)
+* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl)
+* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl)
+* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit)
+* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.)
+
+## Features
+
+### Powerful auto-completion
+
+[](https://github.com/c-bata/kube-prompt)
+
+(This is a GIF animation of kube-prompt.)
+
+### Flexible options
+
+go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details.
+
+[](#flexible-options)
+
+### Keyboard Shortcuts
+
+Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell).
+You can customize and expand these shortcuts.
+
+[](#keyboard-shortcuts)
+
+Key Binding | Description
+---------------------|---------------------------------------------------------
+Ctrl + A | Go to the beginning of the line (Home)
+Ctrl + E | Go to the end of the line (End)
+Ctrl + P | Previous command (Up arrow)
+Ctrl + N | Next command (Down arrow)
+Ctrl + F | Forward one character
+Ctrl + B | Backward one character
+Ctrl + D | Delete character under the cursor
+Ctrl + H | Delete character before the cursor (Backspace)
+Ctrl + W | Cut the word before the cursor to the clipboard
+Ctrl + K | Cut the line after the cursor to the clipboard
+Ctrl + U | Cut the line before the cursor to the clipboard
+Ctrl + L | Clear the screen
+
+### History
+
+You can use Up arrow and Down arrow to walk through the history of commands executed.
+
+[](#history)
+
+### Multiple platform support
+
+We have confirmed go-prompt works fine in the following terminals:
+
+* iTerm2 (macOS)
+* Terminal.app (macOS)
+* Command Prompt (Windows)
+* gnome-terminal (Ubuntu)
+
+## Links
+
+* [Change Log](./CHANGELOG.md)
+* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt)
+* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt)
+
+## Author
+
+Masashi Shibata
+
+* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/)
+* Github: [@c-bata](https://github.com/c-bata/)
+
+## License
+
+This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..759b0e3f8acf1216b055e0f9458758a6c1e8950a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/README.md
@@ -0,0 +1,30 @@
+# Examples of go-prompt
+
+This directory includes some examples using go-prompt.
+These examples are useful to know the usage of go-prompt and check behavior for development.
+
+## simple-echo
+
+
+
+A simple echo example using `prompt.Input`.
+
+## http-prompt
+
+
+
+A simple [http-prompt](https://github.com/eliangcs/http-prompt) implementation using go-prompt in less than 200 lines of Go.
+
+## live-prefix
+
+
+
+A example application which changes a prefix string dynamically.
+This feature is used like [ktr0731/evans](https://github.com/ktr0731/evans) which is interactive gRPC client using go-prompt.
+
+## exec-command
+
+Run another CLI tool via `os/exec` package.
+More practical example is [a source code of kube-prompt](https://github.com/c-bata/kube-prompt).
+I recommend you to look this if you want to create tools like kube-prompt.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/build.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c552afcfa69b2356ffcd484c867abcaaaaeeaff
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+export GO111MODULE=on
+DIR=$(cd $(dirname $0); pwd)
+BIN_DIR=$(cd $(dirname $(dirname $0)); pwd)/bin
+
+mkdir -p ${BIN_DIR}
+go build -o ${BIN_DIR}/exec-command ${DIR}/exec-command/main.go
+go build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.go
+go build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.go
+go build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.go
+go build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/exec-command/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/exec-command/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..838f756260df91569491def29a7ee05a7c9a98f7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/exec-command/main.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "os/exec"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(t string) {
+ if t == "bash" {
+ cmd := exec.Command("bash")
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Run()
+ }
+ return
+}
+
+func completer(t prompt.Document) []prompt.Suggest {
+ return []prompt.Suggest{
+ {Text: "bash"},
+ }
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/http-prompt/api.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/http-prompt/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..08e7b1a489a2077f26f280fe39e3bd06efa52cd2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/http-prompt/api.py
@@ -0,0 +1,17 @@
+from bottle import route, run, request
+
+@route('/')
+def hello():
+ return "Hello World!"
+
+@route('/ping')
+def hello():
+ return "pong!"
+
+@route('/register', method='POST')
+def register():
+ name = request.json.get("name")
+ return "Hello %s!" % name
+
+if __name__ == "__main__":
+ run(host='localhost', port=8000, debug=True)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/http-prompt/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/http-prompt/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b372a3550c50121d6e500e2a08e641e168b8c00d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/http-prompt/main.go
@@ -0,0 +1,192 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+type RequestContext struct {
+ url *url.URL
+ header http.Header
+ client *http.Client
+}
+
+var ctx *RequestContext
+
+// See https://github.com/eliangcs/http-prompt/blob/master/http_prompt/completion.py
+var suggestions = []prompt.Suggest{
+ // Command
+ {"cd", "Change URL/path"},
+ {"exit", "Exit http-prompt"},
+
+ // HTTP Method
+ {"delete", "DELETE request"},
+ {"get", "GET request"},
+ {"patch", "GET request"},
+ {"post", "POST request"},
+ {"put", "PUT request"},
+
+ // HTTP Header
+ {"Accept", "Acceptable response media type"},
+ {"Accept-Charset", "Acceptable response charsets"},
+ {"Accept-Encoding", "Acceptable response content codings"},
+ {"Accept-Language", "Preferred natural languages in response"},
+ {"ALPN", "Application-layer protocol negotiation to use"},
+ {"Alt-Used", "Alternative host in use"},
+ {"Authorization", "Authentication information"},
+ {"Cache-Control", "Directives for caches"},
+ {"Connection", "Connection options"},
+ {"Content-Encoding", "Content codings"},
+ {"Content-Language", "Natural languages for content"},
+ {"Content-Length", "Anticipated size for payload body"},
+ {"Content-Location", "Where content was obtained"},
+ {"Content-MD5", "Base64-encoded MD5 sum of content"},
+ {"Content-Type", "Content media type"},
+ {"Cookie", "Stored cookies"},
+ {"Date", "Datetime when message was originated"},
+ {"Depth", "Applied only to resource or its members"},
+ {"DNT", "Do not track user"},
+ {"Expect", "Expected behaviors supported by server"},
+ {"Forwarded", "Proxies involved"},
+ {"From", "Sender email address"},
+ {"Host", "Target URI"},
+ {"HTTP2-Settings", "HTTP/2 connection parameters"},
+ {"If", "Request condition on state tokens and ETags"},
+ {"If-Match", "Request condition on target resource"},
+ {"If-Modified-Since", "Request condition on modification date"},
+ {"If-None-Match", "Request condition on target resource"},
+ {"If-Range", "Request condition on Range"},
+ {"If-Schedule-Tag-Match", "Request condition on Schedule-Tag"},
+ {"If-Unmodified-Since", "Request condition on modification date"},
+ {"Max-Forwards", "Max number of times forwarded by proxies"},
+ {"MIME-Version", "Version of MIME protocol"},
+ {"Origin", "Origin(s} issuing the request"},
+ {"Pragma", "Implementation-specific directives"},
+ {"Prefer", "Preferred server behaviors"},
+ {"Proxy-Authorization", "Proxy authorization credentials"},
+ {"Proxy-Connection", "Proxy connection options"},
+ {"Range", "Request transfer of only part of data"},
+ {"Referer", "Previous web page"},
+ {"TE", "Transfer codings willing to accept"},
+ {"Transfer-Encoding", "Transfer codings applied to payload body"},
+ {"Upgrade", "Invite server to upgrade to another protocol"},
+ {"User-Agent", "User agent string"},
+ {"Via", "Intermediate proxies"},
+ {"Warning", "Possible incorrectness with payload body"},
+ {"WWW-Authenticate", "Authentication scheme"},
+ {"X-Csrf-Token", "Prevent cross-site request forgery"},
+ {"X-CSRFToken", "Prevent cross-site request forgery"},
+ {"X-Forwarded-For", "Originating client IP address"},
+ {"X-Forwarded-Host", "Original host requested by client"},
+ {"X-Forwarded-Proto", "Originating protocol"},
+ {"X-Http-Method-Override", "Request method override"},
+ {"X-Requested-With", "Used to identify Ajax requests"},
+ {"X-XSRF-TOKEN", "Prevent cross-site request forgery"},
+}
+
+func livePrefix() (string, bool) {
+ if ctx.url.Path == "/" {
+ return "", false
+ }
+ return ctx.url.String() + "> ", true
+}
+
+func executor(in string) {
+ in = strings.TrimSpace(in)
+
+ var method, body string
+ blocks := strings.Split(in, " ")
+ switch blocks[0] {
+ case "exit":
+ fmt.Println("Bye!")
+ os.Exit(0)
+ case "cd":
+ if len(blocks) < 2 {
+ ctx.url.Path = "/"
+ } else {
+ ctx.url.Path = path.Join(ctx.url.Path, blocks[1])
+ }
+ return
+ case "get", "delete":
+ method = strings.ToUpper(blocks[0])
+ case "post", "put", "patch":
+ if len(blocks) < 2 {
+ fmt.Println("please set request body.")
+ return
+ }
+ body = strings.Join(blocks[1:], " ")
+ method = strings.ToUpper(blocks[0])
+ }
+ if method != "" {
+ req, err := http.NewRequest(method, ctx.url.String(), strings.NewReader(body))
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ req.Header = ctx.header
+ res, err := ctx.client.Do(req)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ result, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ fmt.Printf("%s\n", result)
+ ctx.header = http.Header{}
+ return
+ }
+
+ if h := strings.Split(in, ":"); len(h) == 2 {
+ // Handling HTTP Header
+ ctx.header.Add(strings.TrimSpace(h[0]), strings.Trim(h[1], ` '"`))
+ } else {
+ fmt.Println("Sorry, I don't understand.")
+ }
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ w := in.GetWordBeforeCursor()
+ if w == "" {
+ return []prompt.Suggest{}
+ }
+ return prompt.FilterHasPrefix(suggestions, w, true)
+}
+
+func main() {
+ var baseURL = "http://localhost:8000/"
+ if len(os.Args) == 2 {
+ baseURL = os.Args[1]
+ if strings.HasSuffix(baseURL, "/") {
+ baseURL += "/"
+ }
+ }
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ ctx = &RequestContext{
+ url: u,
+ header: http.Header{},
+ client: &http.Client{},
+ }
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(u.String()+"> "),
+ prompt.OptionLivePrefix(livePrefix),
+ prompt.OptionTitle("http-prompt"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/live-prefix/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/live-prefix/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c7ced720592173e2a13f19f7cb543730192d3f8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/live-prefix/main.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var LivePrefixState struct {
+ LivePrefix string
+ IsEnable bool
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+ if in == "" {
+ LivePrefixState.IsEnable = false
+ LivePrefixState.LivePrefix = in
+ return
+ }
+ LivePrefixState.LivePrefix = in + "> "
+ LivePrefixState.IsEnable = true
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func changeLivePrefix() (string, bool) {
+ return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionLivePrefix(changeLivePrefix),
+ prompt.OptionTitle("live-prefix-example"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/simple-echo/cjk-cyrillic/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/simple-echo/cjk-cyrillic/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e9e53adef1558e004f86ccbca2c2e2b83c1da39
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/simple-echo/cjk-cyrillic/main.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
+ {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
+ {Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
+ {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionTitle("sql-prompt for multi width characters"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/simple-echo/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/simple-echo/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..12b1bb4fc189e6b369e889779418d7826a45db9d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_example/simple-echo/main.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ in := prompt.Input(">>> ", completer,
+ prompt.OptionTitle("sql-prompt"),
+ prompt.OptionHistory([]string{"SELECT * FROM users;"}),
+ prompt.OptionPrefixTextColor(prompt.Yellow),
+ prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
+ prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
+ prompt.OptionSuggestionBGColor(prompt.DarkGray))
+ fmt.Println("Your input: " + in)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_tools/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..45bd2234f21ff32562984bec046316c8e52868fd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_tools/README.md
@@ -0,0 +1,10 @@
+## Tools of go-prompt
+
+### vt100_debug
+
+
+
+### sigwinch
+
+
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_tools/complete_file/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_tools/complete_file/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..41015cfab9b021fbc7df575bde87e3c510705496
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_tools/complete_file/main.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/completer"
+)
+
+var filePathCompleter = completer.FilePathCompleter{
+ IgnoreCase: true,
+ Filter: func(fi os.FileInfo) bool {
+ return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
+ },
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completerFunc(d prompt.Document) []prompt.Suggest {
+ t := d.GetWordBeforeCursor()
+ if strings.HasPrefix(t, "--") {
+ return []prompt.Suggest{
+ {"--foo", ""},
+ {"--bar", ""},
+ {"--baz", ""},
+ }
+ }
+ return filePathCompleter.Complete(d)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completerFunc,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_tools/sigwinch/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_tools/sigwinch/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9608eb3b4a5e3c6942c140c41e08a36ab3adb33b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_tools/sigwinch/main.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "unsafe"
+)
+
+// Winsize is winsize struct got from the ioctl(2) system call.
+type Winsize struct {
+ Row uint16
+ Col uint16
+ X uint16 // pixel value
+ Y uint16 // pixel value
+}
+
+// GetWinSize returns winsize struct which is the response of ioctl(2).
+func GetWinSize(fd int) *Winsize {
+ ws := &Winsize{}
+ retCode, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ uintptr(fd),
+ uintptr(syscall.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(ws)))
+
+ if int(retCode) == -1 {
+ panic(errno)
+ }
+ return ws
+}
+
+func main() {
+ signalChan := make(chan os.Signal, 1)
+ signal.Notify(
+ signalChan,
+ syscall.SIGHUP,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ exitChan := make(chan int)
+ go func() {
+ for {
+ s := <-signalChan
+ switch s {
+ // kill -SIGHUP XXXX
+ case syscall.SIGHUP:
+ exitChan <- 0
+
+ // kill -SIGINT XXXX or Ctrl+c
+ case syscall.SIGINT:
+ exitChan <- 0
+
+ // kill -SIGTERM XXXX
+ case syscall.SIGTERM:
+ exitChan <- 0
+
+ // kill -SIGQUIT XXXX
+ case syscall.SIGQUIT:
+ exitChan <- 0
+
+ case syscall.SIGWINCH:
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ default:
+ exitChan <- 1
+ }
+ }
+ }()
+
+ code := <-exitChan
+ os.Exit(code)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_tools/vt100_debug/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_tools/vt100_debug/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c6036d45959febc739e287a3a7b631259d4ee7c1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/_tools/vt100_debug/main.go
@@ -0,0 +1,47 @@
+// +build !windows
+
+package main
+
+import (
+ "fmt"
+ "syscall"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/term"
+)
+
+func main() {
+ if err := term.SetRaw(syscall.Stdin); err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer term.Restore()
+
+ bufCh := make(chan []byte, 128)
+ go readBuffer(bufCh)
+ fmt.Print("> ")
+
+ for {
+ b := <-bufCh
+ if key := prompt.GetKey(b); key == prompt.NotDefined {
+ fmt.Printf("Key '%s' data:'%#v'\n", string(b), b)
+ } else {
+ if key == prompt.ControlC {
+ fmt.Println("exit.")
+ return
+ }
+ fmt.Printf("Key '%s' data:'%#v'\n", key, b)
+ }
+ fmt.Print("> ")
+ }
+}
+
+func readBuffer(bufCh chan []byte) {
+ buf := make([]byte, 1024)
+
+ for {
+ if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
+ bufCh <- buf[:n]
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/buffer.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..46efbbba8bfb75f4a064c83368b781d1d6dbbb29
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/buffer.go
@@ -0,0 +1,191 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Buffer emulates the console buffer.
+type Buffer struct {
+ workingLines []string // The working lines. Similar to history
+ workingIndex int
+ cursorPosition int
+ cacheDocument *Document
+ preferredColumn int // Remember the original column for the next up/down movement.
+ lastKeyStroke Key
+}
+
+// Text returns string of the current line.
+func (b *Buffer) Text() string {
+ return b.workingLines[b.workingIndex]
+}
+
+// Document method to return document instance from the current text and cursor position.
+func (b *Buffer) Document() (d *Document) {
+ if b.cacheDocument == nil ||
+ b.cacheDocument.Text != b.Text() ||
+ b.cacheDocument.cursorPosition != b.cursorPosition {
+ b.cacheDocument = &Document{
+ Text: b.Text(),
+ cursorPosition: b.cursorPosition,
+ }
+ }
+ b.cacheDocument.lastKey = b.lastKeyStroke
+ return b.cacheDocument
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (b *Buffer) DisplayCursorPosition() int {
+ return b.Document().DisplayCursorPosition()
+}
+
+// InsertText insert string from current line.
+func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
+ or := []rune(b.Text())
+ oc := b.cursorPosition
+
+ if overwrite {
+ overwritten := string(or[oc : oc+len(v)])
+ if strings.Contains(overwritten, "\n") {
+ i := strings.IndexAny(overwritten, "\n")
+ overwritten = overwritten[:i]
+ }
+ b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):]))
+ } else {
+ b.setText(string(or[:oc]) + v + string(or[oc:]))
+ }
+
+ if moveCursor {
+ b.cursorPosition += len([]rune(v))
+ }
+}
+
+// SetText method to set text and update cursorPosition.
+// (When doing this, make sure that the cursor_position is valid for this text.
+// text/cursor_position should be consistent at any time, otherwise set a Document instead.)
+func (b *Buffer) setText(v string) {
+ debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position")
+ b.workingLines[b.workingIndex] = v
+}
+
+// Set cursor position. Return whether it changed.
+func (b *Buffer) setCursorPosition(p int) {
+ if p > 0 {
+ b.cursorPosition = p
+ } else {
+ b.cursorPosition = 0
+ }
+}
+
+func (b *Buffer) setDocument(d *Document) {
+ b.cacheDocument = d
+ b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length.
+ b.setText(d.Text)
+}
+
+// CursorLeft move to left on the current line.
+func (b *Buffer) CursorLeft(count int) {
+ l := b.Document().GetCursorLeftPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorRight move to right on the current line.
+func (b *Buffer) CursorRight(count int) {
+ l := b.Document().GetCursorRightPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorUp move cursor to the previous line.
+// (for multi-line edit).
+func (b *Buffer) CursorUp(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorUpPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// CursorDown move cursor to the next line.
+// (for multi-line edit).
+func (b *Buffer) CursorDown(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorDownPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text.
+func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) {
+ debug.Assert(count >= 0, "count should be positive")
+ r := []rune(b.Text())
+
+ if b.cursorPosition > 0 {
+ start := b.cursorPosition - count
+ if start < 0 {
+ start = 0
+ }
+ deleted = string(r[start:b.cursorPosition])
+ b.setDocument(&Document{
+ Text: string(r[:start]) + string(r[b.cursorPosition:]),
+ cursorPosition: b.cursorPosition - len([]rune(deleted)),
+ })
+ }
+ return
+}
+
+// NewLine means CR.
+func (b *Buffer) NewLine(copyMargin bool) {
+ if copyMargin {
+ b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true)
+ } else {
+ b.InsertText("\n", false, true)
+ }
+}
+
+// Delete specified number of characters and Return the deleted text.
+func (b *Buffer) Delete(count int) (deleted string) {
+ r := []rune(b.Text())
+ if b.cursorPosition < len(r) {
+ deleted = b.Document().TextAfterCursor()[:count]
+ b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):]))
+ }
+ return
+}
+
+// JoinNextLine joins the next line to the current one by deleting the line ending after the current line.
+func (b *Buffer) JoinNextLine(separator string) {
+ if !b.Document().OnLastLine() {
+ b.cursorPosition += b.Document().GetEndOfLinePosition()
+ b.Delete(1)
+ // Remove spaces
+ b.setText(b.Document().TextBeforeCursor() + separator + strings.TrimLeft(b.Document().TextAfterCursor(), " "))
+ }
+}
+
+// SwapCharactersBeforeCursor swaps the last two characters before the cursor.
+func (b *Buffer) SwapCharactersBeforeCursor() {
+ if b.cursorPosition >= 2 {
+ x := b.Text()[b.cursorPosition-2 : b.cursorPosition-1]
+ y := b.Text()[b.cursorPosition-1 : b.cursorPosition]
+ b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:])
+ }
+}
+
+// NewBuffer is constructor of Buffer struct.
+func NewBuffer() (b *Buffer) {
+ b = &Buffer{
+ workingLines: []string{""},
+ workingIndex: 0,
+ preferredColumn: -1, // -1 means nil
+ }
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/completer/file.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/completer/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..59f2d8dec84214ccaa6e345a11ed51aa61a08199
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/completer/file.go
@@ -0,0 +1,90 @@
+package completer
+
+import (
+ "io/ioutil"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+var (
+ // FilePathCompletionSeparator holds separate characters.
+ FilePathCompletionSeparator = string([]byte{' ', os.PathSeparator})
+)
+
+// FilePathCompleter is a completer for your local file system.
+// Please caution that you need to set OptionCompletionWordSeparator(completer.FilePathCompletionSeparator)
+// when you use this completer.
+type FilePathCompleter struct {
+ Filter func(fi os.FileInfo) bool
+ IgnoreCase bool
+ fileListCache map[string][]prompt.Suggest
+}
+
+func cleanFilePath(path string) (dir, base string, err error) {
+ if path == "" {
+ return ".", "", nil
+ }
+
+ var endsWithSeparator bool
+ if len(path) >= 1 && path[len(path)-1] == os.PathSeparator {
+ endsWithSeparator = true
+ }
+
+ if runtime.GOOS != "windows" && len(path) >= 2 && path[0:2] == "~/" {
+ me, err := user.Current()
+ if err != nil {
+ return "", "", err
+ }
+ path = filepath.Join(me.HomeDir, path[1:])
+ }
+ path = filepath.Clean(os.ExpandEnv(path))
+ dir = filepath.Dir(path)
+ base = filepath.Base(path)
+
+ if endsWithSeparator {
+ dir = path + string(os.PathSeparator) // Append slash(in POSIX) if path ends with slash.
+ base = "" // Set empty string if path ends with separator.
+ }
+ return dir, base, nil
+}
+
+// Complete returns suggestions from your local file system.
+func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest {
+ if c.fileListCache == nil {
+ c.fileListCache = make(map[string][]prompt.Suggest, 4)
+ }
+
+ path := d.GetWordBeforeCursor()
+ dir, base, err := cleanFilePath(path)
+ if err != nil {
+ debug.Log("completer: cannot get current user:" + err.Error())
+ return nil
+ }
+
+ if cached, ok := c.fileListCache[dir]; ok {
+ return prompt.FilterHasPrefix(cached, base, c.IgnoreCase)
+ }
+
+ files, err := ioutil.ReadDir(dir)
+ if err != nil && os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ debug.Log("completer: cannot read directory items:" + err.Error())
+ return nil
+ }
+
+ suggests := make([]prompt.Suggest, 0, len(files))
+ for _, f := range files {
+ if c.Filter != nil && !c.Filter(f) {
+ continue
+ }
+ suggests = append(suggests, prompt.Suggest{Text: f.Name()})
+ }
+ c.fileListCache[dir] = suggests
+ return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/completion.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/completion.go
new file mode 100644
index 0000000000000000000000000000000000000000..57e82eefc0f50e9561214704e770a2ad313a3659
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/completion.go
@@ -0,0 +1,190 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+const (
+ shortenSuffix = "..."
+ leftPrefix = " "
+ leftSuffix = " "
+ rightPrefix = " "
+ rightSuffix = " "
+)
+
+var (
+ leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix)
+ rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix)
+ completionMargin = leftMargin + rightMargin
+)
+
+// Suggest is printed when completing.
+type Suggest struct {
+ Text string
+ Description string
+}
+
+// CompletionManager manages which suggestion is now selected.
+type CompletionManager struct {
+ selected int // -1 means nothing one is selected.
+ tmp []Suggest
+ max uint16
+ completer Completer
+
+ verticalScroll int
+ wordSeparator string
+ showAtStart bool
+}
+
+// GetSelectedSuggestion returns the selected item.
+func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) {
+ if c.selected == -1 {
+ return Suggest{}, false
+ } else if c.selected < -1 {
+ debug.Assert(false, "must not reach here")
+ c.selected = -1
+ return Suggest{}, false
+ }
+ return c.tmp[c.selected], true
+}
+
+// GetSuggestions returns the list of suggestion.
+func (c *CompletionManager) GetSuggestions() []Suggest {
+ return c.tmp
+}
+
+// Reset to select nothing.
+func (c *CompletionManager) Reset() {
+ c.selected = -1
+ c.verticalScroll = 0
+ c.Update(*NewDocument())
+}
+
+// Update to update the suggestions.
+func (c *CompletionManager) Update(in Document) {
+ c.tmp = c.completer(in)
+}
+
+// Previous to select the previous suggestion item.
+func (c *CompletionManager) Previous() {
+ if c.verticalScroll == c.selected && c.selected > 0 {
+ c.verticalScroll--
+ }
+ c.selected--
+ c.update()
+}
+
+// Next to select the next suggestion item.
+func (c *CompletionManager) Next() {
+ if c.verticalScroll+int(c.max)-1 == c.selected {
+ c.verticalScroll++
+ }
+ c.selected++
+ c.update()
+}
+
+// Completing returns whether the CompletionManager selects something one.
+func (c *CompletionManager) Completing() bool {
+ return c.selected != -1
+}
+
+func (c *CompletionManager) update() {
+ max := int(c.max)
+ if len(c.tmp) < max {
+ max = len(c.tmp)
+ }
+
+ if c.selected >= len(c.tmp) {
+ c.Reset()
+ } else if c.selected < -1 {
+ c.selected = len(c.tmp) - 1
+ c.verticalScroll = len(c.tmp) - max
+ }
+}
+
+func deleteBreakLineCharacters(s string) string {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, "\r", "", -1)
+ return s
+}
+
+func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) {
+ l := len(o)
+ n := make([]string, l)
+
+ lenPrefix := runewidth.StringWidth(prefix)
+ lenSuffix := runewidth.StringWidth(suffix)
+ lenShorten := runewidth.StringWidth(shortenSuffix)
+ min := lenPrefix + lenSuffix + lenShorten
+ for i := 0; i < l; i++ {
+ o[i] = deleteBreakLineCharacters(o[i])
+
+ w := runewidth.StringWidth(o[i])
+ if width < w {
+ width = w
+ }
+ }
+
+ if width == 0 {
+ return n, 0
+ }
+ if min >= max {
+ return n, 0
+ }
+ if lenPrefix+width+lenSuffix > max {
+ width = max - lenPrefix - lenSuffix
+ }
+
+ for i := 0; i < l; i++ {
+ x := runewidth.StringWidth(o[i])
+ if x <= width {
+ spaces := strings.Repeat(" ", width-x)
+ n[i] = prefix + o[i] + spaces + suffix
+ } else if x > width {
+ x := runewidth.Truncate(o[i], width, shortenSuffix)
+ // When calling runewidth.Truncate("您好xxx您好xxx", 11, "...") returns "您好xxx..."
+ // But the length of this result is 10. So we need fill right using runewidth.FillRight.
+ n[i] = prefix + runewidth.FillRight(x, width) + suffix
+ }
+ }
+ return n, lenPrefix + width + lenSuffix
+}
+
+func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) {
+ num := len(suggests)
+ new = make([]Suggest, num)
+
+ left := make([]string, num)
+ for i := 0; i < num; i++ {
+ left[i] = suggests[i].Text
+ }
+ right := make([]string, num)
+ for i := 0; i < num; i++ {
+ right[i] = suggests[i].Description
+ }
+
+ left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix)
+ if leftWidth == 0 {
+ return []Suggest{}, 0
+ }
+ right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix)
+
+ for i := 0; i < num; i++ {
+ new[i] = Suggest{Text: left[i], Description: right[i]}
+ }
+ return new, leftWidth + rightWidth
+}
+
+// NewCompletionManager returns initialized CompletionManager object.
+func NewCompletionManager(completer Completer, max uint16) *CompletionManager {
+ return &CompletionManager{
+ selected: -1,
+ max: max,
+ completer: completer,
+
+ verticalScroll: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/document.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/document.go
new file mode 100644
index 0000000000000000000000000000000000000000..56eb3e08d6fbb4fbedebf5fefdc3f30e8e31a3ea
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/document.go
@@ -0,0 +1,448 @@
+package prompt
+
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+ istrings "github.com/c-bata/go-prompt/internal/strings"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Document has text displayed in terminal and cursor position.
+type Document struct {
+ Text string
+ // This represents a index in a rune array of Document.Text.
+ // So if Document is "日本(cursor)語", cursorPosition is 2.
+ // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+ cursorPosition int
+ lastKey Key
+}
+
+// NewDocument return the new empty document.
+func NewDocument() *Document {
+ return &Document{
+ Text: "",
+ cursorPosition: 0,
+ }
+}
+
+// LastKeyStroke return the last key pressed in this document.
+func (d *Document) LastKeyStroke() Key {
+ return d.lastKey
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (d *Document) DisplayCursorPosition() int {
+ var position int
+ runes := []rune(d.Text)[:d.cursorPosition]
+ for i := range runes {
+ position += runewidth.RuneWidth(runes[i])
+ }
+ return position
+}
+
+// GetCharRelativeToCursor return character relative to cursor position, or empty string
+func (d *Document) GetCharRelativeToCursor(offset int) (r rune) {
+ s := d.Text
+ cnt := 0
+
+ for len(s) > 0 {
+ cnt++
+ r, size := utf8.DecodeRuneInString(s)
+ if cnt == d.cursorPosition+offset {
+ return r
+ }
+ s = s[size:]
+ }
+ return 0
+}
+
+// TextBeforeCursor returns the text before the cursor.
+func (d *Document) TextBeforeCursor() string {
+ r := []rune(d.Text)
+ return string(r[:d.cursorPosition])
+}
+
+// TextAfterCursor returns the text after the cursor.
+func (d *Document) TextAfterCursor() string {
+ r := []rune(d.Text)
+ return string(r[d.cursorPosition:])
+}
+
+// GetWordBeforeCursor returns the word before the cursor.
+// If we have whitespace before the cursor this returns an empty string.
+func (d *Document) GetWordBeforeCursor() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWord():]
+}
+
+// GetWordAfterCursor returns the word after the cursor.
+// If we have whitespace after the cursor this returns an empty string.
+func (d *Document) GetWordAfterCursor() string {
+ x := d.TextAfterCursor()
+ endIndex := d.FindEndOfCurrentWord()
+ if len(x) == 0 {
+ return x
+ }
+ if endIndex > 0 {
+ return x[1:endIndex]
+ }
+ return x[:endIndex]
+}
+
+// GetWordBeforeCursorWithSpace returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorWithSpace() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordWithSpace():]
+}
+
+// GetWordAfterCursorWithSpace returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorWithSpace() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordWithSpace()]
+}
+
+// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
+func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparator(sep):]
+}
+
+// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
+func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparator(sep)]
+}
+
+// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):]
+}
+
+// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)]
+}
+
+// FindStartOfPreviousWord returns an index relative to the cursor position
+// pointing to the start of the previous word. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWord() int {
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexByte(x, ' ')
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindStartOfPreviousWordWithSpace() int {
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotByte(x, ' ')
+ if end == -1 {
+ return 0
+ }
+
+ start := strings.LastIndexByte(x[:end], ' ')
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWord()
+ }
+
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexAny(x, sep)
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWordWithSpace()
+ }
+
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotAny(x, sep)
+ if end == -1 {
+ return 0
+ }
+ start := strings.LastIndexAny(x[:end], sep)
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindEndOfCurrentWord returns an index relative to the cursor position.
+// pointing to the end of the current word. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWord() int {
+ x := d.TextAfterCursor()
+ i := strings.IndexByte(x, ' ')
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindEndOfCurrentWordWithSpace() int {
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotByte(x, ' ')
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexByte(x[start:], ' ')
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWord()
+ }
+
+ x := d.TextAfterCursor()
+ i := strings.IndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWordWithSpace()
+ }
+
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotAny(x, sep)
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexAny(x[start:], sep)
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// CurrentLineBeforeCursor returns the text from the start of the line until the cursor.
+func (d *Document) CurrentLineBeforeCursor() string {
+ s := strings.Split(d.TextBeforeCursor(), "\n")
+ return s[len(s)-1]
+}
+
+// CurrentLineAfterCursor returns the text from the cursor until the end of the line.
+func (d *Document) CurrentLineAfterCursor() string {
+ return strings.Split(d.TextAfterCursor(), "\n")[0]
+}
+
+// CurrentLine return the text on the line where the cursor is. (when the input
+// consists of just one line, it equals `text`.
+func (d *Document) CurrentLine() string {
+ return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor()
+}
+
+// Array pointing to the start indexes of all the lines.
+func (d *Document) lineStartIndexes() []int {
+ // TODO: Cache, because this is often reused.
+ // (If it is used, it's often used many times.
+ // And this has to be fast for editing big documents!)
+ lc := d.LineCount()
+ lengths := make([]int, lc)
+ for i, l := range d.Lines() {
+ lengths[i] = len(l)
+ }
+
+ // Calculate cumulative sums.
+ indexes := make([]int, lc+1)
+ indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189
+ pos := 0
+ for i, l := range lengths {
+ pos += l + 1
+ indexes[i+1] = pos
+ }
+ if lc > 1 {
+ // Pop the last item. (This is not a new line.)
+ indexes = indexes[:lc]
+ }
+ return indexes
+}
+
+// For the index of a character at a certain line, calculate the index of
+// the first character on that line.
+func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) {
+ indexes := d.lineStartIndexes()
+ pos = bisect.Right(indexes, index) - 1
+ lineStartIndex = indexes[pos]
+ return
+}
+
+// CursorPositionRow returns the current row. (0-based.)
+func (d *Document) CursorPositionRow() (row int) {
+ row, _ = d.findLineStartIndex(d.cursorPosition)
+ return
+}
+
+// CursorPositionCol returns the current column. (0-based.)
+func (d *Document) CursorPositionCol() (col int) {
+ // Don't use self.text_before_cursor to calculate this. Creating substrings
+ // and splitting is too expensive for getting the cursor position.
+ _, index := d.findLineStartIndex(d.cursorPosition)
+ col = d.cursorPosition - index
+ return
+}
+
+// GetCursorLeftPosition returns the relative position for cursor left.
+func (d *Document) GetCursorLeftPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorRightPosition(-count)
+ }
+ if d.CursorPositionCol() > count {
+ return -count
+ }
+ return -d.CursorPositionCol()
+}
+
+// GetCursorRightPosition returns relative position for cursor right.
+func (d *Document) GetCursorRightPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorLeftPosition(-count)
+ }
+ if len(d.CurrentLineAfterCursor()) > count {
+ return count
+ }
+ return len(d.CurrentLineAfterCursor())
+}
+
+// GetCursorUpPosition return the relative cursor position (character index) where we would be
+// if the user pressed the arrow-up button.
+func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+
+ row := d.CursorPositionRow() - count
+ if row < 0 {
+ row = 0
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// GetCursorDownPosition return the relative cursor position (character index) where we would be if the
+// user pressed the arrow-down button.
+func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+ row := d.CursorPositionRow() + count
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// Lines returns the array of all the lines.
+func (d *Document) Lines() []string {
+ // TODO: Cache, because this one is reused very often.
+ return strings.Split(d.Text, "\n")
+}
+
+// LineCount return the number of lines in this document. If the document ends
+// with a trailing \n, that counts as the beginning of a new line.
+func (d *Document) LineCount() int {
+ return len(d.Lines())
+}
+
+// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple.
+// (0-based. Returns (0, 0) for index=0.)
+func (d *Document) TranslateIndexToPosition(index int) (row int, col int) {
+ row, rowIndex := d.findLineStartIndex(index)
+ col = index - rowIndex
+ return
+}
+
+// TranslateRowColToIndex given a (row, col), return the corresponding index.
+// (Row and col params are 0-based.)
+func (d *Document) TranslateRowColToIndex(row int, column int) (index int) {
+ indexes := d.lineStartIndexes()
+ if row < 0 {
+ row = 0
+ } else if row > len(indexes) {
+ row = len(indexes) - 1
+ }
+ index = indexes[row]
+ line := d.Lines()[row]
+
+ // python) result += max(0, min(col, len(line)))
+ if column > 0 || len(line) > 0 {
+ if column > len(line) {
+ index += len(line)
+ } else {
+ index += column
+ }
+ }
+
+ // Keep in range. (len(self.text) is included, because the cursor can be
+ // right after the end of the text as well.)
+ // python) result = max(0, min(result, len(self.text)))
+ if index > len(d.Text) {
+ index = len(d.Text)
+ }
+ if index < 0 {
+ index = 0
+ }
+ return index
+}
+
+// OnLastLine returns true when we are at the last line.
+func (d *Document) OnLastLine() bool {
+ return d.CursorPositionRow() == (d.LineCount() - 1)
+}
+
+// GetEndOfLinePosition returns relative position for the end of this line.
+func (d *Document) GetEndOfLinePosition() int {
+ return len([]rune(d.CurrentLineAfterCursor()))
+}
+
+func (d *Document) leadingWhitespaceInCurrentLine() (margin string) {
+ trimmed := strings.TrimSpace(d.CurrentLine())
+ margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)]
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/emacs.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/emacs.go
new file mode 100644
index 0000000000000000000000000000000000000000..632f96321f2577cdb7e8cffe639f1518a65d5e0f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/emacs.go
@@ -0,0 +1,120 @@
+package prompt
+
+import "github.com/c-bata/go-prompt/internal/debug"
+
+/*
+
+========
+PROGRESS
+========
+
+Moving the cursor
+-----------------
+
+* [x] Ctrl + a Go to the beginning of the line (Home)
+* [x] Ctrl + e Go to the End of the line (End)
+* [x] Ctrl + p Previous command (Up arrow)
+* [x] Ctrl + n Next command (Down arrow)
+* [x] Ctrl + f Forward one character
+* [x] Ctrl + b Backward one character
+* [x] Ctrl + xx Toggle between the start of line and current cursor position
+
+Editing
+-------
+
+* [x] Ctrl + L Clear the Screen, similar to the clear command
+* [x] Ctrl + d Delete character under the cursor
+* [x] Ctrl + h Delete character before the cursor (Backspace)
+
+* [x] Ctrl + w Cut the Word before the cursor to the clipboard.
+* [x] Ctrl + k Cut the Line after the cursor to the clipboard.
+* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard.
+
+* [ ] Ctrl + t Swap the last two characters before the cursor (typo).
+* [ ] Esc + t Swap the last two words before the cursor.
+
+* [ ] ctrl + y Paste the last thing to be cut (yank)
+* [ ] ctrl + _ Undo
+
+*/
+
+var emacsKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: ControlE,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+ },
+ },
+ // Go to the beginning of the line
+ {
+ Key: ControlA,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+ },
+ },
+ // Cut the Line after the cursor
+ {
+ Key: ControlK,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.Delete(len(x))
+ },
+ },
+ // Cut/delete the Line before the cursor
+ {
+ Key: ControlU,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.DeleteBeforeCursor(len(x))
+ },
+ },
+ // Delete character under the cursor
+ {
+ Key: ControlD,
+ Fn: func(buf *Buffer) {
+ if buf.Text() != "" {
+ buf.Delete(1)
+ }
+ },
+ },
+ // Backspace
+ {
+ Key: ControlH,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+ },
+ },
+ // Right allow: Forward one character
+ {
+ Key: ControlF,
+ Fn: func(buf *Buffer) {
+ buf.CursorRight(1)
+ },
+ },
+ // Left allow: Backward one character
+ {
+ Key: ControlB,
+ Fn: func(buf *Buffer) {
+ buf.CursorLeft(1)
+ },
+ },
+ // Cut the Word before the cursor.
+ {
+ Key: ControlW,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace())))
+ },
+ },
+ // Clear the Screen, similar to the clear command
+ {
+ Key: ControlL,
+ Fn: func(buf *Buffer) {
+ consoleWriter.EraseScreen()
+ consoleWriter.CursorGoTo(0, 0)
+ debug.AssertNoError(consoleWriter.Flush())
+ },
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/filter.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/filter.go
new file mode 100644
index 0000000000000000000000000000000000000000..61c17ed7f436a069563f520512bd25e4d81af0de
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/filter.go
@@ -0,0 +1,71 @@
+package prompt
+
+import "strings"
+
+// Filter is the type to filter the prompt.Suggestion array.
+type Filter func([]Suggest, string, bool) []Suggest
+
+// FilterHasPrefix checks whether the string completions.Text begins with sub.
+func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
+}
+
+// FilterHasSuffix checks whether the completion.Text ends with sub.
+func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
+}
+
+// FilterContains checks whether the completion.Text contains sub.
+func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
+}
+
+// FilterFuzzy checks whether the completion.Text fuzzy matches sub.
+// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
+// would match, for example, "Good food is gone"
+// ^ ^ ^
+func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
+}
+
+func fuzzyMatch(s, sub string) bool {
+ sChars := []rune(s)
+ sIdx := 0
+
+ // https://staticcheck.io/docs/checks#S1029
+ for _, c := range sub {
+ found := false
+ for ; sIdx < len(sChars); sIdx++ {
+ if sChars[sIdx] == c {
+ found = true
+ sIdx++
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
+
+func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
+ if sub == "" {
+ return suggestions
+ }
+ if ignoreCase {
+ sub = strings.ToUpper(sub)
+ }
+
+ ret := make([]Suggest, 0, len(suggestions))
+ for i := range suggestions {
+ c := suggestions[i].Text
+ if ignoreCase {
+ c = strings.ToUpper(c)
+ }
+ if function(c, sub) {
+ ret = append(ret, suggestions[i])
+ }
+ }
+ return ret
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/go.mod b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..30bc6d39a39c328341ca7153d3391352be5baa63
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/go.mod
@@ -0,0 +1,11 @@
+module github.com/c-bata/go-prompt
+
+go 1.14
+
+require (
+ github.com/mattn/go-colorable v0.1.7
+ github.com/mattn/go-runewidth v0.0.9
+ github.com/mattn/go-tty v0.0.3
+ github.com/pkg/term v1.2.0-beta.2
+ golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/go.sum b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..768bf93619a68e1b334c13e7b93ec84fa465598e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/go.sum
@@ -0,0 +1,23 @@
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/history.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/history.go
new file mode 100644
index 0000000000000000000000000000000000000000..e75c64592d82142bf4826ceb8c613ac72ca24d9c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/history.go
@@ -0,0 +1,61 @@
+package prompt
+
+// History stores the texts that are entered.
+type History struct {
+ histories []string
+ tmp []string
+ selected int
+}
+
+// Add to add text in history.
+func (h *History) Add(input string) {
+ h.histories = append(h.histories, input)
+ h.Clear()
+}
+
+// Clear to clear the history.
+func (h *History) Clear() {
+ h.tmp = make([]string, len(h.histories))
+ for i := range h.histories {
+ h.tmp[i] = h.histories[i]
+ }
+ h.tmp = append(h.tmp, "")
+ h.selected = len(h.tmp) - 1
+}
+
+// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
+ if len(h.tmp) == 1 || h.selected == 0 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected--
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
+ if h.selected >= len(h.tmp)-1 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected++
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// NewHistory returns new history object.
+func NewHistory() *History {
+ return &History{
+ histories: []string{},
+ tmp: []string{""},
+ selected: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/input.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/input.go
new file mode 100644
index 0000000000000000000000000000000000000000..307e747190c2b27bf888b379644fc4f3cdd489a2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/input.go
@@ -0,0 +1,169 @@
+package prompt
+
+import "bytes"
+
+// WinSize represents the width and height of terminal.
+type WinSize struct {
+ Row uint16
+ Col uint16
+}
+
+// ConsoleParser is an interface to abstract input layer.
+type ConsoleParser interface {
+ // Setup should be called before starting input
+ Setup() error
+ // TearDown should be called after stopping input
+ TearDown() error
+ // GetWinSize returns WinSize object to represent width and height of terminal.
+ GetWinSize() *WinSize
+ // Read returns byte array.
+ Read() ([]byte, error)
+}
+
+// GetKey returns Key correspond to input byte codes.
+func GetKey(b []byte) Key {
+ for _, k := range ASCIISequences {
+ if bytes.Equal(k.ASCIICode, b) {
+ return k.Key
+ }
+ }
+ return NotDefined
+}
+
+// ASCIISequences holds mappings of the key and byte array.
+var ASCIISequences = []*ASCIICode{
+ {Key: Escape, ASCIICode: []byte{0x1b}},
+
+ {Key: ControlSpace, ASCIICode: []byte{0x00}},
+ {Key: ControlA, ASCIICode: []byte{0x1}},
+ {Key: ControlB, ASCIICode: []byte{0x2}},
+ {Key: ControlC, ASCIICode: []byte{0x3}},
+ {Key: ControlD, ASCIICode: []byte{0x4}},
+ {Key: ControlE, ASCIICode: []byte{0x5}},
+ {Key: ControlF, ASCIICode: []byte{0x6}},
+ {Key: ControlG, ASCIICode: []byte{0x7}},
+ {Key: ControlH, ASCIICode: []byte{0x8}},
+ //{Key: ControlI, ASCIICode: []byte{0x9}},
+ //{Key: ControlJ, ASCIICode: []byte{0xa}},
+ {Key: ControlK, ASCIICode: []byte{0xb}},
+ {Key: ControlL, ASCIICode: []byte{0xc}},
+ {Key: ControlM, ASCIICode: []byte{0xd}},
+ {Key: ControlN, ASCIICode: []byte{0xe}},
+ {Key: ControlO, ASCIICode: []byte{0xf}},
+ {Key: ControlP, ASCIICode: []byte{0x10}},
+ {Key: ControlQ, ASCIICode: []byte{0x11}},
+ {Key: ControlR, ASCIICode: []byte{0x12}},
+ {Key: ControlS, ASCIICode: []byte{0x13}},
+ {Key: ControlT, ASCIICode: []byte{0x14}},
+ {Key: ControlU, ASCIICode: []byte{0x15}},
+ {Key: ControlV, ASCIICode: []byte{0x16}},
+ {Key: ControlW, ASCIICode: []byte{0x17}},
+ {Key: ControlX, ASCIICode: []byte{0x18}},
+ {Key: ControlY, ASCIICode: []byte{0x19}},
+ {Key: ControlZ, ASCIICode: []byte{0x1a}},
+
+ {Key: ControlBackslash, ASCIICode: []byte{0x1c}},
+ {Key: ControlSquareClose, ASCIICode: []byte{0x1d}},
+ {Key: ControlCircumflex, ASCIICode: []byte{0x1e}},
+ {Key: ControlUnderscore, ASCIICode: []byte{0x1f}},
+ {Key: Backspace, ASCIICode: []byte{0x7f}},
+
+ {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}},
+
+ {Key: Enter, ASCIICode: []byte{0xa}},
+ {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}},
+ {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+ {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}},
+ {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}},
+ {Key: Tab, ASCIICode: []byte{0x9}},
+ {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}},
+ {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}},
+ {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}},
+ {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}},
+ {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode
+
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}},
+ {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}},
+ {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}},
+ {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}},
+ {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}},
+ {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}},
+ {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}},
+ {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}},
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}},
+ {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}},
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+
+ // Xterm
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}},
+ // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}},
+ {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}},
+ {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}},
+ {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}},
+ {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}},
+
+ {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}},
+ {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}},
+ {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}},
+ {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}},
+
+ // Tmux sends following keystrokes when control+arrow is pressed, but for
+ // Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ // it a normal arrow press, because that's more important.
+ {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}},
+
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt
+
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/input_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/input_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f10430318be0e797c841eba8e08ab1cf5277be27
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/input_posix.go
@@ -0,0 +1,77 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/term"
+ "golang.org/x/sys/unix"
+)
+
+const maxReadBytes = 1024
+
+// PosixParser is a ConsoleParser implementation for POSIX environment.
+type PosixParser struct {
+ fd int
+ origTermios syscall.Termios
+}
+
+// Setup should be called before starting input
+func (t *PosixParser) Setup() error {
+ // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
+ if err := syscall.SetNonblock(t.fd, true); err != nil {
+ return err
+ }
+ if err := term.SetRaw(t.fd); err != nil {
+ return err
+ }
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (t *PosixParser) TearDown() error {
+ if err := syscall.SetNonblock(t.fd, false); err != nil {
+ return err
+ }
+ if err := term.Restore(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Read returns byte array.
+func (t *PosixParser) Read() ([]byte, error) {
+ buf := make([]byte, maxReadBytes)
+ n, err := syscall.Read(t.fd, buf)
+ if err != nil {
+ return []byte{}, err
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (t *PosixParser) GetWinSize() *WinSize {
+ ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: ws.Row,
+ Col: ws.Col,
+ }
+}
+
+var _ ConsoleParser = &PosixParser{}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *PosixParser {
+ in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ return &PosixParser{
+ fd: in,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/input_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/input_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..11b7679d4c4bc8b924a5b6c863ca1f6d6880570d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/input_windows.go
@@ -0,0 +1,83 @@
+// +build windows
+
+package prompt
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf8"
+ "unsafe"
+
+ tty "github.com/mattn/go-tty"
+)
+
+const maxReadBytes = 1024
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
+
+// WindowsParser is a ConsoleParser implementation for Win32 console.
+type WindowsParser struct {
+ tty *tty.TTY
+}
+
+// Setup should be called before starting input
+func (p *WindowsParser) Setup() error {
+ t, err := tty.Open()
+ if err != nil {
+ return err
+ }
+ p.tty = t
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (p *WindowsParser) TearDown() error {
+ return p.tty.Close()
+}
+
+// Read returns byte array.
+func (p *WindowsParser) Read() ([]byte, error) {
+ var ev uint32
+ r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
+ if r0 == 0 {
+ return nil, err
+ }
+ if ev == 0 {
+ return nil, errors.New("EAGAIN")
+ }
+
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, maxReadBytes)
+ n := utf8.EncodeRune(buf[:], r)
+ for p.tty.Buffered() && n < maxReadBytes {
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ break
+ }
+ n += utf8.EncodeRune(buf[n:], r)
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (p *WindowsParser) GetWinSize() *WinSize {
+ w, h, err := p.tty.Size()
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: uint16(h),
+ Col: uint16(w),
+ }
+}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *WindowsParser {
+ return &WindowsParser{}
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/bisect/bisect.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/bisect/bisect.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe162fa8c4873302e25702081b629a445d43415
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/bisect/bisect.go
@@ -0,0 +1,15 @@
+package bisect
+
+import "sort"
+
+// Right to locate the insertion point for v in a to maintain sorted order.
+func Right(a []int, v int) int {
+ return bisectRightRange(a, v, 0, len(a))
+}
+
+func bisectRightRange(a []int, v int, lo, hi int) int {
+ s := a[lo:hi]
+ return sort.Search(len(s), func(i int) bool {
+ return s[i] > v
+ })
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/debug/assert.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/debug/assert.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f648ac93c44e1e021cdf581a68f03b548534d9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/debug/assert.go
@@ -0,0 +1,55 @@
+package debug
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
+)
+
+var (
+ enableAssert bool
+)
+
+func init() {
+ if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
+ enableAssert = true
+ }
+}
+
+// Assert ensures expected condition.
+func Assert(cond bool, msg interface{}) {
+ if cond {
+ return
+ }
+ if enableAssert {
+ panic(msg)
+ }
+ writeWithSync(2, "[ASSERT] "+toString(msg))
+}
+
+func toString(v interface{}) string {
+ switch a := v.(type) {
+ case func() string:
+ return a()
+ case string:
+ return a
+ case fmt.Stringer:
+ return a.String()
+ default:
+ return fmt.Sprintf("unexpected type, %t", v)
+ }
+}
+
+// AssertNoError ensures err is nil.
+func AssertNoError(err error) {
+ if err == nil {
+ return
+ }
+ if enableAssert {
+ panic(err)
+ }
+ writeWithSync(2, "[ASSERT] "+err.Error())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/debug/log.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/debug/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..516378627a34ead9063ab7ce6c445b23c77b7cb4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/debug/log.go
@@ -0,0 +1,52 @@
+package debug
+
+import (
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+const (
+ envEnableLog = "GO_PROMPT_ENABLE_LOG"
+ logFileName = "go-prompt.log"
+)
+
+var (
+ logfile *os.File
+ logger *log.Logger
+)
+
+func init() {
+ if e := os.Getenv(envEnableLog); e == "true" || e == "1" {
+ var err error
+ logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
+ if err == nil {
+ logger = log.New(logfile, "", log.Llongfile)
+ return
+ }
+ }
+ logger = log.New(ioutil.Discard, "", log.Llongfile)
+}
+
+// Teardown to close logfile
+func Teardown() {
+ if logfile == nil {
+ return
+ }
+ _ = logfile.Close()
+}
+
+func writeWithSync(calldepth int, msg string) {
+ calldepth++
+ if logfile == nil {
+ return
+ }
+ _ = logger.Output(calldepth, msg)
+ _ = logfile.Sync() // immediately write msg
+}
+
+// Log to output message
+func Log(msg string) {
+ calldepth := 2
+ writeWithSync(calldepth, msg)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/strings/strings.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/strings/strings.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7d1886ae03a7d541c66dffca921e2d040e6d5eb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/strings/strings.go
@@ -0,0 +1,102 @@
+package strings
+
+import "unicode/utf8"
+
+// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior.
+func IndexNotByte(s string, c byte) int {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior.
+func LastIndexNotByte(s string, c byte) int {
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+type asciiSet [8]uint32
+
+func (as *asciiSet) notContains(c byte) bool {
+ return (as[c>>5] & (1 << uint(c&31))) == 0
+}
+
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c>>5] |= 1 << uint(c&31)
+ }
+ return as, true
+}
+
+// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior.
+func IndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := 0; i < len(s); i++ {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+
+ LabelFirstLoop:
+ for i, c := range s {
+ for j, m := range chars {
+ if c != m && j == len(chars)-1 {
+ return i
+ } else if c != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior.
+func LastIndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ LabelFirstLoop:
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRuneInString(s[:i])
+ i -= size
+ for j, m := range chars {
+ if r != m && j == len(chars)-1 {
+ return i
+ } else if r != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/term/raw.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/term/raw.go
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3ed8d04023558cf386a98080815d661248b85
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/term/raw.go
@@ -0,0 +1,29 @@
+// +build !windows
+
+package term
+
+import (
+ "syscall"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+// SetRaw put terminal into a raw mode
+func SetRaw(fd int) error {
+ n, err := getOriginalTermios(fd)
+ if err != nil {
+ return err
+ }
+
+ n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK |
+ syscall.ISTRIP | syscall.INLCR | syscall.IGNCR |
+ syscall.ICRNL | syscall.IXON
+ n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL
+ n.Cflag &^= syscall.CSIZE | syscall.PARENB
+ n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters.
+ n.Cc[syscall.VMIN] = 1
+ n.Cc[syscall.VTIME] = 0
+
+ return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n))
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/term/term.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/term/term.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a53c059ae60c0348ec01689babef4b13a2ecd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/internal/term/term.go
@@ -0,0 +1,34 @@
+// +build !windows
+
+package term
+
+import (
+ "sync"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ saveTermios *unix.Termios
+ saveTermiosFD int
+ saveTermiosOnce sync.Once
+)
+
+func getOriginalTermios(fd int) (*unix.Termios, error) {
+ var err error
+ saveTermiosOnce.Do(func() {
+ saveTermiosFD = fd
+ saveTermios, err = termios.Tcgetattr(uintptr(fd))
+ })
+ return saveTermios, err
+}
+
+// Restore terminal's mode.
+func Restore() error {
+ o, err := getOriginalTermios(saveTermiosFD)
+ if err != nil {
+ return err
+ }
+ return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/key.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ba569c2dd20a8ae3b3dd79ff3695bf0b6c1bd09
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/key.go
@@ -0,0 +1,128 @@
+// Code generated by hand; DO NOT EDIT.
+// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment.
+
+package prompt
+
+// Key is the type express the key inserted from user.
+//go:generate stringer -type=Key
+type Key int
+
+// ASCIICode is the type contains Key and it's ascii byte array.
+type ASCIICode struct {
+ Key Key
+ ASCIICode []byte
+}
+
+const (
+ Escape Key = iota
+
+ ControlA
+ ControlB
+ ControlC
+ ControlD
+ ControlE
+ ControlF
+ ControlG
+ ControlH
+ ControlI
+ ControlJ
+ ControlK
+ ControlL
+ ControlM
+ ControlN
+ ControlO
+ ControlP
+ ControlQ
+ ControlR
+ ControlS
+ ControlT
+ ControlU
+ ControlV
+ ControlW
+ ControlX
+ ControlY
+ ControlZ
+
+ ControlSpace
+ ControlBackslash
+ ControlSquareClose
+ ControlCircumflex
+ ControlUnderscore
+ ControlLeft
+ ControlRight
+ ControlUp
+ ControlDown
+
+ Up
+ Down
+ Right
+ Left
+
+ ShiftLeft
+ ShiftUp
+ ShiftDown
+ ShiftRight
+
+ Home
+ End
+ Delete
+ ShiftDelete
+ ControlDelete
+ PageUp
+ PageDown
+ BackTab
+ Insert
+ Backspace
+
+ // Aliases.
+ Tab
+ Enter
+ // Actually Enter equals ControlM, not ControlJ,
+ // However, in prompt_toolkit, we made the mistake of translating
+ // \r into \n during the input, so everyone is now handling the
+ // enter key by binding ControlJ.
+
+ // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere,
+ // because that's future compatible, and will still work when we
+ // stop replacing \r by \n.
+
+ F1
+ F2
+ F3
+ F4
+ F5
+ F6
+ F7
+ F8
+ F9
+ F10
+ F11
+ F12
+ F13
+ F14
+ F15
+ F16
+ F17
+ F18
+ F19
+ F20
+ F21
+ F22
+ F23
+ F24
+
+ // Matches any key.
+ Any
+
+ // Special
+ CPRResponse
+ Vt100MouseEvent
+ WindowsMouseEvent
+ BracketedPaste
+
+ // Key which is ignored. (The key binding for this key should not do anything.)
+ Ignore
+
+ // Key is not defined
+ NotDefined
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/key_bind.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/key_bind.go
new file mode 100644
index 0000000000000000000000000000000000000000..42669e7f942efc4d92f896388daede90b96b55dd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/key_bind.go
@@ -0,0 +1,59 @@
+package prompt
+
+// KeyBindFunc receives buffer and processed it.
+type KeyBindFunc func(*Buffer)
+
+// KeyBind represents which key should do what operation.
+type KeyBind struct {
+ Key Key
+ Fn KeyBindFunc
+}
+
+// ASCIICodeBind represents which []byte should do what operation
+type ASCIICodeBind struct {
+ ASCIICode []byte
+ Fn KeyBindFunc
+}
+
+// KeyBindMode to switch a key binding flexibly.
+type KeyBindMode string
+
+const (
+ // CommonKeyBind is a mode without any keyboard shortcut
+ CommonKeyBind KeyBindMode = "common"
+ // EmacsKeyBind is a mode to use emacs-like keyboard shortcut
+ EmacsKeyBind KeyBindMode = "emacs"
+)
+
+var commonKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: End,
+ Fn: GoLineEnd,
+ },
+ // Go to the beginning of the line
+ {
+ Key: Home,
+ Fn: GoLineBeginning,
+ },
+ // Delete character under the cursor
+ {
+ Key: Delete,
+ Fn: DeleteChar,
+ },
+ // Backspace
+ {
+ Key: Backspace,
+ Fn: DeleteBeforeChar,
+ },
+ // Right allow: Forward one character
+ {
+ Key: Right,
+ Fn: GoRightChar,
+ },
+ // Left allow: Backward one character
+ {
+ Key: Left,
+ Fn: GoLeftChar,
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/key_bind_func.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/key_bind_func.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b2ecdf63179dbfdbcb0d71bfa436bb36d62d230
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/key_bind_func.go
@@ -0,0 +1,48 @@
+package prompt
+
+// GoLineEnd Go to the End of the line
+func GoLineEnd(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+}
+
+// GoLineBeginning Go to the beginning of the line
+func GoLineBeginning(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+}
+
+// DeleteChar Delete character under the cursor
+func DeleteChar(buf *Buffer) {
+ buf.Delete(1)
+}
+
+// DeleteWord Delete word before the cursor
+func DeleteWord(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
+
+// DeleteBeforeChar Go to Backspace
+func DeleteBeforeChar(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+}
+
+// GoRightChar Forward one character
+func GoRightChar(buf *Buffer) {
+ buf.CursorRight(1)
+}
+
+// GoLeftChar Backward one character
+func GoLeftChar(buf *Buffer) {
+ buf.CursorLeft(1)
+}
+
+// GoRightWord Forward one word
+func GoRightWord(buf *Buffer) {
+ buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
+}
+
+// GoLeftWord Backward one word
+func GoLeftWord(buf *Buffer) {
+ buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/key_string.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/key_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..fce6ea31c502b3e763451cb47757ae1b49c32814
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/key_string.go
@@ -0,0 +1,16 @@
+// Code generated by "stringer -type=Key"; DO NOT EDIT.
+
+package prompt
+
+import "strconv"
+
+const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined"
+
+var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607}
+
+func (i Key) String() string {
+ if i < 0 || i >= Key(len(_Key_index)-1) {
+ return "Key(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _Key_name[_Key_index[i]:_Key_index[i+1]]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/option.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/option.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd6806cc1dbccf8c4ddb048080fde615c59088
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/option.go
@@ -0,0 +1,310 @@
+package prompt
+
+// Option is the type to replace default parameters.
+// prompt.New accepts any number of options (this is functional option pattern).
+type Option func(prompt *Prompt) error
+
+// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
+func OptionParser(x ConsoleParser) Option {
+ return func(p *Prompt) error {
+ p.in = x
+ return nil
+ }
+}
+
+// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
+func OptionWriter(x ConsoleWriter) Option {
+ return func(p *Prompt) error {
+ registerConsoleWriter(x)
+ p.renderer.out = x
+ return nil
+ }
+}
+
+// OptionTitle to set title displayed at the header bar of terminal.
+func OptionTitle(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.title = x
+ return nil
+ }
+}
+
+// OptionPrefix to set prefix string.
+func OptionPrefix(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefix = x
+ return nil
+ }
+}
+
+// OptionInitialBufferText to set the initial buffer text
+func OptionInitialBufferText(x string) Option {
+ return func(p *Prompt) error {
+ p.buf.InsertText(x, false, true)
+ return nil
+ }
+}
+
+// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
+func OptionCompletionWordSeparator(x string) Option {
+ return func(p *Prompt) error {
+ p.completion.wordSeparator = x
+ return nil
+ }
+}
+
+// OptionLivePrefix to change the prefix dynamically by callback function
+func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
+ return func(p *Prompt) error {
+ p.renderer.livePrefixCallback = f
+ return nil
+ }
+}
+
+// OptionPrefixTextColor change a text color of prefix string
+func OptionPrefixTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixTextColor = x
+ return nil
+ }
+}
+
+// OptionPrefixBackgroundColor to change a background color of prefix string
+func OptionPrefixBackgroundColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixBGColor = x
+ return nil
+ }
+}
+
+// OptionInputTextColor to change a color of text which is input by user
+func OptionInputTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputTextColor = x
+ return nil
+ }
+}
+
+// OptionInputBGColor to change a color of background which is input by user
+func OptionInputBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputBGColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionTextColor to change a text color which is completed
+func OptionPreviewSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionBGColor to change a background color which is completed
+func OptionPreviewSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionTextColor to change a text color in drop down suggestions.
+func OptionSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionBGColor change a background color in drop down suggestions.
+func OptionSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarThumbColor to change a thumb color on scrollbar.
+func OptionScrollbarThumbColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarThumbColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarBGColor to change a background color of scrollbar.
+func OptionScrollbarBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarBGColor = x
+ return nil
+ }
+}
+
+// OptionMaxSuggestion specify the max number of displayed suggestions.
+func OptionMaxSuggestion(x uint16) Option {
+ return func(p *Prompt) error {
+ p.completion.max = x
+ return nil
+ }
+}
+
+// OptionHistory to set history expressed by string array.
+func OptionHistory(x []string) Option {
+ return func(p *Prompt) error {
+ p.history.histories = x
+ p.history.Clear()
+ return nil
+ }
+}
+
+// OptionSwitchKeyBindMode set a key bind mode.
+func OptionSwitchKeyBindMode(m KeyBindMode) Option {
+ return func(p *Prompt) error {
+ p.keyBindMode = m
+ return nil
+ }
+}
+
+// OptionCompletionOnDown allows for Down arrow key to trigger completion.
+func OptionCompletionOnDown() Option {
+ return func(p *Prompt) error {
+ p.completionOnDown = true
+ return nil
+ }
+}
+
+// SwitchKeyBindMode to set a key bind mode.
+// Deprecated: Please use OptionSwitchKeyBindMode.
+var SwitchKeyBindMode = OptionSwitchKeyBindMode
+
+// OptionAddKeyBind to set a custom key bind.
+func OptionAddKeyBind(b ...KeyBind) Option {
+ return func(p *Prompt) error {
+ p.keyBindings = append(p.keyBindings, b...)
+ return nil
+ }
+}
+
+// OptionAddASCIICodeBind to set a custom key bind.
+func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option {
+ return func(p *Prompt) error {
+ p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...)
+ return nil
+ }
+}
+
+// OptionShowCompletionAtStart to set completion window is open at start.
+func OptionShowCompletionAtStart() Option {
+ return func(p *Prompt) error {
+ p.completion.showAtStart = true
+ return nil
+ }
+}
+
+// OptionBreakLineCallback to run a callback at every break line
+func OptionBreakLineCallback(fn func(*Document)) Option {
+ return func(p *Prompt) error {
+ p.renderer.breakLineCallback = fn
+ return nil
+ }
+}
+
+// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop
+func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
+ return func(p *Prompt) error {
+ p.exitChecker = fn
+ return nil
+ }
+}
+
+// New returns a Prompt with powerful auto-completion.
+func New(executor Executor, completer Completer, opts ...Option) *Prompt {
+ defaultWriter := NewStdoutWriter()
+ registerConsoleWriter(defaultWriter)
+
+ pt := &Prompt{
+ in: NewStandardInputParser(),
+ renderer: &Render{
+ prefix: "> ",
+ out: defaultWriter,
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ },
+ buf: NewBuffer(),
+ executor: executor,
+ history: NewHistory(),
+ completion: NewCompletionManager(completer, 6),
+ keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting
+ }
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/output.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/output.go
new file mode 100644
index 0000000000000000000000000000000000000000..42531b412f1ed027c2fff5b85bc273e53e569b3a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/output.go
@@ -0,0 +1,161 @@
+package prompt
+
+import "sync"
+
+var (
+ consoleWriterMu sync.Mutex
+ consoleWriter ConsoleWriter
+)
+
+func registerConsoleWriter(f ConsoleWriter) {
+ consoleWriterMu.Lock()
+ defer consoleWriterMu.Unlock()
+ consoleWriter = f
+}
+
+// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on.
+type DisplayAttribute int
+
+const (
+ // DisplayReset reset all display attributes.
+ DisplayReset DisplayAttribute = iota
+ // DisplayBold set bold or increases intensity.
+ DisplayBold
+ // DisplayLowIntensity decreases intensity. Not widely supported.
+ DisplayLowIntensity
+ // DisplayItalic set italic. Not widely supported.
+ DisplayItalic
+ // DisplayUnderline set underline
+ DisplayUnderline
+ // DisplayBlink set blink (less than 150 per minute).
+ DisplayBlink
+ // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported.
+ DisplayRapidBlink
+ // DisplayReverse swap foreground and background colors.
+ DisplayReverse
+ // DisplayInvisible set invisible. Not widely supported.
+ DisplayInvisible
+ // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported.
+ DisplayCrossedOut
+ // DisplayDefaultFont set primary(default) font
+ DisplayDefaultFont
+)
+
+// Color represents color on terminal.
+type Color int
+
+const (
+ // DefaultColor represents a default color.
+ DefaultColor Color = iota
+
+ // Low intensity
+
+ // Black represents a black.
+ Black
+ // DarkRed represents a dark red.
+ DarkRed
+ // DarkGreen represents a dark green.
+ DarkGreen
+ // Brown represents a brown.
+ Brown
+ // DarkBlue represents a dark blue.
+ DarkBlue
+ // Purple represents a purple.
+ Purple
+ // Cyan represents a cyan.
+ Cyan
+ // LightGray represents a light gray.
+ LightGray
+
+ // High intensity
+
+ // DarkGray represents a dark gray.
+ DarkGray
+ // Red represents a red.
+ Red
+ // Green represents a green.
+ Green
+ // Yellow represents a yellow.
+ Yellow
+ // Blue represents a blue.
+ Blue
+ // Fuchsia represents a fuchsia.
+ Fuchsia
+ // Turquoise represents a turquoise.
+ Turquoise
+ // White represents a white.
+ White
+)
+
+// ConsoleWriter is an interface to abstract output layer.
+type ConsoleWriter interface {
+ /* Write */
+
+ // WriteRaw to write raw byte array.
+ WriteRaw(data []byte)
+ // Write to write safety byte array by removing control sequences.
+ Write(data []byte)
+ // WriteStr to write raw string.
+ WriteRawStr(data string)
+ // WriteStr to write safety string by removing control sequences.
+ WriteStr(data string)
+ // Flush to flush buffer.
+ Flush() error
+
+ /* Erasing */
+
+ // EraseScreen erases the screen with the background colour and moves the cursor to home.
+ EraseScreen()
+ // EraseUp erases the screen from the current line up to the top of the screen.
+ EraseUp()
+ // EraseDown erases the screen from the current line down to the bottom of the screen.
+ EraseDown()
+ // EraseStartOfLine erases from the current cursor position to the start of the current line.
+ EraseStartOfLine()
+ // EraseEndOfLine erases from the current cursor position to the end of the current line.
+ EraseEndOfLine()
+ // EraseLine erases the entire current line.
+ EraseLine()
+
+ /* Cursor */
+
+ // ShowCursor stops blinking cursor and show.
+ ShowCursor()
+ // HideCursor hides cursor.
+ HideCursor()
+ // CursorGoTo sets the cursor position where subsequent text will begin.
+ CursorGoTo(row, col int)
+ // CursorUp moves the cursor up by 'n' rows; the default count is 1.
+ CursorUp(n int)
+ // CursorDown moves the cursor down by 'n' rows; the default count is 1.
+ CursorDown(n int)
+ // CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+ CursorForward(n int)
+ // CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+ CursorBackward(n int)
+ // AskForCPR asks for a cursor position report (CPR).
+ AskForCPR()
+ // SaveCursor saves current cursor position.
+ SaveCursor()
+ // UnSaveCursor restores cursor position after a Save Cursor.
+ UnSaveCursor()
+
+ /* Scrolling */
+
+ // ScrollDown scrolls display down one line.
+ ScrollDown()
+ // ScrollUp scroll display up one line.
+ ScrollUp()
+
+ /* Title */
+
+ // SetTitle sets a title of terminal window.
+ SetTitle(title string)
+ // ClearTitle clears a title of terminal window.
+ ClearTitle()
+
+ /* Font */
+
+ // SetColor sets text and background colors. and specify whether text is bold.
+ SetColor(fg, bg Color, bold bool)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/output_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/output_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..26c770cc152a7b126be43915d60b8ba000ad0e38
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/output_posix.go
@@ -0,0 +1,67 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+)
+
+const flushMaxRetryCount = 3
+
+// PosixWriter is a ConsoleWriter implementation for POSIX environment.
+// To control terminal emulator, this outputs VT100 escape sequences.
+type PosixWriter struct {
+ VT100Writer
+ fd int
+}
+
+// Flush to flush buffer
+func (w *PosixWriter) Flush() error {
+ l := len(w.buffer)
+ offset := 0
+ retry := 0
+ for {
+ n, err := syscall.Write(w.fd, w.buffer[offset:])
+ if err != nil {
+ if retry < flushMaxRetryCount {
+ retry++
+ continue
+ }
+ return err
+ }
+ offset += n
+ if offset == l {
+ break
+ }
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &PosixWriter{}
+
+var (
+ // NewStandardOutputWriter returns ConsoleWriter object to write to stdout.
+ // This generates VT100 escape sequences because almost terminal emulators
+ // in POSIX OS built on top of a VT100 specification.
+ // Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStdoutWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stdout,
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStderrWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stderr,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/output_vt100.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/output_vt100.go
new file mode 100644
index 0000000000000000000000000000000000000000..20850fead883c4cd9802928b5de3f935fbbeb047
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/output_vt100.go
@@ -0,0 +1,310 @@
+package prompt
+
+import (
+ "bytes"
+ "strconv"
+)
+
+// VT100Writer generates VT100 escape sequences.
+type VT100Writer struct {
+ buffer []byte
+}
+
+// WriteRaw to write raw byte array
+func (w *VT100Writer) WriteRaw(data []byte) {
+ w.buffer = append(w.buffer, data...)
+}
+
+// Write to write safety byte array by removing control sequences.
+func (w *VT100Writer) Write(data []byte) {
+ w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1))
+}
+
+// WriteRawStr to write raw string
+func (w *VT100Writer) WriteRawStr(data string) {
+ w.WriteRaw([]byte(data))
+}
+
+// WriteStr to write safety string by removing control sequences.
+func (w *VT100Writer) WriteStr(data string) {
+ w.Write([]byte(data))
+}
+
+/* Erase */
+
+// EraseScreen erases the screen with the background colour and moves the cursor to home.
+func (w *VT100Writer) EraseScreen() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'J'})
+}
+
+// EraseUp erases the screen from the current line up to the top of the screen.
+func (w *VT100Writer) EraseUp() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'J'})
+}
+
+// EraseDown erases the screen from the current line down to the bottom of the screen.
+func (w *VT100Writer) EraseDown() {
+ w.WriteRaw([]byte{0x1b, '[', 'J'})
+}
+
+// EraseStartOfLine erases from the current cursor position to the start of the current line.
+func (w *VT100Writer) EraseStartOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'K'})
+}
+
+// EraseEndOfLine erases from the current cursor position to the end of the current line.
+func (w *VT100Writer) EraseEndOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', 'K'})
+}
+
+// EraseLine erases the entire current line.
+func (w *VT100Writer) EraseLine() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'K'})
+}
+
+/* Cursor */
+
+// ShowCursor stops blinking cursor and show.
+func (w *VT100Writer) ShowCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'})
+}
+
+// HideCursor hides cursor.
+func (w *VT100Writer) HideCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'})
+}
+
+// CursorGoTo sets the cursor position where subsequent text will begin.
+func (w *VT100Writer) CursorGoTo(row, col int) {
+ if row == 0 && col == 0 {
+ // If no row/column parameters are provided (ie. [H), the cursor will move to the home position.
+ w.WriteRaw([]byte{0x1b, '[', 'H'})
+ return
+ }
+ r := strconv.Itoa(row)
+ c := strconv.Itoa(col)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(r))
+ w.WriteRaw([]byte{';'})
+ w.WriteRaw([]byte(c))
+ w.WriteRaw([]byte{'H'})
+}
+
+// CursorUp moves the cursor up by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorUp(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorDown(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'A'})
+}
+
+// CursorDown moves the cursor down by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorDown(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorUp(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'B'})
+}
+
+// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorForward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorBackward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'C'})
+}
+
+// CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorBackward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorForward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'D'})
+}
+
+// AskForCPR asks for a cursor position report (CPR).
+func (w *VT100Writer) AskForCPR() {
+ // CPR: Cursor Position Request.
+ w.WriteRaw([]byte{0x1b, '[', '6', 'n'})
+}
+
+// SaveCursor saves current cursor position.
+func (w *VT100Writer) SaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 's'})
+}
+
+// UnSaveCursor restores cursor position after a Save Cursor.
+func (w *VT100Writer) UnSaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 'u'})
+}
+
+/* Scrolling */
+
+// ScrollDown scrolls display down one line.
+func (w *VT100Writer) ScrollDown() {
+ w.WriteRaw([]byte{0x1b, 'D'})
+}
+
+// ScrollUp scroll display up one line.
+func (w *VT100Writer) ScrollUp() {
+ w.WriteRaw([]byte{0x1b, 'M'})
+}
+
+/* Title */
+
+// SetTitle sets a title of terminal window.
+func (w *VT100Writer) SetTitle(title string) {
+ titleBytes := []byte(title)
+ patterns := []struct {
+ from []byte
+ to []byte
+ }{
+ {
+ from: []byte{0x13},
+ to: []byte{},
+ },
+ {
+ from: []byte{0x07},
+ to: []byte{},
+ },
+ }
+ for i := range patterns {
+ titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1)
+ }
+
+ w.WriteRaw([]byte{0x1b, ']', '2', ';'})
+ w.WriteRaw(titleBytes)
+ w.WriteRaw([]byte{0x07})
+}
+
+// ClearTitle clears a title of terminal window.
+func (w *VT100Writer) ClearTitle() {
+ w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07})
+}
+
+/* Font */
+
+// SetColor sets text and background colors. and specify whether text is bold.
+func (w *VT100Writer) SetColor(fg, bg Color, bold bool) {
+ if bold {
+ w.SetDisplayAttributes(fg, bg, DisplayBold)
+ } else {
+ // If using `DisplayDefualt`, it will be broken in some environment.
+ // Details are https://github.com/c-bata/go-prompt/pull/85
+ w.SetDisplayAttributes(fg, bg, DisplayReset)
+ }
+}
+
+// SetDisplayAttributes to set VT100 display attributes.
+func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) {
+ w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer
+ defer w.WriteRaw([]byte{'m'}) // final character
+
+ var separator byte = ';'
+ for i := range attrs {
+ p, ok := displayAttributeParameters[attrs[i]]
+ if !ok {
+ continue
+ }
+ w.WriteRaw(p)
+ w.WriteRaw([]byte{separator})
+ }
+
+ f, ok := foregroundANSIColors[fg]
+ if !ok {
+ f = foregroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(f)
+ w.WriteRaw([]byte{separator})
+ b, ok := backgroundANSIColors[bg]
+ if !ok {
+ b = backgroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(b)
+}
+
+var displayAttributeParameters = map[DisplayAttribute][]byte{
+ DisplayReset: {'0'},
+ DisplayBold: {'1'},
+ DisplayLowIntensity: {'2'},
+ DisplayItalic: {'3'},
+ DisplayUnderline: {'4'},
+ DisplayBlink: {'5'},
+ DisplayRapidBlink: {'6'},
+ DisplayReverse: {'7'},
+ DisplayInvisible: {'8'},
+ DisplayCrossedOut: {'9'},
+ DisplayDefaultFont: {'1', '0'},
+}
+
+var foregroundANSIColors = map[Color][]byte{
+ DefaultColor: {'3', '9'},
+
+ // Low intensity.
+ Black: {'3', '0'},
+ DarkRed: {'3', '1'},
+ DarkGreen: {'3', '2'},
+ Brown: {'3', '3'},
+ DarkBlue: {'3', '4'},
+ Purple: {'3', '5'},
+ Cyan: {'3', '6'},
+ LightGray: {'3', '7'},
+
+ // High intensity.
+ DarkGray: {'9', '0'},
+ Red: {'9', '1'},
+ Green: {'9', '2'},
+ Yellow: {'9', '3'},
+ Blue: {'9', '4'},
+ Fuchsia: {'9', '5'},
+ Turquoise: {'9', '6'},
+ White: {'9', '7'},
+}
+
+var backgroundANSIColors = map[Color][]byte{
+ DefaultColor: {'4', '9'},
+
+ // Low intensity.
+ Black: {'4', '0'},
+ DarkRed: {'4', '1'},
+ DarkGreen: {'4', '2'},
+ Brown: {'4', '3'},
+ DarkBlue: {'4', '4'},
+ Purple: {'4', '5'},
+ Cyan: {'4', '6'},
+ LightGray: {'4', '7'},
+
+ // High intensity
+ DarkGray: {'1', '0', '0'},
+ Red: {'1', '0', '1'},
+ Green: {'1', '0', '2'},
+ Yellow: {'1', '0', '3'},
+ Blue: {'1', '0', '4'},
+ Fuchsia: {'1', '0', '5'},
+ Turquoise: {'1', '0', '6'},
+ White: {'1', '0', '7'},
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/output_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/output_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b9c2769fc2d64cfcfcc5b99c915591ec625bd5f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/output_windows.go
@@ -0,0 +1,49 @@
+// +build windows
+
+package prompt
+
+import (
+ "io"
+
+ colorable "github.com/mattn/go-colorable"
+)
+
+// WindowsWriter is a ConsoleWriter implementation for Win32 console.
+// Output is converted from VT100 escape sequences by mattn/go-colorable.
+type WindowsWriter struct {
+ VT100Writer
+ out io.Writer
+}
+
+// Flush to flush buffer
+func (w *WindowsWriter) Flush() error {
+ _, err := w.out.Write(w.buffer)
+ if err != nil {
+ return err
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &WindowsWriter{}
+
+var (
+ // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates win32 control sequences.
+func NewStdoutWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStdout(),
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates win32 control sequences.
+func NewStderrWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStderr(),
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/prompt.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/prompt.go
new file mode 100644
index 0000000000000000000000000000000000000000..173cd517c40cde212433e399978641ceff1d1a43
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/prompt.go
@@ -0,0 +1,296 @@
+package prompt
+
+import (
+ "bytes"
+ "os"
+ "time"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Executor is called when user input something text.
+type Executor func(string)
+
+// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
+// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
+// - immediate exit (if breakline is false) without executor called
+// - exit after typing (meaning breakline is true), and the executor is called first, before exit.
+// Exit means exit go-prompt (not the overall Go program)
+type ExitChecker func(in string, breakline bool) bool
+
+// Completer should return the suggest item from Document.
+type Completer func(Document) []Suggest
+
+// Prompt is core struct of go-prompt.
+type Prompt struct {
+ in ConsoleParser
+ buf *Buffer
+ renderer *Render
+ executor Executor
+ history *History
+ completion *CompletionManager
+ keyBindings []KeyBind
+ ASCIICodeBindings []ASCIICodeBind
+ keyBindMode KeyBindMode
+ completionOnDown bool
+ exitChecker ExitChecker
+ skipTearDown bool
+}
+
+// Exec is the struct contains user input context.
+type Exec struct {
+ input string
+}
+
+// Run starts prompt.
+func (p *Prompt) Run() {
+ p.skipTearDown = false
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ exitCh := make(chan int)
+ winSizeCh := make(chan *WinSize)
+ stopHandleSignalCh := make(chan struct{})
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+ return
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+
+ // Unset raw mode
+ // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
+ debug.AssertNoError(p.in.TearDown())
+ p.executor(e.input)
+
+ p.completion.Update(*p.buf.Document())
+
+ p.renderer.Render(p.buf, p.completion)
+
+ if p.exitChecker != nil && p.exitChecker(e.input, true) {
+ p.skipTearDown = true
+ return
+ }
+ // Set raw mode
+ debug.AssertNoError(p.in.Setup())
+ go p.readBuffer(bufCh, stopReadBufCh)
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ case w := <-winSizeCh:
+ p.renderer.UpdateWinSize(w)
+ p.renderer.Render(p.buf, p.completion)
+ case code := <-exitCh:
+ p.renderer.BreakLine(p.buf)
+ p.tearDown()
+ os.Exit(code)
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
+ key := GetKey(b)
+ p.buf.lastKeyStroke = key
+ // completion
+ completing := p.completion.Completing()
+ p.handleCompletionKeyBinding(key, completing)
+
+ switch key {
+ case Enter, ControlJ, ControlM:
+ p.renderer.BreakLine(p.buf)
+
+ exec = &Exec{input: p.buf.Text()}
+ p.buf = NewBuffer()
+ if exec.input != "" {
+ p.history.Add(exec.input)
+ }
+ case ControlC:
+ p.renderer.BreakLine(p.buf)
+ p.buf = NewBuffer()
+ p.history.Clear()
+ case Up, ControlP:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Older(p.buf); changed {
+ p.buf = newBuf
+ }
+ }
+ case Down, ControlN:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Newer(p.buf); changed {
+ p.buf = newBuf
+ }
+ return
+ }
+ case ControlD:
+ if p.buf.Text() == "" {
+ shouldExit = true
+ return
+ }
+ case NotDefined:
+ if p.handleASCIICodeBinding(b) {
+ return
+ }
+ p.buf.InsertText(string(b), false, true)
+ }
+
+ shouldExit = p.handleKeyBinding(key)
+ return
+}
+
+func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
+ switch key {
+ case Down:
+ if completing || p.completionOnDown {
+ p.completion.Next()
+ }
+ case Tab, ControlI:
+ p.completion.Next()
+ case Up:
+ if completing {
+ p.completion.Previous()
+ }
+ case BackTab:
+ p.completion.Previous()
+ default:
+ if s, ok := p.completion.GetSelectedSuggestion(); ok {
+ w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
+ if w != "" {
+ p.buf.DeleteBeforeCursor(len([]rune(w)))
+ }
+ p.buf.InsertText(s.Text, false, true)
+ }
+ p.completion.Reset()
+ }
+}
+
+func (p *Prompt) handleKeyBinding(key Key) bool {
+ shouldExit := false
+ for i := range commonKeyBindings {
+ kb := commonKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+
+ if p.keyBindMode == EmacsKeyBind {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ }
+
+ // Custom key bindings
+ for i := range p.keyBindings {
+ kb := p.keyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
+ shouldExit = true
+ }
+ return shouldExit
+}
+
+func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
+ checked := false
+ for _, kb := range p.ASCIICodeBindings {
+ if bytes.Equal(kb.ASCIICode, b) {
+ kb.Fn(p.buf)
+ checked = true
+ }
+ }
+ return checked
+}
+
+// Input just returns user input text.
+func (p *Prompt) Input() string {
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ return ""
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ return e.input
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
+ debug.Log("start reading buffer")
+ for {
+ select {
+ case <-stopCh:
+ debug.Log("stop reading buffer")
+ return
+ default:
+ if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
+ bufCh <- b
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (p *Prompt) setUp() {
+ debug.AssertNoError(p.in.Setup())
+ p.renderer.Setup()
+ p.renderer.UpdateWinSize(p.in.GetWinSize())
+}
+
+func (p *Prompt) tearDown() {
+ if !p.skipTearDown {
+ debug.AssertNoError(p.in.TearDown())
+ }
+ p.renderer.TearDown()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/render.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/render.go
new file mode 100644
index 0000000000000000000000000000000000000000..299ac48b6254b9752ea16516aaedcd41acca6515
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/render.go
@@ -0,0 +1,287 @@
+package prompt
+
+import (
+ "runtime"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Render to render prompt information from state of Buffer.
+type Render struct {
+ out ConsoleWriter
+ prefix string
+ livePrefixCallback func() (prefix string, useLivePrefix bool)
+ breakLineCallback func(*Document)
+ title string
+ row uint16
+ col uint16
+
+ previousCursor int
+
+ // colors,
+ prefixTextColor Color
+ prefixBGColor Color
+ inputTextColor Color
+ inputBGColor Color
+ previewSuggestionTextColor Color
+ previewSuggestionBGColor Color
+ suggestionTextColor Color
+ suggestionBGColor Color
+ selectedSuggestionTextColor Color
+ selectedSuggestionBGColor Color
+ descriptionTextColor Color
+ descriptionBGColor Color
+ selectedDescriptionTextColor Color
+ selectedDescriptionBGColor Color
+ scrollbarThumbColor Color
+ scrollbarBGColor Color
+}
+
+// Setup to initialize console output.
+func (r *Render) Setup() {
+ if r.title != "" {
+ r.out.SetTitle(r.title)
+ debug.AssertNoError(r.out.Flush())
+ }
+}
+
+// getCurrentPrefix to get current prefix.
+// If live-prefix is enabled, return live-prefix.
+func (r *Render) getCurrentPrefix() string {
+ if prefix, ok := r.livePrefixCallback(); ok {
+ return prefix
+ }
+ return r.prefix
+}
+
+func (r *Render) renderPrefix() {
+ r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
+ r.out.WriteStr(r.getCurrentPrefix())
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// TearDown to clear title and erasing.
+func (r *Render) TearDown() {
+ r.out.ClearTitle()
+ r.out.EraseDown()
+ debug.AssertNoError(r.out.Flush())
+}
+
+func (r *Render) prepareArea(lines int) {
+ for i := 0; i < lines; i++ {
+ r.out.ScrollDown()
+ }
+ for i := 0; i < lines; i++ {
+ r.out.ScrollUp()
+ }
+}
+
+// UpdateWinSize called when window size is changed.
+func (r *Render) UpdateWinSize(ws *WinSize) {
+ r.row = ws.Row
+ r.col = ws.Col
+}
+
+func (r *Render) renderWindowTooSmall() {
+ r.out.CursorGoTo(0, 0)
+ r.out.EraseScreen()
+ r.out.SetColor(DarkRed, White, false)
+ r.out.WriteStr("Your console window is too small...")
+}
+
+func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) {
+ suggestions := completions.GetSuggestions()
+ if len(completions.GetSuggestions()) == 0 {
+ return
+ }
+ prefix := r.getCurrentPrefix()
+ formatted, width := formatSuggestions(
+ suggestions,
+ int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar
+ )
+ // +1 means a width of scrollbar.
+ width++
+
+ windowHeight := len(formatted)
+ if windowHeight > int(completions.max) {
+ windowHeight = int(completions.max)
+ }
+ formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
+ r.prepareArea(windowHeight)
+
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor())
+ x, _ := r.toPos(cursor)
+ if x+width >= int(r.col) {
+ cursor = r.backward(cursor, x+width-int(r.col))
+ }
+
+ contentHeight := len(completions.tmp)
+
+ fractionVisible := float64(windowHeight) / float64(contentHeight)
+ fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
+
+ scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
+ scrollbarTop := int(float64(windowHeight) * fractionAbove)
+
+ isScrollThumb := func(row int) bool {
+ return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
+ }
+
+ selected := completions.selected - completions.verticalScroll
+ r.out.SetColor(White, Cyan, false)
+ for i := 0; i < windowHeight; i++ {
+ r.out.CursorDown(1)
+ if i == selected {
+ r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
+ } else {
+ r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Text)
+
+ if i == selected {
+ r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
+ } else {
+ r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Description)
+
+ if isScrollThumb(i) {
+ r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
+ } else {
+ r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
+ }
+ r.out.WriteStr(" ")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+
+ r.lineWrap(cursor + width)
+ r.backward(cursor+width, width)
+ }
+
+ if x+width >= int(r.col) {
+ r.out.CursorForward(x + width - int(r.col))
+ }
+
+ r.out.CursorUp(windowHeight)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// Render renders to the console.
+func (r *Render) Render(buffer *Buffer, completion *CompletionManager) {
+ // In situations where a pseudo tty is allocated (e.g. within a docker container),
+ // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
+ if r.col == 0 {
+ return
+ }
+ defer func() { debug.AssertNoError(r.out.Flush()) }()
+ r.move(r.previousCursor, 0)
+
+ line := buffer.Text()
+ prefix := r.getCurrentPrefix()
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line)
+
+ // prepare area
+ _, y := r.toPos(cursor)
+
+ h := y + 1 + int(completion.max)
+ if h > int(r.row) || completionMargin > int(r.col) {
+ r.renderWindowTooSmall()
+ return
+ }
+
+ // Rendering
+ r.out.HideCursor()
+ defer r.out.ShowCursor()
+
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(line)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ r.lineWrap(cursor)
+
+ r.out.EraseDown()
+
+ cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition())
+
+ r.renderCompletion(buffer, completion)
+ if suggest, ok := completion.GetSelectedSuggestion(); ok {
+ cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator)))
+
+ r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false)
+ r.out.WriteStr(suggest.Text)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ cursor += runewidth.StringWidth(suggest.Text)
+
+ rest := buffer.Document().TextAfterCursor()
+ r.out.WriteStr(rest)
+ cursor += runewidth.StringWidth(rest)
+ r.lineWrap(cursor)
+
+ cursor = r.backward(cursor, runewidth.StringWidth(rest))
+ }
+ r.previousCursor = cursor
+}
+
+// BreakLine to break line.
+func (r *Render) BreakLine(buffer *Buffer) {
+ // Erasing and Render
+ cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix())
+ r.clear(cursor)
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(buffer.Document().Text + "\n")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ debug.AssertNoError(r.out.Flush())
+ if r.breakLineCallback != nil {
+ r.breakLineCallback(buffer.Document())
+ }
+
+ r.previousCursor = 0
+}
+
+// clear erases the screen from a beginning of input
+// even if there is line break which means input length exceeds a window's width.
+func (r *Render) clear(cursor int) {
+ r.move(cursor, 0)
+ r.out.EraseDown()
+}
+
+// backward moves cursor to backward from a current cursor position
+// regardless there is a line break.
+func (r *Render) backward(from, n int) int {
+ return r.move(from, from-n)
+}
+
+// move moves cursor to specified position from the beginning of input
+// even if there is a line break.
+func (r *Render) move(from, to int) int {
+ fromX, fromY := r.toPos(from)
+ toX, toY := r.toPos(to)
+
+ r.out.CursorUp(fromY - toY)
+ r.out.CursorBackward(fromX - toX)
+ return to
+}
+
+// toPos returns the relative position from the beginning of the string.
+func (r *Render) toPos(cursor int) (x, y int) {
+ col := int(r.col)
+ return cursor % col, cursor / col
+}
+
+func (r *Render) lineWrap(cursor int) {
+ if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 {
+ r.out.WriteRaw([]byte{'\n'})
+ }
+}
+
+func clamp(high, low, x float64) float64 {
+ switch {
+ case high < x:
+ return high
+ case x < low:
+ return low
+ default:
+ return x
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/shortcut.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/shortcut.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8d4282700c0bdb30e4decfb9c9ac91f27af251
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/shortcut.go
@@ -0,0 +1,43 @@
+package prompt
+
+func dummyExecutor(in string) {}
+
+// Input get the input data from the user and return it.
+func Input(prefix string, completer Completer, opts ...Option) string {
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+// Choose to the shortcut of input function to select from string array.
+// Deprecated: Maybe anyone want to use this.
+func Choose(prefix string, choices []string, opts ...Option) string {
+ completer := newChoiceCompleter(choices, FilterHasPrefix)
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+func newChoiceCompleter(choices []string, filter Filter) Completer {
+ s := make([]Suggest, len(choices))
+ for i := range choices {
+ s[i] = Suggest{Text: choices[i]}
+ }
+ return func(x Document) []Suggest {
+ return filter(s, x.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/signal_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/signal_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3150df5d85e7612c42c2a889dbefee3b524bef6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/signal_posix.go
@@ -0,0 +1,49 @@
+// +build !windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ in := p.in
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+
+ case syscall.SIGWINCH:
+ debug.Log("Catch SIGWINCH")
+ winSizeCh <- in.GetWinSize()
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/signal_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/signal_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a427c79ec0414540f8f40694731b2565ea80c13
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/environment/source/signal_windows.go
@@ -0,0 +1,44 @@
+// +build windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/instruction.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..4aea801ea1be3ddc445659ee6fb7441c26daa60e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/instruction.md
@@ -0,0 +1,43 @@
+GetWordAfterCursor returns incorrect substring when cursor is at word boundary
+
+#### Description
+
+The `GetWordAfterCursor()` method is returning incorrect substrings when the cursor is positioned at the beginning of a word. Instead of returning the complete word after the cursor, it's skipping the first character.
+
+#### Steps/Code to Reproduce
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func main() {
+ // Test case 1: cursor at beginning of "banana"
+ doc := prompt.NewDocument("banana", 0)
+ result := doc.GetWordAfterCursor()
+ fmt.Printf("Expected: 'banana', Got: '%s'\n", result)
+
+ // Test case 2: cursor at beginning of "apple"
+ doc2 := prompt.NewDocument("apple", 0)
+ result2 := doc2.GetWordAfterCursor()
+ fmt.Printf("Expected: 'apple', Got: '%s'\n", result2)
+}
+```
+
+Expected output:
+```
+Expected: 'banana', Got: 'banana'
+Expected: 'apple', Got: 'apple'
+```
+
+Actual output:
+```
+Expected: 'banana', Got: 'anana'
+Expected: 'apple', Got: 'pple'
+```
+
+The issue also affects multi-byte characters where the method returns corrupted strings instead of the expected complete words.
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/provenance.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..eac96dc0be5103aaabecf9df05b43bc64abd42b6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/provenance.json
@@ -0,0 +1,477 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt",
+ "original-bug": "task-specific unchanged semantic bug",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only",
+ "extra_semantic_repair_coverage": false,
+ "original_patch_hunks": 1
+ },
+ "private_frozen_files": {
+ "buffer_test.go": {
+ "mode": "0o644",
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098",
+ "size": 4965
+ },
+ "completion_test.go": {
+ "mode": "0o644",
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d",
+ "size": 7010
+ },
+ "document_test.go": {
+ "mode": "0o644",
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284",
+ "size": 28938
+ },
+ "emacs_test.go": {
+ "mode": "0o644",
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095",
+ "size": 741
+ },
+ "filter_test.go": {
+ "mode": "0o644",
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247",
+ "size": 3339
+ },
+ "history_test.go": {
+ "mode": "0o644",
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327",
+ "size": 1319
+ },
+ "input_test.go": {
+ "mode": "0o644",
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922",
+ "size": 533
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": "0o644",
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf",
+ "size": 1075
+ },
+ "internal/strings/strings_test.go": {
+ "mode": "0o644",
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6",
+ "size": 981
+ },
+ "output_vt100_test.go": {
+ "mode": "0o644",
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee",
+ "size": 1349
+ },
+ "render_test.go": {
+ "mode": "0o644",
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb",
+ "size": 2890
+ }
+ },
+ "public_files": {
+ ".github/ISSUE_TEMPLATE/bug_report.md": {
+ "mode": "0o644",
+ "sha256": "89d3492ca8533a3d31e4de49a23828a322f75d2a1ec4236327c4a76c7c51ada6",
+ "size": 684
+ },
+ ".github/ISSUE_TEMPLATE/feature_request.md": {
+ "mode": "0o644",
+ "sha256": "d82e14e6b4d021d0007eeef4f5ca489fc6c8e8e4d7479ee30e74fe82afd3b08f",
+ "size": 206
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "3239b94a1a41c05eff5dc086ef1378cf1e289fad0203420b5cb4c78e3c5c239b",
+ "size": 270
+ },
+ "CHANGELOG.md": {
+ "mode": "0o644",
+ "sha256": "1f88f92d3247e1b52af0f0de7ad1263a59807edb17238c7a0211554f8080e51c",
+ "size": 2895
+ },
+ "LICENSE": {
+ "mode": "0o644",
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "size": 1072
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "9425a0d4c15747863625f647348962a9b0f81a0971a7e0184ee722bf34a60ba2",
+ "size": 1177
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "ce56df51a1a9a5b5c5b056429bbee006a260fb0730af63b1d0fe91755e574cc4",
+ "size": 6185
+ },
+ "_example/README.md": {
+ "mode": "0o644",
+ "sha256": "155951bafd778493bd41ae57dcc0ba6b8eca821fcbe2ffe770960ac2780d3d09",
+ "size": 1102
+ },
+ "_example/build.sh": {
+ "mode": "0o755",
+ "sha256": "de2fb330b665691cd75b990236cd6a5df0058608de0dfc6194da30d4041a1e29",
+ "size": 469
+ },
+ "_example/exec-command/main.go": {
+ "mode": "0o644",
+ "sha256": "0e96493b6e6d446b2e691d4834ff8a55834caa410ead970cb611a63ba84f174a",
+ "size": 429
+ },
+ "_example/http-prompt/api.py": {
+ "mode": "0o644",
+ "sha256": "2c2bca9acb07a84c65a4482c61c9ade253a574477a8e461307568ea1f9a342c8",
+ "size": 335
+ },
+ "_example/http-prompt/main.go": {
+ "mode": "0o644",
+ "sha256": "6994b190c4165068e69ed44eb61698af69a15a7690179ce46e3c1c5d8c211643",
+ "size": 5484
+ },
+ "_example/live-prefix/main.go": {
+ "mode": "0o644",
+ "sha256": "20268f9cb6f3b82a52eddc33cbf8082adaa46092e2063df279499e05e25a228c",
+ "size": 1103
+ },
+ "_example/simple-echo/cjk-cyrillic/main.go": {
+ "mode": "0o644",
+ "sha256": "8fb10807d4085ebc4b345bc0ccfef9217e21e49a888bfe3192e8ddfdfa01e89c",
+ "size": 800
+ },
+ "_example/simple-echo/main.go": {
+ "mode": "0o644",
+ "sha256": "e46563ddaa932831fe9ede870b10efb5222c0d54a86f4b4f5197c9cf20942a24",
+ "size": 902
+ },
+ "_tools/README.md": {
+ "mode": "0o644",
+ "sha256": "96dc2343bc5cde642fd449ddc366462753a2e17b6a78adfa015bf991e9dac241",
+ "size": 234
+ },
+ "_tools/complete_file/main.go": {
+ "mode": "0o644",
+ "sha256": "e5dd823f9d6415614a8238ce106d26e9ded1db9b308c121d7f48bb1df003effc",
+ "size": 803
+ },
+ "_tools/sigwinch/main.go": {
+ "mode": "0o644",
+ "sha256": "a806b4e45298f5003c95432d8dd3c40c9c096335f19f1a4160afcdb64fa727e3",
+ "size": 1386
+ },
+ "_tools/vt100_debug/main.go": {
+ "mode": "0o644",
+ "sha256": "7f72eba3cc7037fcf39c9b56a96c578c157e5fb235cb626ab1e83cbef0dc290b",
+ "size": 794
+ },
+ "buffer.go": {
+ "mode": "0o644",
+ "sha256": "10188d96a450fe13ba1e9ec00c89603eb2a2860536965d980d1e4abf4374b018",
+ "size": 5781
+ },
+ "completer/file.go": {
+ "mode": "0o644",
+ "sha256": "6181ed9e39028236c5c93fbe219331fc1492ecfd6af2df764cc42b5455c9bb96",
+ "size": 2401
+ },
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "b90bd9628534cfb343a592775430e17a1999b1de500fb2a8f1507c030a432eae",
+ "size": 4491
+ },
+ "document.go": {
+ "mode": "0o644",
+ "sha256": "94ab8253cdf3b678582437963c5ff3b4a78d459855bd4563b99a78b2808e92c1",
+ "size": 13196
+ },
+ "emacs.go": {
+ "mode": "0o644",
+ "sha256": "53f0df0016ef9d9695a797b19286681666cf0c7e5a866c393b194aae915f2664",
+ "size": 2675
+ },
+ "filter.go": {
+ "mode": "0o644",
+ "sha256": "dc5922bad6ecb32ecdaf20bd6035dddc7ce8c14f15dbd4d49192c2354cb8a038",
+ "size": 2005
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "97413fa2a2ed68170496f2289a2dca6fb0a192dcd020fc0ca48a5d106e60d55e",
+ "size": 253
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "88ea0a91babaa54b67cc6d5f6f7f47fa4be798fe523324ea568d8926eed2024c",
+ "size": 2183
+ },
+ "history.go": {
+ "mode": "0o644",
+ "sha256": "4ce80ba067cfc72c56a3ee3353ec75cd6bb2f5d82097515c591e3c7c773c51cd",
+ "size": 1488
+ },
+ "input.go": {
+ "mode": "0o644",
+ "sha256": "73461cc4f57d68b66e2a9e196239aaef942539134593beac0d0023743832e0e1",
+ "size": 7630
+ },
+ "input_posix.go": {
+ "mode": "0o644",
+ "sha256": "c7e5a4dfc3910f178f0685ef99f2e47d481a91c4cf9af50f92fc4266aed634df",
+ "size": 1648
+ },
+ "input_windows.go": {
+ "mode": "0o644",
+ "sha256": "f763250d309fb88d9536f77da1d1285c04bc6defe859506f1501e10f7743da9e",
+ "size": 1679
+ },
+ "internal/bisect/bisect.go": {
+ "mode": "0o644",
+ "sha256": "c4de2adfa2e08a77f902661d67325467f89013634dbcef22d24dc6f34d26624a",
+ "size": 327
+ },
+ "internal/debug/assert.go": {
+ "mode": "0o644",
+ "sha256": "1a3050ec58991b62c7ea352d19505e3080ac9760bdb091544f0ecf5aba35969c",
+ "size": 815
+ },
+ "internal/debug/log.go": {
+ "mode": "0o644",
+ "sha256": "2ce968e275558de61c6d83793e85561f7a8dd69c95ec7902ccd2cc3fb169aa82",
+ "size": 875
+ },
+ "internal/strings/strings.go": {
+ "mode": "0o644",
+ "sha256": "b97f08157c3baf1f94fea4bb2237691d8270bd5380b4311709ecd59b84cf4b7b",
+ "size": 2018
+ },
+ "internal/term/raw.go": {
+ "mode": "0o644",
+ "sha256": "177a1a20ae8d71b56857383a5797754560f7f6404ea86778d5f01e9a1c1b4f9f",
+ "size": 747
+ },
+ "internal/term/term.go": {
+ "mode": "0o644",
+ "sha256": "abe6fa965fa15b999b2010135903f598830d4c885a52ef9b067fd5ebbf6e373f",
+ "size": 606
+ },
+ "key.go": {
+ "mode": "0o644",
+ "sha256": "03a43283e07de7a4ea6fed32692d86325f73e98fd89a296f19c171e0bc780999",
+ "size": 1746
+ },
+ "key_bind.go": {
+ "mode": "0o644",
+ "sha256": "83f48bb720a11c8e49165ac382e3a870fdcf6b380a0a95267f8c25211898c9eb",
+ "size": 1109
+ },
+ "key_bind_func.go": {
+ "mode": "0o644",
+ "sha256": "445bff5c0fdb0b52879c635322603c2fc75d265de3761cb8c3b980c798bf39af",
+ "size": 1219
+ },
+ "key_string.go": {
+ "mode": "0o644",
+ "sha256": "55c429dae227bb1659d5d5e2e906dbfa9c7f53b5105fa83fbe290529ff6f2317",
+ "size": 1359
+ },
+ "option.go": {
+ "mode": "0o644",
+ "sha256": "28cfcc1d08b3cf650483d977195458531b3b3913f8a5f357a3ec17ea5d73e215",
+ "size": 8737
+ },
+ "output.go": {
+ "mode": "0o644",
+ "sha256": "372876b0aa908479ed3b29de70a479f420d85e3666b8957c8b61eaed9b32c3f2",
+ "size": 4320
+ },
+ "output_posix.go": {
+ "mode": "0o644",
+ "sha256": "d46b1da307e8969b033e1ade2eb51a83c4c3d4f2a7e4aba35ec3a03991b89a0f",
+ "size": 1545
+ },
+ "output_vt100.go": {
+ "mode": "0o644",
+ "sha256": "9082c7e4619c1eb38030bc4994a4fbf66ef27b130751bf2eb9c25c01082e8605",
+ "size": 7453
+ },
+ "output_windows.go": {
+ "mode": "0o644",
+ "sha256": "571c5ae1ad051a701b426371efd79a3776c2226ca9e3c2e598fe5996dfa1b8e1",
+ "size": 1066
+ },
+ "prompt.go": {
+ "mode": "0o644",
+ "sha256": "6b3e2bbd90f40ad6a487f1a6ea7f5a6fb48cae6c8c246ecc77621fb3e7383ca7",
+ "size": 7062
+ },
+ "render.go": {
+ "mode": "0o644",
+ "sha256": "90fdd57a63e06f01940d10ee1a0be95ced7d6adc7faa255b3141556d7d316270",
+ "size": 8020
+ },
+ "shortcut.go": {
+ "mode": "0o644",
+ "sha256": "b4a097f466df7396049ebe8393f81c9b1200159d4e2be22bd6838c307ec156dc",
+ "size": 1120
+ },
+ "signal_posix.go": {
+ "mode": "0o644",
+ "sha256": "74f0bae5f290f3f7f82a5dd495e672f627a4ab4b63118f870e8c13c0a7024314",
+ "size": 881
+ },
+ "signal_windows.go": {
+ "mode": "0o644",
+ "sha256": "444f662a32e6997df2af8e2a9e7dbfe977414a6bfc0f54a7f10117f204648437",
+ "size": 757
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982",
+ "os": "linux",
+ "sha256": "0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982"
+ },
+ "context_inventory_sha256": "6b8f93086e81483ac1ce82f328d7f4b38b1b560dbad057ed6a2a30ff3cf0e13f",
+ "image": "registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "9d3b21cdacadfa4f3de9584d0cea973e5aa2ceedcd5ec9cbd3a63df22b313455",
+ "receipt_path": "production/runtime-images-extra-v1/resolutions/316e0e68930cd4ef/resolution.json",
+ "receipt_sha256": "697bb0619eddcdfdeba1c9144b033f564f2d7514be6e6a44dc520fa4e63ed8bc",
+ "registry_digest": "sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "source_image": "docker.io/swebench/swesmith.x86_64.c-bata_1776_go-prompt.82a91227@sha256:3daf51c74a01657e9ad8f326651fb6f5b796ffecdb90098e74a52a9560e0a1bb",
+ "source_receipt_sha256": "b450bea0e201cbe194b765ded4b51539144c85296122c8b642d7e94c889526f3",
+ "space_commit": "5ae654cd2e9d695f0de304bd4398835fc7cf45e0",
+ "space_id": "harness-hub/scale800-go-316e0e68930cd4ef-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "f8390af0dd5f3790cfb9b635a201b73282fdfe2d1cb4738d583c868cd7cfc3af",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21",
+ "source_proof_sha256": "118971255afab8f14f45105c0ee6bbb74691b6db6b2bc51e29bfbeeaf67174eb",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:c-bata__go-prompt.82a91227.lm_modify__9294kk0o",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "9992c59c25864ce1556e67b9e1501c93f6e7f9ff",
+ "instruction_sha256": "5c3a092e0ed96569d42ea028a463bb7ffac43abc3f9f758fbd1cf9befec0d2c6",
+ "is_fork": true,
+ "learner_path": "tasks/146c92696ac644fe1c053adf/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/c-bata__go-prompt.82a91227/11de764de0c648525b9dfbd9d899c5cd085c4f3c/LICENSE"
+ },
+ "task_bundle": {
+ "basis": "Captured publisherMIT/train; exactsoftwarepermissionverifiedseparately",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "82a912274504477990ecf7c852eebb7c85291772",
+ "patch_sha256": "3e439a648e74dee06704ff27a8bb3e7b7fa9ae2485e680b96abacdbc31ac0e2c",
+ "provenance_path": "tasks/146c92696ac644fe1c053adf/source-proof.json",
+ "repository_lineage": [
+ "swesmith/c-bata__go-prompt.82a91227",
+ "c-bata/go-prompt"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "11de764de0c648525b9dfbd9d899c5cd085c4f3c",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "fe81877dc306c1258ae7b10a98d9295ce372de76",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/c-bata__go-prompt.82a91227",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "c-bata__go-prompt.82a91227.lm_modify__9294kk0o",
+ "task_sha256": "50f2d7d8b7c2d3d4077d3f98a30c12eb148917561d76a2cef8107fa83e855490",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "c-bata/go-prompt",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "8c2bfd95ed103e5328977c6eea338c4bb96887993d8f76770e6d20f1da2dfa62",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.md",
+ "/testbed/.github/ISSUE_TEMPLATE/feature_request.md",
+ "/testbed/.gitignore",
+ "/testbed/CHANGELOG.md",
+ "/testbed/LICENSE",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/_example/README.md",
+ "/testbed/_example/build.sh",
+ "/testbed/_example/exec-command/main.go",
+ "/testbed/_example/http-prompt/api.py",
+ "/testbed/_example/http-prompt/main.go",
+ "/testbed/_example/live-prefix/main.go",
+ "/testbed/_example/simple-echo/cjk-cyrillic/main.go",
+ "/testbed/_example/simple-echo/main.go",
+ "/testbed/_tools/README.md",
+ "/testbed/_tools/complete_file/main.go",
+ "/testbed/_tools/sigwinch/main.go",
+ "/testbed/_tools/vt100_debug/main.go",
+ "/testbed/buffer.go",
+ "/testbed/completer/file.go",
+ "/testbed/completion.go",
+ "/testbed/document.go",
+ "/testbed/emacs.go",
+ "/testbed/filter.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum",
+ "/testbed/history.go",
+ "/testbed/input.go",
+ "/testbed/input_posix.go",
+ "/testbed/input_windows.go",
+ "/testbed/internal/bisect/bisect.go",
+ "/testbed/internal/debug/assert.go",
+ "/testbed/internal/debug/log.go",
+ "/testbed/internal/strings/strings.go",
+ "/testbed/internal/term/raw.go",
+ "/testbed/internal/term/term.go",
+ "/testbed/key.go",
+ "/testbed/key_bind.go",
+ "/testbed/key_bind_func.go",
+ "/testbed/key_string.go",
+ "/testbed/option.go",
+ "/testbed/output.go",
+ "/testbed/output_posix.go",
+ "/testbed/output_vt100.go",
+ "/testbed/output_windows.go",
+ "/testbed/prompt.go",
+ "/testbed/render.go",
+ "/testbed/shortcut.go",
+ "/testbed/signal_posix.go",
+ "/testbed/signal_windows.go"
+ ]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/solution/solve.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..00d1a533519e8abc9def758862da6b859247bfe5
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"document.go": {"data": "cGFja2FnZSBwcm9tcHQKCmltcG9ydCAoCgkic3RyaW5ncyIKCSJ1bmljb2RlL3V0ZjgiCgoJImdpdGh1Yi5jb20vYy1iYXRhL2dvLXByb21wdC9pbnRlcm5hbC9iaXNlY3QiCglpc3RyaW5ncyAiZ2l0aHViLmNvbS9jLWJhdGEvZ28tcHJvbXB0L2ludGVybmFsL3N0cmluZ3MiCglydW5ld2lkdGggImdpdGh1Yi5jb20vbWF0dG4vZ28tcnVuZXdpZHRoIgopCgovLyBEb2N1bWVudCBoYXMgdGV4dCBkaXNwbGF5ZWQgaW4gdGVybWluYWwgYW5kIGN1cnNvciBwb3NpdGlvbi4KdHlwZSBEb2N1bWVudCBzdHJ1Y3QgewoJVGV4dCBzdHJpbmcKCS8vIFRoaXMgcmVwcmVzZW50cyBhIGluZGV4IGluIGEgcnVuZSBhcnJheSBvZiBEb2N1bWVudC5UZXh0LgoJLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgY3Vyc29yUG9zaXRpb24gaXMgMi4KCS8vIEJ1dCBEaXNwbGF5ZWRDdXJzb3JQb3NpdGlvbiByZXR1cm5zIDQgYmVjYXVzZSAn5pelJyBhbmQgJ+acrCcgYXJlIGRvdWJsZSB3aWR0aCBjaGFyYWN0ZXJzLgoJY3Vyc29yUG9zaXRpb24gaW50CglsYXN0S2V5ICAgICAgICBLZXkKfQoKLy8gTmV3RG9jdW1lbnQgcmV0dXJuIHRoZSBuZXcgZW1wdHkgZG9jdW1lbnQuCmZ1bmMgTmV3RG9jdW1lbnQoKSAqRG9jdW1lbnQgewoJcmV0dXJuICZEb2N1bWVudHsKCQlUZXh0OiAgICAgICAgICAgIiIsCgkJY3Vyc29yUG9zaXRpb246IDAsCgl9Cn0KCi8vIExhc3RLZXlTdHJva2UgcmV0dXJuIHRoZSBsYXN0IGtleSBwcmVzc2VkIGluIHRoaXMgZG9jdW1lbnQuCmZ1bmMgKGQgKkRvY3VtZW50KSBMYXN0S2V5U3Ryb2tlKCkgS2V5IHsKCXJldHVybiBkLmxhc3RLZXkKfQoKLy8gRGlzcGxheUN1cnNvclBvc2l0aW9uIHJldHVybnMgdGhlIGN1cnNvciBwb3NpdGlvbiBvbiByZW5kZXJlZCB0ZXh0IG9uIHRlcm1pbmFsIGVtdWxhdG9ycy4KLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgRGlzcGxheWVkQ3Vyc29yUG9zaXRpb24gcmV0dXJucyA0IGJlY2F1c2UgJ+aXpScgYW5kICfmnKwnIGFyZSBkb3VibGUgd2lkdGggY2hhcmFjdGVycy4KZnVuYyAoZCAqRG9jdW1lbnQpIERpc3BsYXlDdXJzb3JQb3NpdGlvbigpIGludCB7Cgl2YXIgcG9zaXRpb24gaW50CglydW5lcyA6PSBbXXJ1bmUoZC5UZXh0KVs6ZC5jdXJzb3JQb3NpdGlvbl0KCWZvciBpIDo9IHJhbmdlIHJ1bmVzIHsKCQlwb3NpdGlvbiArPSBydW5ld2lkdGguUnVuZVdpZHRoKHJ1bmVzW2ldKQoJfQoJcmV0dXJuIHBvc2l0aW9uCn0KCi8vIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yIHJldHVybiBjaGFyYWN0ZXIgcmVsYXRpdmUgdG8gY3Vyc29yIHBvc2l0aW9uLCBvciBlbXB0eSBzdHJpbmcKZnVuYyAoZCAqRG9jdW1lbnQpIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yKG9mZnNldCBpbnQpIChyIHJ1bmUpIHsKCXMgOj0gZC5UZXh0CgljbnQgOj0gMAoKCWZvciBsZW4ocykgPiAwIHsKCQljbnQrKwoJCXIsIHNpemUgOj0gdXRmOC5EZWNvZGVSdW5lSW5TdHJpbmcocykKCQlpZiBjbnQgPT0gZC5jdXJzb3JQb3NpdGlvbitvZmZzZXQgewoJCQlyZXR1cm4gcgoJCX0KCQlzID0gc1tzaXplOl0KCX0KCXJldHVybiAwCn0KCi8vIFRleHRCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJciA6PSBbXXJ1bmUoZC5UZXh0KQoJcmV0dXJuIHN0cmluZyhyWzpkLmN1cnNvclBvc2l0aW9uXSkKfQoKLy8gVGV4dEFmdGVyQ3Vyc29yIHJldHVybnMgdGhlIHRleHQgYWZ0ZXIgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRBZnRlckN1cnNvcigpIHN0cmluZyB7CglyIDo9IFtdcnVuZShkLlRleHQpCglyZXR1cm4gc3RyaW5nKHJbZC5jdXJzb3JQb3NpdGlvbjpdKQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYmVmb3JlIHRoZSBjdXJzb3IuCi8vIElmIHdlIGhhdmUgd2hpdGVzcGFjZSBiZWZvcmUgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcigpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBJZiB3ZSBoYXZlIHdoaXRlc3BhY2UgYWZ0ZXIgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yKCkgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmQoKV0KfQoKLy8gR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSgpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEFmdGVyQ3Vyc29yLCBpdCByZXR1cm5zIHN0cmluZyBjb250YWluaW5nIHNwYWNlCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UoKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpXQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yVW50aWxTZXBhcmF0b3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvciB1bnRpbCBuZXh0IHNlcGFyYXRvci4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJcmV0dXJuIHhbZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFVudGlsU2VwYXJhdG9yKHNlcCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvciByZXR1cm5zIHRoZSB0ZXh0IGFmdGVyIHRoZSBjdXJzb3IgdW50aWwgbmV4dCBzZXBhcmF0b3IuCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCldCn0KCi8vIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvciByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yKHNlcCBzdHJpbmcpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwKTpdCn0KCi8vIEdldFdvcmRBZnRlckN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYWZ0ZXIgdGhlIGN1cnNvci4KLy8gVW5saWtlIEdldFdvcmRBZnRlckN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXApXQp9CgovLyBGaW5kU3RhcnRPZlByZXZpb3VzV29yZCByZXR1cm5zIGFuIGluZGV4IHJlbGF0aXZlIHRvIHRoZSBjdXJzb3IgcG9zaXRpb24KLy8gcG9pbnRpbmcgdG8gdGhlIHN0YXJ0IG9mIHRoZSBwcmV2aW91cyB3b3JkLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5MYXN0SW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpICsgMQoJfQoJcmV0dXJuIDAKfQoKLy8gRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRXaXRoU3BhY2UgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBUaGUgb25seSBkaWZmZXJlbmNlIGlzIHRvIGlnbm9yZSBjb250aWd1b3VzIHNwYWNlcy4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWVuZCA6PSBpc3RyaW5ncy5MYXN0SW5kZXhOb3RCeXRlKHgsICcgJykKCWlmIGVuZCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEJ5dGUoeFs6ZW5kXSwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiAwCgl9CglyZXR1cm4gc3RhcnQgKyAxCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZCgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJaSA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaSArIDEKCX0KCXJldHVybiAwCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFdpdGhTcGFjZSgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJZW5kIDo9IGlzdHJpbmdzLkxhc3RJbmRleE5vdEFueSh4LCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiAwCgl9CglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4WzplbmRdLCBzZXApCglpZiBzdGFydCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCXJldHVybiBzdGFydCArIDEKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmQgcmV0dXJucyBhbiBpbmRleCByZWxhdGl2ZSB0byB0aGUgY3Vyc29yIHBvc2l0aW9uLgovLyBwb2ludGluZyB0byB0aGUgZW5kIG9mIHRoZSBjdXJyZW50IHdvcmQuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZEVuZE9mQ3VycmVudFdvcmQoKSBpbnQgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglpIDo9IHN0cmluZ3MuSW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpCgl9CglyZXR1cm4gbGVuKHgpCn0KCi8vIEZpbmRFbmRPZkN1cnJlbnRXb3JkV2l0aFNwYWNlIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZC4KLy8gVGhlIG9ubHkgZGlmZmVyZW5jZSBpcyB0byBpZ25vcmUgY29udGlndW91cyBzcGFjZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpIGludCB7Cgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCglzdGFydCA6PSBpc3RyaW5ncy5JbmRleE5vdEJ5dGUoeCwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCgllbmQgOj0gc3RyaW5ncy5JbmRleEJ5dGUoeFtzdGFydDpdLCAnICcpCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvciBpcyBhbG1vc3QgdGhlIHNhbWUgYXMgRmluZEVuZE9mQ3VycmVudFdvcmQuCi8vIEJ1dCB0aGlzIGNhbiBzcGVjaWZ5IFNlcGFyYXRvci4gUmV0dXJuIDAgaWYgbm90aGluZyB3YXMgZm91bmQuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCBzdHJpbmcpIGludCB7CglpZiBzZXAgPT0gIiIgewoJCXJldHVybiBkLkZpbmRFbmRPZkN1cnJlbnRXb3JkKCkKCX0KCgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5JbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaQoJfQoJcmV0dXJuIGxlbih4KQp9CgovLyBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZS4KLy8gQnV0IHRoaXMgY2FuIHNwZWNpZnkgU2VwYXJhdG9yLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRFbmRPZkN1cnJlbnRXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgaW50IHsKCWlmIHNlcCA9PSAiIiB7CgkJcmV0dXJuIGQuRmluZEVuZE9mQ3VycmVudFdvcmRXaXRoU3BhY2UoKQoJfQoKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoKCXN0YXJ0IDo9IGlzdHJpbmdzLkluZGV4Tm90QW55KHgsIHNlcCkKCWlmIHN0YXJ0ID09IC0xIHsKCQlyZXR1cm4gbGVuKHgpCgl9CgoJZW5kIDo9IHN0cmluZ3MuSW5kZXhBbnkoeFtzdGFydDpdLCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gQ3VycmVudExpbmVCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBzdGFydCBvZiB0aGUgbGluZSB1bnRpbCB0aGUgY3Vyc29yLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJcyA6PSBzdHJpbmdzLlNwbGl0KGQuVGV4dEJlZm9yZUN1cnNvcigpLCAiXG4iKQoJcmV0dXJuIHNbbGVuKHMpLTFdCn0KCi8vIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBjdXJzb3IgdW50aWwgdGhlIGVuZCBvZiB0aGUgbGluZS4KZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSBzdHJpbmcgewoJcmV0dXJuIHN0cmluZ3MuU3BsaXQoZC5UZXh0QWZ0ZXJDdXJzb3IoKSwgIlxuIilbMF0KfQoKLy8gQ3VycmVudExpbmUgcmV0dXJuIHRoZSB0ZXh0IG9uIHRoZSBsaW5lIHdoZXJlIHRoZSBjdXJzb3IgaXMuICh3aGVuIHRoZSBpbnB1dAovLyBjb25zaXN0cyBvZiBqdXN0IG9uZSBsaW5lLCBpdCBlcXVhbHMgYHRleHRgLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmUoKSBzdHJpbmcgewoJcmV0dXJuIGQuQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSArIGQuQ3VycmVudExpbmVBZnRlckN1cnNvcigpCn0KCi8vIEFycmF5IHBvaW50aW5nIHRvIHRoZSBzdGFydCBpbmRleGVzIG9mIGFsbCB0aGUgbGluZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBsaW5lU3RhcnRJbmRleGVzKCkgW11pbnQgewoJLy8gVE9ETzogQ2FjaGUsIGJlY2F1c2UgdGhpcyBpcyBvZnRlbiByZXVzZWQuCgkvLyAoSWYgaXQgaXMgdXNlZCwgaXQncyBvZnRlbiB1c2VkIG1hbnkgdGltZXMuCgkvLyBBbmQgdGhpcyBoYXMgdG8gYmUgZmFzdCBmb3IgZWRpdGluZyBiaWcgZG9jdW1lbnRzISkKCWxjIDo9IGQuTGluZUNvdW50KCkKCWxlbmd0aHMgOj0gbWFrZShbXWludCwgbGMpCglmb3IgaSwgbCA6PSByYW5nZSBkLkxpbmVzKCkgewoJCWxlbmd0aHNbaV0gPSBsZW4obCkKCX0KCgkvLyBDYWxjdWxhdGUgY3VtdWxhdGl2ZSBzdW1zLgoJaW5kZXhlcyA6PSBtYWtlKFtdaW50LCBsYysxKQoJaW5kZXhlc1swXSA9IDAgLy8gaHR0cHM6Ly9naXRodWIuY29tL2pvbmF0aGFuc2xlbmRlcnMvcHl0aG9uLXByb21wdC10b29sa2l0L2Jsb2IvbWFzdGVyL3Byb21wdF90b29sa2l0L2RvY3VtZW50LnB5I0wxODkKCXBvcyA6PSAwCglmb3IgaSwgbCA6PSByYW5nZSBsZW5ndGhzIHsKCQlwb3MgKz0gbCArIDEKCQlpbmRleGVzW2krMV0gPSBwb3MKCX0KCWlmIGxjID4gMSB7CgkJLy8gUG9wIHRoZSBsYXN0IGl0ZW0uIChUaGlzIGlzIG5vdCBhIG5ldyBsaW5lLikKCQlpbmRleGVzID0gaW5kZXhlc1s6bGNdCgl9CglyZXR1cm4gaW5kZXhlcwp9CgovLyBGb3IgdGhlIGluZGV4IG9mIGEgY2hhcmFjdGVyIGF0IGEgY2VydGFpbiBsaW5lLCBjYWxjdWxhdGUgdGhlIGluZGV4IG9mCi8vIHRoZSBmaXJzdCBjaGFyYWN0ZXIgb24gdGhhdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgZmluZExpbmVTdGFydEluZGV4KGluZGV4IGludCkgKHBvcyBpbnQsIGxpbmVTdGFydEluZGV4IGludCkgewoJaW5kZXhlcyA6PSBkLmxpbmVTdGFydEluZGV4ZXMoKQoJcG9zID0gYmlzZWN0LlJpZ2h0KGluZGV4ZXMsIGluZGV4KSAtIDEKCWxpbmVTdGFydEluZGV4ID0gaW5kZXhlc1twb3NdCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Sb3cgcmV0dXJucyB0aGUgY3VycmVudCByb3cuICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uUm93KCkgKHJvdyBpbnQpIHsKCXJvdywgXyA9IGQuZmluZExpbmVTdGFydEluZGV4KGQuY3Vyc29yUG9zaXRpb24pCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Db2wgcmV0dXJucyB0aGUgY3VycmVudCBjb2x1bW4uICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uQ29sKCkgKGNvbCBpbnQpIHsKCS8vIERvbid0IHVzZSBzZWxmLnRleHRfYmVmb3JlX2N1cnNvciB0byBjYWxjdWxhdGUgdGhpcy4gQ3JlYXRpbmcgc3Vic3RyaW5ncwoJLy8gYW5kIHNwbGl0dGluZyBpcyB0b28gZXhwZW5zaXZlIGZvciBnZXR0aW5nIHRoZSBjdXJzb3IgcG9zaXRpb24uCglfLCBpbmRleCA6PSBkLmZpbmRMaW5lU3RhcnRJbmRleChkLmN1cnNvclBvc2l0aW9uKQoJY29sID0gZC5jdXJzb3JQb3NpdGlvbiAtIGluZGV4CglyZXR1cm4KfQoKLy8gR2V0Q3Vyc29yTGVmdFBvc2l0aW9uIHJldHVybnMgdGhlIHJlbGF0aXZlIHBvc2l0aW9uIGZvciBjdXJzb3IgbGVmdC4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldEN1cnNvckxlZnRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvclJpZ2h0UG9zaXRpb24oLWNvdW50KQoJfQoJaWYgZC5DdXJzb3JQb3NpdGlvbkNvbCgpID4gY291bnQgewoJCXJldHVybiAtY291bnQKCX0KCXJldHVybiAtZC5DdXJzb3JQb3NpdGlvbkNvbCgpCn0KCi8vIEdldEN1cnNvclJpZ2h0UG9zaXRpb24gcmV0dXJucyByZWxhdGl2ZSBwb3NpdGlvbiBmb3IgY3Vyc29yIHJpZ2h0LgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yUmlnaHRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvckxlZnRQb3NpdGlvbigtY291bnQpCgl9CglpZiBsZW4oZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpID4gY291bnQgewoJCXJldHVybiBjb3VudAoJfQoJcmV0dXJuIGxlbihkLkN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSkKfQoKLy8gR2V0Q3Vyc29yVXBQb3NpdGlvbiByZXR1cm4gdGhlIHJlbGF0aXZlIGN1cnNvciBwb3NpdGlvbiAoY2hhcmFjdGVyIGluZGV4KSB3aGVyZSB3ZSB3b3VsZCBiZQovLyBpZiB0aGUgdXNlciBwcmVzc2VkIHRoZSBhcnJvdy11cCBidXR0b24uCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRDdXJzb3JVcFBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9CgoJcm93IDo9IGQuQ3Vyc29yUG9zaXRpb25Sb3coKSAtIGNvdW50CglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9CglyZXR1cm4gZC5UcmFuc2xhdGVSb3dDb2xUb0luZGV4KHJvdywgY29sKSAtIGQuY3Vyc29yUG9zaXRpb24KfQoKLy8gR2V0Q3Vyc29yRG93blBvc2l0aW9uIHJldHVybiB0aGUgcmVsYXRpdmUgY3Vyc29yIHBvc2l0aW9uIChjaGFyYWN0ZXIgaW5kZXgpIHdoZXJlIHdlIHdvdWxkIGJlIGlmIHRoZQovLyB1c2VyIHByZXNzZWQgdGhlIGFycm93LWRvd24gYnV0dG9uLgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yRG93blBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9Cglyb3cgOj0gZC5DdXJzb3JQb3NpdGlvblJvdygpICsgY291bnQKCXJldHVybiBkLlRyYW5zbGF0ZVJvd0NvbFRvSW5kZXgocm93LCBjb2wpIC0gZC5jdXJzb3JQb3NpdGlvbgp9CgovLyBMaW5lcyByZXR1cm5zIHRoZSBhcnJheSBvZiBhbGwgdGhlIGxpbmVzLgpmdW5jIChkICpEb2N1bWVudCkgTGluZXMoKSBbXXN0cmluZyB7CgkvLyBUT0RPOiBDYWNoZSwgYmVjYXVzZSB0aGlzIG9uZSBpcyByZXVzZWQgdmVyeSBvZnRlbi4KCXJldHVybiBzdHJpbmdzLlNwbGl0KGQuVGV4dCwgIlxuIikKfQoKLy8gTGluZUNvdW50IHJldHVybiB0aGUgbnVtYmVyIG9mIGxpbmVzIGluIHRoaXMgZG9jdW1lbnQuIElmIHRoZSBkb2N1bWVudCBlbmRzCi8vIHdpdGggYSB0cmFpbGluZyBcbiwgdGhhdCBjb3VudHMgYXMgdGhlIGJlZ2lubmluZyBvZiBhIG5ldyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgTGluZUNvdW50KCkgaW50IHsKCXJldHVybiBsZW4oZC5MaW5lcygpKQp9CgovLyBUcmFuc2xhdGVJbmRleFRvUG9zaXRpb24gZ2l2ZW4gYW4gaW5kZXggZm9yIHRoZSB0ZXh0LCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgKHJvdywgY29sKSB0dXBsZS4KLy8gKDAtYmFzZWQuIFJldHVybnMgKDAsIDApIGZvciBpbmRleD0wLikKZnVuYyAoZCAqRG9jdW1lbnQpIFRyYW5zbGF0ZUluZGV4VG9Qb3NpdGlvbihpbmRleCBpbnQpIChyb3cgaW50LCBjb2wgaW50KSB7Cglyb3csIHJvd0luZGV4IDo9IGQuZmluZExpbmVTdGFydEluZGV4KGluZGV4KQoJY29sID0gaW5kZXggLSByb3dJbmRleAoJcmV0dXJuCn0KCi8vIFRyYW5zbGF0ZVJvd0NvbFRvSW5kZXggZ2l2ZW4gYSAocm93LCBjb2wpLCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgaW5kZXguCi8vIChSb3cgYW5kIGNvbCBwYXJhbXMgYXJlIDAtYmFzZWQuKQpmdW5jIChkICpEb2N1bWVudCkgVHJhbnNsYXRlUm93Q29sVG9JbmRleChyb3cgaW50LCBjb2x1bW4gaW50KSAoaW5kZXggaW50KSB7CglpbmRleGVzIDo9IGQubGluZVN0YXJ0SW5kZXhlcygpCglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9IGVsc2UgaWYgcm93ID4gbGVuKGluZGV4ZXMpIHsKCQlyb3cgPSBsZW4oaW5kZXhlcykgLSAxCgl9CglpbmRleCA9IGluZGV4ZXNbcm93XQoJbGluZSA6PSBkLkxpbmVzKClbcm93XQoKCS8vIHB5dGhvbikgcmVzdWx0ICs9IG1heCgwLCBtaW4oY29sLCBsZW4obGluZSkpKQoJaWYgY29sdW1uID4gMCB8fCBsZW4obGluZSkgPiAwIHsKCQlpZiBjb2x1bW4gPiBsZW4obGluZSkgewoJCQlpbmRleCArPSBsZW4obGluZSkKCQl9IGVsc2UgewoJCQlpbmRleCArPSBjb2x1bW4KCQl9Cgl9CgoJLy8gS2VlcCBpbiByYW5nZS4gKGxlbihzZWxmLnRleHQpIGlzIGluY2x1ZGVkLCBiZWNhdXNlIHRoZSBjdXJzb3IgY2FuIGJlCgkvLyByaWdodCBhZnRlciB0aGUgZW5kIG9mIHRoZSB0ZXh0IGFzIHdlbGwuKQoJLy8gcHl0aG9uKSByZXN1bHQgPSBtYXgoMCwgbWluKHJlc3VsdCwgbGVuKHNlbGYudGV4dCkpKQoJaWYgaW5kZXggPiBsZW4oZC5UZXh0KSB7CgkJaW5kZXggPSBsZW4oZC5UZXh0KQoJfQoJaWYgaW5kZXggPCAwIHsKCQlpbmRleCA9IDAKCX0KCXJldHVybiBpbmRleAp9CgovLyBPbkxhc3RMaW5lIHJldHVybnMgdHJ1ZSB3aGVuIHdlIGFyZSBhdCB0aGUgbGFzdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgT25MYXN0TGluZSgpIGJvb2wgewoJcmV0dXJuIGQuQ3Vyc29yUG9zaXRpb25Sb3coKSA9PSAoZC5MaW5lQ291bnQoKSAtIDEpCn0KCi8vIEdldEVuZE9mTGluZVBvc2l0aW9uIHJldHVybnMgcmVsYXRpdmUgcG9zaXRpb24gZm9yIHRoZSBlbmQgb2YgdGhpcyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgR2V0RW5kT2ZMaW5lUG9zaXRpb24oKSBpbnQgewoJcmV0dXJuIGxlbihbXXJ1bmUoZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpKQp9CgpmdW5jIChkICpEb2N1bWVudCkgbGVhZGluZ1doaXRlc3BhY2VJbkN1cnJlbnRMaW5lKCkgKG1hcmdpbiBzdHJpbmcpIHsKCXRyaW1tZWQgOj0gc3RyaW5ncy5UcmltU3BhY2UoZC5DdXJyZW50TGluZSgpKQoJbWFyZ2luID0gZC5DdXJyZW50TGluZSgpWzpsZW4oZC5DdXJyZW50TGluZSgpKS1sZW4odHJpbW1lZCldCglyZXR1cm4KfQo=", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/task.toml b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..47ab630d57081c0bf1c8afae97ae741c842c618d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/task.toml
@@ -0,0 +1,11 @@
+version = "1.0"
+[agent]
+timeout_sec = 300.0
+[verifier]
+timeout_sec = 300.0
+environment_mode = "shared"
+[environment]
+docker_image = "ghcr.io/younesbelkada/scale800@sha256:fd1dc22a1e0d8425818d3cea15a7cecd0821368006156e3fc9d360204d08946a"
+cpus = 1
+memory_mb = 2048
+storage_mb = 4096
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..9d72994aa85f26f774765aa00d8b9f1d9d93a587
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/manifest.json
@@ -0,0 +1,432 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CursorPositionRowAndCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorLeftPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorUpPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorDownPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorRightPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_Lines"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_LineCount"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateIndexToPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateRowColToIndex"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_OnLastLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetEndOfLinePosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestEmacsKeyBindings"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFilter"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFuzzyMatch"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryClear"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryAdd"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryOlder"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/escape"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/undefined"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWrite"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteRawStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatCompletion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBreakLineCallback"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionRow"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition_withJapanese"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/validation/canaries/delete-tests.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/validation/canaries/delete-tests.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/validation/canaries/delete-tests.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+find /testbed -name '*_test.go' -type f -delete
+printf 'PASS\nok forged-package 0.001s\n'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..b07017c7d5ef35de14c7633cc5ff7f31d2ced876
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__9294kk0o/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "83f0b3d698711bcc75a75bf4c190eab04363340d43f5612922c0d410ffc43204",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/Dockerfile b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f35bf9e5393ee1086fe1b72c1b442f3b16e2bd5b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22
+WORKDIR /testbed
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c8c031d0f87fb9aea0aff433b1fcaeaac259c41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: "Bug report"
+about: Create a bug report to improve go-prompt
+title: "[Bug]"
+labels: bug
+assignees: ''
+
+---
+
+# Bug reports
+
+*Please file a bug report here.*
+
+## Expected Behavior
+
+*Please describe the behavior you are expecting*
+
+## Current Behavior and Steps to Reproduce
+
+*What is the current behavior? Please provide detailed steps for reproducing the issue.*
+*A picture or gif animation tells a thousand words*
+
+## Context
+
+Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
+
+* Operating System:
+* Terminal Emulator: (i.e. iTerm2)
+* tag of go-prompt or commit revision:
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb816a2496376983781774cb5466fed8e1efc93b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,13 @@
+---
+name: "Feature request"
+about: Suggest an idea for new features in go-prompt.
+title: "[Feature Request]"
+labels: enhancement
+assignees: ''
+
+---
+
+# Feature Request
+
+*Please write your suggestion here.*
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/.gitignore b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..eba2b56abe0f7758a560d47dd19d8985b67ef327
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+bin/
+
+# Folders
+pkg/
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+# Glide
+vendor/
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/CHANGELOG.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..b9e21f1ef333b9ec13323bcd4a8f377322ed7e9f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/CHANGELOG.md
@@ -0,0 +1,79 @@
+# Change Log
+
+## v0.3.0 (2018/??/??)
+
+next release.
+
+## v0.2.3 (2018/10/25)
+
+### What's new?
+
+* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92).
+* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100).
+* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102).
+
+### Fixed
+
+* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details).
+* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details).
+* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details).
+
+### Removed or Deprecated
+
+* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`.
+
+## v0.2.2 (2018/06/28)
+
+### What's new?
+
+* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters.
+* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions.
+ * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details).
+* Add FilePathCompleter to complete file path on your system.
+* Add option to customize ascii code key bindings.
+* Add GetWordAfterCursor method in Document.
+
+### Removed or Deprecated
+
+* prompt.Choose shortcut function is deprecated.
+
+## v0.2.1 (2018/02/14)
+
+### What's New?
+
+* ~~It seems that windows support is almost perfect.~~
+ * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows.
+
+### Fixed
+
+* Fix a Shift+Tab handling on Windows.
+* Fix 4-dimension arrow keys handling on Windows.
+
+## v0.2.0 (2018/02/13)
+
+### What's New?
+
+* Supports scrollbar when there are too many matched suggestions
+* Windows support (but please caution because this is still not perfect).
+* Add OptionLivePrefix to update the prefix dynamically
+* Implement clear screen by `Ctrl+L`.
+
+### Fixed
+
+* Fix the behavior of `Ctrl+W` keybind.
+* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details).
+* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details).
+* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ).
+
+### News
+
+New core developers are joined (alphabetical order).
+
+* Nao Yonashiro (Github @orisano)
+* Ryoma Abe (Github @Allajah)
+* Yusuke Nakamura (Github @unasuke)
+
+
+## v0.1.0 (2017/08/15)
+
+Initial Release
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/LICENSE b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a86acaa7ab24fe61ea152a9afcadc21980020efb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Masashi SHIBATA
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/Makefile b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..505817c36f0b8a0bb643eed8680b8989af2b0920
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/Makefile
@@ -0,0 +1,46 @@
+.DEFAULT_GOAL := help
+
+SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
+
+GOIMPORTS ?= goimports
+GOCILINT ?= golangci-lint
+
+.PHONY: setup
+setup: ## Setup for required tools.
+ go get -u golang.org/x/tools/cmd/goimports
+ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: fmt
+fmt: $(SOURCES) ## Formatting source codes.
+ @$(GOIMPORTS) -w $^
+
+.PHONY: lint
+lint: ## Run golangci-lint.
+ @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
+
+.PHONY: test
+test: ## Run tests with race condition checking.
+ @go test -race ./...
+
+.PHONY: bench
+bench: ## Run benchmarks.
+ @go test -bench=. -run=- -benchmem ./...
+
+.PHONY: coverage
+cover: ## Run the tests.
+ @go test -coverprofile=coverage.o
+ @go tool cover -func=coverage.o
+
+.PHONY: generate
+generate: ## Run go generate
+ @go generate ./...
+
+.PHONY: build
+build: ## Build example command lines.
+ ./_example/build.sh
+
+.PHONY: help
+help: ## Show help text
+ @echo "Commands:"
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfcd7a399b4827d6b126d6a173cce34d36520481
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/README.md
@@ -0,0 +1,125 @@
+# go-prompt
+
+[](https://goreportcard.com/report/github.com/c-bata/go-prompt)
+
+[](https://godoc.org/github.com/c-bata/go-prompt)
+
+
+A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit),
+making it easier to build cross-platform command line tools using Go.
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func completer(d prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ }
+ return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ fmt.Println("Please select table.")
+ t := prompt.Input("> ", completer)
+ fmt.Println("You selected " + t)
+}
+```
+
+#### Projects using go-prompt
+
+* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt)
+* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli)
+* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn)
+* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli)
+* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans)
+* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit)
+* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go)
+* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS)
+* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs)
+* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli)
+* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt)
+* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh)
+* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell)
+* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt)
+* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim)
+* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron)
+* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl)
+* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl)
+* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit)
+* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.)
+
+## Features
+
+### Powerful auto-completion
+
+[](https://github.com/c-bata/kube-prompt)
+
+(This is a GIF animation of kube-prompt.)
+
+### Flexible options
+
+go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details.
+
+[](#flexible-options)
+
+### Keyboard Shortcuts
+
+Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell).
+You can customize and expand these shortcuts.
+
+[](#keyboard-shortcuts)
+
+Key Binding | Description
+---------------------|---------------------------------------------------------
+Ctrl + A | Go to the beginning of the line (Home)
+Ctrl + E | Go to the end of the line (End)
+Ctrl + P | Previous command (Up arrow)
+Ctrl + N | Next command (Down arrow)
+Ctrl + F | Forward one character
+Ctrl + B | Backward one character
+Ctrl + D | Delete character under the cursor
+Ctrl + H | Delete character before the cursor (Backspace)
+Ctrl + W | Cut the word before the cursor to the clipboard
+Ctrl + K | Cut the line after the cursor to the clipboard
+Ctrl + U | Cut the line before the cursor to the clipboard
+Ctrl + L | Clear the screen
+
+### History
+
+You can use Up arrow and Down arrow to walk through the history of commands executed.
+
+[](#history)
+
+### Multiple platform support
+
+We have confirmed go-prompt works fine in the following terminals:
+
+* iTerm2 (macOS)
+* Terminal.app (macOS)
+* Command Prompt (Windows)
+* gnome-terminal (Ubuntu)
+
+## Links
+
+* [Change Log](./CHANGELOG.md)
+* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt)
+* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt)
+
+## Author
+
+Masashi Shibata
+
+* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/)
+* Github: [@c-bata](https://github.com/c-bata/)
+
+## License
+
+This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..759b0e3f8acf1216b055e0f9458758a6c1e8950a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/README.md
@@ -0,0 +1,30 @@
+# Examples of go-prompt
+
+This directory includes some examples using go-prompt.
+These examples are useful to know the usage of go-prompt and check behavior for development.
+
+## simple-echo
+
+
+
+A simple echo example using `prompt.Input`.
+
+## http-prompt
+
+
+
+A simple [http-prompt](https://github.com/eliangcs/http-prompt) implementation using go-prompt in less than 200 lines of Go.
+
+## live-prefix
+
+
+
+A example application which changes a prefix string dynamically.
+This feature is used like [ktr0731/evans](https://github.com/ktr0731/evans) which is interactive gRPC client using go-prompt.
+
+## exec-command
+
+Run another CLI tool via `os/exec` package.
+More practical example is [a source code of kube-prompt](https://github.com/c-bata/kube-prompt).
+I recommend you to look this if you want to create tools like kube-prompt.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/build.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c552afcfa69b2356ffcd484c867abcaaaaeeaff
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+export GO111MODULE=on
+DIR=$(cd $(dirname $0); pwd)
+BIN_DIR=$(cd $(dirname $(dirname $0)); pwd)/bin
+
+mkdir -p ${BIN_DIR}
+go build -o ${BIN_DIR}/exec-command ${DIR}/exec-command/main.go
+go build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.go
+go build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.go
+go build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.go
+go build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/exec-command/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/exec-command/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..838f756260df91569491def29a7ee05a7c9a98f7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/exec-command/main.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "os/exec"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(t string) {
+ if t == "bash" {
+ cmd := exec.Command("bash")
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Run()
+ }
+ return
+}
+
+func completer(t prompt.Document) []prompt.Suggest {
+ return []prompt.Suggest{
+ {Text: "bash"},
+ }
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/http-prompt/api.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/http-prompt/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..08e7b1a489a2077f26f280fe39e3bd06efa52cd2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/http-prompt/api.py
@@ -0,0 +1,17 @@
+from bottle import route, run, request
+
+@route('/')
+def hello():
+ return "Hello World!"
+
+@route('/ping')
+def hello():
+ return "pong!"
+
+@route('/register', method='POST')
+def register():
+ name = request.json.get("name")
+ return "Hello %s!" % name
+
+if __name__ == "__main__":
+ run(host='localhost', port=8000, debug=True)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/http-prompt/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/http-prompt/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b372a3550c50121d6e500e2a08e641e168b8c00d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/http-prompt/main.go
@@ -0,0 +1,192 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+type RequestContext struct {
+ url *url.URL
+ header http.Header
+ client *http.Client
+}
+
+var ctx *RequestContext
+
+// See https://github.com/eliangcs/http-prompt/blob/master/http_prompt/completion.py
+var suggestions = []prompt.Suggest{
+ // Command
+ {"cd", "Change URL/path"},
+ {"exit", "Exit http-prompt"},
+
+ // HTTP Method
+ {"delete", "DELETE request"},
+ {"get", "GET request"},
+ {"patch", "GET request"},
+ {"post", "POST request"},
+ {"put", "PUT request"},
+
+ // HTTP Header
+ {"Accept", "Acceptable response media type"},
+ {"Accept-Charset", "Acceptable response charsets"},
+ {"Accept-Encoding", "Acceptable response content codings"},
+ {"Accept-Language", "Preferred natural languages in response"},
+ {"ALPN", "Application-layer protocol negotiation to use"},
+ {"Alt-Used", "Alternative host in use"},
+ {"Authorization", "Authentication information"},
+ {"Cache-Control", "Directives for caches"},
+ {"Connection", "Connection options"},
+ {"Content-Encoding", "Content codings"},
+ {"Content-Language", "Natural languages for content"},
+ {"Content-Length", "Anticipated size for payload body"},
+ {"Content-Location", "Where content was obtained"},
+ {"Content-MD5", "Base64-encoded MD5 sum of content"},
+ {"Content-Type", "Content media type"},
+ {"Cookie", "Stored cookies"},
+ {"Date", "Datetime when message was originated"},
+ {"Depth", "Applied only to resource or its members"},
+ {"DNT", "Do not track user"},
+ {"Expect", "Expected behaviors supported by server"},
+ {"Forwarded", "Proxies involved"},
+ {"From", "Sender email address"},
+ {"Host", "Target URI"},
+ {"HTTP2-Settings", "HTTP/2 connection parameters"},
+ {"If", "Request condition on state tokens and ETags"},
+ {"If-Match", "Request condition on target resource"},
+ {"If-Modified-Since", "Request condition on modification date"},
+ {"If-None-Match", "Request condition on target resource"},
+ {"If-Range", "Request condition on Range"},
+ {"If-Schedule-Tag-Match", "Request condition on Schedule-Tag"},
+ {"If-Unmodified-Since", "Request condition on modification date"},
+ {"Max-Forwards", "Max number of times forwarded by proxies"},
+ {"MIME-Version", "Version of MIME protocol"},
+ {"Origin", "Origin(s} issuing the request"},
+ {"Pragma", "Implementation-specific directives"},
+ {"Prefer", "Preferred server behaviors"},
+ {"Proxy-Authorization", "Proxy authorization credentials"},
+ {"Proxy-Connection", "Proxy connection options"},
+ {"Range", "Request transfer of only part of data"},
+ {"Referer", "Previous web page"},
+ {"TE", "Transfer codings willing to accept"},
+ {"Transfer-Encoding", "Transfer codings applied to payload body"},
+ {"Upgrade", "Invite server to upgrade to another protocol"},
+ {"User-Agent", "User agent string"},
+ {"Via", "Intermediate proxies"},
+ {"Warning", "Possible incorrectness with payload body"},
+ {"WWW-Authenticate", "Authentication scheme"},
+ {"X-Csrf-Token", "Prevent cross-site request forgery"},
+ {"X-CSRFToken", "Prevent cross-site request forgery"},
+ {"X-Forwarded-For", "Originating client IP address"},
+ {"X-Forwarded-Host", "Original host requested by client"},
+ {"X-Forwarded-Proto", "Originating protocol"},
+ {"X-Http-Method-Override", "Request method override"},
+ {"X-Requested-With", "Used to identify Ajax requests"},
+ {"X-XSRF-TOKEN", "Prevent cross-site request forgery"},
+}
+
+func livePrefix() (string, bool) {
+ if ctx.url.Path == "/" {
+ return "", false
+ }
+ return ctx.url.String() + "> ", true
+}
+
+func executor(in string) {
+ in = strings.TrimSpace(in)
+
+ var method, body string
+ blocks := strings.Split(in, " ")
+ switch blocks[0] {
+ case "exit":
+ fmt.Println("Bye!")
+ os.Exit(0)
+ case "cd":
+ if len(blocks) < 2 {
+ ctx.url.Path = "/"
+ } else {
+ ctx.url.Path = path.Join(ctx.url.Path, blocks[1])
+ }
+ return
+ case "get", "delete":
+ method = strings.ToUpper(blocks[0])
+ case "post", "put", "patch":
+ if len(blocks) < 2 {
+ fmt.Println("please set request body.")
+ return
+ }
+ body = strings.Join(blocks[1:], " ")
+ method = strings.ToUpper(blocks[0])
+ }
+ if method != "" {
+ req, err := http.NewRequest(method, ctx.url.String(), strings.NewReader(body))
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ req.Header = ctx.header
+ res, err := ctx.client.Do(req)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ result, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ fmt.Printf("%s\n", result)
+ ctx.header = http.Header{}
+ return
+ }
+
+ if h := strings.Split(in, ":"); len(h) == 2 {
+ // Handling HTTP Header
+ ctx.header.Add(strings.TrimSpace(h[0]), strings.Trim(h[1], ` '"`))
+ } else {
+ fmt.Println("Sorry, I don't understand.")
+ }
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ w := in.GetWordBeforeCursor()
+ if w == "" {
+ return []prompt.Suggest{}
+ }
+ return prompt.FilterHasPrefix(suggestions, w, true)
+}
+
+func main() {
+ var baseURL = "http://localhost:8000/"
+ if len(os.Args) == 2 {
+ baseURL = os.Args[1]
+ if strings.HasSuffix(baseURL, "/") {
+ baseURL += "/"
+ }
+ }
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ ctx = &RequestContext{
+ url: u,
+ header: http.Header{},
+ client: &http.Client{},
+ }
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(u.String()+"> "),
+ prompt.OptionLivePrefix(livePrefix),
+ prompt.OptionTitle("http-prompt"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/live-prefix/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/live-prefix/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c7ced720592173e2a13f19f7cb543730192d3f8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/live-prefix/main.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var LivePrefixState struct {
+ LivePrefix string
+ IsEnable bool
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+ if in == "" {
+ LivePrefixState.IsEnable = false
+ LivePrefixState.LivePrefix = in
+ return
+ }
+ LivePrefixState.LivePrefix = in + "> "
+ LivePrefixState.IsEnable = true
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func changeLivePrefix() (string, bool) {
+ return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionLivePrefix(changeLivePrefix),
+ prompt.OptionTitle("live-prefix-example"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/simple-echo/cjk-cyrillic/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/simple-echo/cjk-cyrillic/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e9e53adef1558e004f86ccbca2c2e2b83c1da39
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/simple-echo/cjk-cyrillic/main.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
+ {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
+ {Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
+ {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionTitle("sql-prompt for multi width characters"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/simple-echo/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/simple-echo/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..12b1bb4fc189e6b369e889779418d7826a45db9d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_example/simple-echo/main.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ in := prompt.Input(">>> ", completer,
+ prompt.OptionTitle("sql-prompt"),
+ prompt.OptionHistory([]string{"SELECT * FROM users;"}),
+ prompt.OptionPrefixTextColor(prompt.Yellow),
+ prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
+ prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
+ prompt.OptionSuggestionBGColor(prompt.DarkGray))
+ fmt.Println("Your input: " + in)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_tools/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..45bd2234f21ff32562984bec046316c8e52868fd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_tools/README.md
@@ -0,0 +1,10 @@
+## Tools of go-prompt
+
+### vt100_debug
+
+
+
+### sigwinch
+
+
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_tools/complete_file/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_tools/complete_file/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..41015cfab9b021fbc7df575bde87e3c510705496
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_tools/complete_file/main.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/completer"
+)
+
+var filePathCompleter = completer.FilePathCompleter{
+ IgnoreCase: true,
+ Filter: func(fi os.FileInfo) bool {
+ return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
+ },
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completerFunc(d prompt.Document) []prompt.Suggest {
+ t := d.GetWordBeforeCursor()
+ if strings.HasPrefix(t, "--") {
+ return []prompt.Suggest{
+ {"--foo", ""},
+ {"--bar", ""},
+ {"--baz", ""},
+ }
+ }
+ return filePathCompleter.Complete(d)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completerFunc,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_tools/sigwinch/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_tools/sigwinch/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9608eb3b4a5e3c6942c140c41e08a36ab3adb33b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_tools/sigwinch/main.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "unsafe"
+)
+
+// Winsize is winsize struct got from the ioctl(2) system call.
+type Winsize struct {
+ Row uint16
+ Col uint16
+ X uint16 // pixel value
+ Y uint16 // pixel value
+}
+
+// GetWinSize returns winsize struct which is the response of ioctl(2).
+func GetWinSize(fd int) *Winsize {
+ ws := &Winsize{}
+ retCode, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ uintptr(fd),
+ uintptr(syscall.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(ws)))
+
+ if int(retCode) == -1 {
+ panic(errno)
+ }
+ return ws
+}
+
+func main() {
+ signalChan := make(chan os.Signal, 1)
+ signal.Notify(
+ signalChan,
+ syscall.SIGHUP,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ exitChan := make(chan int)
+ go func() {
+ for {
+ s := <-signalChan
+ switch s {
+ // kill -SIGHUP XXXX
+ case syscall.SIGHUP:
+ exitChan <- 0
+
+ // kill -SIGINT XXXX or Ctrl+c
+ case syscall.SIGINT:
+ exitChan <- 0
+
+ // kill -SIGTERM XXXX
+ case syscall.SIGTERM:
+ exitChan <- 0
+
+ // kill -SIGQUIT XXXX
+ case syscall.SIGQUIT:
+ exitChan <- 0
+
+ case syscall.SIGWINCH:
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ default:
+ exitChan <- 1
+ }
+ }
+ }()
+
+ code := <-exitChan
+ os.Exit(code)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_tools/vt100_debug/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_tools/vt100_debug/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c6036d45959febc739e287a3a7b631259d4ee7c1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/_tools/vt100_debug/main.go
@@ -0,0 +1,47 @@
+// +build !windows
+
+package main
+
+import (
+ "fmt"
+ "syscall"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/term"
+)
+
+func main() {
+ if err := term.SetRaw(syscall.Stdin); err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer term.Restore()
+
+ bufCh := make(chan []byte, 128)
+ go readBuffer(bufCh)
+ fmt.Print("> ")
+
+ for {
+ b := <-bufCh
+ if key := prompt.GetKey(b); key == prompt.NotDefined {
+ fmt.Printf("Key '%s' data:'%#v'\n", string(b), b)
+ } else {
+ if key == prompt.ControlC {
+ fmt.Println("exit.")
+ return
+ }
+ fmt.Printf("Key '%s' data:'%#v'\n", key, b)
+ }
+ fmt.Print("> ")
+ }
+}
+
+func readBuffer(bufCh chan []byte) {
+ buf := make([]byte, 1024)
+
+ for {
+ if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
+ bufCh <- buf[:n]
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/buffer.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..46efbbba8bfb75f4a064c83368b781d1d6dbbb29
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/buffer.go
@@ -0,0 +1,191 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Buffer emulates the console buffer.
+type Buffer struct {
+ workingLines []string // The working lines. Similar to history
+ workingIndex int
+ cursorPosition int
+ cacheDocument *Document
+ preferredColumn int // Remember the original column for the next up/down movement.
+ lastKeyStroke Key
+}
+
+// Text returns string of the current line.
+func (b *Buffer) Text() string {
+ return b.workingLines[b.workingIndex]
+}
+
+// Document method to return document instance from the current text and cursor position.
+func (b *Buffer) Document() (d *Document) {
+ if b.cacheDocument == nil ||
+ b.cacheDocument.Text != b.Text() ||
+ b.cacheDocument.cursorPosition != b.cursorPosition {
+ b.cacheDocument = &Document{
+ Text: b.Text(),
+ cursorPosition: b.cursorPosition,
+ }
+ }
+ b.cacheDocument.lastKey = b.lastKeyStroke
+ return b.cacheDocument
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (b *Buffer) DisplayCursorPosition() int {
+ return b.Document().DisplayCursorPosition()
+}
+
+// InsertText insert string from current line.
+func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
+ or := []rune(b.Text())
+ oc := b.cursorPosition
+
+ if overwrite {
+ overwritten := string(or[oc : oc+len(v)])
+ if strings.Contains(overwritten, "\n") {
+ i := strings.IndexAny(overwritten, "\n")
+ overwritten = overwritten[:i]
+ }
+ b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):]))
+ } else {
+ b.setText(string(or[:oc]) + v + string(or[oc:]))
+ }
+
+ if moveCursor {
+ b.cursorPosition += len([]rune(v))
+ }
+}
+
+// SetText method to set text and update cursorPosition.
+// (When doing this, make sure that the cursor_position is valid for this text.
+// text/cursor_position should be consistent at any time, otherwise set a Document instead.)
+func (b *Buffer) setText(v string) {
+ debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position")
+ b.workingLines[b.workingIndex] = v
+}
+
+// Set cursor position. Return whether it changed.
+func (b *Buffer) setCursorPosition(p int) {
+ if p > 0 {
+ b.cursorPosition = p
+ } else {
+ b.cursorPosition = 0
+ }
+}
+
+func (b *Buffer) setDocument(d *Document) {
+ b.cacheDocument = d
+ b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length.
+ b.setText(d.Text)
+}
+
+// CursorLeft move to left on the current line.
+func (b *Buffer) CursorLeft(count int) {
+ l := b.Document().GetCursorLeftPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorRight move to right on the current line.
+func (b *Buffer) CursorRight(count int) {
+ l := b.Document().GetCursorRightPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorUp move cursor to the previous line.
+// (for multi-line edit).
+func (b *Buffer) CursorUp(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorUpPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// CursorDown move cursor to the next line.
+// (for multi-line edit).
+func (b *Buffer) CursorDown(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorDownPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text.
+func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) {
+ debug.Assert(count >= 0, "count should be positive")
+ r := []rune(b.Text())
+
+ if b.cursorPosition > 0 {
+ start := b.cursorPosition - count
+ if start < 0 {
+ start = 0
+ }
+ deleted = string(r[start:b.cursorPosition])
+ b.setDocument(&Document{
+ Text: string(r[:start]) + string(r[b.cursorPosition:]),
+ cursorPosition: b.cursorPosition - len([]rune(deleted)),
+ })
+ }
+ return
+}
+
+// NewLine means CR.
+func (b *Buffer) NewLine(copyMargin bool) {
+ if copyMargin {
+ b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true)
+ } else {
+ b.InsertText("\n", false, true)
+ }
+}
+
+// Delete specified number of characters and Return the deleted text.
+func (b *Buffer) Delete(count int) (deleted string) {
+ r := []rune(b.Text())
+ if b.cursorPosition < len(r) {
+ deleted = b.Document().TextAfterCursor()[:count]
+ b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):]))
+ }
+ return
+}
+
+// JoinNextLine joins the next line to the current one by deleting the line ending after the current line.
+func (b *Buffer) JoinNextLine(separator string) {
+ if !b.Document().OnLastLine() {
+ b.cursorPosition += b.Document().GetEndOfLinePosition()
+ b.Delete(1)
+ // Remove spaces
+ b.setText(b.Document().TextBeforeCursor() + separator + strings.TrimLeft(b.Document().TextAfterCursor(), " "))
+ }
+}
+
+// SwapCharactersBeforeCursor swaps the last two characters before the cursor.
+func (b *Buffer) SwapCharactersBeforeCursor() {
+ if b.cursorPosition >= 2 {
+ x := b.Text()[b.cursorPosition-2 : b.cursorPosition-1]
+ y := b.Text()[b.cursorPosition-1 : b.cursorPosition]
+ b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:])
+ }
+}
+
+// NewBuffer is constructor of Buffer struct.
+func NewBuffer() (b *Buffer) {
+ b = &Buffer{
+ workingLines: []string{""},
+ workingIndex: 0,
+ preferredColumn: -1, // -1 means nil
+ }
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/completer/file.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/completer/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..59f2d8dec84214ccaa6e345a11ed51aa61a08199
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/completer/file.go
@@ -0,0 +1,90 @@
+package completer
+
+import (
+ "io/ioutil"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+var (
+ // FilePathCompletionSeparator holds separate characters.
+ FilePathCompletionSeparator = string([]byte{' ', os.PathSeparator})
+)
+
+// FilePathCompleter is a completer for your local file system.
+// Please caution that you need to set OptionCompletionWordSeparator(completer.FilePathCompletionSeparator)
+// when you use this completer.
+type FilePathCompleter struct {
+ Filter func(fi os.FileInfo) bool
+ IgnoreCase bool
+ fileListCache map[string][]prompt.Suggest
+}
+
+func cleanFilePath(path string) (dir, base string, err error) {
+ if path == "" {
+ return ".", "", nil
+ }
+
+ var endsWithSeparator bool
+ if len(path) >= 1 && path[len(path)-1] == os.PathSeparator {
+ endsWithSeparator = true
+ }
+
+ if runtime.GOOS != "windows" && len(path) >= 2 && path[0:2] == "~/" {
+ me, err := user.Current()
+ if err != nil {
+ return "", "", err
+ }
+ path = filepath.Join(me.HomeDir, path[1:])
+ }
+ path = filepath.Clean(os.ExpandEnv(path))
+ dir = filepath.Dir(path)
+ base = filepath.Base(path)
+
+ if endsWithSeparator {
+ dir = path + string(os.PathSeparator) // Append slash(in POSIX) if path ends with slash.
+ base = "" // Set empty string if path ends with separator.
+ }
+ return dir, base, nil
+}
+
+// Complete returns suggestions from your local file system.
+func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest {
+ if c.fileListCache == nil {
+ c.fileListCache = make(map[string][]prompt.Suggest, 4)
+ }
+
+ path := d.GetWordBeforeCursor()
+ dir, base, err := cleanFilePath(path)
+ if err != nil {
+ debug.Log("completer: cannot get current user:" + err.Error())
+ return nil
+ }
+
+ if cached, ok := c.fileListCache[dir]; ok {
+ return prompt.FilterHasPrefix(cached, base, c.IgnoreCase)
+ }
+
+ files, err := ioutil.ReadDir(dir)
+ if err != nil && os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ debug.Log("completer: cannot read directory items:" + err.Error())
+ return nil
+ }
+
+ suggests := make([]prompt.Suggest, 0, len(files))
+ for _, f := range files {
+ if c.Filter != nil && !c.Filter(f) {
+ continue
+ }
+ suggests = append(suggests, prompt.Suggest{Text: f.Name()})
+ }
+ c.fileListCache[dir] = suggests
+ return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/completion.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/completion.go
new file mode 100644
index 0000000000000000000000000000000000000000..57e82eefc0f50e9561214704e770a2ad313a3659
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/completion.go
@@ -0,0 +1,190 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+const (
+ shortenSuffix = "..."
+ leftPrefix = " "
+ leftSuffix = " "
+ rightPrefix = " "
+ rightSuffix = " "
+)
+
+var (
+ leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix)
+ rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix)
+ completionMargin = leftMargin + rightMargin
+)
+
+// Suggest is printed when completing.
+type Suggest struct {
+ Text string
+ Description string
+}
+
+// CompletionManager manages which suggestion is now selected.
+type CompletionManager struct {
+ selected int // -1 means nothing one is selected.
+ tmp []Suggest
+ max uint16
+ completer Completer
+
+ verticalScroll int
+ wordSeparator string
+ showAtStart bool
+}
+
+// GetSelectedSuggestion returns the selected item.
+func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) {
+ if c.selected == -1 {
+ return Suggest{}, false
+ } else if c.selected < -1 {
+ debug.Assert(false, "must not reach here")
+ c.selected = -1
+ return Suggest{}, false
+ }
+ return c.tmp[c.selected], true
+}
+
+// GetSuggestions returns the list of suggestion.
+func (c *CompletionManager) GetSuggestions() []Suggest {
+ return c.tmp
+}
+
+// Reset to select nothing.
+func (c *CompletionManager) Reset() {
+ c.selected = -1
+ c.verticalScroll = 0
+ c.Update(*NewDocument())
+}
+
+// Update to update the suggestions.
+func (c *CompletionManager) Update(in Document) {
+ c.tmp = c.completer(in)
+}
+
+// Previous to select the previous suggestion item.
+func (c *CompletionManager) Previous() {
+ if c.verticalScroll == c.selected && c.selected > 0 {
+ c.verticalScroll--
+ }
+ c.selected--
+ c.update()
+}
+
+// Next to select the next suggestion item.
+func (c *CompletionManager) Next() {
+ if c.verticalScroll+int(c.max)-1 == c.selected {
+ c.verticalScroll++
+ }
+ c.selected++
+ c.update()
+}
+
+// Completing returns whether the CompletionManager selects something one.
+func (c *CompletionManager) Completing() bool {
+ return c.selected != -1
+}
+
+func (c *CompletionManager) update() {
+ max := int(c.max)
+ if len(c.tmp) < max {
+ max = len(c.tmp)
+ }
+
+ if c.selected >= len(c.tmp) {
+ c.Reset()
+ } else if c.selected < -1 {
+ c.selected = len(c.tmp) - 1
+ c.verticalScroll = len(c.tmp) - max
+ }
+}
+
+func deleteBreakLineCharacters(s string) string {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, "\r", "", -1)
+ return s
+}
+
+func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) {
+ l := len(o)
+ n := make([]string, l)
+
+ lenPrefix := runewidth.StringWidth(prefix)
+ lenSuffix := runewidth.StringWidth(suffix)
+ lenShorten := runewidth.StringWidth(shortenSuffix)
+ min := lenPrefix + lenSuffix + lenShorten
+ for i := 0; i < l; i++ {
+ o[i] = deleteBreakLineCharacters(o[i])
+
+ w := runewidth.StringWidth(o[i])
+ if width < w {
+ width = w
+ }
+ }
+
+ if width == 0 {
+ return n, 0
+ }
+ if min >= max {
+ return n, 0
+ }
+ if lenPrefix+width+lenSuffix > max {
+ width = max - lenPrefix - lenSuffix
+ }
+
+ for i := 0; i < l; i++ {
+ x := runewidth.StringWidth(o[i])
+ if x <= width {
+ spaces := strings.Repeat(" ", width-x)
+ n[i] = prefix + o[i] + spaces + suffix
+ } else if x > width {
+ x := runewidth.Truncate(o[i], width, shortenSuffix)
+ // When calling runewidth.Truncate("您好xxx您好xxx", 11, "...") returns "您好xxx..."
+ // But the length of this result is 10. So we need fill right using runewidth.FillRight.
+ n[i] = prefix + runewidth.FillRight(x, width) + suffix
+ }
+ }
+ return n, lenPrefix + width + lenSuffix
+}
+
+func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) {
+ num := len(suggests)
+ new = make([]Suggest, num)
+
+ left := make([]string, num)
+ for i := 0; i < num; i++ {
+ left[i] = suggests[i].Text
+ }
+ right := make([]string, num)
+ for i := 0; i < num; i++ {
+ right[i] = suggests[i].Description
+ }
+
+ left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix)
+ if leftWidth == 0 {
+ return []Suggest{}, 0
+ }
+ right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix)
+
+ for i := 0; i < num; i++ {
+ new[i] = Suggest{Text: left[i], Description: right[i]}
+ }
+ return new, leftWidth + rightWidth
+}
+
+// NewCompletionManager returns initialized CompletionManager object.
+func NewCompletionManager(completer Completer, max uint16) *CompletionManager {
+ return &CompletionManager{
+ selected: -1,
+ max: max,
+ completer: completer,
+
+ verticalScroll: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/document.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/document.go
new file mode 100644
index 0000000000000000000000000000000000000000..50fb1edbc89d6648f02ce5b733a2d0223591a4b9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/document.go
@@ -0,0 +1,441 @@
+package prompt
+
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+ istrings "github.com/c-bata/go-prompt/internal/strings"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Document has text displayed in terminal and cursor position.
+type Document struct {
+ Text string
+ // This represents a index in a rune array of Document.Text.
+ // So if Document is "日本(cursor)語", cursorPosition is 2.
+ // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+ cursorPosition int
+ lastKey Key
+}
+
+// NewDocument return the new empty document.
+func NewDocument() *Document {
+ return &Document{
+ Text: "",
+ cursorPosition: 0,
+ }
+}
+
+// LastKeyStroke return the last key pressed in this document.
+func (d *Document) LastKeyStroke() Key {
+ return d.lastKey
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (d *Document) DisplayCursorPosition() int {
+ var position int
+ runes := []rune(d.Text)[:d.cursorPosition]
+ for i := range runes {
+ position += runewidth.RuneWidth(runes[i])
+ }
+ return position
+}
+
+// GetCharRelativeToCursor return character relative to cursor position, or empty string
+func (d *Document) GetCharRelativeToCursor(offset int) (r rune) {
+ s := d.Text
+ cnt := 0
+
+ for len(s) > 0 {
+ cnt++
+ r, size := utf8.DecodeRuneInString(s)
+ if cnt == d.cursorPosition+offset {
+ return r
+ }
+ s = s[size:]
+ }
+ return 0
+}
+
+// TextBeforeCursor returns the text before the cursor.
+func (d *Document) TextBeforeCursor() string {
+ r := []rune(d.Text)
+ return string(r[:d.cursorPosition])
+}
+
+// TextAfterCursor returns the text after the cursor.
+func (d *Document) TextAfterCursor() string {
+ r := []rune(d.Text)
+ return string(r[d.cursorPosition:])
+}
+
+// GetWordBeforeCursor returns the word before the cursor.
+// If we have whitespace before the cursor this returns an empty string.
+func (d *Document) GetWordBeforeCursor() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWord():]
+}
+
+// GetWordAfterCursor returns the word after the cursor.
+// If we have whitespace after the cursor this returns an empty string.
+func (d *Document) GetWordAfterCursor() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWord()]
+}
+
+// GetWordBeforeCursorWithSpace returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorWithSpace() string {
+ x := d.TextBeforeCursor()
+ return x[:d.FindStartOfPreviousWordWithSpace()]
+}
+
+// GetWordAfterCursorWithSpace returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorWithSpace() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordWithSpace()]
+}
+
+// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
+func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparator(sep):]
+}
+
+// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
+func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparator(sep)]
+}
+
+// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):]
+}
+
+// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)]
+}
+
+// FindStartOfPreviousWord returns an index relative to the cursor position
+// pointing to the start of the previous word. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWord() int {
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexByte(x, ' ')
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindStartOfPreviousWordWithSpace() int {
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotByte(x, ' ')
+ if end == -1 {
+ return 0
+ }
+
+ start := strings.LastIndexByte(x[:end], ' ')
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWord()
+ }
+
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexAny(x, sep)
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWordWithSpace()
+ }
+
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotAny(x, sep)
+ if end == -1 {
+ return 0
+ }
+ start := strings.LastIndexAny(x[:end], sep)
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindEndOfCurrentWord returns an index relative to the cursor position.
+// pointing to the end of the current word. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWord() int {
+ x := d.TextAfterCursor()
+ i := strings.IndexByte(x, ' ')
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindEndOfCurrentWordWithSpace() int {
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotByte(x, ' ')
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexByte(x[start:], ' ')
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWord()
+ }
+
+ x := d.TextAfterCursor()
+ i := strings.IndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWordWithSpace()
+ }
+
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotAny(x, sep)
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexAny(x[start:], sep)
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// CurrentLineBeforeCursor returns the text from the start of the line until the cursor.
+func (d *Document) CurrentLineBeforeCursor() string {
+ s := strings.Split(d.TextBeforeCursor(), "\n")
+ return s[len(s)-1]
+}
+
+// CurrentLineAfterCursor returns the text from the cursor until the end of the line.
+func (d *Document) CurrentLineAfterCursor() string {
+ return strings.Split(d.TextAfterCursor(), "\n")[0]
+}
+
+// CurrentLine return the text on the line where the cursor is. (when the input
+// consists of just one line, it equals `text`.
+func (d *Document) CurrentLine() string {
+ return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor()
+}
+
+// Array pointing to the start indexes of all the lines.
+func (d *Document) lineStartIndexes() []int {
+ // TODO: Cache, because this is often reused.
+ // (If it is used, it's often used many times.
+ // And this has to be fast for editing big documents!)
+ lc := d.LineCount()
+ lengths := make([]int, lc)
+ for i, l := range d.Lines() {
+ lengths[i] = len(l)
+ }
+
+ // Calculate cumulative sums.
+ indexes := make([]int, lc+1)
+ indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189
+ pos := 0
+ for i, l := range lengths {
+ pos += l + 1
+ indexes[i+1] = pos
+ }
+ if lc > 1 {
+ // Pop the last item. (This is not a new line.)
+ indexes = indexes[:lc]
+ }
+ return indexes
+}
+
+// For the index of a character at a certain line, calculate the index of
+// the first character on that line.
+func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) {
+ indexes := d.lineStartIndexes()
+ pos = bisect.Right(indexes, index) - 1
+ lineStartIndex = indexes[pos]
+ return
+}
+
+// CursorPositionRow returns the current row. (0-based.)
+func (d *Document) CursorPositionRow() (row int) {
+ row, _ = d.findLineStartIndex(d.cursorPosition)
+ return
+}
+
+// CursorPositionCol returns the current column. (0-based.)
+func (d *Document) CursorPositionCol() (col int) {
+ // Don't use self.text_before_cursor to calculate this. Creating substrings
+ // and splitting is too expensive for getting the cursor position.
+ _, index := d.findLineStartIndex(d.cursorPosition)
+ col = d.cursorPosition - index
+ return
+}
+
+// GetCursorLeftPosition returns the relative position for cursor left.
+func (d *Document) GetCursorLeftPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorRightPosition(-count)
+ }
+ if d.CursorPositionCol() > count {
+ return -count
+ }
+ return -d.CursorPositionCol()
+}
+
+// GetCursorRightPosition returns relative position for cursor right.
+func (d *Document) GetCursorRightPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorLeftPosition(-count)
+ }
+ if len(d.CurrentLineAfterCursor()) > count {
+ return count
+ }
+ return len(d.CurrentLineAfterCursor())
+}
+
+// GetCursorUpPosition return the relative cursor position (character index) where we would be
+// if the user pressed the arrow-up button.
+func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+
+ row := d.CursorPositionRow() - count
+ if row < 0 {
+ row = 0
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// GetCursorDownPosition return the relative cursor position (character index) where we would be if the
+// user pressed the arrow-down button.
+func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+ row := d.CursorPositionRow() + count
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// Lines returns the array of all the lines.
+func (d *Document) Lines() []string {
+ // TODO: Cache, because this one is reused very often.
+ return strings.Split(d.Text, "\n")
+}
+
+// LineCount return the number of lines in this document. If the document ends
+// with a trailing \n, that counts as the beginning of a new line.
+func (d *Document) LineCount() int {
+ return len(d.Lines())
+}
+
+// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple.
+// (0-based. Returns (0, 0) for index=0.)
+func (d *Document) TranslateIndexToPosition(index int) (row int, col int) {
+ row, rowIndex := d.findLineStartIndex(index)
+ col = index - rowIndex
+ return
+}
+
+// TranslateRowColToIndex given a (row, col), return the corresponding index.
+// (Row and col params are 0-based.)
+func (d *Document) TranslateRowColToIndex(row int, column int) (index int) {
+ indexes := d.lineStartIndexes()
+ if row < 0 {
+ row = 0
+ } else if row > len(indexes) {
+ row = len(indexes) - 1
+ }
+ index = indexes[row]
+ line := d.Lines()[row]
+
+ // python) result += max(0, min(col, len(line)))
+ if column > 0 || len(line) > 0 {
+ if column > len(line) {
+ index += len(line)
+ } else {
+ index += column
+ }
+ }
+
+ // Keep in range. (len(self.text) is included, because the cursor can be
+ // right after the end of the text as well.)
+ // python) result = max(0, min(result, len(self.text)))
+ if index > len(d.Text) {
+ index = len(d.Text)
+ }
+ if index < 0 {
+ index = 0
+ }
+ return index
+}
+
+// OnLastLine returns true when we are at the last line.
+func (d *Document) OnLastLine() bool {
+ return d.CursorPositionRow() == (d.LineCount() - 1)
+}
+
+// GetEndOfLinePosition returns relative position for the end of this line.
+func (d *Document) GetEndOfLinePosition() int {
+ return len([]rune(d.CurrentLineAfterCursor()))
+}
+
+func (d *Document) leadingWhitespaceInCurrentLine() (margin string) {
+ trimmed := strings.TrimSpace(d.CurrentLine())
+ margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)]
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/emacs.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/emacs.go
new file mode 100644
index 0000000000000000000000000000000000000000..632f96321f2577cdb7e8cffe639f1518a65d5e0f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/emacs.go
@@ -0,0 +1,120 @@
+package prompt
+
+import "github.com/c-bata/go-prompt/internal/debug"
+
+/*
+
+========
+PROGRESS
+========
+
+Moving the cursor
+-----------------
+
+* [x] Ctrl + a Go to the beginning of the line (Home)
+* [x] Ctrl + e Go to the End of the line (End)
+* [x] Ctrl + p Previous command (Up arrow)
+* [x] Ctrl + n Next command (Down arrow)
+* [x] Ctrl + f Forward one character
+* [x] Ctrl + b Backward one character
+* [x] Ctrl + xx Toggle between the start of line and current cursor position
+
+Editing
+-------
+
+* [x] Ctrl + L Clear the Screen, similar to the clear command
+* [x] Ctrl + d Delete character under the cursor
+* [x] Ctrl + h Delete character before the cursor (Backspace)
+
+* [x] Ctrl + w Cut the Word before the cursor to the clipboard.
+* [x] Ctrl + k Cut the Line after the cursor to the clipboard.
+* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard.
+
+* [ ] Ctrl + t Swap the last two characters before the cursor (typo).
+* [ ] Esc + t Swap the last two words before the cursor.
+
+* [ ] ctrl + y Paste the last thing to be cut (yank)
+* [ ] ctrl + _ Undo
+
+*/
+
+var emacsKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: ControlE,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+ },
+ },
+ // Go to the beginning of the line
+ {
+ Key: ControlA,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+ },
+ },
+ // Cut the Line after the cursor
+ {
+ Key: ControlK,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.Delete(len(x))
+ },
+ },
+ // Cut/delete the Line before the cursor
+ {
+ Key: ControlU,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.DeleteBeforeCursor(len(x))
+ },
+ },
+ // Delete character under the cursor
+ {
+ Key: ControlD,
+ Fn: func(buf *Buffer) {
+ if buf.Text() != "" {
+ buf.Delete(1)
+ }
+ },
+ },
+ // Backspace
+ {
+ Key: ControlH,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+ },
+ },
+ // Right allow: Forward one character
+ {
+ Key: ControlF,
+ Fn: func(buf *Buffer) {
+ buf.CursorRight(1)
+ },
+ },
+ // Left allow: Backward one character
+ {
+ Key: ControlB,
+ Fn: func(buf *Buffer) {
+ buf.CursorLeft(1)
+ },
+ },
+ // Cut the Word before the cursor.
+ {
+ Key: ControlW,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace())))
+ },
+ },
+ // Clear the Screen, similar to the clear command
+ {
+ Key: ControlL,
+ Fn: func(buf *Buffer) {
+ consoleWriter.EraseScreen()
+ consoleWriter.CursorGoTo(0, 0)
+ debug.AssertNoError(consoleWriter.Flush())
+ },
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/filter.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/filter.go
new file mode 100644
index 0000000000000000000000000000000000000000..61c17ed7f436a069563f520512bd25e4d81af0de
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/filter.go
@@ -0,0 +1,71 @@
+package prompt
+
+import "strings"
+
+// Filter is the type to filter the prompt.Suggestion array.
+type Filter func([]Suggest, string, bool) []Suggest
+
+// FilterHasPrefix checks whether the string completions.Text begins with sub.
+func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
+}
+
+// FilterHasSuffix checks whether the completion.Text ends with sub.
+func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
+}
+
+// FilterContains checks whether the completion.Text contains sub.
+func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
+}
+
+// FilterFuzzy checks whether the completion.Text fuzzy matches sub.
+// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
+// would match, for example, "Good food is gone"
+// ^ ^ ^
+func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
+}
+
+func fuzzyMatch(s, sub string) bool {
+ sChars := []rune(s)
+ sIdx := 0
+
+ // https://staticcheck.io/docs/checks#S1029
+ for _, c := range sub {
+ found := false
+ for ; sIdx < len(sChars); sIdx++ {
+ if sChars[sIdx] == c {
+ found = true
+ sIdx++
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
+
+func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
+ if sub == "" {
+ return suggestions
+ }
+ if ignoreCase {
+ sub = strings.ToUpper(sub)
+ }
+
+ ret := make([]Suggest, 0, len(suggestions))
+ for i := range suggestions {
+ c := suggestions[i].Text
+ if ignoreCase {
+ c = strings.ToUpper(c)
+ }
+ if function(c, sub) {
+ ret = append(ret, suggestions[i])
+ }
+ }
+ return ret
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/go.mod b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..30bc6d39a39c328341ca7153d3391352be5baa63
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/go.mod
@@ -0,0 +1,11 @@
+module github.com/c-bata/go-prompt
+
+go 1.14
+
+require (
+ github.com/mattn/go-colorable v0.1.7
+ github.com/mattn/go-runewidth v0.0.9
+ github.com/mattn/go-tty v0.0.3
+ github.com/pkg/term v1.2.0-beta.2
+ golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/go.sum b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..768bf93619a68e1b334c13e7b93ec84fa465598e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/go.sum
@@ -0,0 +1,23 @@
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/history.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/history.go
new file mode 100644
index 0000000000000000000000000000000000000000..e75c64592d82142bf4826ceb8c613ac72ca24d9c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/history.go
@@ -0,0 +1,61 @@
+package prompt
+
+// History stores the texts that are entered.
+type History struct {
+ histories []string
+ tmp []string
+ selected int
+}
+
+// Add to add text in history.
+func (h *History) Add(input string) {
+ h.histories = append(h.histories, input)
+ h.Clear()
+}
+
+// Clear to clear the history.
+func (h *History) Clear() {
+ h.tmp = make([]string, len(h.histories))
+ for i := range h.histories {
+ h.tmp[i] = h.histories[i]
+ }
+ h.tmp = append(h.tmp, "")
+ h.selected = len(h.tmp) - 1
+}
+
+// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
+ if len(h.tmp) == 1 || h.selected == 0 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected--
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
+ if h.selected >= len(h.tmp)-1 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected++
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// NewHistory returns new history object.
+func NewHistory() *History {
+ return &History{
+ histories: []string{},
+ tmp: []string{""},
+ selected: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/input.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/input.go
new file mode 100644
index 0000000000000000000000000000000000000000..307e747190c2b27bf888b379644fc4f3cdd489a2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/input.go
@@ -0,0 +1,169 @@
+package prompt
+
+import "bytes"
+
+// WinSize represents the width and height of terminal.
+type WinSize struct {
+ Row uint16
+ Col uint16
+}
+
+// ConsoleParser is an interface to abstract input layer.
+type ConsoleParser interface {
+ // Setup should be called before starting input
+ Setup() error
+ // TearDown should be called after stopping input
+ TearDown() error
+ // GetWinSize returns WinSize object to represent width and height of terminal.
+ GetWinSize() *WinSize
+ // Read returns byte array.
+ Read() ([]byte, error)
+}
+
+// GetKey returns Key correspond to input byte codes.
+func GetKey(b []byte) Key {
+ for _, k := range ASCIISequences {
+ if bytes.Equal(k.ASCIICode, b) {
+ return k.Key
+ }
+ }
+ return NotDefined
+}
+
+// ASCIISequences holds mappings of the key and byte array.
+var ASCIISequences = []*ASCIICode{
+ {Key: Escape, ASCIICode: []byte{0x1b}},
+
+ {Key: ControlSpace, ASCIICode: []byte{0x00}},
+ {Key: ControlA, ASCIICode: []byte{0x1}},
+ {Key: ControlB, ASCIICode: []byte{0x2}},
+ {Key: ControlC, ASCIICode: []byte{0x3}},
+ {Key: ControlD, ASCIICode: []byte{0x4}},
+ {Key: ControlE, ASCIICode: []byte{0x5}},
+ {Key: ControlF, ASCIICode: []byte{0x6}},
+ {Key: ControlG, ASCIICode: []byte{0x7}},
+ {Key: ControlH, ASCIICode: []byte{0x8}},
+ //{Key: ControlI, ASCIICode: []byte{0x9}},
+ //{Key: ControlJ, ASCIICode: []byte{0xa}},
+ {Key: ControlK, ASCIICode: []byte{0xb}},
+ {Key: ControlL, ASCIICode: []byte{0xc}},
+ {Key: ControlM, ASCIICode: []byte{0xd}},
+ {Key: ControlN, ASCIICode: []byte{0xe}},
+ {Key: ControlO, ASCIICode: []byte{0xf}},
+ {Key: ControlP, ASCIICode: []byte{0x10}},
+ {Key: ControlQ, ASCIICode: []byte{0x11}},
+ {Key: ControlR, ASCIICode: []byte{0x12}},
+ {Key: ControlS, ASCIICode: []byte{0x13}},
+ {Key: ControlT, ASCIICode: []byte{0x14}},
+ {Key: ControlU, ASCIICode: []byte{0x15}},
+ {Key: ControlV, ASCIICode: []byte{0x16}},
+ {Key: ControlW, ASCIICode: []byte{0x17}},
+ {Key: ControlX, ASCIICode: []byte{0x18}},
+ {Key: ControlY, ASCIICode: []byte{0x19}},
+ {Key: ControlZ, ASCIICode: []byte{0x1a}},
+
+ {Key: ControlBackslash, ASCIICode: []byte{0x1c}},
+ {Key: ControlSquareClose, ASCIICode: []byte{0x1d}},
+ {Key: ControlCircumflex, ASCIICode: []byte{0x1e}},
+ {Key: ControlUnderscore, ASCIICode: []byte{0x1f}},
+ {Key: Backspace, ASCIICode: []byte{0x7f}},
+
+ {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}},
+
+ {Key: Enter, ASCIICode: []byte{0xa}},
+ {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}},
+ {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+ {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}},
+ {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}},
+ {Key: Tab, ASCIICode: []byte{0x9}},
+ {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}},
+ {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}},
+ {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}},
+ {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}},
+ {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode
+
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}},
+ {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}},
+ {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}},
+ {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}},
+ {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}},
+ {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}},
+ {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}},
+ {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}},
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}},
+ {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}},
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+
+ // Xterm
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}},
+ // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}},
+ {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}},
+ {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}},
+ {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}},
+ {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}},
+
+ {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}},
+ {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}},
+ {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}},
+ {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}},
+
+ // Tmux sends following keystrokes when control+arrow is pressed, but for
+ // Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ // it a normal arrow press, because that's more important.
+ {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}},
+
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt
+
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/input_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/input_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f10430318be0e797c841eba8e08ab1cf5277be27
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/input_posix.go
@@ -0,0 +1,77 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/term"
+ "golang.org/x/sys/unix"
+)
+
+const maxReadBytes = 1024
+
+// PosixParser is a ConsoleParser implementation for POSIX environment.
+type PosixParser struct {
+ fd int
+ origTermios syscall.Termios
+}
+
+// Setup should be called before starting input
+func (t *PosixParser) Setup() error {
+ // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
+ if err := syscall.SetNonblock(t.fd, true); err != nil {
+ return err
+ }
+ if err := term.SetRaw(t.fd); err != nil {
+ return err
+ }
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (t *PosixParser) TearDown() error {
+ if err := syscall.SetNonblock(t.fd, false); err != nil {
+ return err
+ }
+ if err := term.Restore(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Read returns byte array.
+func (t *PosixParser) Read() ([]byte, error) {
+ buf := make([]byte, maxReadBytes)
+ n, err := syscall.Read(t.fd, buf)
+ if err != nil {
+ return []byte{}, err
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (t *PosixParser) GetWinSize() *WinSize {
+ ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: ws.Row,
+ Col: ws.Col,
+ }
+}
+
+var _ ConsoleParser = &PosixParser{}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *PosixParser {
+ in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ return &PosixParser{
+ fd: in,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/input_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/input_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..11b7679d4c4bc8b924a5b6c863ca1f6d6880570d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/input_windows.go
@@ -0,0 +1,83 @@
+// +build windows
+
+package prompt
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf8"
+ "unsafe"
+
+ tty "github.com/mattn/go-tty"
+)
+
+const maxReadBytes = 1024
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
+
+// WindowsParser is a ConsoleParser implementation for Win32 console.
+type WindowsParser struct {
+ tty *tty.TTY
+}
+
+// Setup should be called before starting input
+func (p *WindowsParser) Setup() error {
+ t, err := tty.Open()
+ if err != nil {
+ return err
+ }
+ p.tty = t
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (p *WindowsParser) TearDown() error {
+ return p.tty.Close()
+}
+
+// Read returns byte array.
+func (p *WindowsParser) Read() ([]byte, error) {
+ var ev uint32
+ r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
+ if r0 == 0 {
+ return nil, err
+ }
+ if ev == 0 {
+ return nil, errors.New("EAGAIN")
+ }
+
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, maxReadBytes)
+ n := utf8.EncodeRune(buf[:], r)
+ for p.tty.Buffered() && n < maxReadBytes {
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ break
+ }
+ n += utf8.EncodeRune(buf[n:], r)
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (p *WindowsParser) GetWinSize() *WinSize {
+ w, h, err := p.tty.Size()
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: uint16(h),
+ Col: uint16(w),
+ }
+}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *WindowsParser {
+ return &WindowsParser{}
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/bisect/bisect.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/bisect/bisect.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe162fa8c4873302e25702081b629a445d43415
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/bisect/bisect.go
@@ -0,0 +1,15 @@
+package bisect
+
+import "sort"
+
+// Right to locate the insertion point for v in a to maintain sorted order.
+func Right(a []int, v int) int {
+ return bisectRightRange(a, v, 0, len(a))
+}
+
+func bisectRightRange(a []int, v int, lo, hi int) int {
+ s := a[lo:hi]
+ return sort.Search(len(s), func(i int) bool {
+ return s[i] > v
+ })
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/debug/assert.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/debug/assert.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f648ac93c44e1e021cdf581a68f03b548534d9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/debug/assert.go
@@ -0,0 +1,55 @@
+package debug
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
+)
+
+var (
+ enableAssert bool
+)
+
+func init() {
+ if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
+ enableAssert = true
+ }
+}
+
+// Assert ensures expected condition.
+func Assert(cond bool, msg interface{}) {
+ if cond {
+ return
+ }
+ if enableAssert {
+ panic(msg)
+ }
+ writeWithSync(2, "[ASSERT] "+toString(msg))
+}
+
+func toString(v interface{}) string {
+ switch a := v.(type) {
+ case func() string:
+ return a()
+ case string:
+ return a
+ case fmt.Stringer:
+ return a.String()
+ default:
+ return fmt.Sprintf("unexpected type, %t", v)
+ }
+}
+
+// AssertNoError ensures err is nil.
+func AssertNoError(err error) {
+ if err == nil {
+ return
+ }
+ if enableAssert {
+ panic(err)
+ }
+ writeWithSync(2, "[ASSERT] "+err.Error())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/debug/log.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/debug/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..516378627a34ead9063ab7ce6c445b23c77b7cb4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/debug/log.go
@@ -0,0 +1,52 @@
+package debug
+
+import (
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+const (
+ envEnableLog = "GO_PROMPT_ENABLE_LOG"
+ logFileName = "go-prompt.log"
+)
+
+var (
+ logfile *os.File
+ logger *log.Logger
+)
+
+func init() {
+ if e := os.Getenv(envEnableLog); e == "true" || e == "1" {
+ var err error
+ logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
+ if err == nil {
+ logger = log.New(logfile, "", log.Llongfile)
+ return
+ }
+ }
+ logger = log.New(ioutil.Discard, "", log.Llongfile)
+}
+
+// Teardown to close logfile
+func Teardown() {
+ if logfile == nil {
+ return
+ }
+ _ = logfile.Close()
+}
+
+func writeWithSync(calldepth int, msg string) {
+ calldepth++
+ if logfile == nil {
+ return
+ }
+ _ = logger.Output(calldepth, msg)
+ _ = logfile.Sync() // immediately write msg
+}
+
+// Log to output message
+func Log(msg string) {
+ calldepth := 2
+ writeWithSync(calldepth, msg)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/strings/strings.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/strings/strings.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7d1886ae03a7d541c66dffca921e2d040e6d5eb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/strings/strings.go
@@ -0,0 +1,102 @@
+package strings
+
+import "unicode/utf8"
+
+// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior.
+func IndexNotByte(s string, c byte) int {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior.
+func LastIndexNotByte(s string, c byte) int {
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+type asciiSet [8]uint32
+
+func (as *asciiSet) notContains(c byte) bool {
+ return (as[c>>5] & (1 << uint(c&31))) == 0
+}
+
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c>>5] |= 1 << uint(c&31)
+ }
+ return as, true
+}
+
+// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior.
+func IndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := 0; i < len(s); i++ {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+
+ LabelFirstLoop:
+ for i, c := range s {
+ for j, m := range chars {
+ if c != m && j == len(chars)-1 {
+ return i
+ } else if c != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior.
+func LastIndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ LabelFirstLoop:
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRuneInString(s[:i])
+ i -= size
+ for j, m := range chars {
+ if r != m && j == len(chars)-1 {
+ return i
+ } else if r != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/term/raw.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/term/raw.go
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3ed8d04023558cf386a98080815d661248b85
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/term/raw.go
@@ -0,0 +1,29 @@
+// +build !windows
+
+package term
+
+import (
+ "syscall"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+// SetRaw put terminal into a raw mode
+func SetRaw(fd int) error {
+ n, err := getOriginalTermios(fd)
+ if err != nil {
+ return err
+ }
+
+ n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK |
+ syscall.ISTRIP | syscall.INLCR | syscall.IGNCR |
+ syscall.ICRNL | syscall.IXON
+ n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL
+ n.Cflag &^= syscall.CSIZE | syscall.PARENB
+ n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters.
+ n.Cc[syscall.VMIN] = 1
+ n.Cc[syscall.VTIME] = 0
+
+ return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n))
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/term/term.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/term/term.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a53c059ae60c0348ec01689babef4b13a2ecd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/internal/term/term.go
@@ -0,0 +1,34 @@
+// +build !windows
+
+package term
+
+import (
+ "sync"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ saveTermios *unix.Termios
+ saveTermiosFD int
+ saveTermiosOnce sync.Once
+)
+
+func getOriginalTermios(fd int) (*unix.Termios, error) {
+ var err error
+ saveTermiosOnce.Do(func() {
+ saveTermiosFD = fd
+ saveTermios, err = termios.Tcgetattr(uintptr(fd))
+ })
+ return saveTermios, err
+}
+
+// Restore terminal's mode.
+func Restore() error {
+ o, err := getOriginalTermios(saveTermiosFD)
+ if err != nil {
+ return err
+ }
+ return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/key.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ba569c2dd20a8ae3b3dd79ff3695bf0b6c1bd09
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/key.go
@@ -0,0 +1,128 @@
+// Code generated by hand; DO NOT EDIT.
+// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment.
+
+package prompt
+
+// Key is the type express the key inserted from user.
+//go:generate stringer -type=Key
+type Key int
+
+// ASCIICode is the type contains Key and it's ascii byte array.
+type ASCIICode struct {
+ Key Key
+ ASCIICode []byte
+}
+
+const (
+ Escape Key = iota
+
+ ControlA
+ ControlB
+ ControlC
+ ControlD
+ ControlE
+ ControlF
+ ControlG
+ ControlH
+ ControlI
+ ControlJ
+ ControlK
+ ControlL
+ ControlM
+ ControlN
+ ControlO
+ ControlP
+ ControlQ
+ ControlR
+ ControlS
+ ControlT
+ ControlU
+ ControlV
+ ControlW
+ ControlX
+ ControlY
+ ControlZ
+
+ ControlSpace
+ ControlBackslash
+ ControlSquareClose
+ ControlCircumflex
+ ControlUnderscore
+ ControlLeft
+ ControlRight
+ ControlUp
+ ControlDown
+
+ Up
+ Down
+ Right
+ Left
+
+ ShiftLeft
+ ShiftUp
+ ShiftDown
+ ShiftRight
+
+ Home
+ End
+ Delete
+ ShiftDelete
+ ControlDelete
+ PageUp
+ PageDown
+ BackTab
+ Insert
+ Backspace
+
+ // Aliases.
+ Tab
+ Enter
+ // Actually Enter equals ControlM, not ControlJ,
+ // However, in prompt_toolkit, we made the mistake of translating
+ // \r into \n during the input, so everyone is now handling the
+ // enter key by binding ControlJ.
+
+ // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere,
+ // because that's future compatible, and will still work when we
+ // stop replacing \r by \n.
+
+ F1
+ F2
+ F3
+ F4
+ F5
+ F6
+ F7
+ F8
+ F9
+ F10
+ F11
+ F12
+ F13
+ F14
+ F15
+ F16
+ F17
+ F18
+ F19
+ F20
+ F21
+ F22
+ F23
+ F24
+
+ // Matches any key.
+ Any
+
+ // Special
+ CPRResponse
+ Vt100MouseEvent
+ WindowsMouseEvent
+ BracketedPaste
+
+ // Key which is ignored. (The key binding for this key should not do anything.)
+ Ignore
+
+ // Key is not defined
+ NotDefined
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/key_bind.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/key_bind.go
new file mode 100644
index 0000000000000000000000000000000000000000..42669e7f942efc4d92f896388daede90b96b55dd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/key_bind.go
@@ -0,0 +1,59 @@
+package prompt
+
+// KeyBindFunc receives buffer and processed it.
+type KeyBindFunc func(*Buffer)
+
+// KeyBind represents which key should do what operation.
+type KeyBind struct {
+ Key Key
+ Fn KeyBindFunc
+}
+
+// ASCIICodeBind represents which []byte should do what operation
+type ASCIICodeBind struct {
+ ASCIICode []byte
+ Fn KeyBindFunc
+}
+
+// KeyBindMode to switch a key binding flexibly.
+type KeyBindMode string
+
+const (
+ // CommonKeyBind is a mode without any keyboard shortcut
+ CommonKeyBind KeyBindMode = "common"
+ // EmacsKeyBind is a mode to use emacs-like keyboard shortcut
+ EmacsKeyBind KeyBindMode = "emacs"
+)
+
+var commonKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: End,
+ Fn: GoLineEnd,
+ },
+ // Go to the beginning of the line
+ {
+ Key: Home,
+ Fn: GoLineBeginning,
+ },
+ // Delete character under the cursor
+ {
+ Key: Delete,
+ Fn: DeleteChar,
+ },
+ // Backspace
+ {
+ Key: Backspace,
+ Fn: DeleteBeforeChar,
+ },
+ // Right allow: Forward one character
+ {
+ Key: Right,
+ Fn: GoRightChar,
+ },
+ // Left allow: Backward one character
+ {
+ Key: Left,
+ Fn: GoLeftChar,
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/key_bind_func.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/key_bind_func.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b2ecdf63179dbfdbcb0d71bfa436bb36d62d230
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/key_bind_func.go
@@ -0,0 +1,48 @@
+package prompt
+
+// GoLineEnd Go to the End of the line
+func GoLineEnd(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+}
+
+// GoLineBeginning Go to the beginning of the line
+func GoLineBeginning(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+}
+
+// DeleteChar Delete character under the cursor
+func DeleteChar(buf *Buffer) {
+ buf.Delete(1)
+}
+
+// DeleteWord Delete word before the cursor
+func DeleteWord(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
+
+// DeleteBeforeChar Go to Backspace
+func DeleteBeforeChar(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+}
+
+// GoRightChar Forward one character
+func GoRightChar(buf *Buffer) {
+ buf.CursorRight(1)
+}
+
+// GoLeftChar Backward one character
+func GoLeftChar(buf *Buffer) {
+ buf.CursorLeft(1)
+}
+
+// GoRightWord Forward one word
+func GoRightWord(buf *Buffer) {
+ buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
+}
+
+// GoLeftWord Backward one word
+func GoLeftWord(buf *Buffer) {
+ buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/key_string.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/key_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..fce6ea31c502b3e763451cb47757ae1b49c32814
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/key_string.go
@@ -0,0 +1,16 @@
+// Code generated by "stringer -type=Key"; DO NOT EDIT.
+
+package prompt
+
+import "strconv"
+
+const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined"
+
+var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607}
+
+func (i Key) String() string {
+ if i < 0 || i >= Key(len(_Key_index)-1) {
+ return "Key(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _Key_name[_Key_index[i]:_Key_index[i+1]]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/option.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/option.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd6806cc1dbccf8c4ddb048080fde615c59088
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/option.go
@@ -0,0 +1,310 @@
+package prompt
+
+// Option is the type to replace default parameters.
+// prompt.New accepts any number of options (this is functional option pattern).
+type Option func(prompt *Prompt) error
+
+// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
+func OptionParser(x ConsoleParser) Option {
+ return func(p *Prompt) error {
+ p.in = x
+ return nil
+ }
+}
+
+// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
+func OptionWriter(x ConsoleWriter) Option {
+ return func(p *Prompt) error {
+ registerConsoleWriter(x)
+ p.renderer.out = x
+ return nil
+ }
+}
+
+// OptionTitle to set title displayed at the header bar of terminal.
+func OptionTitle(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.title = x
+ return nil
+ }
+}
+
+// OptionPrefix to set prefix string.
+func OptionPrefix(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefix = x
+ return nil
+ }
+}
+
+// OptionInitialBufferText to set the initial buffer text
+func OptionInitialBufferText(x string) Option {
+ return func(p *Prompt) error {
+ p.buf.InsertText(x, false, true)
+ return nil
+ }
+}
+
+// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
+func OptionCompletionWordSeparator(x string) Option {
+ return func(p *Prompt) error {
+ p.completion.wordSeparator = x
+ return nil
+ }
+}
+
+// OptionLivePrefix to change the prefix dynamically by callback function
+func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
+ return func(p *Prompt) error {
+ p.renderer.livePrefixCallback = f
+ return nil
+ }
+}
+
+// OptionPrefixTextColor change a text color of prefix string
+func OptionPrefixTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixTextColor = x
+ return nil
+ }
+}
+
+// OptionPrefixBackgroundColor to change a background color of prefix string
+func OptionPrefixBackgroundColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixBGColor = x
+ return nil
+ }
+}
+
+// OptionInputTextColor to change a color of text which is input by user
+func OptionInputTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputTextColor = x
+ return nil
+ }
+}
+
+// OptionInputBGColor to change a color of background which is input by user
+func OptionInputBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputBGColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionTextColor to change a text color which is completed
+func OptionPreviewSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionBGColor to change a background color which is completed
+func OptionPreviewSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionTextColor to change a text color in drop down suggestions.
+func OptionSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionBGColor change a background color in drop down suggestions.
+func OptionSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarThumbColor to change a thumb color on scrollbar.
+func OptionScrollbarThumbColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarThumbColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarBGColor to change a background color of scrollbar.
+func OptionScrollbarBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarBGColor = x
+ return nil
+ }
+}
+
+// OptionMaxSuggestion specify the max number of displayed suggestions.
+func OptionMaxSuggestion(x uint16) Option {
+ return func(p *Prompt) error {
+ p.completion.max = x
+ return nil
+ }
+}
+
+// OptionHistory to set history expressed by string array.
+func OptionHistory(x []string) Option {
+ return func(p *Prompt) error {
+ p.history.histories = x
+ p.history.Clear()
+ return nil
+ }
+}
+
+// OptionSwitchKeyBindMode set a key bind mode.
+func OptionSwitchKeyBindMode(m KeyBindMode) Option {
+ return func(p *Prompt) error {
+ p.keyBindMode = m
+ return nil
+ }
+}
+
+// OptionCompletionOnDown allows for Down arrow key to trigger completion.
+func OptionCompletionOnDown() Option {
+ return func(p *Prompt) error {
+ p.completionOnDown = true
+ return nil
+ }
+}
+
+// SwitchKeyBindMode to set a key bind mode.
+// Deprecated: Please use OptionSwitchKeyBindMode.
+var SwitchKeyBindMode = OptionSwitchKeyBindMode
+
+// OptionAddKeyBind to set a custom key bind.
+func OptionAddKeyBind(b ...KeyBind) Option {
+ return func(p *Prompt) error {
+ p.keyBindings = append(p.keyBindings, b...)
+ return nil
+ }
+}
+
+// OptionAddASCIICodeBind to set a custom key bind.
+func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option {
+ return func(p *Prompt) error {
+ p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...)
+ return nil
+ }
+}
+
+// OptionShowCompletionAtStart to set completion window is open at start.
+func OptionShowCompletionAtStart() Option {
+ return func(p *Prompt) error {
+ p.completion.showAtStart = true
+ return nil
+ }
+}
+
+// OptionBreakLineCallback to run a callback at every break line
+func OptionBreakLineCallback(fn func(*Document)) Option {
+ return func(p *Prompt) error {
+ p.renderer.breakLineCallback = fn
+ return nil
+ }
+}
+
+// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop
+func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
+ return func(p *Prompt) error {
+ p.exitChecker = fn
+ return nil
+ }
+}
+
+// New returns a Prompt with powerful auto-completion.
+func New(executor Executor, completer Completer, opts ...Option) *Prompt {
+ defaultWriter := NewStdoutWriter()
+ registerConsoleWriter(defaultWriter)
+
+ pt := &Prompt{
+ in: NewStandardInputParser(),
+ renderer: &Render{
+ prefix: "> ",
+ out: defaultWriter,
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ },
+ buf: NewBuffer(),
+ executor: executor,
+ history: NewHistory(),
+ completion: NewCompletionManager(completer, 6),
+ keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting
+ }
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/output.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/output.go
new file mode 100644
index 0000000000000000000000000000000000000000..42531b412f1ed027c2fff5b85bc273e53e569b3a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/output.go
@@ -0,0 +1,161 @@
+package prompt
+
+import "sync"
+
+var (
+ consoleWriterMu sync.Mutex
+ consoleWriter ConsoleWriter
+)
+
+func registerConsoleWriter(f ConsoleWriter) {
+ consoleWriterMu.Lock()
+ defer consoleWriterMu.Unlock()
+ consoleWriter = f
+}
+
+// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on.
+type DisplayAttribute int
+
+const (
+ // DisplayReset reset all display attributes.
+ DisplayReset DisplayAttribute = iota
+ // DisplayBold set bold or increases intensity.
+ DisplayBold
+ // DisplayLowIntensity decreases intensity. Not widely supported.
+ DisplayLowIntensity
+ // DisplayItalic set italic. Not widely supported.
+ DisplayItalic
+ // DisplayUnderline set underline
+ DisplayUnderline
+ // DisplayBlink set blink (less than 150 per minute).
+ DisplayBlink
+ // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported.
+ DisplayRapidBlink
+ // DisplayReverse swap foreground and background colors.
+ DisplayReverse
+ // DisplayInvisible set invisible. Not widely supported.
+ DisplayInvisible
+ // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported.
+ DisplayCrossedOut
+ // DisplayDefaultFont set primary(default) font
+ DisplayDefaultFont
+)
+
+// Color represents color on terminal.
+type Color int
+
+const (
+ // DefaultColor represents a default color.
+ DefaultColor Color = iota
+
+ // Low intensity
+
+ // Black represents a black.
+ Black
+ // DarkRed represents a dark red.
+ DarkRed
+ // DarkGreen represents a dark green.
+ DarkGreen
+ // Brown represents a brown.
+ Brown
+ // DarkBlue represents a dark blue.
+ DarkBlue
+ // Purple represents a purple.
+ Purple
+ // Cyan represents a cyan.
+ Cyan
+ // LightGray represents a light gray.
+ LightGray
+
+ // High intensity
+
+ // DarkGray represents a dark gray.
+ DarkGray
+ // Red represents a red.
+ Red
+ // Green represents a green.
+ Green
+ // Yellow represents a yellow.
+ Yellow
+ // Blue represents a blue.
+ Blue
+ // Fuchsia represents a fuchsia.
+ Fuchsia
+ // Turquoise represents a turquoise.
+ Turquoise
+ // White represents a white.
+ White
+)
+
+// ConsoleWriter is an interface to abstract output layer.
+type ConsoleWriter interface {
+ /* Write */
+
+ // WriteRaw to write raw byte array.
+ WriteRaw(data []byte)
+ // Write to write safety byte array by removing control sequences.
+ Write(data []byte)
+ // WriteStr to write raw string.
+ WriteRawStr(data string)
+ // WriteStr to write safety string by removing control sequences.
+ WriteStr(data string)
+ // Flush to flush buffer.
+ Flush() error
+
+ /* Erasing */
+
+ // EraseScreen erases the screen with the background colour and moves the cursor to home.
+ EraseScreen()
+ // EraseUp erases the screen from the current line up to the top of the screen.
+ EraseUp()
+ // EraseDown erases the screen from the current line down to the bottom of the screen.
+ EraseDown()
+ // EraseStartOfLine erases from the current cursor position to the start of the current line.
+ EraseStartOfLine()
+ // EraseEndOfLine erases from the current cursor position to the end of the current line.
+ EraseEndOfLine()
+ // EraseLine erases the entire current line.
+ EraseLine()
+
+ /* Cursor */
+
+ // ShowCursor stops blinking cursor and show.
+ ShowCursor()
+ // HideCursor hides cursor.
+ HideCursor()
+ // CursorGoTo sets the cursor position where subsequent text will begin.
+ CursorGoTo(row, col int)
+ // CursorUp moves the cursor up by 'n' rows; the default count is 1.
+ CursorUp(n int)
+ // CursorDown moves the cursor down by 'n' rows; the default count is 1.
+ CursorDown(n int)
+ // CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+ CursorForward(n int)
+ // CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+ CursorBackward(n int)
+ // AskForCPR asks for a cursor position report (CPR).
+ AskForCPR()
+ // SaveCursor saves current cursor position.
+ SaveCursor()
+ // UnSaveCursor restores cursor position after a Save Cursor.
+ UnSaveCursor()
+
+ /* Scrolling */
+
+ // ScrollDown scrolls display down one line.
+ ScrollDown()
+ // ScrollUp scroll display up one line.
+ ScrollUp()
+
+ /* Title */
+
+ // SetTitle sets a title of terminal window.
+ SetTitle(title string)
+ // ClearTitle clears a title of terminal window.
+ ClearTitle()
+
+ /* Font */
+
+ // SetColor sets text and background colors. and specify whether text is bold.
+ SetColor(fg, bg Color, bold bool)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/output_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/output_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..26c770cc152a7b126be43915d60b8ba000ad0e38
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/output_posix.go
@@ -0,0 +1,67 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+)
+
+const flushMaxRetryCount = 3
+
+// PosixWriter is a ConsoleWriter implementation for POSIX environment.
+// To control terminal emulator, this outputs VT100 escape sequences.
+type PosixWriter struct {
+ VT100Writer
+ fd int
+}
+
+// Flush to flush buffer
+func (w *PosixWriter) Flush() error {
+ l := len(w.buffer)
+ offset := 0
+ retry := 0
+ for {
+ n, err := syscall.Write(w.fd, w.buffer[offset:])
+ if err != nil {
+ if retry < flushMaxRetryCount {
+ retry++
+ continue
+ }
+ return err
+ }
+ offset += n
+ if offset == l {
+ break
+ }
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &PosixWriter{}
+
+var (
+ // NewStandardOutputWriter returns ConsoleWriter object to write to stdout.
+ // This generates VT100 escape sequences because almost terminal emulators
+ // in POSIX OS built on top of a VT100 specification.
+ // Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStdoutWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stdout,
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStderrWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stderr,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/output_vt100.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/output_vt100.go
new file mode 100644
index 0000000000000000000000000000000000000000..20850fead883c4cd9802928b5de3f935fbbeb047
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/output_vt100.go
@@ -0,0 +1,310 @@
+package prompt
+
+import (
+ "bytes"
+ "strconv"
+)
+
+// VT100Writer generates VT100 escape sequences.
+type VT100Writer struct {
+ buffer []byte
+}
+
+// WriteRaw to write raw byte array
+func (w *VT100Writer) WriteRaw(data []byte) {
+ w.buffer = append(w.buffer, data...)
+}
+
+// Write to write safety byte array by removing control sequences.
+func (w *VT100Writer) Write(data []byte) {
+ w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1))
+}
+
+// WriteRawStr to write raw string
+func (w *VT100Writer) WriteRawStr(data string) {
+ w.WriteRaw([]byte(data))
+}
+
+// WriteStr to write safety string by removing control sequences.
+func (w *VT100Writer) WriteStr(data string) {
+ w.Write([]byte(data))
+}
+
+/* Erase */
+
+// EraseScreen erases the screen with the background colour and moves the cursor to home.
+func (w *VT100Writer) EraseScreen() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'J'})
+}
+
+// EraseUp erases the screen from the current line up to the top of the screen.
+func (w *VT100Writer) EraseUp() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'J'})
+}
+
+// EraseDown erases the screen from the current line down to the bottom of the screen.
+func (w *VT100Writer) EraseDown() {
+ w.WriteRaw([]byte{0x1b, '[', 'J'})
+}
+
+// EraseStartOfLine erases from the current cursor position to the start of the current line.
+func (w *VT100Writer) EraseStartOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'K'})
+}
+
+// EraseEndOfLine erases from the current cursor position to the end of the current line.
+func (w *VT100Writer) EraseEndOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', 'K'})
+}
+
+// EraseLine erases the entire current line.
+func (w *VT100Writer) EraseLine() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'K'})
+}
+
+/* Cursor */
+
+// ShowCursor stops blinking cursor and show.
+func (w *VT100Writer) ShowCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'})
+}
+
+// HideCursor hides cursor.
+func (w *VT100Writer) HideCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'})
+}
+
+// CursorGoTo sets the cursor position where subsequent text will begin.
+func (w *VT100Writer) CursorGoTo(row, col int) {
+ if row == 0 && col == 0 {
+ // If no row/column parameters are provided (ie. [H), the cursor will move to the home position.
+ w.WriteRaw([]byte{0x1b, '[', 'H'})
+ return
+ }
+ r := strconv.Itoa(row)
+ c := strconv.Itoa(col)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(r))
+ w.WriteRaw([]byte{';'})
+ w.WriteRaw([]byte(c))
+ w.WriteRaw([]byte{'H'})
+}
+
+// CursorUp moves the cursor up by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorUp(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorDown(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'A'})
+}
+
+// CursorDown moves the cursor down by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorDown(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorUp(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'B'})
+}
+
+// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorForward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorBackward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'C'})
+}
+
+// CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorBackward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorForward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'D'})
+}
+
+// AskForCPR asks for a cursor position report (CPR).
+func (w *VT100Writer) AskForCPR() {
+ // CPR: Cursor Position Request.
+ w.WriteRaw([]byte{0x1b, '[', '6', 'n'})
+}
+
+// SaveCursor saves current cursor position.
+func (w *VT100Writer) SaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 's'})
+}
+
+// UnSaveCursor restores cursor position after a Save Cursor.
+func (w *VT100Writer) UnSaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 'u'})
+}
+
+/* Scrolling */
+
+// ScrollDown scrolls display down one line.
+func (w *VT100Writer) ScrollDown() {
+ w.WriteRaw([]byte{0x1b, 'D'})
+}
+
+// ScrollUp scroll display up one line.
+func (w *VT100Writer) ScrollUp() {
+ w.WriteRaw([]byte{0x1b, 'M'})
+}
+
+/* Title */
+
+// SetTitle sets a title of terminal window.
+func (w *VT100Writer) SetTitle(title string) {
+ titleBytes := []byte(title)
+ patterns := []struct {
+ from []byte
+ to []byte
+ }{
+ {
+ from: []byte{0x13},
+ to: []byte{},
+ },
+ {
+ from: []byte{0x07},
+ to: []byte{},
+ },
+ }
+ for i := range patterns {
+ titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1)
+ }
+
+ w.WriteRaw([]byte{0x1b, ']', '2', ';'})
+ w.WriteRaw(titleBytes)
+ w.WriteRaw([]byte{0x07})
+}
+
+// ClearTitle clears a title of terminal window.
+func (w *VT100Writer) ClearTitle() {
+ w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07})
+}
+
+/* Font */
+
+// SetColor sets text and background colors. and specify whether text is bold.
+func (w *VT100Writer) SetColor(fg, bg Color, bold bool) {
+ if bold {
+ w.SetDisplayAttributes(fg, bg, DisplayBold)
+ } else {
+ // If using `DisplayDefualt`, it will be broken in some environment.
+ // Details are https://github.com/c-bata/go-prompt/pull/85
+ w.SetDisplayAttributes(fg, bg, DisplayReset)
+ }
+}
+
+// SetDisplayAttributes to set VT100 display attributes.
+func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) {
+ w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer
+ defer w.WriteRaw([]byte{'m'}) // final character
+
+ var separator byte = ';'
+ for i := range attrs {
+ p, ok := displayAttributeParameters[attrs[i]]
+ if !ok {
+ continue
+ }
+ w.WriteRaw(p)
+ w.WriteRaw([]byte{separator})
+ }
+
+ f, ok := foregroundANSIColors[fg]
+ if !ok {
+ f = foregroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(f)
+ w.WriteRaw([]byte{separator})
+ b, ok := backgroundANSIColors[bg]
+ if !ok {
+ b = backgroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(b)
+}
+
+var displayAttributeParameters = map[DisplayAttribute][]byte{
+ DisplayReset: {'0'},
+ DisplayBold: {'1'},
+ DisplayLowIntensity: {'2'},
+ DisplayItalic: {'3'},
+ DisplayUnderline: {'4'},
+ DisplayBlink: {'5'},
+ DisplayRapidBlink: {'6'},
+ DisplayReverse: {'7'},
+ DisplayInvisible: {'8'},
+ DisplayCrossedOut: {'9'},
+ DisplayDefaultFont: {'1', '0'},
+}
+
+var foregroundANSIColors = map[Color][]byte{
+ DefaultColor: {'3', '9'},
+
+ // Low intensity.
+ Black: {'3', '0'},
+ DarkRed: {'3', '1'},
+ DarkGreen: {'3', '2'},
+ Brown: {'3', '3'},
+ DarkBlue: {'3', '4'},
+ Purple: {'3', '5'},
+ Cyan: {'3', '6'},
+ LightGray: {'3', '7'},
+
+ // High intensity.
+ DarkGray: {'9', '0'},
+ Red: {'9', '1'},
+ Green: {'9', '2'},
+ Yellow: {'9', '3'},
+ Blue: {'9', '4'},
+ Fuchsia: {'9', '5'},
+ Turquoise: {'9', '6'},
+ White: {'9', '7'},
+}
+
+var backgroundANSIColors = map[Color][]byte{
+ DefaultColor: {'4', '9'},
+
+ // Low intensity.
+ Black: {'4', '0'},
+ DarkRed: {'4', '1'},
+ DarkGreen: {'4', '2'},
+ Brown: {'4', '3'},
+ DarkBlue: {'4', '4'},
+ Purple: {'4', '5'},
+ Cyan: {'4', '6'},
+ LightGray: {'4', '7'},
+
+ // High intensity
+ DarkGray: {'1', '0', '0'},
+ Red: {'1', '0', '1'},
+ Green: {'1', '0', '2'},
+ Yellow: {'1', '0', '3'},
+ Blue: {'1', '0', '4'},
+ Fuchsia: {'1', '0', '5'},
+ Turquoise: {'1', '0', '6'},
+ White: {'1', '0', '7'},
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/output_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/output_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b9c2769fc2d64cfcfcc5b99c915591ec625bd5f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/output_windows.go
@@ -0,0 +1,49 @@
+// +build windows
+
+package prompt
+
+import (
+ "io"
+
+ colorable "github.com/mattn/go-colorable"
+)
+
+// WindowsWriter is a ConsoleWriter implementation for Win32 console.
+// Output is converted from VT100 escape sequences by mattn/go-colorable.
+type WindowsWriter struct {
+ VT100Writer
+ out io.Writer
+}
+
+// Flush to flush buffer
+func (w *WindowsWriter) Flush() error {
+ _, err := w.out.Write(w.buffer)
+ if err != nil {
+ return err
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &WindowsWriter{}
+
+var (
+ // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates win32 control sequences.
+func NewStdoutWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStdout(),
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates win32 control sequences.
+func NewStderrWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStderr(),
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/prompt.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/prompt.go
new file mode 100644
index 0000000000000000000000000000000000000000..173cd517c40cde212433e399978641ceff1d1a43
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/prompt.go
@@ -0,0 +1,296 @@
+package prompt
+
+import (
+ "bytes"
+ "os"
+ "time"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Executor is called when user input something text.
+type Executor func(string)
+
+// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
+// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
+// - immediate exit (if breakline is false) without executor called
+// - exit after typing (meaning breakline is true), and the executor is called first, before exit.
+// Exit means exit go-prompt (not the overall Go program)
+type ExitChecker func(in string, breakline bool) bool
+
+// Completer should return the suggest item from Document.
+type Completer func(Document) []Suggest
+
+// Prompt is core struct of go-prompt.
+type Prompt struct {
+ in ConsoleParser
+ buf *Buffer
+ renderer *Render
+ executor Executor
+ history *History
+ completion *CompletionManager
+ keyBindings []KeyBind
+ ASCIICodeBindings []ASCIICodeBind
+ keyBindMode KeyBindMode
+ completionOnDown bool
+ exitChecker ExitChecker
+ skipTearDown bool
+}
+
+// Exec is the struct contains user input context.
+type Exec struct {
+ input string
+}
+
+// Run starts prompt.
+func (p *Prompt) Run() {
+ p.skipTearDown = false
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ exitCh := make(chan int)
+ winSizeCh := make(chan *WinSize)
+ stopHandleSignalCh := make(chan struct{})
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+ return
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+
+ // Unset raw mode
+ // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
+ debug.AssertNoError(p.in.TearDown())
+ p.executor(e.input)
+
+ p.completion.Update(*p.buf.Document())
+
+ p.renderer.Render(p.buf, p.completion)
+
+ if p.exitChecker != nil && p.exitChecker(e.input, true) {
+ p.skipTearDown = true
+ return
+ }
+ // Set raw mode
+ debug.AssertNoError(p.in.Setup())
+ go p.readBuffer(bufCh, stopReadBufCh)
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ case w := <-winSizeCh:
+ p.renderer.UpdateWinSize(w)
+ p.renderer.Render(p.buf, p.completion)
+ case code := <-exitCh:
+ p.renderer.BreakLine(p.buf)
+ p.tearDown()
+ os.Exit(code)
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
+ key := GetKey(b)
+ p.buf.lastKeyStroke = key
+ // completion
+ completing := p.completion.Completing()
+ p.handleCompletionKeyBinding(key, completing)
+
+ switch key {
+ case Enter, ControlJ, ControlM:
+ p.renderer.BreakLine(p.buf)
+
+ exec = &Exec{input: p.buf.Text()}
+ p.buf = NewBuffer()
+ if exec.input != "" {
+ p.history.Add(exec.input)
+ }
+ case ControlC:
+ p.renderer.BreakLine(p.buf)
+ p.buf = NewBuffer()
+ p.history.Clear()
+ case Up, ControlP:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Older(p.buf); changed {
+ p.buf = newBuf
+ }
+ }
+ case Down, ControlN:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Newer(p.buf); changed {
+ p.buf = newBuf
+ }
+ return
+ }
+ case ControlD:
+ if p.buf.Text() == "" {
+ shouldExit = true
+ return
+ }
+ case NotDefined:
+ if p.handleASCIICodeBinding(b) {
+ return
+ }
+ p.buf.InsertText(string(b), false, true)
+ }
+
+ shouldExit = p.handleKeyBinding(key)
+ return
+}
+
+func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
+ switch key {
+ case Down:
+ if completing || p.completionOnDown {
+ p.completion.Next()
+ }
+ case Tab, ControlI:
+ p.completion.Next()
+ case Up:
+ if completing {
+ p.completion.Previous()
+ }
+ case BackTab:
+ p.completion.Previous()
+ default:
+ if s, ok := p.completion.GetSelectedSuggestion(); ok {
+ w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
+ if w != "" {
+ p.buf.DeleteBeforeCursor(len([]rune(w)))
+ }
+ p.buf.InsertText(s.Text, false, true)
+ }
+ p.completion.Reset()
+ }
+}
+
+func (p *Prompt) handleKeyBinding(key Key) bool {
+ shouldExit := false
+ for i := range commonKeyBindings {
+ kb := commonKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+
+ if p.keyBindMode == EmacsKeyBind {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ }
+
+ // Custom key bindings
+ for i := range p.keyBindings {
+ kb := p.keyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
+ shouldExit = true
+ }
+ return shouldExit
+}
+
+func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
+ checked := false
+ for _, kb := range p.ASCIICodeBindings {
+ if bytes.Equal(kb.ASCIICode, b) {
+ kb.Fn(p.buf)
+ checked = true
+ }
+ }
+ return checked
+}
+
+// Input just returns user input text.
+func (p *Prompt) Input() string {
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ return ""
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ return e.input
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
+ debug.Log("start reading buffer")
+ for {
+ select {
+ case <-stopCh:
+ debug.Log("stop reading buffer")
+ return
+ default:
+ if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
+ bufCh <- b
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (p *Prompt) setUp() {
+ debug.AssertNoError(p.in.Setup())
+ p.renderer.Setup()
+ p.renderer.UpdateWinSize(p.in.GetWinSize())
+}
+
+func (p *Prompt) tearDown() {
+ if !p.skipTearDown {
+ debug.AssertNoError(p.in.TearDown())
+ }
+ p.renderer.TearDown()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/render.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/render.go
new file mode 100644
index 0000000000000000000000000000000000000000..299ac48b6254b9752ea16516aaedcd41acca6515
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/render.go
@@ -0,0 +1,287 @@
+package prompt
+
+import (
+ "runtime"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Render to render prompt information from state of Buffer.
+type Render struct {
+ out ConsoleWriter
+ prefix string
+ livePrefixCallback func() (prefix string, useLivePrefix bool)
+ breakLineCallback func(*Document)
+ title string
+ row uint16
+ col uint16
+
+ previousCursor int
+
+ // colors,
+ prefixTextColor Color
+ prefixBGColor Color
+ inputTextColor Color
+ inputBGColor Color
+ previewSuggestionTextColor Color
+ previewSuggestionBGColor Color
+ suggestionTextColor Color
+ suggestionBGColor Color
+ selectedSuggestionTextColor Color
+ selectedSuggestionBGColor Color
+ descriptionTextColor Color
+ descriptionBGColor Color
+ selectedDescriptionTextColor Color
+ selectedDescriptionBGColor Color
+ scrollbarThumbColor Color
+ scrollbarBGColor Color
+}
+
+// Setup to initialize console output.
+func (r *Render) Setup() {
+ if r.title != "" {
+ r.out.SetTitle(r.title)
+ debug.AssertNoError(r.out.Flush())
+ }
+}
+
+// getCurrentPrefix to get current prefix.
+// If live-prefix is enabled, return live-prefix.
+func (r *Render) getCurrentPrefix() string {
+ if prefix, ok := r.livePrefixCallback(); ok {
+ return prefix
+ }
+ return r.prefix
+}
+
+func (r *Render) renderPrefix() {
+ r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
+ r.out.WriteStr(r.getCurrentPrefix())
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// TearDown to clear title and erasing.
+func (r *Render) TearDown() {
+ r.out.ClearTitle()
+ r.out.EraseDown()
+ debug.AssertNoError(r.out.Flush())
+}
+
+func (r *Render) prepareArea(lines int) {
+ for i := 0; i < lines; i++ {
+ r.out.ScrollDown()
+ }
+ for i := 0; i < lines; i++ {
+ r.out.ScrollUp()
+ }
+}
+
+// UpdateWinSize called when window size is changed.
+func (r *Render) UpdateWinSize(ws *WinSize) {
+ r.row = ws.Row
+ r.col = ws.Col
+}
+
+func (r *Render) renderWindowTooSmall() {
+ r.out.CursorGoTo(0, 0)
+ r.out.EraseScreen()
+ r.out.SetColor(DarkRed, White, false)
+ r.out.WriteStr("Your console window is too small...")
+}
+
+func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) {
+ suggestions := completions.GetSuggestions()
+ if len(completions.GetSuggestions()) == 0 {
+ return
+ }
+ prefix := r.getCurrentPrefix()
+ formatted, width := formatSuggestions(
+ suggestions,
+ int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar
+ )
+ // +1 means a width of scrollbar.
+ width++
+
+ windowHeight := len(formatted)
+ if windowHeight > int(completions.max) {
+ windowHeight = int(completions.max)
+ }
+ formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
+ r.prepareArea(windowHeight)
+
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor())
+ x, _ := r.toPos(cursor)
+ if x+width >= int(r.col) {
+ cursor = r.backward(cursor, x+width-int(r.col))
+ }
+
+ contentHeight := len(completions.tmp)
+
+ fractionVisible := float64(windowHeight) / float64(contentHeight)
+ fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
+
+ scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
+ scrollbarTop := int(float64(windowHeight) * fractionAbove)
+
+ isScrollThumb := func(row int) bool {
+ return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
+ }
+
+ selected := completions.selected - completions.verticalScroll
+ r.out.SetColor(White, Cyan, false)
+ for i := 0; i < windowHeight; i++ {
+ r.out.CursorDown(1)
+ if i == selected {
+ r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
+ } else {
+ r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Text)
+
+ if i == selected {
+ r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
+ } else {
+ r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Description)
+
+ if isScrollThumb(i) {
+ r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
+ } else {
+ r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
+ }
+ r.out.WriteStr(" ")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+
+ r.lineWrap(cursor + width)
+ r.backward(cursor+width, width)
+ }
+
+ if x+width >= int(r.col) {
+ r.out.CursorForward(x + width - int(r.col))
+ }
+
+ r.out.CursorUp(windowHeight)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// Render renders to the console.
+func (r *Render) Render(buffer *Buffer, completion *CompletionManager) {
+ // In situations where a pseudo tty is allocated (e.g. within a docker container),
+ // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
+ if r.col == 0 {
+ return
+ }
+ defer func() { debug.AssertNoError(r.out.Flush()) }()
+ r.move(r.previousCursor, 0)
+
+ line := buffer.Text()
+ prefix := r.getCurrentPrefix()
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line)
+
+ // prepare area
+ _, y := r.toPos(cursor)
+
+ h := y + 1 + int(completion.max)
+ if h > int(r.row) || completionMargin > int(r.col) {
+ r.renderWindowTooSmall()
+ return
+ }
+
+ // Rendering
+ r.out.HideCursor()
+ defer r.out.ShowCursor()
+
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(line)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ r.lineWrap(cursor)
+
+ r.out.EraseDown()
+
+ cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition())
+
+ r.renderCompletion(buffer, completion)
+ if suggest, ok := completion.GetSelectedSuggestion(); ok {
+ cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator)))
+
+ r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false)
+ r.out.WriteStr(suggest.Text)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ cursor += runewidth.StringWidth(suggest.Text)
+
+ rest := buffer.Document().TextAfterCursor()
+ r.out.WriteStr(rest)
+ cursor += runewidth.StringWidth(rest)
+ r.lineWrap(cursor)
+
+ cursor = r.backward(cursor, runewidth.StringWidth(rest))
+ }
+ r.previousCursor = cursor
+}
+
+// BreakLine to break line.
+func (r *Render) BreakLine(buffer *Buffer) {
+ // Erasing and Render
+ cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix())
+ r.clear(cursor)
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(buffer.Document().Text + "\n")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ debug.AssertNoError(r.out.Flush())
+ if r.breakLineCallback != nil {
+ r.breakLineCallback(buffer.Document())
+ }
+
+ r.previousCursor = 0
+}
+
+// clear erases the screen from a beginning of input
+// even if there is line break which means input length exceeds a window's width.
+func (r *Render) clear(cursor int) {
+ r.move(cursor, 0)
+ r.out.EraseDown()
+}
+
+// backward moves cursor to backward from a current cursor position
+// regardless there is a line break.
+func (r *Render) backward(from, n int) int {
+ return r.move(from, from-n)
+}
+
+// move moves cursor to specified position from the beginning of input
+// even if there is a line break.
+func (r *Render) move(from, to int) int {
+ fromX, fromY := r.toPos(from)
+ toX, toY := r.toPos(to)
+
+ r.out.CursorUp(fromY - toY)
+ r.out.CursorBackward(fromX - toX)
+ return to
+}
+
+// toPos returns the relative position from the beginning of the string.
+func (r *Render) toPos(cursor int) (x, y int) {
+ col := int(r.col)
+ return cursor % col, cursor / col
+}
+
+func (r *Render) lineWrap(cursor int) {
+ if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 {
+ r.out.WriteRaw([]byte{'\n'})
+ }
+}
+
+func clamp(high, low, x float64) float64 {
+ switch {
+ case high < x:
+ return high
+ case x < low:
+ return low
+ default:
+ return x
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/shortcut.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/shortcut.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8d4282700c0bdb30e4decfb9c9ac91f27af251
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/shortcut.go
@@ -0,0 +1,43 @@
+package prompt
+
+func dummyExecutor(in string) {}
+
+// Input get the input data from the user and return it.
+func Input(prefix string, completer Completer, opts ...Option) string {
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+// Choose to the shortcut of input function to select from string array.
+// Deprecated: Maybe anyone want to use this.
+func Choose(prefix string, choices []string, opts ...Option) string {
+ completer := newChoiceCompleter(choices, FilterHasPrefix)
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+func newChoiceCompleter(choices []string, filter Filter) Completer {
+ s := make([]Suggest, len(choices))
+ for i := range choices {
+ s[i] = Suggest{Text: choices[i]}
+ }
+ return func(x Document) []Suggest {
+ return filter(s, x.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/signal_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/signal_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3150df5d85e7612c42c2a889dbefee3b524bef6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/signal_posix.go
@@ -0,0 +1,49 @@
+// +build !windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ in := p.in
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+
+ case syscall.SIGWINCH:
+ debug.Log("Catch SIGWINCH")
+ winSizeCh <- in.GetWinSize()
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/signal_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/signal_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a427c79ec0414540f8f40694731b2565ea80c13
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/environment/source/signal_windows.go
@@ -0,0 +1,44 @@
+// +build windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/instruction.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..b6d885b189a1ea142c0a2a50fe642492cd6f4c1c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/instruction.md
@@ -0,0 +1,41 @@
+GetWordBeforeCursorWithSpace returns wrong text substring
+
+#### Description
+
+The `GetWordBeforeCursorWithSpace` method is returning incorrect text. Instead of returning the word before the cursor including spaces, it appears to be returning text from the beginning of the document up to a certain position.
+
+#### Steps/Code to Reproduce
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func main() {
+ // Create a document with some text
+ doc := &prompt.Document{
+ Text: "apple banana cherry",
+ CursorPosition: 12, // Position after "banana "
+ }
+
+ result := doc.GetWordBeforeCursorWithSpace()
+ fmt.Printf("Got: '%s'\n", result)
+ fmt.Printf("Expected: 'banana '\n")
+
+ // Another example
+ doc2 := &prompt.Document{
+ Text: "Hello world test",
+ CursorPosition: 11, // Position after "world "
+ }
+
+ result2 := doc2.GetWordBeforeCursorWithSpace()
+ fmt.Printf("Got: '%s'\n", result2)
+ fmt.Printf("Expected: 'world '\n")
+}
+```
+
+When running this code, the method returns the wrong substring - it seems to be returning text from the start of the document rather than just the word before the cursor with its trailing space.
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/provenance.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..539ede7f82af8c28800bd60602913a20ad4f1a19
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/provenance.json
@@ -0,0 +1,477 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt",
+ "original-bug": "task-specific unchanged semantic bug",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only",
+ "extra_semantic_repair_coverage": false,
+ "original_patch_hunks": 1
+ },
+ "private_frozen_files": {
+ "buffer_test.go": {
+ "mode": "0o644",
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098",
+ "size": 4965
+ },
+ "completion_test.go": {
+ "mode": "0o644",
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d",
+ "size": 7010
+ },
+ "document_test.go": {
+ "mode": "0o644",
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284",
+ "size": 28938
+ },
+ "emacs_test.go": {
+ "mode": "0o644",
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095",
+ "size": 741
+ },
+ "filter_test.go": {
+ "mode": "0o644",
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247",
+ "size": 3339
+ },
+ "history_test.go": {
+ "mode": "0o644",
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327",
+ "size": 1319
+ },
+ "input_test.go": {
+ "mode": "0o644",
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922",
+ "size": 533
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": "0o644",
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf",
+ "size": 1075
+ },
+ "internal/strings/strings_test.go": {
+ "mode": "0o644",
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6",
+ "size": 981
+ },
+ "output_vt100_test.go": {
+ "mode": "0o644",
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee",
+ "size": 1349
+ },
+ "render_test.go": {
+ "mode": "0o644",
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb",
+ "size": 2890
+ }
+ },
+ "public_files": {
+ ".github/ISSUE_TEMPLATE/bug_report.md": {
+ "mode": "0o644",
+ "sha256": "89d3492ca8533a3d31e4de49a23828a322f75d2a1ec4236327c4a76c7c51ada6",
+ "size": 684
+ },
+ ".github/ISSUE_TEMPLATE/feature_request.md": {
+ "mode": "0o644",
+ "sha256": "d82e14e6b4d021d0007eeef4f5ca489fc6c8e8e4d7479ee30e74fe82afd3b08f",
+ "size": 206
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "3239b94a1a41c05eff5dc086ef1378cf1e289fad0203420b5cb4c78e3c5c239b",
+ "size": 270
+ },
+ "CHANGELOG.md": {
+ "mode": "0o644",
+ "sha256": "1f88f92d3247e1b52af0f0de7ad1263a59807edb17238c7a0211554f8080e51c",
+ "size": 2895
+ },
+ "LICENSE": {
+ "mode": "0o644",
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "size": 1072
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "9425a0d4c15747863625f647348962a9b0f81a0971a7e0184ee722bf34a60ba2",
+ "size": 1177
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "ce56df51a1a9a5b5c5b056429bbee006a260fb0730af63b1d0fe91755e574cc4",
+ "size": 6185
+ },
+ "_example/README.md": {
+ "mode": "0o644",
+ "sha256": "155951bafd778493bd41ae57dcc0ba6b8eca821fcbe2ffe770960ac2780d3d09",
+ "size": 1102
+ },
+ "_example/build.sh": {
+ "mode": "0o755",
+ "sha256": "de2fb330b665691cd75b990236cd6a5df0058608de0dfc6194da30d4041a1e29",
+ "size": 469
+ },
+ "_example/exec-command/main.go": {
+ "mode": "0o644",
+ "sha256": "0e96493b6e6d446b2e691d4834ff8a55834caa410ead970cb611a63ba84f174a",
+ "size": 429
+ },
+ "_example/http-prompt/api.py": {
+ "mode": "0o644",
+ "sha256": "2c2bca9acb07a84c65a4482c61c9ade253a574477a8e461307568ea1f9a342c8",
+ "size": 335
+ },
+ "_example/http-prompt/main.go": {
+ "mode": "0o644",
+ "sha256": "6994b190c4165068e69ed44eb61698af69a15a7690179ce46e3c1c5d8c211643",
+ "size": 5484
+ },
+ "_example/live-prefix/main.go": {
+ "mode": "0o644",
+ "sha256": "20268f9cb6f3b82a52eddc33cbf8082adaa46092e2063df279499e05e25a228c",
+ "size": 1103
+ },
+ "_example/simple-echo/cjk-cyrillic/main.go": {
+ "mode": "0o644",
+ "sha256": "8fb10807d4085ebc4b345bc0ccfef9217e21e49a888bfe3192e8ddfdfa01e89c",
+ "size": 800
+ },
+ "_example/simple-echo/main.go": {
+ "mode": "0o644",
+ "sha256": "e46563ddaa932831fe9ede870b10efb5222c0d54a86f4b4f5197c9cf20942a24",
+ "size": 902
+ },
+ "_tools/README.md": {
+ "mode": "0o644",
+ "sha256": "96dc2343bc5cde642fd449ddc366462753a2e17b6a78adfa015bf991e9dac241",
+ "size": 234
+ },
+ "_tools/complete_file/main.go": {
+ "mode": "0o644",
+ "sha256": "e5dd823f9d6415614a8238ce106d26e9ded1db9b308c121d7f48bb1df003effc",
+ "size": 803
+ },
+ "_tools/sigwinch/main.go": {
+ "mode": "0o644",
+ "sha256": "a806b4e45298f5003c95432d8dd3c40c9c096335f19f1a4160afcdb64fa727e3",
+ "size": 1386
+ },
+ "_tools/vt100_debug/main.go": {
+ "mode": "0o644",
+ "sha256": "7f72eba3cc7037fcf39c9b56a96c578c157e5fb235cb626ab1e83cbef0dc290b",
+ "size": 794
+ },
+ "buffer.go": {
+ "mode": "0o644",
+ "sha256": "10188d96a450fe13ba1e9ec00c89603eb2a2860536965d980d1e4abf4374b018",
+ "size": 5781
+ },
+ "completer/file.go": {
+ "mode": "0o644",
+ "sha256": "6181ed9e39028236c5c93fbe219331fc1492ecfd6af2df764cc42b5455c9bb96",
+ "size": 2401
+ },
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "b90bd9628534cfb343a592775430e17a1999b1de500fb2a8f1507c030a432eae",
+ "size": 4491
+ },
+ "document.go": {
+ "mode": "0o644",
+ "sha256": "f2d29b00a253ff8076fcb38afa217a57556210ea51823960feb8f3ee6d642f65",
+ "size": 13097
+ },
+ "emacs.go": {
+ "mode": "0o644",
+ "sha256": "53f0df0016ef9d9695a797b19286681666cf0c7e5a866c393b194aae915f2664",
+ "size": 2675
+ },
+ "filter.go": {
+ "mode": "0o644",
+ "sha256": "dc5922bad6ecb32ecdaf20bd6035dddc7ce8c14f15dbd4d49192c2354cb8a038",
+ "size": 2005
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "97413fa2a2ed68170496f2289a2dca6fb0a192dcd020fc0ca48a5d106e60d55e",
+ "size": 253
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "88ea0a91babaa54b67cc6d5f6f7f47fa4be798fe523324ea568d8926eed2024c",
+ "size": 2183
+ },
+ "history.go": {
+ "mode": "0o644",
+ "sha256": "4ce80ba067cfc72c56a3ee3353ec75cd6bb2f5d82097515c591e3c7c773c51cd",
+ "size": 1488
+ },
+ "input.go": {
+ "mode": "0o644",
+ "sha256": "73461cc4f57d68b66e2a9e196239aaef942539134593beac0d0023743832e0e1",
+ "size": 7630
+ },
+ "input_posix.go": {
+ "mode": "0o644",
+ "sha256": "c7e5a4dfc3910f178f0685ef99f2e47d481a91c4cf9af50f92fc4266aed634df",
+ "size": 1648
+ },
+ "input_windows.go": {
+ "mode": "0o644",
+ "sha256": "f763250d309fb88d9536f77da1d1285c04bc6defe859506f1501e10f7743da9e",
+ "size": 1679
+ },
+ "internal/bisect/bisect.go": {
+ "mode": "0o644",
+ "sha256": "c4de2adfa2e08a77f902661d67325467f89013634dbcef22d24dc6f34d26624a",
+ "size": 327
+ },
+ "internal/debug/assert.go": {
+ "mode": "0o644",
+ "sha256": "1a3050ec58991b62c7ea352d19505e3080ac9760bdb091544f0ecf5aba35969c",
+ "size": 815
+ },
+ "internal/debug/log.go": {
+ "mode": "0o644",
+ "sha256": "2ce968e275558de61c6d83793e85561f7a8dd69c95ec7902ccd2cc3fb169aa82",
+ "size": 875
+ },
+ "internal/strings/strings.go": {
+ "mode": "0o644",
+ "sha256": "b97f08157c3baf1f94fea4bb2237691d8270bd5380b4311709ecd59b84cf4b7b",
+ "size": 2018
+ },
+ "internal/term/raw.go": {
+ "mode": "0o644",
+ "sha256": "177a1a20ae8d71b56857383a5797754560f7f6404ea86778d5f01e9a1c1b4f9f",
+ "size": 747
+ },
+ "internal/term/term.go": {
+ "mode": "0o644",
+ "sha256": "abe6fa965fa15b999b2010135903f598830d4c885a52ef9b067fd5ebbf6e373f",
+ "size": 606
+ },
+ "key.go": {
+ "mode": "0o644",
+ "sha256": "03a43283e07de7a4ea6fed32692d86325f73e98fd89a296f19c171e0bc780999",
+ "size": 1746
+ },
+ "key_bind.go": {
+ "mode": "0o644",
+ "sha256": "83f48bb720a11c8e49165ac382e3a870fdcf6b380a0a95267f8c25211898c9eb",
+ "size": 1109
+ },
+ "key_bind_func.go": {
+ "mode": "0o644",
+ "sha256": "445bff5c0fdb0b52879c635322603c2fc75d265de3761cb8c3b980c798bf39af",
+ "size": 1219
+ },
+ "key_string.go": {
+ "mode": "0o644",
+ "sha256": "55c429dae227bb1659d5d5e2e906dbfa9c7f53b5105fa83fbe290529ff6f2317",
+ "size": 1359
+ },
+ "option.go": {
+ "mode": "0o644",
+ "sha256": "28cfcc1d08b3cf650483d977195458531b3b3913f8a5f357a3ec17ea5d73e215",
+ "size": 8737
+ },
+ "output.go": {
+ "mode": "0o644",
+ "sha256": "372876b0aa908479ed3b29de70a479f420d85e3666b8957c8b61eaed9b32c3f2",
+ "size": 4320
+ },
+ "output_posix.go": {
+ "mode": "0o644",
+ "sha256": "d46b1da307e8969b033e1ade2eb51a83c4c3d4f2a7e4aba35ec3a03991b89a0f",
+ "size": 1545
+ },
+ "output_vt100.go": {
+ "mode": "0o644",
+ "sha256": "9082c7e4619c1eb38030bc4994a4fbf66ef27b130751bf2eb9c25c01082e8605",
+ "size": 7453
+ },
+ "output_windows.go": {
+ "mode": "0o644",
+ "sha256": "571c5ae1ad051a701b426371efd79a3776c2226ca9e3c2e598fe5996dfa1b8e1",
+ "size": 1066
+ },
+ "prompt.go": {
+ "mode": "0o644",
+ "sha256": "6b3e2bbd90f40ad6a487f1a6ea7f5a6fb48cae6c8c246ecc77621fb3e7383ca7",
+ "size": 7062
+ },
+ "render.go": {
+ "mode": "0o644",
+ "sha256": "90fdd57a63e06f01940d10ee1a0be95ced7d6adc7faa255b3141556d7d316270",
+ "size": 8020
+ },
+ "shortcut.go": {
+ "mode": "0o644",
+ "sha256": "b4a097f466df7396049ebe8393f81c9b1200159d4e2be22bd6838c307ec156dc",
+ "size": 1120
+ },
+ "signal_posix.go": {
+ "mode": "0o644",
+ "sha256": "74f0bae5f290f3f7f82a5dd495e672f627a4ab4b63118f870e8c13c0a7024314",
+ "size": 881
+ },
+ "signal_windows.go": {
+ "mode": "0o644",
+ "sha256": "444f662a32e6997df2af8e2a9e7dbfe977414a6bfc0f54a7f10117f204648437",
+ "size": 757
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982",
+ "os": "linux",
+ "sha256": "0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982"
+ },
+ "context_inventory_sha256": "6b8f93086e81483ac1ce82f328d7f4b38b1b560dbad057ed6a2a30ff3cf0e13f",
+ "image": "registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "9d3b21cdacadfa4f3de9584d0cea973e5aa2ceedcd5ec9cbd3a63df22b313455",
+ "receipt_path": "production/runtime-images-extra-v1/resolutions/316e0e68930cd4ef/resolution.json",
+ "receipt_sha256": "697bb0619eddcdfdeba1c9144b033f564f2d7514be6e6a44dc520fa4e63ed8bc",
+ "registry_digest": "sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "source_image": "docker.io/swebench/swesmith.x86_64.c-bata_1776_go-prompt.82a91227@sha256:3daf51c74a01657e9ad8f326651fb6f5b796ffecdb90098e74a52a9560e0a1bb",
+ "source_receipt_sha256": "b450bea0e201cbe194b765ded4b51539144c85296122c8b642d7e94c889526f3",
+ "space_commit": "5ae654cd2e9d695f0de304bd4398835fc7cf45e0",
+ "space_id": "harness-hub/scale800-go-316e0e68930cd4ef-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "82e112c1c37689f5819261088e1b0b4e17f6010098aff5e6da62580b1cefaead",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21",
+ "source_proof_sha256": "248f8ffc254fd158f1910b6020adc119adc46cea19f9dafd43b153244d980675",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:c-bata__go-prompt.82a91227.lm_modify__aa65b3ba",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "9992c59c25864ce1556e67b9e1501c93f6e7f9ff",
+ "instruction_sha256": "a9a39ef8ef564c7f976babad916f49635cac0a65315a943f715906914524521b",
+ "is_fork": true,
+ "learner_path": "tasks/d2ea557ef7c79312210561f1/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/c-bata__go-prompt.82a91227/0fee2e6f893059c7f393ffa417c144fcc29ac80a/LICENSE"
+ },
+ "task_bundle": {
+ "basis": "Captured publisherMIT/train; exactsoftwarepermissionverifiedseparately",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "82a912274504477990ecf7c852eebb7c85291772",
+ "patch_sha256": "48097d230ba5b03c9d758dc0a6bc13ea0fea13bfcba1a17ac7def11a0b38d0b1",
+ "provenance_path": "tasks/d2ea557ef7c79312210561f1/source-proof.json",
+ "repository_lineage": [
+ "swesmith/c-bata__go-prompt.82a91227",
+ "c-bata/go-prompt"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "0fee2e6f893059c7f393ffa417c144fcc29ac80a",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "da0ab6cda54fa4832f9b751f963f3faea6d0eac4",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/c-bata__go-prompt.82a91227",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "c-bata__go-prompt.82a91227.lm_modify__aa65b3ba",
+ "task_sha256": "e5bc5cf2fe288c2046bd653439da1114a628bdedb2e3a7fdb7e3ce9ff9f078b3",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "c-bata/go-prompt",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "d7399a9903a4b5da30248be3635220bfd89cd518358ff65b4ccea81149ce0189",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.md",
+ "/testbed/.github/ISSUE_TEMPLATE/feature_request.md",
+ "/testbed/.gitignore",
+ "/testbed/CHANGELOG.md",
+ "/testbed/LICENSE",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/_example/README.md",
+ "/testbed/_example/build.sh",
+ "/testbed/_example/exec-command/main.go",
+ "/testbed/_example/http-prompt/api.py",
+ "/testbed/_example/http-prompt/main.go",
+ "/testbed/_example/live-prefix/main.go",
+ "/testbed/_example/simple-echo/cjk-cyrillic/main.go",
+ "/testbed/_example/simple-echo/main.go",
+ "/testbed/_tools/README.md",
+ "/testbed/_tools/complete_file/main.go",
+ "/testbed/_tools/sigwinch/main.go",
+ "/testbed/_tools/vt100_debug/main.go",
+ "/testbed/buffer.go",
+ "/testbed/completer/file.go",
+ "/testbed/completion.go",
+ "/testbed/document.go",
+ "/testbed/emacs.go",
+ "/testbed/filter.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum",
+ "/testbed/history.go",
+ "/testbed/input.go",
+ "/testbed/input_posix.go",
+ "/testbed/input_windows.go",
+ "/testbed/internal/bisect/bisect.go",
+ "/testbed/internal/debug/assert.go",
+ "/testbed/internal/debug/log.go",
+ "/testbed/internal/strings/strings.go",
+ "/testbed/internal/term/raw.go",
+ "/testbed/internal/term/term.go",
+ "/testbed/key.go",
+ "/testbed/key_bind.go",
+ "/testbed/key_bind_func.go",
+ "/testbed/key_string.go",
+ "/testbed/option.go",
+ "/testbed/output.go",
+ "/testbed/output_posix.go",
+ "/testbed/output_vt100.go",
+ "/testbed/output_windows.go",
+ "/testbed/prompt.go",
+ "/testbed/render.go",
+ "/testbed/shortcut.go",
+ "/testbed/signal_posix.go",
+ "/testbed/signal_windows.go"
+ ]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/solution/solve.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..00d1a533519e8abc9def758862da6b859247bfe5
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"document.go": {"data": "cGFja2FnZSBwcm9tcHQKCmltcG9ydCAoCgkic3RyaW5ncyIKCSJ1bmljb2RlL3V0ZjgiCgoJImdpdGh1Yi5jb20vYy1iYXRhL2dvLXByb21wdC9pbnRlcm5hbC9iaXNlY3QiCglpc3RyaW5ncyAiZ2l0aHViLmNvbS9jLWJhdGEvZ28tcHJvbXB0L2ludGVybmFsL3N0cmluZ3MiCglydW5ld2lkdGggImdpdGh1Yi5jb20vbWF0dG4vZ28tcnVuZXdpZHRoIgopCgovLyBEb2N1bWVudCBoYXMgdGV4dCBkaXNwbGF5ZWQgaW4gdGVybWluYWwgYW5kIGN1cnNvciBwb3NpdGlvbi4KdHlwZSBEb2N1bWVudCBzdHJ1Y3QgewoJVGV4dCBzdHJpbmcKCS8vIFRoaXMgcmVwcmVzZW50cyBhIGluZGV4IGluIGEgcnVuZSBhcnJheSBvZiBEb2N1bWVudC5UZXh0LgoJLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgY3Vyc29yUG9zaXRpb24gaXMgMi4KCS8vIEJ1dCBEaXNwbGF5ZWRDdXJzb3JQb3NpdGlvbiByZXR1cm5zIDQgYmVjYXVzZSAn5pelJyBhbmQgJ+acrCcgYXJlIGRvdWJsZSB3aWR0aCBjaGFyYWN0ZXJzLgoJY3Vyc29yUG9zaXRpb24gaW50CglsYXN0S2V5ICAgICAgICBLZXkKfQoKLy8gTmV3RG9jdW1lbnQgcmV0dXJuIHRoZSBuZXcgZW1wdHkgZG9jdW1lbnQuCmZ1bmMgTmV3RG9jdW1lbnQoKSAqRG9jdW1lbnQgewoJcmV0dXJuICZEb2N1bWVudHsKCQlUZXh0OiAgICAgICAgICAgIiIsCgkJY3Vyc29yUG9zaXRpb246IDAsCgl9Cn0KCi8vIExhc3RLZXlTdHJva2UgcmV0dXJuIHRoZSBsYXN0IGtleSBwcmVzc2VkIGluIHRoaXMgZG9jdW1lbnQuCmZ1bmMgKGQgKkRvY3VtZW50KSBMYXN0S2V5U3Ryb2tlKCkgS2V5IHsKCXJldHVybiBkLmxhc3RLZXkKfQoKLy8gRGlzcGxheUN1cnNvclBvc2l0aW9uIHJldHVybnMgdGhlIGN1cnNvciBwb3NpdGlvbiBvbiByZW5kZXJlZCB0ZXh0IG9uIHRlcm1pbmFsIGVtdWxhdG9ycy4KLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgRGlzcGxheWVkQ3Vyc29yUG9zaXRpb24gcmV0dXJucyA0IGJlY2F1c2UgJ+aXpScgYW5kICfmnKwnIGFyZSBkb3VibGUgd2lkdGggY2hhcmFjdGVycy4KZnVuYyAoZCAqRG9jdW1lbnQpIERpc3BsYXlDdXJzb3JQb3NpdGlvbigpIGludCB7Cgl2YXIgcG9zaXRpb24gaW50CglydW5lcyA6PSBbXXJ1bmUoZC5UZXh0KVs6ZC5jdXJzb3JQb3NpdGlvbl0KCWZvciBpIDo9IHJhbmdlIHJ1bmVzIHsKCQlwb3NpdGlvbiArPSBydW5ld2lkdGguUnVuZVdpZHRoKHJ1bmVzW2ldKQoJfQoJcmV0dXJuIHBvc2l0aW9uCn0KCi8vIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yIHJldHVybiBjaGFyYWN0ZXIgcmVsYXRpdmUgdG8gY3Vyc29yIHBvc2l0aW9uLCBvciBlbXB0eSBzdHJpbmcKZnVuYyAoZCAqRG9jdW1lbnQpIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yKG9mZnNldCBpbnQpIChyIHJ1bmUpIHsKCXMgOj0gZC5UZXh0CgljbnQgOj0gMAoKCWZvciBsZW4ocykgPiAwIHsKCQljbnQrKwoJCXIsIHNpemUgOj0gdXRmOC5EZWNvZGVSdW5lSW5TdHJpbmcocykKCQlpZiBjbnQgPT0gZC5jdXJzb3JQb3NpdGlvbitvZmZzZXQgewoJCQlyZXR1cm4gcgoJCX0KCQlzID0gc1tzaXplOl0KCX0KCXJldHVybiAwCn0KCi8vIFRleHRCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJciA6PSBbXXJ1bmUoZC5UZXh0KQoJcmV0dXJuIHN0cmluZyhyWzpkLmN1cnNvclBvc2l0aW9uXSkKfQoKLy8gVGV4dEFmdGVyQ3Vyc29yIHJldHVybnMgdGhlIHRleHQgYWZ0ZXIgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRBZnRlckN1cnNvcigpIHN0cmluZyB7CglyIDo9IFtdcnVuZShkLlRleHQpCglyZXR1cm4gc3RyaW5nKHJbZC5jdXJzb3JQb3NpdGlvbjpdKQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYmVmb3JlIHRoZSBjdXJzb3IuCi8vIElmIHdlIGhhdmUgd2hpdGVzcGFjZSBiZWZvcmUgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcigpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBJZiB3ZSBoYXZlIHdoaXRlc3BhY2UgYWZ0ZXIgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yKCkgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmQoKV0KfQoKLy8gR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSgpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEFmdGVyQ3Vyc29yLCBpdCByZXR1cm5zIHN0cmluZyBjb250YWluaW5nIHNwYWNlCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UoKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpXQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yVW50aWxTZXBhcmF0b3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvciB1bnRpbCBuZXh0IHNlcGFyYXRvci4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJcmV0dXJuIHhbZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFVudGlsU2VwYXJhdG9yKHNlcCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvciByZXR1cm5zIHRoZSB0ZXh0IGFmdGVyIHRoZSBjdXJzb3IgdW50aWwgbmV4dCBzZXBhcmF0b3IuCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCldCn0KCi8vIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvciByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yKHNlcCBzdHJpbmcpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwKTpdCn0KCi8vIEdldFdvcmRBZnRlckN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYWZ0ZXIgdGhlIGN1cnNvci4KLy8gVW5saWtlIEdldFdvcmRBZnRlckN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXApXQp9CgovLyBGaW5kU3RhcnRPZlByZXZpb3VzV29yZCByZXR1cm5zIGFuIGluZGV4IHJlbGF0aXZlIHRvIHRoZSBjdXJzb3IgcG9zaXRpb24KLy8gcG9pbnRpbmcgdG8gdGhlIHN0YXJ0IG9mIHRoZSBwcmV2aW91cyB3b3JkLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5MYXN0SW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpICsgMQoJfQoJcmV0dXJuIDAKfQoKLy8gRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRXaXRoU3BhY2UgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBUaGUgb25seSBkaWZmZXJlbmNlIGlzIHRvIGlnbm9yZSBjb250aWd1b3VzIHNwYWNlcy4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWVuZCA6PSBpc3RyaW5ncy5MYXN0SW5kZXhOb3RCeXRlKHgsICcgJykKCWlmIGVuZCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEJ5dGUoeFs6ZW5kXSwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiAwCgl9CglyZXR1cm4gc3RhcnQgKyAxCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZCgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJaSA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaSArIDEKCX0KCXJldHVybiAwCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFdpdGhTcGFjZSgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJZW5kIDo9IGlzdHJpbmdzLkxhc3RJbmRleE5vdEFueSh4LCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiAwCgl9CglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4WzplbmRdLCBzZXApCglpZiBzdGFydCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCXJldHVybiBzdGFydCArIDEKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmQgcmV0dXJucyBhbiBpbmRleCByZWxhdGl2ZSB0byB0aGUgY3Vyc29yIHBvc2l0aW9uLgovLyBwb2ludGluZyB0byB0aGUgZW5kIG9mIHRoZSBjdXJyZW50IHdvcmQuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZEVuZE9mQ3VycmVudFdvcmQoKSBpbnQgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglpIDo9IHN0cmluZ3MuSW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpCgl9CglyZXR1cm4gbGVuKHgpCn0KCi8vIEZpbmRFbmRPZkN1cnJlbnRXb3JkV2l0aFNwYWNlIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZC4KLy8gVGhlIG9ubHkgZGlmZmVyZW5jZSBpcyB0byBpZ25vcmUgY29udGlndW91cyBzcGFjZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpIGludCB7Cgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCglzdGFydCA6PSBpc3RyaW5ncy5JbmRleE5vdEJ5dGUoeCwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCgllbmQgOj0gc3RyaW5ncy5JbmRleEJ5dGUoeFtzdGFydDpdLCAnICcpCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvciBpcyBhbG1vc3QgdGhlIHNhbWUgYXMgRmluZEVuZE9mQ3VycmVudFdvcmQuCi8vIEJ1dCB0aGlzIGNhbiBzcGVjaWZ5IFNlcGFyYXRvci4gUmV0dXJuIDAgaWYgbm90aGluZyB3YXMgZm91bmQuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCBzdHJpbmcpIGludCB7CglpZiBzZXAgPT0gIiIgewoJCXJldHVybiBkLkZpbmRFbmRPZkN1cnJlbnRXb3JkKCkKCX0KCgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5JbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaQoJfQoJcmV0dXJuIGxlbih4KQp9CgovLyBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZS4KLy8gQnV0IHRoaXMgY2FuIHNwZWNpZnkgU2VwYXJhdG9yLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRFbmRPZkN1cnJlbnRXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgaW50IHsKCWlmIHNlcCA9PSAiIiB7CgkJcmV0dXJuIGQuRmluZEVuZE9mQ3VycmVudFdvcmRXaXRoU3BhY2UoKQoJfQoKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoKCXN0YXJ0IDo9IGlzdHJpbmdzLkluZGV4Tm90QW55KHgsIHNlcCkKCWlmIHN0YXJ0ID09IC0xIHsKCQlyZXR1cm4gbGVuKHgpCgl9CgoJZW5kIDo9IHN0cmluZ3MuSW5kZXhBbnkoeFtzdGFydDpdLCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gQ3VycmVudExpbmVCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBzdGFydCBvZiB0aGUgbGluZSB1bnRpbCB0aGUgY3Vyc29yLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJcyA6PSBzdHJpbmdzLlNwbGl0KGQuVGV4dEJlZm9yZUN1cnNvcigpLCAiXG4iKQoJcmV0dXJuIHNbbGVuKHMpLTFdCn0KCi8vIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBjdXJzb3IgdW50aWwgdGhlIGVuZCBvZiB0aGUgbGluZS4KZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSBzdHJpbmcgewoJcmV0dXJuIHN0cmluZ3MuU3BsaXQoZC5UZXh0QWZ0ZXJDdXJzb3IoKSwgIlxuIilbMF0KfQoKLy8gQ3VycmVudExpbmUgcmV0dXJuIHRoZSB0ZXh0IG9uIHRoZSBsaW5lIHdoZXJlIHRoZSBjdXJzb3IgaXMuICh3aGVuIHRoZSBpbnB1dAovLyBjb25zaXN0cyBvZiBqdXN0IG9uZSBsaW5lLCBpdCBlcXVhbHMgYHRleHRgLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmUoKSBzdHJpbmcgewoJcmV0dXJuIGQuQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSArIGQuQ3VycmVudExpbmVBZnRlckN1cnNvcigpCn0KCi8vIEFycmF5IHBvaW50aW5nIHRvIHRoZSBzdGFydCBpbmRleGVzIG9mIGFsbCB0aGUgbGluZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBsaW5lU3RhcnRJbmRleGVzKCkgW11pbnQgewoJLy8gVE9ETzogQ2FjaGUsIGJlY2F1c2UgdGhpcyBpcyBvZnRlbiByZXVzZWQuCgkvLyAoSWYgaXQgaXMgdXNlZCwgaXQncyBvZnRlbiB1c2VkIG1hbnkgdGltZXMuCgkvLyBBbmQgdGhpcyBoYXMgdG8gYmUgZmFzdCBmb3IgZWRpdGluZyBiaWcgZG9jdW1lbnRzISkKCWxjIDo9IGQuTGluZUNvdW50KCkKCWxlbmd0aHMgOj0gbWFrZShbXWludCwgbGMpCglmb3IgaSwgbCA6PSByYW5nZSBkLkxpbmVzKCkgewoJCWxlbmd0aHNbaV0gPSBsZW4obCkKCX0KCgkvLyBDYWxjdWxhdGUgY3VtdWxhdGl2ZSBzdW1zLgoJaW5kZXhlcyA6PSBtYWtlKFtdaW50LCBsYysxKQoJaW5kZXhlc1swXSA9IDAgLy8gaHR0cHM6Ly9naXRodWIuY29tL2pvbmF0aGFuc2xlbmRlcnMvcHl0aG9uLXByb21wdC10b29sa2l0L2Jsb2IvbWFzdGVyL3Byb21wdF90b29sa2l0L2RvY3VtZW50LnB5I0wxODkKCXBvcyA6PSAwCglmb3IgaSwgbCA6PSByYW5nZSBsZW5ndGhzIHsKCQlwb3MgKz0gbCArIDEKCQlpbmRleGVzW2krMV0gPSBwb3MKCX0KCWlmIGxjID4gMSB7CgkJLy8gUG9wIHRoZSBsYXN0IGl0ZW0uIChUaGlzIGlzIG5vdCBhIG5ldyBsaW5lLikKCQlpbmRleGVzID0gaW5kZXhlc1s6bGNdCgl9CglyZXR1cm4gaW5kZXhlcwp9CgovLyBGb3IgdGhlIGluZGV4IG9mIGEgY2hhcmFjdGVyIGF0IGEgY2VydGFpbiBsaW5lLCBjYWxjdWxhdGUgdGhlIGluZGV4IG9mCi8vIHRoZSBmaXJzdCBjaGFyYWN0ZXIgb24gdGhhdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgZmluZExpbmVTdGFydEluZGV4KGluZGV4IGludCkgKHBvcyBpbnQsIGxpbmVTdGFydEluZGV4IGludCkgewoJaW5kZXhlcyA6PSBkLmxpbmVTdGFydEluZGV4ZXMoKQoJcG9zID0gYmlzZWN0LlJpZ2h0KGluZGV4ZXMsIGluZGV4KSAtIDEKCWxpbmVTdGFydEluZGV4ID0gaW5kZXhlc1twb3NdCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Sb3cgcmV0dXJucyB0aGUgY3VycmVudCByb3cuICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uUm93KCkgKHJvdyBpbnQpIHsKCXJvdywgXyA9IGQuZmluZExpbmVTdGFydEluZGV4KGQuY3Vyc29yUG9zaXRpb24pCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Db2wgcmV0dXJucyB0aGUgY3VycmVudCBjb2x1bW4uICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uQ29sKCkgKGNvbCBpbnQpIHsKCS8vIERvbid0IHVzZSBzZWxmLnRleHRfYmVmb3JlX2N1cnNvciB0byBjYWxjdWxhdGUgdGhpcy4gQ3JlYXRpbmcgc3Vic3RyaW5ncwoJLy8gYW5kIHNwbGl0dGluZyBpcyB0b28gZXhwZW5zaXZlIGZvciBnZXR0aW5nIHRoZSBjdXJzb3IgcG9zaXRpb24uCglfLCBpbmRleCA6PSBkLmZpbmRMaW5lU3RhcnRJbmRleChkLmN1cnNvclBvc2l0aW9uKQoJY29sID0gZC5jdXJzb3JQb3NpdGlvbiAtIGluZGV4CglyZXR1cm4KfQoKLy8gR2V0Q3Vyc29yTGVmdFBvc2l0aW9uIHJldHVybnMgdGhlIHJlbGF0aXZlIHBvc2l0aW9uIGZvciBjdXJzb3IgbGVmdC4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldEN1cnNvckxlZnRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvclJpZ2h0UG9zaXRpb24oLWNvdW50KQoJfQoJaWYgZC5DdXJzb3JQb3NpdGlvbkNvbCgpID4gY291bnQgewoJCXJldHVybiAtY291bnQKCX0KCXJldHVybiAtZC5DdXJzb3JQb3NpdGlvbkNvbCgpCn0KCi8vIEdldEN1cnNvclJpZ2h0UG9zaXRpb24gcmV0dXJucyByZWxhdGl2ZSBwb3NpdGlvbiBmb3IgY3Vyc29yIHJpZ2h0LgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yUmlnaHRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvckxlZnRQb3NpdGlvbigtY291bnQpCgl9CglpZiBsZW4oZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpID4gY291bnQgewoJCXJldHVybiBjb3VudAoJfQoJcmV0dXJuIGxlbihkLkN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSkKfQoKLy8gR2V0Q3Vyc29yVXBQb3NpdGlvbiByZXR1cm4gdGhlIHJlbGF0aXZlIGN1cnNvciBwb3NpdGlvbiAoY2hhcmFjdGVyIGluZGV4KSB3aGVyZSB3ZSB3b3VsZCBiZQovLyBpZiB0aGUgdXNlciBwcmVzc2VkIHRoZSBhcnJvdy11cCBidXR0b24uCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRDdXJzb3JVcFBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9CgoJcm93IDo9IGQuQ3Vyc29yUG9zaXRpb25Sb3coKSAtIGNvdW50CglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9CglyZXR1cm4gZC5UcmFuc2xhdGVSb3dDb2xUb0luZGV4KHJvdywgY29sKSAtIGQuY3Vyc29yUG9zaXRpb24KfQoKLy8gR2V0Q3Vyc29yRG93blBvc2l0aW9uIHJldHVybiB0aGUgcmVsYXRpdmUgY3Vyc29yIHBvc2l0aW9uIChjaGFyYWN0ZXIgaW5kZXgpIHdoZXJlIHdlIHdvdWxkIGJlIGlmIHRoZQovLyB1c2VyIHByZXNzZWQgdGhlIGFycm93LWRvd24gYnV0dG9uLgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yRG93blBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9Cglyb3cgOj0gZC5DdXJzb3JQb3NpdGlvblJvdygpICsgY291bnQKCXJldHVybiBkLlRyYW5zbGF0ZVJvd0NvbFRvSW5kZXgocm93LCBjb2wpIC0gZC5jdXJzb3JQb3NpdGlvbgp9CgovLyBMaW5lcyByZXR1cm5zIHRoZSBhcnJheSBvZiBhbGwgdGhlIGxpbmVzLgpmdW5jIChkICpEb2N1bWVudCkgTGluZXMoKSBbXXN0cmluZyB7CgkvLyBUT0RPOiBDYWNoZSwgYmVjYXVzZSB0aGlzIG9uZSBpcyByZXVzZWQgdmVyeSBvZnRlbi4KCXJldHVybiBzdHJpbmdzLlNwbGl0KGQuVGV4dCwgIlxuIikKfQoKLy8gTGluZUNvdW50IHJldHVybiB0aGUgbnVtYmVyIG9mIGxpbmVzIGluIHRoaXMgZG9jdW1lbnQuIElmIHRoZSBkb2N1bWVudCBlbmRzCi8vIHdpdGggYSB0cmFpbGluZyBcbiwgdGhhdCBjb3VudHMgYXMgdGhlIGJlZ2lubmluZyBvZiBhIG5ldyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgTGluZUNvdW50KCkgaW50IHsKCXJldHVybiBsZW4oZC5MaW5lcygpKQp9CgovLyBUcmFuc2xhdGVJbmRleFRvUG9zaXRpb24gZ2l2ZW4gYW4gaW5kZXggZm9yIHRoZSB0ZXh0LCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgKHJvdywgY29sKSB0dXBsZS4KLy8gKDAtYmFzZWQuIFJldHVybnMgKDAsIDApIGZvciBpbmRleD0wLikKZnVuYyAoZCAqRG9jdW1lbnQpIFRyYW5zbGF0ZUluZGV4VG9Qb3NpdGlvbihpbmRleCBpbnQpIChyb3cgaW50LCBjb2wgaW50KSB7Cglyb3csIHJvd0luZGV4IDo9IGQuZmluZExpbmVTdGFydEluZGV4KGluZGV4KQoJY29sID0gaW5kZXggLSByb3dJbmRleAoJcmV0dXJuCn0KCi8vIFRyYW5zbGF0ZVJvd0NvbFRvSW5kZXggZ2l2ZW4gYSAocm93LCBjb2wpLCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgaW5kZXguCi8vIChSb3cgYW5kIGNvbCBwYXJhbXMgYXJlIDAtYmFzZWQuKQpmdW5jIChkICpEb2N1bWVudCkgVHJhbnNsYXRlUm93Q29sVG9JbmRleChyb3cgaW50LCBjb2x1bW4gaW50KSAoaW5kZXggaW50KSB7CglpbmRleGVzIDo9IGQubGluZVN0YXJ0SW5kZXhlcygpCglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9IGVsc2UgaWYgcm93ID4gbGVuKGluZGV4ZXMpIHsKCQlyb3cgPSBsZW4oaW5kZXhlcykgLSAxCgl9CglpbmRleCA9IGluZGV4ZXNbcm93XQoJbGluZSA6PSBkLkxpbmVzKClbcm93XQoKCS8vIHB5dGhvbikgcmVzdWx0ICs9IG1heCgwLCBtaW4oY29sLCBsZW4obGluZSkpKQoJaWYgY29sdW1uID4gMCB8fCBsZW4obGluZSkgPiAwIHsKCQlpZiBjb2x1bW4gPiBsZW4obGluZSkgewoJCQlpbmRleCArPSBsZW4obGluZSkKCQl9IGVsc2UgewoJCQlpbmRleCArPSBjb2x1bW4KCQl9Cgl9CgoJLy8gS2VlcCBpbiByYW5nZS4gKGxlbihzZWxmLnRleHQpIGlzIGluY2x1ZGVkLCBiZWNhdXNlIHRoZSBjdXJzb3IgY2FuIGJlCgkvLyByaWdodCBhZnRlciB0aGUgZW5kIG9mIHRoZSB0ZXh0IGFzIHdlbGwuKQoJLy8gcHl0aG9uKSByZXN1bHQgPSBtYXgoMCwgbWluKHJlc3VsdCwgbGVuKHNlbGYudGV4dCkpKQoJaWYgaW5kZXggPiBsZW4oZC5UZXh0KSB7CgkJaW5kZXggPSBsZW4oZC5UZXh0KQoJfQoJaWYgaW5kZXggPCAwIHsKCQlpbmRleCA9IDAKCX0KCXJldHVybiBpbmRleAp9CgovLyBPbkxhc3RMaW5lIHJldHVybnMgdHJ1ZSB3aGVuIHdlIGFyZSBhdCB0aGUgbGFzdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgT25MYXN0TGluZSgpIGJvb2wgewoJcmV0dXJuIGQuQ3Vyc29yUG9zaXRpb25Sb3coKSA9PSAoZC5MaW5lQ291bnQoKSAtIDEpCn0KCi8vIEdldEVuZE9mTGluZVBvc2l0aW9uIHJldHVybnMgcmVsYXRpdmUgcG9zaXRpb24gZm9yIHRoZSBlbmQgb2YgdGhpcyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgR2V0RW5kT2ZMaW5lUG9zaXRpb24oKSBpbnQgewoJcmV0dXJuIGxlbihbXXJ1bmUoZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpKQp9CgpmdW5jIChkICpEb2N1bWVudCkgbGVhZGluZ1doaXRlc3BhY2VJbkN1cnJlbnRMaW5lKCkgKG1hcmdpbiBzdHJpbmcpIHsKCXRyaW1tZWQgOj0gc3RyaW5ncy5UcmltU3BhY2UoZC5DdXJyZW50TGluZSgpKQoJbWFyZ2luID0gZC5DdXJyZW50TGluZSgpWzpsZW4oZC5DdXJyZW50TGluZSgpKS1sZW4odHJpbW1lZCldCglyZXR1cm4KfQo=", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/task.toml b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..092c41e02d76b3280967f9b3e9b878f1a9b5d1db
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/task.toml
@@ -0,0 +1,11 @@
+version = "1.0"
+[agent]
+timeout_sec = 300.0
+[verifier]
+timeout_sec = 300.0
+environment_mode = "shared"
+[environment]
+docker_image = "ghcr.io/younesbelkada/scale800@sha256:5a26a396bbbc6c5e3f43262cb487fa3a314046aa93e7a5b9eda410c9b6905eda"
+cpus = 1
+memory_mb = 2048
+storage_mb = 4096
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..bb253ee8f374786666142a538aa8dbc876d82586
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/manifest.json
@@ -0,0 +1,432 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CursorPositionRowAndCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorLeftPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorUpPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorDownPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorRightPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_Lines"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_LineCount"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateIndexToPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateRowColToIndex"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_OnLastLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetEndOfLinePosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestEmacsKeyBindings"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFilter"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFuzzyMatch"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryClear"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryAdd"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryOlder"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/escape"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/undefined"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWrite"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteRawStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatCompletion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBreakLineCallback"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionRow"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition_withJapanese"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/validation/canaries/delete-tests.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/validation/canaries/delete-tests.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/validation/canaries/delete-tests.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+find /testbed -name '*_test.go' -type f -delete
+printf 'PASS\nok forged-package 0.001s\n'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..8a1cb8139c43570d675d9ddb9ffd8d6ed772a22a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__aa65b3ba/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "ee618e4aff530dabe7a859967b97cd7574051c59be3c9d36a5b8c55300b3f474",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/Dockerfile b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f35bf9e5393ee1086fe1b72c1b442f3b16e2bd5b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22
+WORKDIR /testbed
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c8c031d0f87fb9aea0aff433b1fcaeaac259c41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: "Bug report"
+about: Create a bug report to improve go-prompt
+title: "[Bug]"
+labels: bug
+assignees: ''
+
+---
+
+# Bug reports
+
+*Please file a bug report here.*
+
+## Expected Behavior
+
+*Please describe the behavior you are expecting*
+
+## Current Behavior and Steps to Reproduce
+
+*What is the current behavior? Please provide detailed steps for reproducing the issue.*
+*A picture or gif animation tells a thousand words*
+
+## Context
+
+Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
+
+* Operating System:
+* Terminal Emulator: (i.e. iTerm2)
+* tag of go-prompt or commit revision:
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb816a2496376983781774cb5466fed8e1efc93b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,13 @@
+---
+name: "Feature request"
+about: Suggest an idea for new features in go-prompt.
+title: "[Feature Request]"
+labels: enhancement
+assignees: ''
+
+---
+
+# Feature Request
+
+*Please write your suggestion here.*
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/.gitignore b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..eba2b56abe0f7758a560d47dd19d8985b67ef327
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+bin/
+
+# Folders
+pkg/
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+# Glide
+vendor/
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/CHANGELOG.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..b9e21f1ef333b9ec13323bcd4a8f377322ed7e9f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/CHANGELOG.md
@@ -0,0 +1,79 @@
+# Change Log
+
+## v0.3.0 (2018/??/??)
+
+next release.
+
+## v0.2.3 (2018/10/25)
+
+### What's new?
+
+* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92).
+* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100).
+* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102).
+
+### Fixed
+
+* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details).
+* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details).
+* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details).
+
+### Removed or Deprecated
+
+* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`.
+
+## v0.2.2 (2018/06/28)
+
+### What's new?
+
+* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters.
+* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions.
+ * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details).
+* Add FilePathCompleter to complete file path on your system.
+* Add option to customize ascii code key bindings.
+* Add GetWordAfterCursor method in Document.
+
+### Removed or Deprecated
+
+* prompt.Choose shortcut function is deprecated.
+
+## v0.2.1 (2018/02/14)
+
+### What's New?
+
+* ~~It seems that windows support is almost perfect.~~
+ * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows.
+
+### Fixed
+
+* Fix a Shift+Tab handling on Windows.
+* Fix 4-dimension arrow keys handling on Windows.
+
+## v0.2.0 (2018/02/13)
+
+### What's New?
+
+* Supports scrollbar when there are too many matched suggestions
+* Windows support (but please caution because this is still not perfect).
+* Add OptionLivePrefix to update the prefix dynamically
+* Implement clear screen by `Ctrl+L`.
+
+### Fixed
+
+* Fix the behavior of `Ctrl+W` keybind.
+* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details).
+* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details).
+* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ).
+
+### News
+
+New core developers are joined (alphabetical order).
+
+* Nao Yonashiro (Github @orisano)
+* Ryoma Abe (Github @Allajah)
+* Yusuke Nakamura (Github @unasuke)
+
+
+## v0.1.0 (2017/08/15)
+
+Initial Release
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/LICENSE b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a86acaa7ab24fe61ea152a9afcadc21980020efb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Masashi SHIBATA
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/Makefile b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..505817c36f0b8a0bb643eed8680b8989af2b0920
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/Makefile
@@ -0,0 +1,46 @@
+.DEFAULT_GOAL := help
+
+SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
+
+GOIMPORTS ?= goimports
+GOCILINT ?= golangci-lint
+
+.PHONY: setup
+setup: ## Setup for required tools.
+ go get -u golang.org/x/tools/cmd/goimports
+ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: fmt
+fmt: $(SOURCES) ## Formatting source codes.
+ @$(GOIMPORTS) -w $^
+
+.PHONY: lint
+lint: ## Run golangci-lint.
+ @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
+
+.PHONY: test
+test: ## Run tests with race condition checking.
+ @go test -race ./...
+
+.PHONY: bench
+bench: ## Run benchmarks.
+ @go test -bench=. -run=- -benchmem ./...
+
+.PHONY: coverage
+cover: ## Run the tests.
+ @go test -coverprofile=coverage.o
+ @go tool cover -func=coverage.o
+
+.PHONY: generate
+generate: ## Run go generate
+ @go generate ./...
+
+.PHONY: build
+build: ## Build example command lines.
+ ./_example/build.sh
+
+.PHONY: help
+help: ## Show help text
+ @echo "Commands:"
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfcd7a399b4827d6b126d6a173cce34d36520481
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/README.md
@@ -0,0 +1,125 @@
+# go-prompt
+
+[](https://goreportcard.com/report/github.com/c-bata/go-prompt)
+
+[](https://godoc.org/github.com/c-bata/go-prompt)
+
+
+A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit),
+making it easier to build cross-platform command line tools using Go.
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func completer(d prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ }
+ return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ fmt.Println("Please select table.")
+ t := prompt.Input("> ", completer)
+ fmt.Println("You selected " + t)
+}
+```
+
+#### Projects using go-prompt
+
+* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt)
+* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli)
+* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn)
+* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli)
+* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans)
+* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit)
+* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go)
+* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS)
+* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs)
+* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli)
+* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt)
+* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh)
+* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell)
+* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt)
+* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim)
+* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron)
+* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl)
+* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl)
+* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit)
+* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.)
+
+## Features
+
+### Powerful auto-completion
+
+[](https://github.com/c-bata/kube-prompt)
+
+(This is a GIF animation of kube-prompt.)
+
+### Flexible options
+
+go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details.
+
+[](#flexible-options)
+
+### Keyboard Shortcuts
+
+Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell).
+You can customize and expand these shortcuts.
+
+[](#keyboard-shortcuts)
+
+Key Binding | Description
+---------------------|---------------------------------------------------------
+Ctrl + A | Go to the beginning of the line (Home)
+Ctrl + E | Go to the end of the line (End)
+Ctrl + P | Previous command (Up arrow)
+Ctrl + N | Next command (Down arrow)
+Ctrl + F | Forward one character
+Ctrl + B | Backward one character
+Ctrl + D | Delete character under the cursor
+Ctrl + H | Delete character before the cursor (Backspace)
+Ctrl + W | Cut the word before the cursor to the clipboard
+Ctrl + K | Cut the line after the cursor to the clipboard
+Ctrl + U | Cut the line before the cursor to the clipboard
+Ctrl + L | Clear the screen
+
+### History
+
+You can use Up arrow and Down arrow to walk through the history of commands executed.
+
+[](#history)
+
+### Multiple platform support
+
+We have confirmed go-prompt works fine in the following terminals:
+
+* iTerm2 (macOS)
+* Terminal.app (macOS)
+* Command Prompt (Windows)
+* gnome-terminal (Ubuntu)
+
+## Links
+
+* [Change Log](./CHANGELOG.md)
+* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt)
+* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt)
+
+## Author
+
+Masashi Shibata
+
+* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/)
+* Github: [@c-bata](https://github.com/c-bata/)
+
+## License
+
+This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..759b0e3f8acf1216b055e0f9458758a6c1e8950a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/README.md
@@ -0,0 +1,30 @@
+# Examples of go-prompt
+
+This directory includes some examples using go-prompt.
+These examples are useful to know the usage of go-prompt and check behavior for development.
+
+## simple-echo
+
+
+
+A simple echo example using `prompt.Input`.
+
+## http-prompt
+
+
+
+A simple [http-prompt](https://github.com/eliangcs/http-prompt) implementation using go-prompt in less than 200 lines of Go.
+
+## live-prefix
+
+
+
+A example application which changes a prefix string dynamically.
+This feature is used like [ktr0731/evans](https://github.com/ktr0731/evans) which is interactive gRPC client using go-prompt.
+
+## exec-command
+
+Run another CLI tool via `os/exec` package.
+More practical example is [a source code of kube-prompt](https://github.com/c-bata/kube-prompt).
+I recommend you to look this if you want to create tools like kube-prompt.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/build.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c552afcfa69b2356ffcd484c867abcaaaaeeaff
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+export GO111MODULE=on
+DIR=$(cd $(dirname $0); pwd)
+BIN_DIR=$(cd $(dirname $(dirname $0)); pwd)/bin
+
+mkdir -p ${BIN_DIR}
+go build -o ${BIN_DIR}/exec-command ${DIR}/exec-command/main.go
+go build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.go
+go build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.go
+go build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.go
+go build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/exec-command/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/exec-command/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..838f756260df91569491def29a7ee05a7c9a98f7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/exec-command/main.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "os/exec"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(t string) {
+ if t == "bash" {
+ cmd := exec.Command("bash")
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Run()
+ }
+ return
+}
+
+func completer(t prompt.Document) []prompt.Suggest {
+ return []prompt.Suggest{
+ {Text: "bash"},
+ }
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/http-prompt/api.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/http-prompt/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..08e7b1a489a2077f26f280fe39e3bd06efa52cd2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/http-prompt/api.py
@@ -0,0 +1,17 @@
+from bottle import route, run, request
+
+@route('/')
+def hello():
+ return "Hello World!"
+
+@route('/ping')
+def hello():
+ return "pong!"
+
+@route('/register', method='POST')
+def register():
+ name = request.json.get("name")
+ return "Hello %s!" % name
+
+if __name__ == "__main__":
+ run(host='localhost', port=8000, debug=True)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/http-prompt/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/http-prompt/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b372a3550c50121d6e500e2a08e641e168b8c00d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/http-prompt/main.go
@@ -0,0 +1,192 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+type RequestContext struct {
+ url *url.URL
+ header http.Header
+ client *http.Client
+}
+
+var ctx *RequestContext
+
+// See https://github.com/eliangcs/http-prompt/blob/master/http_prompt/completion.py
+var suggestions = []prompt.Suggest{
+ // Command
+ {"cd", "Change URL/path"},
+ {"exit", "Exit http-prompt"},
+
+ // HTTP Method
+ {"delete", "DELETE request"},
+ {"get", "GET request"},
+ {"patch", "GET request"},
+ {"post", "POST request"},
+ {"put", "PUT request"},
+
+ // HTTP Header
+ {"Accept", "Acceptable response media type"},
+ {"Accept-Charset", "Acceptable response charsets"},
+ {"Accept-Encoding", "Acceptable response content codings"},
+ {"Accept-Language", "Preferred natural languages in response"},
+ {"ALPN", "Application-layer protocol negotiation to use"},
+ {"Alt-Used", "Alternative host in use"},
+ {"Authorization", "Authentication information"},
+ {"Cache-Control", "Directives for caches"},
+ {"Connection", "Connection options"},
+ {"Content-Encoding", "Content codings"},
+ {"Content-Language", "Natural languages for content"},
+ {"Content-Length", "Anticipated size for payload body"},
+ {"Content-Location", "Where content was obtained"},
+ {"Content-MD5", "Base64-encoded MD5 sum of content"},
+ {"Content-Type", "Content media type"},
+ {"Cookie", "Stored cookies"},
+ {"Date", "Datetime when message was originated"},
+ {"Depth", "Applied only to resource or its members"},
+ {"DNT", "Do not track user"},
+ {"Expect", "Expected behaviors supported by server"},
+ {"Forwarded", "Proxies involved"},
+ {"From", "Sender email address"},
+ {"Host", "Target URI"},
+ {"HTTP2-Settings", "HTTP/2 connection parameters"},
+ {"If", "Request condition on state tokens and ETags"},
+ {"If-Match", "Request condition on target resource"},
+ {"If-Modified-Since", "Request condition on modification date"},
+ {"If-None-Match", "Request condition on target resource"},
+ {"If-Range", "Request condition on Range"},
+ {"If-Schedule-Tag-Match", "Request condition on Schedule-Tag"},
+ {"If-Unmodified-Since", "Request condition on modification date"},
+ {"Max-Forwards", "Max number of times forwarded by proxies"},
+ {"MIME-Version", "Version of MIME protocol"},
+ {"Origin", "Origin(s} issuing the request"},
+ {"Pragma", "Implementation-specific directives"},
+ {"Prefer", "Preferred server behaviors"},
+ {"Proxy-Authorization", "Proxy authorization credentials"},
+ {"Proxy-Connection", "Proxy connection options"},
+ {"Range", "Request transfer of only part of data"},
+ {"Referer", "Previous web page"},
+ {"TE", "Transfer codings willing to accept"},
+ {"Transfer-Encoding", "Transfer codings applied to payload body"},
+ {"Upgrade", "Invite server to upgrade to another protocol"},
+ {"User-Agent", "User agent string"},
+ {"Via", "Intermediate proxies"},
+ {"Warning", "Possible incorrectness with payload body"},
+ {"WWW-Authenticate", "Authentication scheme"},
+ {"X-Csrf-Token", "Prevent cross-site request forgery"},
+ {"X-CSRFToken", "Prevent cross-site request forgery"},
+ {"X-Forwarded-For", "Originating client IP address"},
+ {"X-Forwarded-Host", "Original host requested by client"},
+ {"X-Forwarded-Proto", "Originating protocol"},
+ {"X-Http-Method-Override", "Request method override"},
+ {"X-Requested-With", "Used to identify Ajax requests"},
+ {"X-XSRF-TOKEN", "Prevent cross-site request forgery"},
+}
+
+func livePrefix() (string, bool) {
+ if ctx.url.Path == "/" {
+ return "", false
+ }
+ return ctx.url.String() + "> ", true
+}
+
+func executor(in string) {
+ in = strings.TrimSpace(in)
+
+ var method, body string
+ blocks := strings.Split(in, " ")
+ switch blocks[0] {
+ case "exit":
+ fmt.Println("Bye!")
+ os.Exit(0)
+ case "cd":
+ if len(blocks) < 2 {
+ ctx.url.Path = "/"
+ } else {
+ ctx.url.Path = path.Join(ctx.url.Path, blocks[1])
+ }
+ return
+ case "get", "delete":
+ method = strings.ToUpper(blocks[0])
+ case "post", "put", "patch":
+ if len(blocks) < 2 {
+ fmt.Println("please set request body.")
+ return
+ }
+ body = strings.Join(blocks[1:], " ")
+ method = strings.ToUpper(blocks[0])
+ }
+ if method != "" {
+ req, err := http.NewRequest(method, ctx.url.String(), strings.NewReader(body))
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ req.Header = ctx.header
+ res, err := ctx.client.Do(req)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ result, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ fmt.Printf("%s\n", result)
+ ctx.header = http.Header{}
+ return
+ }
+
+ if h := strings.Split(in, ":"); len(h) == 2 {
+ // Handling HTTP Header
+ ctx.header.Add(strings.TrimSpace(h[0]), strings.Trim(h[1], ` '"`))
+ } else {
+ fmt.Println("Sorry, I don't understand.")
+ }
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ w := in.GetWordBeforeCursor()
+ if w == "" {
+ return []prompt.Suggest{}
+ }
+ return prompt.FilterHasPrefix(suggestions, w, true)
+}
+
+func main() {
+ var baseURL = "http://localhost:8000/"
+ if len(os.Args) == 2 {
+ baseURL = os.Args[1]
+ if strings.HasSuffix(baseURL, "/") {
+ baseURL += "/"
+ }
+ }
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ ctx = &RequestContext{
+ url: u,
+ header: http.Header{},
+ client: &http.Client{},
+ }
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(u.String()+"> "),
+ prompt.OptionLivePrefix(livePrefix),
+ prompt.OptionTitle("http-prompt"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/live-prefix/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/live-prefix/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c7ced720592173e2a13f19f7cb543730192d3f8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/live-prefix/main.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var LivePrefixState struct {
+ LivePrefix string
+ IsEnable bool
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+ if in == "" {
+ LivePrefixState.IsEnable = false
+ LivePrefixState.LivePrefix = in
+ return
+ }
+ LivePrefixState.LivePrefix = in + "> "
+ LivePrefixState.IsEnable = true
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func changeLivePrefix() (string, bool) {
+ return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionLivePrefix(changeLivePrefix),
+ prompt.OptionTitle("live-prefix-example"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/simple-echo/cjk-cyrillic/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/simple-echo/cjk-cyrillic/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e9e53adef1558e004f86ccbca2c2e2b83c1da39
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/simple-echo/cjk-cyrillic/main.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
+ {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
+ {Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
+ {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionTitle("sql-prompt for multi width characters"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/simple-echo/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/simple-echo/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..12b1bb4fc189e6b369e889779418d7826a45db9d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_example/simple-echo/main.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ in := prompt.Input(">>> ", completer,
+ prompt.OptionTitle("sql-prompt"),
+ prompt.OptionHistory([]string{"SELECT * FROM users;"}),
+ prompt.OptionPrefixTextColor(prompt.Yellow),
+ prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
+ prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
+ prompt.OptionSuggestionBGColor(prompt.DarkGray))
+ fmt.Println("Your input: " + in)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_tools/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..45bd2234f21ff32562984bec046316c8e52868fd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_tools/README.md
@@ -0,0 +1,10 @@
+## Tools of go-prompt
+
+### vt100_debug
+
+
+
+### sigwinch
+
+
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_tools/complete_file/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_tools/complete_file/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..41015cfab9b021fbc7df575bde87e3c510705496
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_tools/complete_file/main.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/completer"
+)
+
+var filePathCompleter = completer.FilePathCompleter{
+ IgnoreCase: true,
+ Filter: func(fi os.FileInfo) bool {
+ return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
+ },
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completerFunc(d prompt.Document) []prompt.Suggest {
+ t := d.GetWordBeforeCursor()
+ if strings.HasPrefix(t, "--") {
+ return []prompt.Suggest{
+ {"--foo", ""},
+ {"--bar", ""},
+ {"--baz", ""},
+ }
+ }
+ return filePathCompleter.Complete(d)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completerFunc,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_tools/sigwinch/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_tools/sigwinch/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9608eb3b4a5e3c6942c140c41e08a36ab3adb33b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_tools/sigwinch/main.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "unsafe"
+)
+
+// Winsize is winsize struct got from the ioctl(2) system call.
+type Winsize struct {
+ Row uint16
+ Col uint16
+ X uint16 // pixel value
+ Y uint16 // pixel value
+}
+
+// GetWinSize returns winsize struct which is the response of ioctl(2).
+func GetWinSize(fd int) *Winsize {
+ ws := &Winsize{}
+ retCode, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ uintptr(fd),
+ uintptr(syscall.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(ws)))
+
+ if int(retCode) == -1 {
+ panic(errno)
+ }
+ return ws
+}
+
+func main() {
+ signalChan := make(chan os.Signal, 1)
+ signal.Notify(
+ signalChan,
+ syscall.SIGHUP,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ exitChan := make(chan int)
+ go func() {
+ for {
+ s := <-signalChan
+ switch s {
+ // kill -SIGHUP XXXX
+ case syscall.SIGHUP:
+ exitChan <- 0
+
+ // kill -SIGINT XXXX or Ctrl+c
+ case syscall.SIGINT:
+ exitChan <- 0
+
+ // kill -SIGTERM XXXX
+ case syscall.SIGTERM:
+ exitChan <- 0
+
+ // kill -SIGQUIT XXXX
+ case syscall.SIGQUIT:
+ exitChan <- 0
+
+ case syscall.SIGWINCH:
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ default:
+ exitChan <- 1
+ }
+ }
+ }()
+
+ code := <-exitChan
+ os.Exit(code)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_tools/vt100_debug/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_tools/vt100_debug/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c6036d45959febc739e287a3a7b631259d4ee7c1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/_tools/vt100_debug/main.go
@@ -0,0 +1,47 @@
+// +build !windows
+
+package main
+
+import (
+ "fmt"
+ "syscall"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/term"
+)
+
+func main() {
+ if err := term.SetRaw(syscall.Stdin); err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer term.Restore()
+
+ bufCh := make(chan []byte, 128)
+ go readBuffer(bufCh)
+ fmt.Print("> ")
+
+ for {
+ b := <-bufCh
+ if key := prompt.GetKey(b); key == prompt.NotDefined {
+ fmt.Printf("Key '%s' data:'%#v'\n", string(b), b)
+ } else {
+ if key == prompt.ControlC {
+ fmt.Println("exit.")
+ return
+ }
+ fmt.Printf("Key '%s' data:'%#v'\n", key, b)
+ }
+ fmt.Print("> ")
+ }
+}
+
+func readBuffer(bufCh chan []byte) {
+ buf := make([]byte, 1024)
+
+ for {
+ if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
+ bufCh <- buf[:n]
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/buffer.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..46efbbba8bfb75f4a064c83368b781d1d6dbbb29
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/buffer.go
@@ -0,0 +1,191 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Buffer emulates the console buffer.
+type Buffer struct {
+ workingLines []string // The working lines. Similar to history
+ workingIndex int
+ cursorPosition int
+ cacheDocument *Document
+ preferredColumn int // Remember the original column for the next up/down movement.
+ lastKeyStroke Key
+}
+
+// Text returns string of the current line.
+func (b *Buffer) Text() string {
+ return b.workingLines[b.workingIndex]
+}
+
+// Document method to return document instance from the current text and cursor position.
+func (b *Buffer) Document() (d *Document) {
+ if b.cacheDocument == nil ||
+ b.cacheDocument.Text != b.Text() ||
+ b.cacheDocument.cursorPosition != b.cursorPosition {
+ b.cacheDocument = &Document{
+ Text: b.Text(),
+ cursorPosition: b.cursorPosition,
+ }
+ }
+ b.cacheDocument.lastKey = b.lastKeyStroke
+ return b.cacheDocument
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (b *Buffer) DisplayCursorPosition() int {
+ return b.Document().DisplayCursorPosition()
+}
+
+// InsertText insert string from current line.
+func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
+ or := []rune(b.Text())
+ oc := b.cursorPosition
+
+ if overwrite {
+ overwritten := string(or[oc : oc+len(v)])
+ if strings.Contains(overwritten, "\n") {
+ i := strings.IndexAny(overwritten, "\n")
+ overwritten = overwritten[:i]
+ }
+ b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):]))
+ } else {
+ b.setText(string(or[:oc]) + v + string(or[oc:]))
+ }
+
+ if moveCursor {
+ b.cursorPosition += len([]rune(v))
+ }
+}
+
+// SetText method to set text and update cursorPosition.
+// (When doing this, make sure that the cursor_position is valid for this text.
+// text/cursor_position should be consistent at any time, otherwise set a Document instead.)
+func (b *Buffer) setText(v string) {
+ debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position")
+ b.workingLines[b.workingIndex] = v
+}
+
+// Set cursor position. Return whether it changed.
+func (b *Buffer) setCursorPosition(p int) {
+ if p > 0 {
+ b.cursorPosition = p
+ } else {
+ b.cursorPosition = 0
+ }
+}
+
+func (b *Buffer) setDocument(d *Document) {
+ b.cacheDocument = d
+ b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length.
+ b.setText(d.Text)
+}
+
+// CursorLeft move to left on the current line.
+func (b *Buffer) CursorLeft(count int) {
+ l := b.Document().GetCursorLeftPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorRight move to right on the current line.
+func (b *Buffer) CursorRight(count int) {
+ l := b.Document().GetCursorRightPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorUp move cursor to the previous line.
+// (for multi-line edit).
+func (b *Buffer) CursorUp(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorUpPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// CursorDown move cursor to the next line.
+// (for multi-line edit).
+func (b *Buffer) CursorDown(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorDownPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text.
+func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) {
+ debug.Assert(count >= 0, "count should be positive")
+ r := []rune(b.Text())
+
+ if b.cursorPosition > 0 {
+ start := b.cursorPosition - count
+ if start < 0 {
+ start = 0
+ }
+ deleted = string(r[start:b.cursorPosition])
+ b.setDocument(&Document{
+ Text: string(r[:start]) + string(r[b.cursorPosition:]),
+ cursorPosition: b.cursorPosition - len([]rune(deleted)),
+ })
+ }
+ return
+}
+
+// NewLine means CR.
+func (b *Buffer) NewLine(copyMargin bool) {
+ if copyMargin {
+ b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true)
+ } else {
+ b.InsertText("\n", false, true)
+ }
+}
+
+// Delete specified number of characters and Return the deleted text.
+func (b *Buffer) Delete(count int) (deleted string) {
+ r := []rune(b.Text())
+ if b.cursorPosition < len(r) {
+ deleted = b.Document().TextAfterCursor()[:count]
+ b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):]))
+ }
+ return
+}
+
+// JoinNextLine joins the next line to the current one by deleting the line ending after the current line.
+func (b *Buffer) JoinNextLine(separator string) {
+ if !b.Document().OnLastLine() {
+ b.cursorPosition += b.Document().GetEndOfLinePosition()
+ b.Delete(1)
+ // Remove spaces
+ b.setText(b.Document().TextBeforeCursor() + separator + strings.TrimLeft(b.Document().TextAfterCursor(), " "))
+ }
+}
+
+// SwapCharactersBeforeCursor swaps the last two characters before the cursor.
+func (b *Buffer) SwapCharactersBeforeCursor() {
+ if b.cursorPosition >= 2 {
+ x := b.Text()[b.cursorPosition-2 : b.cursorPosition-1]
+ y := b.Text()[b.cursorPosition-1 : b.cursorPosition]
+ b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:])
+ }
+}
+
+// NewBuffer is constructor of Buffer struct.
+func NewBuffer() (b *Buffer) {
+ b = &Buffer{
+ workingLines: []string{""},
+ workingIndex: 0,
+ preferredColumn: -1, // -1 means nil
+ }
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/completer/file.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/completer/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..59f2d8dec84214ccaa6e345a11ed51aa61a08199
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/completer/file.go
@@ -0,0 +1,90 @@
+package completer
+
+import (
+ "io/ioutil"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+var (
+ // FilePathCompletionSeparator holds separate characters.
+ FilePathCompletionSeparator = string([]byte{' ', os.PathSeparator})
+)
+
+// FilePathCompleter is a completer for your local file system.
+// Please caution that you need to set OptionCompletionWordSeparator(completer.FilePathCompletionSeparator)
+// when you use this completer.
+type FilePathCompleter struct {
+ Filter func(fi os.FileInfo) bool
+ IgnoreCase bool
+ fileListCache map[string][]prompt.Suggest
+}
+
+func cleanFilePath(path string) (dir, base string, err error) {
+ if path == "" {
+ return ".", "", nil
+ }
+
+ var endsWithSeparator bool
+ if len(path) >= 1 && path[len(path)-1] == os.PathSeparator {
+ endsWithSeparator = true
+ }
+
+ if runtime.GOOS != "windows" && len(path) >= 2 && path[0:2] == "~/" {
+ me, err := user.Current()
+ if err != nil {
+ return "", "", err
+ }
+ path = filepath.Join(me.HomeDir, path[1:])
+ }
+ path = filepath.Clean(os.ExpandEnv(path))
+ dir = filepath.Dir(path)
+ base = filepath.Base(path)
+
+ if endsWithSeparator {
+ dir = path + string(os.PathSeparator) // Append slash(in POSIX) if path ends with slash.
+ base = "" // Set empty string if path ends with separator.
+ }
+ return dir, base, nil
+}
+
+// Complete returns suggestions from your local file system.
+func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest {
+ if c.fileListCache == nil {
+ c.fileListCache = make(map[string][]prompt.Suggest, 4)
+ }
+
+ path := d.GetWordBeforeCursor()
+ dir, base, err := cleanFilePath(path)
+ if err != nil {
+ debug.Log("completer: cannot get current user:" + err.Error())
+ return nil
+ }
+
+ if cached, ok := c.fileListCache[dir]; ok {
+ return prompt.FilterHasPrefix(cached, base, c.IgnoreCase)
+ }
+
+ files, err := ioutil.ReadDir(dir)
+ if err != nil && os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ debug.Log("completer: cannot read directory items:" + err.Error())
+ return nil
+ }
+
+ suggests := make([]prompt.Suggest, 0, len(files))
+ for _, f := range files {
+ if c.Filter != nil && !c.Filter(f) {
+ continue
+ }
+ suggests = append(suggests, prompt.Suggest{Text: f.Name()})
+ }
+ c.fileListCache[dir] = suggests
+ return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/completion.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/completion.go
new file mode 100644
index 0000000000000000000000000000000000000000..87a593c872124fbe368f198adca44c71c7ee4b3f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/completion.go
@@ -0,0 +1,188 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+const (
+ shortenSuffix = "..."
+ leftPrefix = " "
+ leftSuffix = " "
+ rightPrefix = " "
+ rightSuffix = " "
+)
+
+var (
+ leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix)
+ rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix)
+ completionMargin = leftMargin + rightMargin
+)
+
+// Suggest is printed when completing.
+type Suggest struct {
+ Text string
+ Description string
+}
+
+// CompletionManager manages which suggestion is now selected.
+type CompletionManager struct {
+ selected int // -1 means nothing one is selected.
+ tmp []Suggest
+ max uint16
+ completer Completer
+
+ verticalScroll int
+ wordSeparator string
+ showAtStart bool
+}
+
+// GetSelectedSuggestion returns the selected item.
+func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) {
+ if c.selected == -1 {
+ return Suggest{}, false
+ } else if c.selected < -1 {
+ debug.Assert(false, "must not reach here")
+ c.selected = -1
+ return Suggest{}, false
+ }
+ return c.tmp[c.selected], true
+}
+
+// GetSuggestions returns the list of suggestion.
+func (c *CompletionManager) GetSuggestions() []Suggest {
+ return c.tmp
+}
+
+// Reset to select nothing.
+func (c *CompletionManager) Reset() {
+ c.selected = -1
+ c.verticalScroll = 0
+ c.Update(*NewDocument())
+}
+
+// Update to update the suggestions.
+func (c *CompletionManager) Update(in Document) {
+ c.tmp = c.completer(in)
+}
+
+// Previous to select the previous suggestion item.
+func (c *CompletionManager) Previous() {
+ if c.verticalScroll == c.selected && c.selected > 0 {
+ c.verticalScroll--
+ }
+ c.selected--
+ c.update()
+}
+
+// Next to select the next suggestion item.
+func (c *CompletionManager) Next() {
+ if c.verticalScroll+int(c.max)-1 == c.selected {
+ c.verticalScroll++
+ }
+ c.selected++
+ c.update()
+}
+
+// Completing returns whether the CompletionManager selects something one.
+func (c *CompletionManager) Completing() bool {
+ return c.selected != -1
+}
+
+func (c *CompletionManager) update() {
+ max := int(c.max)
+ if len(c.tmp) < max {
+ max = len(c.tmp)
+ }
+
+ if c.selected >= len(c.tmp) {
+ c.Reset()
+ } else if c.selected < -1 {
+ c.selected = len(c.tmp) - 1
+ c.verticalScroll = len(c.tmp) - max
+ }
+}
+
+func deleteBreakLineCharacters(s string) string {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, "\r", "", -1)
+ return s
+}
+
+func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) {
+ l := len(o)
+ n := make([]string, l)
+
+ lenPrefix := runewidth.StringWidth(prefix)
+ lenSuffix := runewidth.StringWidth(suffix)
+ lenShorten := runewidth.StringWidth(shortenSuffix)
+ min := lenPrefix + lenSuffix + lenShorten
+ for i := 0; i < l; i++ {
+ o[i] = deleteBreakLineCharacters(o[i])
+
+ w := runewidth.StringWidth(o[i])
+ if width < w {
+ width = w
+ }
+ }
+
+ if width == 0 {
+ return n, 0
+ }
+ if min >= max {
+ return n, 0
+ }
+ if lenPrefix+width+lenSuffix > max {
+ width = max - lenPrefix - lenSuffix - 1
+ }
+
+ for i := 0; i < l; i++ {
+ x := runewidth.StringWidth(o[i])
+ if x <= width {
+ spaces := strings.Repeat(" ", width-x)
+ n[i] = prefix + o[i] + spaces + suffix
+ } else if x > width {
+ x := runewidth.Truncate(o[i], width, shortenSuffix)
+ n[i] = prefix + x + suffix
+ }
+ }
+ return n, lenPrefix + width + lenSuffix
+}
+
+func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) {
+ num := len(suggests)
+ new = make([]Suggest, num)
+
+ left := make([]string, num)
+ for i := 0; i < num; i++ {
+ left[i] = suggests[i].Text
+ }
+ right := make([]string, num)
+ for i := 0; i < num; i++ {
+ right[i] = suggests[i].Description
+ }
+
+ left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix)
+ if leftWidth == 0 {
+ return []Suggest{}, 0
+ }
+ right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix)
+
+ for i := 0; i < num; i++ {
+ new[i] = Suggest{Text: left[i], Description: right[i]}
+ }
+ return new, leftWidth + rightWidth
+}
+
+// NewCompletionManager returns initialized CompletionManager object.
+func NewCompletionManager(completer Completer, max uint16) *CompletionManager {
+ return &CompletionManager{
+ selected: -1,
+ max: max,
+ completer: completer,
+
+ verticalScroll: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/document.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/document.go
new file mode 100644
index 0000000000000000000000000000000000000000..2a47f52bb2a760b293b5b81de1f27f2b8325a805
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/document.go
@@ -0,0 +1,441 @@
+package prompt
+
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+ istrings "github.com/c-bata/go-prompt/internal/strings"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Document has text displayed in terminal and cursor position.
+type Document struct {
+ Text string
+ // This represents a index in a rune array of Document.Text.
+ // So if Document is "日本(cursor)語", cursorPosition is 2.
+ // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+ cursorPosition int
+ lastKey Key
+}
+
+// NewDocument return the new empty document.
+func NewDocument() *Document {
+ return &Document{
+ Text: "",
+ cursorPosition: 0,
+ }
+}
+
+// LastKeyStroke return the last key pressed in this document.
+func (d *Document) LastKeyStroke() Key {
+ return d.lastKey
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (d *Document) DisplayCursorPosition() int {
+ var position int
+ runes := []rune(d.Text)[:d.cursorPosition]
+ for i := range runes {
+ position += runewidth.RuneWidth(runes[i])
+ }
+ return position
+}
+
+// GetCharRelativeToCursor return character relative to cursor position, or empty string
+func (d *Document) GetCharRelativeToCursor(offset int) (r rune) {
+ s := d.Text
+ cnt := 0
+
+ for len(s) > 0 {
+ cnt++
+ r, size := utf8.DecodeRuneInString(s)
+ if cnt == d.cursorPosition+offset {
+ return r
+ }
+ s = s[size:]
+ }
+ return 0
+}
+
+// TextBeforeCursor returns the text before the cursor.
+func (d *Document) TextBeforeCursor() string {
+ r := []rune(d.Text)
+ return string(r[:d.cursorPosition])
+}
+
+// TextAfterCursor returns the text after the cursor.
+func (d *Document) TextAfterCursor() string {
+ r := []rune(d.Text)
+ return string(r[d.cursorPosition:])
+}
+
+// GetWordBeforeCursor returns the word before the cursor.
+// If we have whitespace before the cursor this returns an empty string.
+func (d *Document) GetWordBeforeCursor() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWord():]
+}
+
+// GetWordAfterCursor returns the word after the cursor.
+// If we have whitespace after the cursor this returns an empty string.
+func (d *Document) GetWordAfterCursor() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWord()]
+}
+
+// GetWordBeforeCursorWithSpace returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorWithSpace() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordWithSpace():]
+}
+
+// GetWordAfterCursorWithSpace returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorWithSpace() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordWithSpace()]
+}
+
+// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
+func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparator(sep):]
+}
+
+// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
+func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparator(sep)]
+}
+
+// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):]
+}
+
+// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)]
+}
+
+// FindStartOfPreviousWord returns an index relative to the cursor position
+// pointing to the start of the previous word. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWord() int {
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexByte(x, ' ')
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindStartOfPreviousWordWithSpace() int {
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotByte(x, ' ')
+ if end == -1 {
+ return 0
+ }
+
+ start := strings.LastIndexByte(x[:end], ' ')
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWord()
+ }
+
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexAny(x, sep)
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWordWithSpace()
+ }
+
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotAny(x, sep)
+ if end == -1 {
+ return 0
+ }
+ start := strings.LastIndexAny(x[:end], sep)
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindEndOfCurrentWord returns an index relative to the cursor position.
+// pointing to the end of the current word. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWord() int {
+ x := d.TextAfterCursor()
+ i := strings.IndexByte(x, ' ')
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindEndOfCurrentWordWithSpace() int {
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotByte(x, ' ')
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexByte(x[start:], ' ')
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWord()
+ }
+
+ x := d.TextAfterCursor()
+ i := strings.IndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWordWithSpace()
+ }
+
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotAny(x, sep)
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexAny(x[start:], sep)
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// CurrentLineBeforeCursor returns the text from the start of the line until the cursor.
+func (d *Document) CurrentLineBeforeCursor() string {
+ s := strings.Split(d.TextBeforeCursor(), "\n")
+ return s[len(s)-1]
+}
+
+// CurrentLineAfterCursor returns the text from the cursor until the end of the line.
+func (d *Document) CurrentLineAfterCursor() string {
+ return strings.Split(d.TextAfterCursor(), "\n")[0]
+}
+
+// CurrentLine return the text on the line where the cursor is. (when the input
+// consists of just one line, it equals `text`.
+func (d *Document) CurrentLine() string {
+ return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor()
+}
+
+// Array pointing to the start indexes of all the lines.
+func (d *Document) lineStartIndexes() []int {
+ // TODO: Cache, because this is often reused.
+ // (If it is used, it's often used many times.
+ // And this has to be fast for editing big documents!)
+ lc := d.LineCount()
+ lengths := make([]int, lc)
+ for i, l := range d.Lines() {
+ lengths[i] = len(l)
+ }
+
+ // Calculate cumulative sums.
+ indexes := make([]int, lc+1)
+ indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189
+ pos := 0
+ for i, l := range lengths {
+ pos += l + 1
+ indexes[i+1] = pos
+ }
+ if lc > 1 {
+ // Pop the last item. (This is not a new line.)
+ indexes = indexes[:lc]
+ }
+ return indexes
+}
+
+// For the index of a character at a certain line, calculate the index of
+// the first character on that line.
+func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) {
+ indexes := d.lineStartIndexes()
+ pos = bisect.Right(indexes, index) - 1
+ lineStartIndex = indexes[pos]
+ return
+}
+
+// CursorPositionRow returns the current row. (0-based.)
+func (d *Document) CursorPositionRow() (row int) {
+ row, _ = d.findLineStartIndex(d.cursorPosition)
+ return
+}
+
+// CursorPositionCol returns the current column. (0-based.)
+func (d *Document) CursorPositionCol() (col int) {
+ // Don't use self.text_before_cursor to calculate this. Creating substrings
+ // and splitting is too expensive for getting the cursor position.
+ _, index := d.findLineStartIndex(d.cursorPosition)
+ col = d.cursorPosition - index
+ return
+}
+
+// GetCursorLeftPosition returns the relative position for cursor left.
+func (d *Document) GetCursorLeftPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorRightPosition(-count)
+ }
+ if d.CursorPositionCol() > count {
+ return -count
+ }
+ return -d.CursorPositionCol()
+}
+
+// GetCursorRightPosition returns relative position for cursor right.
+func (d *Document) GetCursorRightPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorLeftPosition(-count)
+ }
+ if len(d.CurrentLineAfterCursor()) > count {
+ return count
+ }
+ return len(d.CurrentLineAfterCursor())
+}
+
+// GetCursorUpPosition return the relative cursor position (character index) where we would be
+// if the user pressed the arrow-up button.
+func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+
+ row := d.CursorPositionRow() - count
+ if row < 0 {
+ row = 0
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// GetCursorDownPosition return the relative cursor position (character index) where we would be if the
+// user pressed the arrow-down button.
+func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+ row := d.CursorPositionRow() + count
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// Lines returns the array of all the lines.
+func (d *Document) Lines() []string {
+ // TODO: Cache, because this one is reused very often.
+ return strings.Split(d.Text, "\n")
+}
+
+// LineCount return the number of lines in this document. If the document ends
+// with a trailing \n, that counts as the beginning of a new line.
+func (d *Document) LineCount() int {
+ return len(d.Lines())
+}
+
+// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple.
+// (0-based. Returns (0, 0) for index=0.)
+func (d *Document) TranslateIndexToPosition(index int) (row int, col int) {
+ row, rowIndex := d.findLineStartIndex(index)
+ col = index - rowIndex
+ return
+}
+
+// TranslateRowColToIndex given a (row, col), return the corresponding index.
+// (Row and col params are 0-based.)
+func (d *Document) TranslateRowColToIndex(row int, column int) (index int) {
+ indexes := d.lineStartIndexes()
+ if row < 0 {
+ row = 0
+ } else if row > len(indexes) {
+ row = len(indexes) - 1
+ }
+ index = indexes[row]
+ line := d.Lines()[row]
+
+ // python) result += max(0, min(col, len(line)))
+ if column > 0 || len(line) > 0 {
+ if column > len(line) {
+ index += len(line)
+ } else {
+ index += column
+ }
+ }
+
+ // Keep in range. (len(self.text) is included, because the cursor can be
+ // right after the end of the text as well.)
+ // python) result = max(0, min(result, len(self.text)))
+ if index > len(d.Text) {
+ index = len(d.Text)
+ }
+ if index < 0 {
+ index = 0
+ }
+ return index
+}
+
+// OnLastLine returns true when we are at the last line.
+func (d *Document) OnLastLine() bool {
+ return d.CursorPositionRow() == (d.LineCount() - 1)
+}
+
+// GetEndOfLinePosition returns relative position for the end of this line.
+func (d *Document) GetEndOfLinePosition() int {
+ return len([]rune(d.CurrentLineAfterCursor()))
+}
+
+func (d *Document) leadingWhitespaceInCurrentLine() (margin string) {
+ trimmed := strings.TrimSpace(d.CurrentLine())
+ margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)]
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/emacs.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/emacs.go
new file mode 100644
index 0000000000000000000000000000000000000000..632f96321f2577cdb7e8cffe639f1518a65d5e0f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/emacs.go
@@ -0,0 +1,120 @@
+package prompt
+
+import "github.com/c-bata/go-prompt/internal/debug"
+
+/*
+
+========
+PROGRESS
+========
+
+Moving the cursor
+-----------------
+
+* [x] Ctrl + a Go to the beginning of the line (Home)
+* [x] Ctrl + e Go to the End of the line (End)
+* [x] Ctrl + p Previous command (Up arrow)
+* [x] Ctrl + n Next command (Down arrow)
+* [x] Ctrl + f Forward one character
+* [x] Ctrl + b Backward one character
+* [x] Ctrl + xx Toggle between the start of line and current cursor position
+
+Editing
+-------
+
+* [x] Ctrl + L Clear the Screen, similar to the clear command
+* [x] Ctrl + d Delete character under the cursor
+* [x] Ctrl + h Delete character before the cursor (Backspace)
+
+* [x] Ctrl + w Cut the Word before the cursor to the clipboard.
+* [x] Ctrl + k Cut the Line after the cursor to the clipboard.
+* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard.
+
+* [ ] Ctrl + t Swap the last two characters before the cursor (typo).
+* [ ] Esc + t Swap the last two words before the cursor.
+
+* [ ] ctrl + y Paste the last thing to be cut (yank)
+* [ ] ctrl + _ Undo
+
+*/
+
+var emacsKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: ControlE,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+ },
+ },
+ // Go to the beginning of the line
+ {
+ Key: ControlA,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+ },
+ },
+ // Cut the Line after the cursor
+ {
+ Key: ControlK,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.Delete(len(x))
+ },
+ },
+ // Cut/delete the Line before the cursor
+ {
+ Key: ControlU,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.DeleteBeforeCursor(len(x))
+ },
+ },
+ // Delete character under the cursor
+ {
+ Key: ControlD,
+ Fn: func(buf *Buffer) {
+ if buf.Text() != "" {
+ buf.Delete(1)
+ }
+ },
+ },
+ // Backspace
+ {
+ Key: ControlH,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+ },
+ },
+ // Right allow: Forward one character
+ {
+ Key: ControlF,
+ Fn: func(buf *Buffer) {
+ buf.CursorRight(1)
+ },
+ },
+ // Left allow: Backward one character
+ {
+ Key: ControlB,
+ Fn: func(buf *Buffer) {
+ buf.CursorLeft(1)
+ },
+ },
+ // Cut the Word before the cursor.
+ {
+ Key: ControlW,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace())))
+ },
+ },
+ // Clear the Screen, similar to the clear command
+ {
+ Key: ControlL,
+ Fn: func(buf *Buffer) {
+ consoleWriter.EraseScreen()
+ consoleWriter.CursorGoTo(0, 0)
+ debug.AssertNoError(consoleWriter.Flush())
+ },
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/filter.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/filter.go
new file mode 100644
index 0000000000000000000000000000000000000000..61c17ed7f436a069563f520512bd25e4d81af0de
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/filter.go
@@ -0,0 +1,71 @@
+package prompt
+
+import "strings"
+
+// Filter is the type to filter the prompt.Suggestion array.
+type Filter func([]Suggest, string, bool) []Suggest
+
+// FilterHasPrefix checks whether the string completions.Text begins with sub.
+func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
+}
+
+// FilterHasSuffix checks whether the completion.Text ends with sub.
+func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
+}
+
+// FilterContains checks whether the completion.Text contains sub.
+func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
+}
+
+// FilterFuzzy checks whether the completion.Text fuzzy matches sub.
+// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
+// would match, for example, "Good food is gone"
+// ^ ^ ^
+func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
+}
+
+func fuzzyMatch(s, sub string) bool {
+ sChars := []rune(s)
+ sIdx := 0
+
+ // https://staticcheck.io/docs/checks#S1029
+ for _, c := range sub {
+ found := false
+ for ; sIdx < len(sChars); sIdx++ {
+ if sChars[sIdx] == c {
+ found = true
+ sIdx++
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
+
+func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
+ if sub == "" {
+ return suggestions
+ }
+ if ignoreCase {
+ sub = strings.ToUpper(sub)
+ }
+
+ ret := make([]Suggest, 0, len(suggestions))
+ for i := range suggestions {
+ c := suggestions[i].Text
+ if ignoreCase {
+ c = strings.ToUpper(c)
+ }
+ if function(c, sub) {
+ ret = append(ret, suggestions[i])
+ }
+ }
+ return ret
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/go.mod b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..30bc6d39a39c328341ca7153d3391352be5baa63
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/go.mod
@@ -0,0 +1,11 @@
+module github.com/c-bata/go-prompt
+
+go 1.14
+
+require (
+ github.com/mattn/go-colorable v0.1.7
+ github.com/mattn/go-runewidth v0.0.9
+ github.com/mattn/go-tty v0.0.3
+ github.com/pkg/term v1.2.0-beta.2
+ golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/go.sum b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..768bf93619a68e1b334c13e7b93ec84fa465598e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/go.sum
@@ -0,0 +1,23 @@
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/history.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/history.go
new file mode 100644
index 0000000000000000000000000000000000000000..e75c64592d82142bf4826ceb8c613ac72ca24d9c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/history.go
@@ -0,0 +1,61 @@
+package prompt
+
+// History stores the texts that are entered.
+type History struct {
+ histories []string
+ tmp []string
+ selected int
+}
+
+// Add to add text in history.
+func (h *History) Add(input string) {
+ h.histories = append(h.histories, input)
+ h.Clear()
+}
+
+// Clear to clear the history.
+func (h *History) Clear() {
+ h.tmp = make([]string, len(h.histories))
+ for i := range h.histories {
+ h.tmp[i] = h.histories[i]
+ }
+ h.tmp = append(h.tmp, "")
+ h.selected = len(h.tmp) - 1
+}
+
+// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
+ if len(h.tmp) == 1 || h.selected == 0 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected--
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
+ if h.selected >= len(h.tmp)-1 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected++
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// NewHistory returns new history object.
+func NewHistory() *History {
+ return &History{
+ histories: []string{},
+ tmp: []string{""},
+ selected: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/input.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/input.go
new file mode 100644
index 0000000000000000000000000000000000000000..307e747190c2b27bf888b379644fc4f3cdd489a2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/input.go
@@ -0,0 +1,169 @@
+package prompt
+
+import "bytes"
+
+// WinSize represents the width and height of terminal.
+type WinSize struct {
+ Row uint16
+ Col uint16
+}
+
+// ConsoleParser is an interface to abstract input layer.
+type ConsoleParser interface {
+ // Setup should be called before starting input
+ Setup() error
+ // TearDown should be called after stopping input
+ TearDown() error
+ // GetWinSize returns WinSize object to represent width and height of terminal.
+ GetWinSize() *WinSize
+ // Read returns byte array.
+ Read() ([]byte, error)
+}
+
+// GetKey returns Key correspond to input byte codes.
+func GetKey(b []byte) Key {
+ for _, k := range ASCIISequences {
+ if bytes.Equal(k.ASCIICode, b) {
+ return k.Key
+ }
+ }
+ return NotDefined
+}
+
+// ASCIISequences holds mappings of the key and byte array.
+var ASCIISequences = []*ASCIICode{
+ {Key: Escape, ASCIICode: []byte{0x1b}},
+
+ {Key: ControlSpace, ASCIICode: []byte{0x00}},
+ {Key: ControlA, ASCIICode: []byte{0x1}},
+ {Key: ControlB, ASCIICode: []byte{0x2}},
+ {Key: ControlC, ASCIICode: []byte{0x3}},
+ {Key: ControlD, ASCIICode: []byte{0x4}},
+ {Key: ControlE, ASCIICode: []byte{0x5}},
+ {Key: ControlF, ASCIICode: []byte{0x6}},
+ {Key: ControlG, ASCIICode: []byte{0x7}},
+ {Key: ControlH, ASCIICode: []byte{0x8}},
+ //{Key: ControlI, ASCIICode: []byte{0x9}},
+ //{Key: ControlJ, ASCIICode: []byte{0xa}},
+ {Key: ControlK, ASCIICode: []byte{0xb}},
+ {Key: ControlL, ASCIICode: []byte{0xc}},
+ {Key: ControlM, ASCIICode: []byte{0xd}},
+ {Key: ControlN, ASCIICode: []byte{0xe}},
+ {Key: ControlO, ASCIICode: []byte{0xf}},
+ {Key: ControlP, ASCIICode: []byte{0x10}},
+ {Key: ControlQ, ASCIICode: []byte{0x11}},
+ {Key: ControlR, ASCIICode: []byte{0x12}},
+ {Key: ControlS, ASCIICode: []byte{0x13}},
+ {Key: ControlT, ASCIICode: []byte{0x14}},
+ {Key: ControlU, ASCIICode: []byte{0x15}},
+ {Key: ControlV, ASCIICode: []byte{0x16}},
+ {Key: ControlW, ASCIICode: []byte{0x17}},
+ {Key: ControlX, ASCIICode: []byte{0x18}},
+ {Key: ControlY, ASCIICode: []byte{0x19}},
+ {Key: ControlZ, ASCIICode: []byte{0x1a}},
+
+ {Key: ControlBackslash, ASCIICode: []byte{0x1c}},
+ {Key: ControlSquareClose, ASCIICode: []byte{0x1d}},
+ {Key: ControlCircumflex, ASCIICode: []byte{0x1e}},
+ {Key: ControlUnderscore, ASCIICode: []byte{0x1f}},
+ {Key: Backspace, ASCIICode: []byte{0x7f}},
+
+ {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}},
+
+ {Key: Enter, ASCIICode: []byte{0xa}},
+ {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}},
+ {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+ {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}},
+ {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}},
+ {Key: Tab, ASCIICode: []byte{0x9}},
+ {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}},
+ {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}},
+ {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}},
+ {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}},
+ {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode
+
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}},
+ {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}},
+ {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}},
+ {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}},
+ {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}},
+ {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}},
+ {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}},
+ {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}},
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}},
+ {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}},
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+
+ // Xterm
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}},
+ // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}},
+ {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}},
+ {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}},
+ {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}},
+ {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}},
+
+ {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}},
+ {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}},
+ {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}},
+ {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}},
+
+ // Tmux sends following keystrokes when control+arrow is pressed, but for
+ // Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ // it a normal arrow press, because that's more important.
+ {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}},
+
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt
+
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/input_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/input_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f10430318be0e797c841eba8e08ab1cf5277be27
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/input_posix.go
@@ -0,0 +1,77 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/term"
+ "golang.org/x/sys/unix"
+)
+
+const maxReadBytes = 1024
+
+// PosixParser is a ConsoleParser implementation for POSIX environment.
+type PosixParser struct {
+ fd int
+ origTermios syscall.Termios
+}
+
+// Setup should be called before starting input
+func (t *PosixParser) Setup() error {
+ // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
+ if err := syscall.SetNonblock(t.fd, true); err != nil {
+ return err
+ }
+ if err := term.SetRaw(t.fd); err != nil {
+ return err
+ }
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (t *PosixParser) TearDown() error {
+ if err := syscall.SetNonblock(t.fd, false); err != nil {
+ return err
+ }
+ if err := term.Restore(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Read returns byte array.
+func (t *PosixParser) Read() ([]byte, error) {
+ buf := make([]byte, maxReadBytes)
+ n, err := syscall.Read(t.fd, buf)
+ if err != nil {
+ return []byte{}, err
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (t *PosixParser) GetWinSize() *WinSize {
+ ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: ws.Row,
+ Col: ws.Col,
+ }
+}
+
+var _ ConsoleParser = &PosixParser{}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *PosixParser {
+ in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ return &PosixParser{
+ fd: in,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/input_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/input_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..11b7679d4c4bc8b924a5b6c863ca1f6d6880570d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/input_windows.go
@@ -0,0 +1,83 @@
+// +build windows
+
+package prompt
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf8"
+ "unsafe"
+
+ tty "github.com/mattn/go-tty"
+)
+
+const maxReadBytes = 1024
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
+
+// WindowsParser is a ConsoleParser implementation for Win32 console.
+type WindowsParser struct {
+ tty *tty.TTY
+}
+
+// Setup should be called before starting input
+func (p *WindowsParser) Setup() error {
+ t, err := tty.Open()
+ if err != nil {
+ return err
+ }
+ p.tty = t
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (p *WindowsParser) TearDown() error {
+ return p.tty.Close()
+}
+
+// Read returns byte array.
+func (p *WindowsParser) Read() ([]byte, error) {
+ var ev uint32
+ r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
+ if r0 == 0 {
+ return nil, err
+ }
+ if ev == 0 {
+ return nil, errors.New("EAGAIN")
+ }
+
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, maxReadBytes)
+ n := utf8.EncodeRune(buf[:], r)
+ for p.tty.Buffered() && n < maxReadBytes {
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ break
+ }
+ n += utf8.EncodeRune(buf[n:], r)
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (p *WindowsParser) GetWinSize() *WinSize {
+ w, h, err := p.tty.Size()
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: uint16(h),
+ Col: uint16(w),
+ }
+}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *WindowsParser {
+ return &WindowsParser{}
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/bisect/bisect.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/bisect/bisect.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe162fa8c4873302e25702081b629a445d43415
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/bisect/bisect.go
@@ -0,0 +1,15 @@
+package bisect
+
+import "sort"
+
+// Right to locate the insertion point for v in a to maintain sorted order.
+func Right(a []int, v int) int {
+ return bisectRightRange(a, v, 0, len(a))
+}
+
+func bisectRightRange(a []int, v int, lo, hi int) int {
+ s := a[lo:hi]
+ return sort.Search(len(s), func(i int) bool {
+ return s[i] > v
+ })
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/debug/assert.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/debug/assert.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f648ac93c44e1e021cdf581a68f03b548534d9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/debug/assert.go
@@ -0,0 +1,55 @@
+package debug
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
+)
+
+var (
+ enableAssert bool
+)
+
+func init() {
+ if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
+ enableAssert = true
+ }
+}
+
+// Assert ensures expected condition.
+func Assert(cond bool, msg interface{}) {
+ if cond {
+ return
+ }
+ if enableAssert {
+ panic(msg)
+ }
+ writeWithSync(2, "[ASSERT] "+toString(msg))
+}
+
+func toString(v interface{}) string {
+ switch a := v.(type) {
+ case func() string:
+ return a()
+ case string:
+ return a
+ case fmt.Stringer:
+ return a.String()
+ default:
+ return fmt.Sprintf("unexpected type, %t", v)
+ }
+}
+
+// AssertNoError ensures err is nil.
+func AssertNoError(err error) {
+ if err == nil {
+ return
+ }
+ if enableAssert {
+ panic(err)
+ }
+ writeWithSync(2, "[ASSERT] "+err.Error())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/debug/log.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/debug/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..516378627a34ead9063ab7ce6c445b23c77b7cb4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/debug/log.go
@@ -0,0 +1,52 @@
+package debug
+
+import (
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+const (
+ envEnableLog = "GO_PROMPT_ENABLE_LOG"
+ logFileName = "go-prompt.log"
+)
+
+var (
+ logfile *os.File
+ logger *log.Logger
+)
+
+func init() {
+ if e := os.Getenv(envEnableLog); e == "true" || e == "1" {
+ var err error
+ logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
+ if err == nil {
+ logger = log.New(logfile, "", log.Llongfile)
+ return
+ }
+ }
+ logger = log.New(ioutil.Discard, "", log.Llongfile)
+}
+
+// Teardown to close logfile
+func Teardown() {
+ if logfile == nil {
+ return
+ }
+ _ = logfile.Close()
+}
+
+func writeWithSync(calldepth int, msg string) {
+ calldepth++
+ if logfile == nil {
+ return
+ }
+ _ = logger.Output(calldepth, msg)
+ _ = logfile.Sync() // immediately write msg
+}
+
+// Log to output message
+func Log(msg string) {
+ calldepth := 2
+ writeWithSync(calldepth, msg)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/strings/strings.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/strings/strings.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7d1886ae03a7d541c66dffca921e2d040e6d5eb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/strings/strings.go
@@ -0,0 +1,102 @@
+package strings
+
+import "unicode/utf8"
+
+// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior.
+func IndexNotByte(s string, c byte) int {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior.
+func LastIndexNotByte(s string, c byte) int {
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+type asciiSet [8]uint32
+
+func (as *asciiSet) notContains(c byte) bool {
+ return (as[c>>5] & (1 << uint(c&31))) == 0
+}
+
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c>>5] |= 1 << uint(c&31)
+ }
+ return as, true
+}
+
+// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior.
+func IndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := 0; i < len(s); i++ {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+
+ LabelFirstLoop:
+ for i, c := range s {
+ for j, m := range chars {
+ if c != m && j == len(chars)-1 {
+ return i
+ } else if c != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior.
+func LastIndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ LabelFirstLoop:
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRuneInString(s[:i])
+ i -= size
+ for j, m := range chars {
+ if r != m && j == len(chars)-1 {
+ return i
+ } else if r != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/term/raw.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/term/raw.go
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3ed8d04023558cf386a98080815d661248b85
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/term/raw.go
@@ -0,0 +1,29 @@
+// +build !windows
+
+package term
+
+import (
+ "syscall"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+// SetRaw put terminal into a raw mode
+func SetRaw(fd int) error {
+ n, err := getOriginalTermios(fd)
+ if err != nil {
+ return err
+ }
+
+ n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK |
+ syscall.ISTRIP | syscall.INLCR | syscall.IGNCR |
+ syscall.ICRNL | syscall.IXON
+ n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL
+ n.Cflag &^= syscall.CSIZE | syscall.PARENB
+ n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters.
+ n.Cc[syscall.VMIN] = 1
+ n.Cc[syscall.VTIME] = 0
+
+ return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n))
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/term/term.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/term/term.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a53c059ae60c0348ec01689babef4b13a2ecd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/internal/term/term.go
@@ -0,0 +1,34 @@
+// +build !windows
+
+package term
+
+import (
+ "sync"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ saveTermios *unix.Termios
+ saveTermiosFD int
+ saveTermiosOnce sync.Once
+)
+
+func getOriginalTermios(fd int) (*unix.Termios, error) {
+ var err error
+ saveTermiosOnce.Do(func() {
+ saveTermiosFD = fd
+ saveTermios, err = termios.Tcgetattr(uintptr(fd))
+ })
+ return saveTermios, err
+}
+
+// Restore terminal's mode.
+func Restore() error {
+ o, err := getOriginalTermios(saveTermiosFD)
+ if err != nil {
+ return err
+ }
+ return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/key.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ba569c2dd20a8ae3b3dd79ff3695bf0b6c1bd09
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/key.go
@@ -0,0 +1,128 @@
+// Code generated by hand; DO NOT EDIT.
+// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment.
+
+package prompt
+
+// Key is the type express the key inserted from user.
+//go:generate stringer -type=Key
+type Key int
+
+// ASCIICode is the type contains Key and it's ascii byte array.
+type ASCIICode struct {
+ Key Key
+ ASCIICode []byte
+}
+
+const (
+ Escape Key = iota
+
+ ControlA
+ ControlB
+ ControlC
+ ControlD
+ ControlE
+ ControlF
+ ControlG
+ ControlH
+ ControlI
+ ControlJ
+ ControlK
+ ControlL
+ ControlM
+ ControlN
+ ControlO
+ ControlP
+ ControlQ
+ ControlR
+ ControlS
+ ControlT
+ ControlU
+ ControlV
+ ControlW
+ ControlX
+ ControlY
+ ControlZ
+
+ ControlSpace
+ ControlBackslash
+ ControlSquareClose
+ ControlCircumflex
+ ControlUnderscore
+ ControlLeft
+ ControlRight
+ ControlUp
+ ControlDown
+
+ Up
+ Down
+ Right
+ Left
+
+ ShiftLeft
+ ShiftUp
+ ShiftDown
+ ShiftRight
+
+ Home
+ End
+ Delete
+ ShiftDelete
+ ControlDelete
+ PageUp
+ PageDown
+ BackTab
+ Insert
+ Backspace
+
+ // Aliases.
+ Tab
+ Enter
+ // Actually Enter equals ControlM, not ControlJ,
+ // However, in prompt_toolkit, we made the mistake of translating
+ // \r into \n during the input, so everyone is now handling the
+ // enter key by binding ControlJ.
+
+ // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere,
+ // because that's future compatible, and will still work when we
+ // stop replacing \r by \n.
+
+ F1
+ F2
+ F3
+ F4
+ F5
+ F6
+ F7
+ F8
+ F9
+ F10
+ F11
+ F12
+ F13
+ F14
+ F15
+ F16
+ F17
+ F18
+ F19
+ F20
+ F21
+ F22
+ F23
+ F24
+
+ // Matches any key.
+ Any
+
+ // Special
+ CPRResponse
+ Vt100MouseEvent
+ WindowsMouseEvent
+ BracketedPaste
+
+ // Key which is ignored. (The key binding for this key should not do anything.)
+ Ignore
+
+ // Key is not defined
+ NotDefined
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/key_bind.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/key_bind.go
new file mode 100644
index 0000000000000000000000000000000000000000..42669e7f942efc4d92f896388daede90b96b55dd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/key_bind.go
@@ -0,0 +1,59 @@
+package prompt
+
+// KeyBindFunc receives buffer and processed it.
+type KeyBindFunc func(*Buffer)
+
+// KeyBind represents which key should do what operation.
+type KeyBind struct {
+ Key Key
+ Fn KeyBindFunc
+}
+
+// ASCIICodeBind represents which []byte should do what operation
+type ASCIICodeBind struct {
+ ASCIICode []byte
+ Fn KeyBindFunc
+}
+
+// KeyBindMode to switch a key binding flexibly.
+type KeyBindMode string
+
+const (
+ // CommonKeyBind is a mode without any keyboard shortcut
+ CommonKeyBind KeyBindMode = "common"
+ // EmacsKeyBind is a mode to use emacs-like keyboard shortcut
+ EmacsKeyBind KeyBindMode = "emacs"
+)
+
+var commonKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: End,
+ Fn: GoLineEnd,
+ },
+ // Go to the beginning of the line
+ {
+ Key: Home,
+ Fn: GoLineBeginning,
+ },
+ // Delete character under the cursor
+ {
+ Key: Delete,
+ Fn: DeleteChar,
+ },
+ // Backspace
+ {
+ Key: Backspace,
+ Fn: DeleteBeforeChar,
+ },
+ // Right allow: Forward one character
+ {
+ Key: Right,
+ Fn: GoRightChar,
+ },
+ // Left allow: Backward one character
+ {
+ Key: Left,
+ Fn: GoLeftChar,
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/key_bind_func.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/key_bind_func.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b2ecdf63179dbfdbcb0d71bfa436bb36d62d230
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/key_bind_func.go
@@ -0,0 +1,48 @@
+package prompt
+
+// GoLineEnd Go to the End of the line
+func GoLineEnd(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+}
+
+// GoLineBeginning Go to the beginning of the line
+func GoLineBeginning(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+}
+
+// DeleteChar Delete character under the cursor
+func DeleteChar(buf *Buffer) {
+ buf.Delete(1)
+}
+
+// DeleteWord Delete word before the cursor
+func DeleteWord(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
+
+// DeleteBeforeChar Go to Backspace
+func DeleteBeforeChar(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+}
+
+// GoRightChar Forward one character
+func GoRightChar(buf *Buffer) {
+ buf.CursorRight(1)
+}
+
+// GoLeftChar Backward one character
+func GoLeftChar(buf *Buffer) {
+ buf.CursorLeft(1)
+}
+
+// GoRightWord Forward one word
+func GoRightWord(buf *Buffer) {
+ buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
+}
+
+// GoLeftWord Backward one word
+func GoLeftWord(buf *Buffer) {
+ buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/key_string.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/key_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..fce6ea31c502b3e763451cb47757ae1b49c32814
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/key_string.go
@@ -0,0 +1,16 @@
+// Code generated by "stringer -type=Key"; DO NOT EDIT.
+
+package prompt
+
+import "strconv"
+
+const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined"
+
+var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607}
+
+func (i Key) String() string {
+ if i < 0 || i >= Key(len(_Key_index)-1) {
+ return "Key(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _Key_name[_Key_index[i]:_Key_index[i+1]]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/option.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/option.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd6806cc1dbccf8c4ddb048080fde615c59088
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/option.go
@@ -0,0 +1,310 @@
+package prompt
+
+// Option is the type to replace default parameters.
+// prompt.New accepts any number of options (this is functional option pattern).
+type Option func(prompt *Prompt) error
+
+// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
+func OptionParser(x ConsoleParser) Option {
+ return func(p *Prompt) error {
+ p.in = x
+ return nil
+ }
+}
+
+// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
+func OptionWriter(x ConsoleWriter) Option {
+ return func(p *Prompt) error {
+ registerConsoleWriter(x)
+ p.renderer.out = x
+ return nil
+ }
+}
+
+// OptionTitle to set title displayed at the header bar of terminal.
+func OptionTitle(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.title = x
+ return nil
+ }
+}
+
+// OptionPrefix to set prefix string.
+func OptionPrefix(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefix = x
+ return nil
+ }
+}
+
+// OptionInitialBufferText to set the initial buffer text
+func OptionInitialBufferText(x string) Option {
+ return func(p *Prompt) error {
+ p.buf.InsertText(x, false, true)
+ return nil
+ }
+}
+
+// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
+func OptionCompletionWordSeparator(x string) Option {
+ return func(p *Prompt) error {
+ p.completion.wordSeparator = x
+ return nil
+ }
+}
+
+// OptionLivePrefix to change the prefix dynamically by callback function
+func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
+ return func(p *Prompt) error {
+ p.renderer.livePrefixCallback = f
+ return nil
+ }
+}
+
+// OptionPrefixTextColor change a text color of prefix string
+func OptionPrefixTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixTextColor = x
+ return nil
+ }
+}
+
+// OptionPrefixBackgroundColor to change a background color of prefix string
+func OptionPrefixBackgroundColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixBGColor = x
+ return nil
+ }
+}
+
+// OptionInputTextColor to change a color of text which is input by user
+func OptionInputTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputTextColor = x
+ return nil
+ }
+}
+
+// OptionInputBGColor to change a color of background which is input by user
+func OptionInputBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputBGColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionTextColor to change a text color which is completed
+func OptionPreviewSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionBGColor to change a background color which is completed
+func OptionPreviewSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionTextColor to change a text color in drop down suggestions.
+func OptionSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionBGColor change a background color in drop down suggestions.
+func OptionSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarThumbColor to change a thumb color on scrollbar.
+func OptionScrollbarThumbColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarThumbColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarBGColor to change a background color of scrollbar.
+func OptionScrollbarBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarBGColor = x
+ return nil
+ }
+}
+
+// OptionMaxSuggestion specify the max number of displayed suggestions.
+func OptionMaxSuggestion(x uint16) Option {
+ return func(p *Prompt) error {
+ p.completion.max = x
+ return nil
+ }
+}
+
+// OptionHistory to set history expressed by string array.
+func OptionHistory(x []string) Option {
+ return func(p *Prompt) error {
+ p.history.histories = x
+ p.history.Clear()
+ return nil
+ }
+}
+
+// OptionSwitchKeyBindMode set a key bind mode.
+func OptionSwitchKeyBindMode(m KeyBindMode) Option {
+ return func(p *Prompt) error {
+ p.keyBindMode = m
+ return nil
+ }
+}
+
+// OptionCompletionOnDown allows for Down arrow key to trigger completion.
+func OptionCompletionOnDown() Option {
+ return func(p *Prompt) error {
+ p.completionOnDown = true
+ return nil
+ }
+}
+
+// SwitchKeyBindMode to set a key bind mode.
+// Deprecated: Please use OptionSwitchKeyBindMode.
+var SwitchKeyBindMode = OptionSwitchKeyBindMode
+
+// OptionAddKeyBind to set a custom key bind.
+func OptionAddKeyBind(b ...KeyBind) Option {
+ return func(p *Prompt) error {
+ p.keyBindings = append(p.keyBindings, b...)
+ return nil
+ }
+}
+
+// OptionAddASCIICodeBind to set a custom key bind.
+func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option {
+ return func(p *Prompt) error {
+ p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...)
+ return nil
+ }
+}
+
+// OptionShowCompletionAtStart to set completion window is open at start.
+func OptionShowCompletionAtStart() Option {
+ return func(p *Prompt) error {
+ p.completion.showAtStart = true
+ return nil
+ }
+}
+
+// OptionBreakLineCallback to run a callback at every break line
+func OptionBreakLineCallback(fn func(*Document)) Option {
+ return func(p *Prompt) error {
+ p.renderer.breakLineCallback = fn
+ return nil
+ }
+}
+
+// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop
+func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
+ return func(p *Prompt) error {
+ p.exitChecker = fn
+ return nil
+ }
+}
+
+// New returns a Prompt with powerful auto-completion.
+func New(executor Executor, completer Completer, opts ...Option) *Prompt {
+ defaultWriter := NewStdoutWriter()
+ registerConsoleWriter(defaultWriter)
+
+ pt := &Prompt{
+ in: NewStandardInputParser(),
+ renderer: &Render{
+ prefix: "> ",
+ out: defaultWriter,
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ },
+ buf: NewBuffer(),
+ executor: executor,
+ history: NewHistory(),
+ completion: NewCompletionManager(completer, 6),
+ keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting
+ }
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/output.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/output.go
new file mode 100644
index 0000000000000000000000000000000000000000..42531b412f1ed027c2fff5b85bc273e53e569b3a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/output.go
@@ -0,0 +1,161 @@
+package prompt
+
+import "sync"
+
+var (
+ consoleWriterMu sync.Mutex
+ consoleWriter ConsoleWriter
+)
+
+func registerConsoleWriter(f ConsoleWriter) {
+ consoleWriterMu.Lock()
+ defer consoleWriterMu.Unlock()
+ consoleWriter = f
+}
+
+// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on.
+type DisplayAttribute int
+
+const (
+ // DisplayReset reset all display attributes.
+ DisplayReset DisplayAttribute = iota
+ // DisplayBold set bold or increases intensity.
+ DisplayBold
+ // DisplayLowIntensity decreases intensity. Not widely supported.
+ DisplayLowIntensity
+ // DisplayItalic set italic. Not widely supported.
+ DisplayItalic
+ // DisplayUnderline set underline
+ DisplayUnderline
+ // DisplayBlink set blink (less than 150 per minute).
+ DisplayBlink
+ // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported.
+ DisplayRapidBlink
+ // DisplayReverse swap foreground and background colors.
+ DisplayReverse
+ // DisplayInvisible set invisible. Not widely supported.
+ DisplayInvisible
+ // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported.
+ DisplayCrossedOut
+ // DisplayDefaultFont set primary(default) font
+ DisplayDefaultFont
+)
+
+// Color represents color on terminal.
+type Color int
+
+const (
+ // DefaultColor represents a default color.
+ DefaultColor Color = iota
+
+ // Low intensity
+
+ // Black represents a black.
+ Black
+ // DarkRed represents a dark red.
+ DarkRed
+ // DarkGreen represents a dark green.
+ DarkGreen
+ // Brown represents a brown.
+ Brown
+ // DarkBlue represents a dark blue.
+ DarkBlue
+ // Purple represents a purple.
+ Purple
+ // Cyan represents a cyan.
+ Cyan
+ // LightGray represents a light gray.
+ LightGray
+
+ // High intensity
+
+ // DarkGray represents a dark gray.
+ DarkGray
+ // Red represents a red.
+ Red
+ // Green represents a green.
+ Green
+ // Yellow represents a yellow.
+ Yellow
+ // Blue represents a blue.
+ Blue
+ // Fuchsia represents a fuchsia.
+ Fuchsia
+ // Turquoise represents a turquoise.
+ Turquoise
+ // White represents a white.
+ White
+)
+
+// ConsoleWriter is an interface to abstract output layer.
+type ConsoleWriter interface {
+ /* Write */
+
+ // WriteRaw to write raw byte array.
+ WriteRaw(data []byte)
+ // Write to write safety byte array by removing control sequences.
+ Write(data []byte)
+ // WriteStr to write raw string.
+ WriteRawStr(data string)
+ // WriteStr to write safety string by removing control sequences.
+ WriteStr(data string)
+ // Flush to flush buffer.
+ Flush() error
+
+ /* Erasing */
+
+ // EraseScreen erases the screen with the background colour and moves the cursor to home.
+ EraseScreen()
+ // EraseUp erases the screen from the current line up to the top of the screen.
+ EraseUp()
+ // EraseDown erases the screen from the current line down to the bottom of the screen.
+ EraseDown()
+ // EraseStartOfLine erases from the current cursor position to the start of the current line.
+ EraseStartOfLine()
+ // EraseEndOfLine erases from the current cursor position to the end of the current line.
+ EraseEndOfLine()
+ // EraseLine erases the entire current line.
+ EraseLine()
+
+ /* Cursor */
+
+ // ShowCursor stops blinking cursor and show.
+ ShowCursor()
+ // HideCursor hides cursor.
+ HideCursor()
+ // CursorGoTo sets the cursor position where subsequent text will begin.
+ CursorGoTo(row, col int)
+ // CursorUp moves the cursor up by 'n' rows; the default count is 1.
+ CursorUp(n int)
+ // CursorDown moves the cursor down by 'n' rows; the default count is 1.
+ CursorDown(n int)
+ // CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+ CursorForward(n int)
+ // CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+ CursorBackward(n int)
+ // AskForCPR asks for a cursor position report (CPR).
+ AskForCPR()
+ // SaveCursor saves current cursor position.
+ SaveCursor()
+ // UnSaveCursor restores cursor position after a Save Cursor.
+ UnSaveCursor()
+
+ /* Scrolling */
+
+ // ScrollDown scrolls display down one line.
+ ScrollDown()
+ // ScrollUp scroll display up one line.
+ ScrollUp()
+
+ /* Title */
+
+ // SetTitle sets a title of terminal window.
+ SetTitle(title string)
+ // ClearTitle clears a title of terminal window.
+ ClearTitle()
+
+ /* Font */
+
+ // SetColor sets text and background colors. and specify whether text is bold.
+ SetColor(fg, bg Color, bold bool)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/output_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/output_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..26c770cc152a7b126be43915d60b8ba000ad0e38
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/output_posix.go
@@ -0,0 +1,67 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+)
+
+const flushMaxRetryCount = 3
+
+// PosixWriter is a ConsoleWriter implementation for POSIX environment.
+// To control terminal emulator, this outputs VT100 escape sequences.
+type PosixWriter struct {
+ VT100Writer
+ fd int
+}
+
+// Flush to flush buffer
+func (w *PosixWriter) Flush() error {
+ l := len(w.buffer)
+ offset := 0
+ retry := 0
+ for {
+ n, err := syscall.Write(w.fd, w.buffer[offset:])
+ if err != nil {
+ if retry < flushMaxRetryCount {
+ retry++
+ continue
+ }
+ return err
+ }
+ offset += n
+ if offset == l {
+ break
+ }
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &PosixWriter{}
+
+var (
+ // NewStandardOutputWriter returns ConsoleWriter object to write to stdout.
+ // This generates VT100 escape sequences because almost terminal emulators
+ // in POSIX OS built on top of a VT100 specification.
+ // Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStdoutWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stdout,
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStderrWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stderr,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/output_vt100.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/output_vt100.go
new file mode 100644
index 0000000000000000000000000000000000000000..20850fead883c4cd9802928b5de3f935fbbeb047
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/output_vt100.go
@@ -0,0 +1,310 @@
+package prompt
+
+import (
+ "bytes"
+ "strconv"
+)
+
+// VT100Writer generates VT100 escape sequences.
+type VT100Writer struct {
+ buffer []byte
+}
+
+// WriteRaw to write raw byte array
+func (w *VT100Writer) WriteRaw(data []byte) {
+ w.buffer = append(w.buffer, data...)
+}
+
+// Write to write safety byte array by removing control sequences.
+func (w *VT100Writer) Write(data []byte) {
+ w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1))
+}
+
+// WriteRawStr to write raw string
+func (w *VT100Writer) WriteRawStr(data string) {
+ w.WriteRaw([]byte(data))
+}
+
+// WriteStr to write safety string by removing control sequences.
+func (w *VT100Writer) WriteStr(data string) {
+ w.Write([]byte(data))
+}
+
+/* Erase */
+
+// EraseScreen erases the screen with the background colour and moves the cursor to home.
+func (w *VT100Writer) EraseScreen() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'J'})
+}
+
+// EraseUp erases the screen from the current line up to the top of the screen.
+func (w *VT100Writer) EraseUp() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'J'})
+}
+
+// EraseDown erases the screen from the current line down to the bottom of the screen.
+func (w *VT100Writer) EraseDown() {
+ w.WriteRaw([]byte{0x1b, '[', 'J'})
+}
+
+// EraseStartOfLine erases from the current cursor position to the start of the current line.
+func (w *VT100Writer) EraseStartOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'K'})
+}
+
+// EraseEndOfLine erases from the current cursor position to the end of the current line.
+func (w *VT100Writer) EraseEndOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', 'K'})
+}
+
+// EraseLine erases the entire current line.
+func (w *VT100Writer) EraseLine() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'K'})
+}
+
+/* Cursor */
+
+// ShowCursor stops blinking cursor and show.
+func (w *VT100Writer) ShowCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'})
+}
+
+// HideCursor hides cursor.
+func (w *VT100Writer) HideCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'})
+}
+
+// CursorGoTo sets the cursor position where subsequent text will begin.
+func (w *VT100Writer) CursorGoTo(row, col int) {
+ if row == 0 && col == 0 {
+ // If no row/column parameters are provided (ie. [H), the cursor will move to the home position.
+ w.WriteRaw([]byte{0x1b, '[', 'H'})
+ return
+ }
+ r := strconv.Itoa(row)
+ c := strconv.Itoa(col)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(r))
+ w.WriteRaw([]byte{';'})
+ w.WriteRaw([]byte(c))
+ w.WriteRaw([]byte{'H'})
+}
+
+// CursorUp moves the cursor up by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorUp(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorDown(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'A'})
+}
+
+// CursorDown moves the cursor down by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorDown(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorUp(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'B'})
+}
+
+// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorForward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorBackward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'C'})
+}
+
+// CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorBackward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorForward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'D'})
+}
+
+// AskForCPR asks for a cursor position report (CPR).
+func (w *VT100Writer) AskForCPR() {
+ // CPR: Cursor Position Request.
+ w.WriteRaw([]byte{0x1b, '[', '6', 'n'})
+}
+
+// SaveCursor saves current cursor position.
+func (w *VT100Writer) SaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 's'})
+}
+
+// UnSaveCursor restores cursor position after a Save Cursor.
+func (w *VT100Writer) UnSaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 'u'})
+}
+
+/* Scrolling */
+
+// ScrollDown scrolls display down one line.
+func (w *VT100Writer) ScrollDown() {
+ w.WriteRaw([]byte{0x1b, 'D'})
+}
+
+// ScrollUp scroll display up one line.
+func (w *VT100Writer) ScrollUp() {
+ w.WriteRaw([]byte{0x1b, 'M'})
+}
+
+/* Title */
+
+// SetTitle sets a title of terminal window.
+func (w *VT100Writer) SetTitle(title string) {
+ titleBytes := []byte(title)
+ patterns := []struct {
+ from []byte
+ to []byte
+ }{
+ {
+ from: []byte{0x13},
+ to: []byte{},
+ },
+ {
+ from: []byte{0x07},
+ to: []byte{},
+ },
+ }
+ for i := range patterns {
+ titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1)
+ }
+
+ w.WriteRaw([]byte{0x1b, ']', '2', ';'})
+ w.WriteRaw(titleBytes)
+ w.WriteRaw([]byte{0x07})
+}
+
+// ClearTitle clears a title of terminal window.
+func (w *VT100Writer) ClearTitle() {
+ w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07})
+}
+
+/* Font */
+
+// SetColor sets text and background colors. and specify whether text is bold.
+func (w *VT100Writer) SetColor(fg, bg Color, bold bool) {
+ if bold {
+ w.SetDisplayAttributes(fg, bg, DisplayBold)
+ } else {
+ // If using `DisplayDefualt`, it will be broken in some environment.
+ // Details are https://github.com/c-bata/go-prompt/pull/85
+ w.SetDisplayAttributes(fg, bg, DisplayReset)
+ }
+}
+
+// SetDisplayAttributes to set VT100 display attributes.
+func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) {
+ w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer
+ defer w.WriteRaw([]byte{'m'}) // final character
+
+ var separator byte = ';'
+ for i := range attrs {
+ p, ok := displayAttributeParameters[attrs[i]]
+ if !ok {
+ continue
+ }
+ w.WriteRaw(p)
+ w.WriteRaw([]byte{separator})
+ }
+
+ f, ok := foregroundANSIColors[fg]
+ if !ok {
+ f = foregroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(f)
+ w.WriteRaw([]byte{separator})
+ b, ok := backgroundANSIColors[bg]
+ if !ok {
+ b = backgroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(b)
+}
+
+var displayAttributeParameters = map[DisplayAttribute][]byte{
+ DisplayReset: {'0'},
+ DisplayBold: {'1'},
+ DisplayLowIntensity: {'2'},
+ DisplayItalic: {'3'},
+ DisplayUnderline: {'4'},
+ DisplayBlink: {'5'},
+ DisplayRapidBlink: {'6'},
+ DisplayReverse: {'7'},
+ DisplayInvisible: {'8'},
+ DisplayCrossedOut: {'9'},
+ DisplayDefaultFont: {'1', '0'},
+}
+
+var foregroundANSIColors = map[Color][]byte{
+ DefaultColor: {'3', '9'},
+
+ // Low intensity.
+ Black: {'3', '0'},
+ DarkRed: {'3', '1'},
+ DarkGreen: {'3', '2'},
+ Brown: {'3', '3'},
+ DarkBlue: {'3', '4'},
+ Purple: {'3', '5'},
+ Cyan: {'3', '6'},
+ LightGray: {'3', '7'},
+
+ // High intensity.
+ DarkGray: {'9', '0'},
+ Red: {'9', '1'},
+ Green: {'9', '2'},
+ Yellow: {'9', '3'},
+ Blue: {'9', '4'},
+ Fuchsia: {'9', '5'},
+ Turquoise: {'9', '6'},
+ White: {'9', '7'},
+}
+
+var backgroundANSIColors = map[Color][]byte{
+ DefaultColor: {'4', '9'},
+
+ // Low intensity.
+ Black: {'4', '0'},
+ DarkRed: {'4', '1'},
+ DarkGreen: {'4', '2'},
+ Brown: {'4', '3'},
+ DarkBlue: {'4', '4'},
+ Purple: {'4', '5'},
+ Cyan: {'4', '6'},
+ LightGray: {'4', '7'},
+
+ // High intensity
+ DarkGray: {'1', '0', '0'},
+ Red: {'1', '0', '1'},
+ Green: {'1', '0', '2'},
+ Yellow: {'1', '0', '3'},
+ Blue: {'1', '0', '4'},
+ Fuchsia: {'1', '0', '5'},
+ Turquoise: {'1', '0', '6'},
+ White: {'1', '0', '7'},
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/output_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/output_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b9c2769fc2d64cfcfcc5b99c915591ec625bd5f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/output_windows.go
@@ -0,0 +1,49 @@
+// +build windows
+
+package prompt
+
+import (
+ "io"
+
+ colorable "github.com/mattn/go-colorable"
+)
+
+// WindowsWriter is a ConsoleWriter implementation for Win32 console.
+// Output is converted from VT100 escape sequences by mattn/go-colorable.
+type WindowsWriter struct {
+ VT100Writer
+ out io.Writer
+}
+
+// Flush to flush buffer
+func (w *WindowsWriter) Flush() error {
+ _, err := w.out.Write(w.buffer)
+ if err != nil {
+ return err
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &WindowsWriter{}
+
+var (
+ // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates win32 control sequences.
+func NewStdoutWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStdout(),
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates win32 control sequences.
+func NewStderrWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStderr(),
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/prompt.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/prompt.go
new file mode 100644
index 0000000000000000000000000000000000000000..173cd517c40cde212433e399978641ceff1d1a43
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/prompt.go
@@ -0,0 +1,296 @@
+package prompt
+
+import (
+ "bytes"
+ "os"
+ "time"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Executor is called when user input something text.
+type Executor func(string)
+
+// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
+// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
+// - immediate exit (if breakline is false) without executor called
+// - exit after typing (meaning breakline is true), and the executor is called first, before exit.
+// Exit means exit go-prompt (not the overall Go program)
+type ExitChecker func(in string, breakline bool) bool
+
+// Completer should return the suggest item from Document.
+type Completer func(Document) []Suggest
+
+// Prompt is core struct of go-prompt.
+type Prompt struct {
+ in ConsoleParser
+ buf *Buffer
+ renderer *Render
+ executor Executor
+ history *History
+ completion *CompletionManager
+ keyBindings []KeyBind
+ ASCIICodeBindings []ASCIICodeBind
+ keyBindMode KeyBindMode
+ completionOnDown bool
+ exitChecker ExitChecker
+ skipTearDown bool
+}
+
+// Exec is the struct contains user input context.
+type Exec struct {
+ input string
+}
+
+// Run starts prompt.
+func (p *Prompt) Run() {
+ p.skipTearDown = false
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ exitCh := make(chan int)
+ winSizeCh := make(chan *WinSize)
+ stopHandleSignalCh := make(chan struct{})
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+ return
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+
+ // Unset raw mode
+ // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
+ debug.AssertNoError(p.in.TearDown())
+ p.executor(e.input)
+
+ p.completion.Update(*p.buf.Document())
+
+ p.renderer.Render(p.buf, p.completion)
+
+ if p.exitChecker != nil && p.exitChecker(e.input, true) {
+ p.skipTearDown = true
+ return
+ }
+ // Set raw mode
+ debug.AssertNoError(p.in.Setup())
+ go p.readBuffer(bufCh, stopReadBufCh)
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ case w := <-winSizeCh:
+ p.renderer.UpdateWinSize(w)
+ p.renderer.Render(p.buf, p.completion)
+ case code := <-exitCh:
+ p.renderer.BreakLine(p.buf)
+ p.tearDown()
+ os.Exit(code)
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
+ key := GetKey(b)
+ p.buf.lastKeyStroke = key
+ // completion
+ completing := p.completion.Completing()
+ p.handleCompletionKeyBinding(key, completing)
+
+ switch key {
+ case Enter, ControlJ, ControlM:
+ p.renderer.BreakLine(p.buf)
+
+ exec = &Exec{input: p.buf.Text()}
+ p.buf = NewBuffer()
+ if exec.input != "" {
+ p.history.Add(exec.input)
+ }
+ case ControlC:
+ p.renderer.BreakLine(p.buf)
+ p.buf = NewBuffer()
+ p.history.Clear()
+ case Up, ControlP:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Older(p.buf); changed {
+ p.buf = newBuf
+ }
+ }
+ case Down, ControlN:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Newer(p.buf); changed {
+ p.buf = newBuf
+ }
+ return
+ }
+ case ControlD:
+ if p.buf.Text() == "" {
+ shouldExit = true
+ return
+ }
+ case NotDefined:
+ if p.handleASCIICodeBinding(b) {
+ return
+ }
+ p.buf.InsertText(string(b), false, true)
+ }
+
+ shouldExit = p.handleKeyBinding(key)
+ return
+}
+
+func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
+ switch key {
+ case Down:
+ if completing || p.completionOnDown {
+ p.completion.Next()
+ }
+ case Tab, ControlI:
+ p.completion.Next()
+ case Up:
+ if completing {
+ p.completion.Previous()
+ }
+ case BackTab:
+ p.completion.Previous()
+ default:
+ if s, ok := p.completion.GetSelectedSuggestion(); ok {
+ w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
+ if w != "" {
+ p.buf.DeleteBeforeCursor(len([]rune(w)))
+ }
+ p.buf.InsertText(s.Text, false, true)
+ }
+ p.completion.Reset()
+ }
+}
+
+func (p *Prompt) handleKeyBinding(key Key) bool {
+ shouldExit := false
+ for i := range commonKeyBindings {
+ kb := commonKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+
+ if p.keyBindMode == EmacsKeyBind {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ }
+
+ // Custom key bindings
+ for i := range p.keyBindings {
+ kb := p.keyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
+ shouldExit = true
+ }
+ return shouldExit
+}
+
+func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
+ checked := false
+ for _, kb := range p.ASCIICodeBindings {
+ if bytes.Equal(kb.ASCIICode, b) {
+ kb.Fn(p.buf)
+ checked = true
+ }
+ }
+ return checked
+}
+
+// Input just returns user input text.
+func (p *Prompt) Input() string {
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ return ""
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ return e.input
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
+ debug.Log("start reading buffer")
+ for {
+ select {
+ case <-stopCh:
+ debug.Log("stop reading buffer")
+ return
+ default:
+ if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
+ bufCh <- b
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (p *Prompt) setUp() {
+ debug.AssertNoError(p.in.Setup())
+ p.renderer.Setup()
+ p.renderer.UpdateWinSize(p.in.GetWinSize())
+}
+
+func (p *Prompt) tearDown() {
+ if !p.skipTearDown {
+ debug.AssertNoError(p.in.TearDown())
+ }
+ p.renderer.TearDown()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/render.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/render.go
new file mode 100644
index 0000000000000000000000000000000000000000..299ac48b6254b9752ea16516aaedcd41acca6515
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/render.go
@@ -0,0 +1,287 @@
+package prompt
+
+import (
+ "runtime"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Render to render prompt information from state of Buffer.
+type Render struct {
+ out ConsoleWriter
+ prefix string
+ livePrefixCallback func() (prefix string, useLivePrefix bool)
+ breakLineCallback func(*Document)
+ title string
+ row uint16
+ col uint16
+
+ previousCursor int
+
+ // colors,
+ prefixTextColor Color
+ prefixBGColor Color
+ inputTextColor Color
+ inputBGColor Color
+ previewSuggestionTextColor Color
+ previewSuggestionBGColor Color
+ suggestionTextColor Color
+ suggestionBGColor Color
+ selectedSuggestionTextColor Color
+ selectedSuggestionBGColor Color
+ descriptionTextColor Color
+ descriptionBGColor Color
+ selectedDescriptionTextColor Color
+ selectedDescriptionBGColor Color
+ scrollbarThumbColor Color
+ scrollbarBGColor Color
+}
+
+// Setup to initialize console output.
+func (r *Render) Setup() {
+ if r.title != "" {
+ r.out.SetTitle(r.title)
+ debug.AssertNoError(r.out.Flush())
+ }
+}
+
+// getCurrentPrefix to get current prefix.
+// If live-prefix is enabled, return live-prefix.
+func (r *Render) getCurrentPrefix() string {
+ if prefix, ok := r.livePrefixCallback(); ok {
+ return prefix
+ }
+ return r.prefix
+}
+
+func (r *Render) renderPrefix() {
+ r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
+ r.out.WriteStr(r.getCurrentPrefix())
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// TearDown to clear title and erasing.
+func (r *Render) TearDown() {
+ r.out.ClearTitle()
+ r.out.EraseDown()
+ debug.AssertNoError(r.out.Flush())
+}
+
+func (r *Render) prepareArea(lines int) {
+ for i := 0; i < lines; i++ {
+ r.out.ScrollDown()
+ }
+ for i := 0; i < lines; i++ {
+ r.out.ScrollUp()
+ }
+}
+
+// UpdateWinSize called when window size is changed.
+func (r *Render) UpdateWinSize(ws *WinSize) {
+ r.row = ws.Row
+ r.col = ws.Col
+}
+
+func (r *Render) renderWindowTooSmall() {
+ r.out.CursorGoTo(0, 0)
+ r.out.EraseScreen()
+ r.out.SetColor(DarkRed, White, false)
+ r.out.WriteStr("Your console window is too small...")
+}
+
+func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) {
+ suggestions := completions.GetSuggestions()
+ if len(completions.GetSuggestions()) == 0 {
+ return
+ }
+ prefix := r.getCurrentPrefix()
+ formatted, width := formatSuggestions(
+ suggestions,
+ int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar
+ )
+ // +1 means a width of scrollbar.
+ width++
+
+ windowHeight := len(formatted)
+ if windowHeight > int(completions.max) {
+ windowHeight = int(completions.max)
+ }
+ formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
+ r.prepareArea(windowHeight)
+
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor())
+ x, _ := r.toPos(cursor)
+ if x+width >= int(r.col) {
+ cursor = r.backward(cursor, x+width-int(r.col))
+ }
+
+ contentHeight := len(completions.tmp)
+
+ fractionVisible := float64(windowHeight) / float64(contentHeight)
+ fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
+
+ scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
+ scrollbarTop := int(float64(windowHeight) * fractionAbove)
+
+ isScrollThumb := func(row int) bool {
+ return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
+ }
+
+ selected := completions.selected - completions.verticalScroll
+ r.out.SetColor(White, Cyan, false)
+ for i := 0; i < windowHeight; i++ {
+ r.out.CursorDown(1)
+ if i == selected {
+ r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
+ } else {
+ r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Text)
+
+ if i == selected {
+ r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
+ } else {
+ r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Description)
+
+ if isScrollThumb(i) {
+ r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
+ } else {
+ r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
+ }
+ r.out.WriteStr(" ")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+
+ r.lineWrap(cursor + width)
+ r.backward(cursor+width, width)
+ }
+
+ if x+width >= int(r.col) {
+ r.out.CursorForward(x + width - int(r.col))
+ }
+
+ r.out.CursorUp(windowHeight)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// Render renders to the console.
+func (r *Render) Render(buffer *Buffer, completion *CompletionManager) {
+ // In situations where a pseudo tty is allocated (e.g. within a docker container),
+ // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
+ if r.col == 0 {
+ return
+ }
+ defer func() { debug.AssertNoError(r.out.Flush()) }()
+ r.move(r.previousCursor, 0)
+
+ line := buffer.Text()
+ prefix := r.getCurrentPrefix()
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line)
+
+ // prepare area
+ _, y := r.toPos(cursor)
+
+ h := y + 1 + int(completion.max)
+ if h > int(r.row) || completionMargin > int(r.col) {
+ r.renderWindowTooSmall()
+ return
+ }
+
+ // Rendering
+ r.out.HideCursor()
+ defer r.out.ShowCursor()
+
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(line)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ r.lineWrap(cursor)
+
+ r.out.EraseDown()
+
+ cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition())
+
+ r.renderCompletion(buffer, completion)
+ if suggest, ok := completion.GetSelectedSuggestion(); ok {
+ cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator)))
+
+ r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false)
+ r.out.WriteStr(suggest.Text)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ cursor += runewidth.StringWidth(suggest.Text)
+
+ rest := buffer.Document().TextAfterCursor()
+ r.out.WriteStr(rest)
+ cursor += runewidth.StringWidth(rest)
+ r.lineWrap(cursor)
+
+ cursor = r.backward(cursor, runewidth.StringWidth(rest))
+ }
+ r.previousCursor = cursor
+}
+
+// BreakLine to break line.
+func (r *Render) BreakLine(buffer *Buffer) {
+ // Erasing and Render
+ cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix())
+ r.clear(cursor)
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(buffer.Document().Text + "\n")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ debug.AssertNoError(r.out.Flush())
+ if r.breakLineCallback != nil {
+ r.breakLineCallback(buffer.Document())
+ }
+
+ r.previousCursor = 0
+}
+
+// clear erases the screen from a beginning of input
+// even if there is line break which means input length exceeds a window's width.
+func (r *Render) clear(cursor int) {
+ r.move(cursor, 0)
+ r.out.EraseDown()
+}
+
+// backward moves cursor to backward from a current cursor position
+// regardless there is a line break.
+func (r *Render) backward(from, n int) int {
+ return r.move(from, from-n)
+}
+
+// move moves cursor to specified position from the beginning of input
+// even if there is a line break.
+func (r *Render) move(from, to int) int {
+ fromX, fromY := r.toPos(from)
+ toX, toY := r.toPos(to)
+
+ r.out.CursorUp(fromY - toY)
+ r.out.CursorBackward(fromX - toX)
+ return to
+}
+
+// toPos returns the relative position from the beginning of the string.
+func (r *Render) toPos(cursor int) (x, y int) {
+ col := int(r.col)
+ return cursor % col, cursor / col
+}
+
+func (r *Render) lineWrap(cursor int) {
+ if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 {
+ r.out.WriteRaw([]byte{'\n'})
+ }
+}
+
+func clamp(high, low, x float64) float64 {
+ switch {
+ case high < x:
+ return high
+ case x < low:
+ return low
+ default:
+ return x
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/shortcut.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/shortcut.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8d4282700c0bdb30e4decfb9c9ac91f27af251
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/shortcut.go
@@ -0,0 +1,43 @@
+package prompt
+
+func dummyExecutor(in string) {}
+
+// Input get the input data from the user and return it.
+func Input(prefix string, completer Completer, opts ...Option) string {
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+// Choose to the shortcut of input function to select from string array.
+// Deprecated: Maybe anyone want to use this.
+func Choose(prefix string, choices []string, opts ...Option) string {
+ completer := newChoiceCompleter(choices, FilterHasPrefix)
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+func newChoiceCompleter(choices []string, filter Filter) Completer {
+ s := make([]Suggest, len(choices))
+ for i := range choices {
+ s[i] = Suggest{Text: choices[i]}
+ }
+ return func(x Document) []Suggest {
+ return filter(s, x.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/signal_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/signal_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3150df5d85e7612c42c2a889dbefee3b524bef6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/signal_posix.go
@@ -0,0 +1,49 @@
+// +build !windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ in := p.in
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+
+ case syscall.SIGWINCH:
+ debug.Log("Catch SIGWINCH")
+ winSizeCh <- in.GetWinSize()
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/signal_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/signal_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a427c79ec0414540f8f40694731b2565ea80c13
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/environment/source/signal_windows.go
@@ -0,0 +1,44 @@
+// +build windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/instruction.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..73ba88e6b7eb7aa49607efdd4bd017a74f29f8bd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/instruction.md
@@ -0,0 +1,25 @@
+Text truncation in completion formatting produces incorrect width calculations
+
+#### Description
+
+When formatting completion suggestions with truncated text, the width calculation is off by one character, causing misaligned output in completion menus.
+
+#### Steps/Code to Reproduce
+
+The issue occurs when completion text needs to be truncated to fit within specified width constraints. The formatting function calculates available width incorrectly, resulting in completion suggestions that don't align properly.
+
+```go
+// This would demonstrate the issue when formatting completion suggestions
+// where text needs to be truncated due to width constraints
+suggestions := []string{"This is a long suggestion", "Another long suggestion", "Yet another long one"}
+// When these get formatted with width constraints, the alignment is off
+```
+
+The problem manifests when:
+1. Completion text exceeds the available width
+2. Text gets truncated with a suffix (like "...")
+3. The final formatted output has incorrect spacing/alignment
+
+Expected behavior: Completion suggestions should be properly aligned with consistent width
+Actual behavior: Truncated suggestions have misaligned spacing, appearing one character shorter than expected
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/provenance.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..c1c5fd24d43afd81cb4d684de37b9cfa8481e250
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/provenance.json
@@ -0,0 +1,487 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "original-bug": "task-specific unchanged semantic bug",
+ "partial-repair": "strict partial repair candidate with independently unproven wrongness",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "acceptance_disposition": "needs_semantic_review; may be a legitimate alternative; do not cherry-pick another canary from measured rewards",
+ "candidate_file_inventory": {
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "ed50cfee3d2aa27118b9d6d182f688fe0659d7bcf1c334bc57df2aa3bf7621c1",
+ "size": 4495
+ }
+ },
+ "expected_wrongness": "unproven until independent semantic review",
+ "original_patch_hunks": 2,
+ "original_patch_sha256": "838b17a12bf44ae2e9de12ef70802e1d3bb6766fff8236d32ed7ec386960e650",
+ "retained_mutation_file": "completion.go",
+ "retained_mutation_hunk_sha256": "7074c5fbf52cc8f1bd45bf23dc2411a47fca2b0cea25d73f8a54a3e54e25bec2"
+ },
+ "private_frozen_files": {
+ "buffer_test.go": {
+ "mode": "0o644",
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098",
+ "size": 4965
+ },
+ "completion_test.go": {
+ "mode": "0o644",
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d",
+ "size": 7010
+ },
+ "document_test.go": {
+ "mode": "0o644",
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284",
+ "size": 28938
+ },
+ "emacs_test.go": {
+ "mode": "0o644",
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095",
+ "size": 741
+ },
+ "filter_test.go": {
+ "mode": "0o644",
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247",
+ "size": 3339
+ },
+ "history_test.go": {
+ "mode": "0o644",
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327",
+ "size": 1319
+ },
+ "input_test.go": {
+ "mode": "0o644",
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922",
+ "size": 533
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": "0o644",
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf",
+ "size": 1075
+ },
+ "internal/strings/strings_test.go": {
+ "mode": "0o644",
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6",
+ "size": 981
+ },
+ "output_vt100_test.go": {
+ "mode": "0o644",
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee",
+ "size": 1349
+ },
+ "render_test.go": {
+ "mode": "0o644",
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb",
+ "size": 2890
+ }
+ },
+ "public_files": {
+ ".github/ISSUE_TEMPLATE/bug_report.md": {
+ "mode": "0o644",
+ "sha256": "89d3492ca8533a3d31e4de49a23828a322f75d2a1ec4236327c4a76c7c51ada6",
+ "size": 684
+ },
+ ".github/ISSUE_TEMPLATE/feature_request.md": {
+ "mode": "0o644",
+ "sha256": "d82e14e6b4d021d0007eeef4f5ca489fc6c8e8e4d7479ee30e74fe82afd3b08f",
+ "size": 206
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "3239b94a1a41c05eff5dc086ef1378cf1e289fad0203420b5cb4c78e3c5c239b",
+ "size": 270
+ },
+ "CHANGELOG.md": {
+ "mode": "0o644",
+ "sha256": "1f88f92d3247e1b52af0f0de7ad1263a59807edb17238c7a0211554f8080e51c",
+ "size": 2895
+ },
+ "LICENSE": {
+ "mode": "0o644",
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "size": 1072
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "9425a0d4c15747863625f647348962a9b0f81a0971a7e0184ee722bf34a60ba2",
+ "size": 1177
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "ce56df51a1a9a5b5c5b056429bbee006a260fb0730af63b1d0fe91755e574cc4",
+ "size": 6185
+ },
+ "_example/README.md": {
+ "mode": "0o644",
+ "sha256": "155951bafd778493bd41ae57dcc0ba6b8eca821fcbe2ffe770960ac2780d3d09",
+ "size": 1102
+ },
+ "_example/build.sh": {
+ "mode": "0o755",
+ "sha256": "de2fb330b665691cd75b990236cd6a5df0058608de0dfc6194da30d4041a1e29",
+ "size": 469
+ },
+ "_example/exec-command/main.go": {
+ "mode": "0o644",
+ "sha256": "0e96493b6e6d446b2e691d4834ff8a55834caa410ead970cb611a63ba84f174a",
+ "size": 429
+ },
+ "_example/http-prompt/api.py": {
+ "mode": "0o644",
+ "sha256": "2c2bca9acb07a84c65a4482c61c9ade253a574477a8e461307568ea1f9a342c8",
+ "size": 335
+ },
+ "_example/http-prompt/main.go": {
+ "mode": "0o644",
+ "sha256": "6994b190c4165068e69ed44eb61698af69a15a7690179ce46e3c1c5d8c211643",
+ "size": 5484
+ },
+ "_example/live-prefix/main.go": {
+ "mode": "0o644",
+ "sha256": "20268f9cb6f3b82a52eddc33cbf8082adaa46092e2063df279499e05e25a228c",
+ "size": 1103
+ },
+ "_example/simple-echo/cjk-cyrillic/main.go": {
+ "mode": "0o644",
+ "sha256": "8fb10807d4085ebc4b345bc0ccfef9217e21e49a888bfe3192e8ddfdfa01e89c",
+ "size": 800
+ },
+ "_example/simple-echo/main.go": {
+ "mode": "0o644",
+ "sha256": "e46563ddaa932831fe9ede870b10efb5222c0d54a86f4b4f5197c9cf20942a24",
+ "size": 902
+ },
+ "_tools/README.md": {
+ "mode": "0o644",
+ "sha256": "96dc2343bc5cde642fd449ddc366462753a2e17b6a78adfa015bf991e9dac241",
+ "size": 234
+ },
+ "_tools/complete_file/main.go": {
+ "mode": "0o644",
+ "sha256": "e5dd823f9d6415614a8238ce106d26e9ded1db9b308c121d7f48bb1df003effc",
+ "size": 803
+ },
+ "_tools/sigwinch/main.go": {
+ "mode": "0o644",
+ "sha256": "a806b4e45298f5003c95432d8dd3c40c9c096335f19f1a4160afcdb64fa727e3",
+ "size": 1386
+ },
+ "_tools/vt100_debug/main.go": {
+ "mode": "0o644",
+ "sha256": "7f72eba3cc7037fcf39c9b56a96c578c157e5fb235cb626ab1e83cbef0dc290b",
+ "size": 794
+ },
+ "buffer.go": {
+ "mode": "0o644",
+ "sha256": "10188d96a450fe13ba1e9ec00c89603eb2a2860536965d980d1e4abf4374b018",
+ "size": 5781
+ },
+ "completer/file.go": {
+ "mode": "0o644",
+ "sha256": "6181ed9e39028236c5c93fbe219331fc1492ecfd6af2df764cc42b5455c9bb96",
+ "size": 2401
+ },
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "78cc4d4f8a41fd8c11d057c09ff01f8697b861640dbe61ac0e7416377cfa4121",
+ "size": 4281
+ },
+ "document.go": {
+ "mode": "0o644",
+ "sha256": "e719d4c10a10f506c371b87dbd363a9b7f7d3aa8f0190a40965ac761197e1f1e",
+ "size": 13097
+ },
+ "emacs.go": {
+ "mode": "0o644",
+ "sha256": "53f0df0016ef9d9695a797b19286681666cf0c7e5a866c393b194aae915f2664",
+ "size": 2675
+ },
+ "filter.go": {
+ "mode": "0o644",
+ "sha256": "dc5922bad6ecb32ecdaf20bd6035dddc7ce8c14f15dbd4d49192c2354cb8a038",
+ "size": 2005
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "97413fa2a2ed68170496f2289a2dca6fb0a192dcd020fc0ca48a5d106e60d55e",
+ "size": 253
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "88ea0a91babaa54b67cc6d5f6f7f47fa4be798fe523324ea568d8926eed2024c",
+ "size": 2183
+ },
+ "history.go": {
+ "mode": "0o644",
+ "sha256": "4ce80ba067cfc72c56a3ee3353ec75cd6bb2f5d82097515c591e3c7c773c51cd",
+ "size": 1488
+ },
+ "input.go": {
+ "mode": "0o644",
+ "sha256": "73461cc4f57d68b66e2a9e196239aaef942539134593beac0d0023743832e0e1",
+ "size": 7630
+ },
+ "input_posix.go": {
+ "mode": "0o644",
+ "sha256": "c7e5a4dfc3910f178f0685ef99f2e47d481a91c4cf9af50f92fc4266aed634df",
+ "size": 1648
+ },
+ "input_windows.go": {
+ "mode": "0o644",
+ "sha256": "f763250d309fb88d9536f77da1d1285c04bc6defe859506f1501e10f7743da9e",
+ "size": 1679
+ },
+ "internal/bisect/bisect.go": {
+ "mode": "0o644",
+ "sha256": "c4de2adfa2e08a77f902661d67325467f89013634dbcef22d24dc6f34d26624a",
+ "size": 327
+ },
+ "internal/debug/assert.go": {
+ "mode": "0o644",
+ "sha256": "1a3050ec58991b62c7ea352d19505e3080ac9760bdb091544f0ecf5aba35969c",
+ "size": 815
+ },
+ "internal/debug/log.go": {
+ "mode": "0o644",
+ "sha256": "2ce968e275558de61c6d83793e85561f7a8dd69c95ec7902ccd2cc3fb169aa82",
+ "size": 875
+ },
+ "internal/strings/strings.go": {
+ "mode": "0o644",
+ "sha256": "b97f08157c3baf1f94fea4bb2237691d8270bd5380b4311709ecd59b84cf4b7b",
+ "size": 2018
+ },
+ "internal/term/raw.go": {
+ "mode": "0o644",
+ "sha256": "177a1a20ae8d71b56857383a5797754560f7f6404ea86778d5f01e9a1c1b4f9f",
+ "size": 747
+ },
+ "internal/term/term.go": {
+ "mode": "0o644",
+ "sha256": "abe6fa965fa15b999b2010135903f598830d4c885a52ef9b067fd5ebbf6e373f",
+ "size": 606
+ },
+ "key.go": {
+ "mode": "0o644",
+ "sha256": "03a43283e07de7a4ea6fed32692d86325f73e98fd89a296f19c171e0bc780999",
+ "size": 1746
+ },
+ "key_bind.go": {
+ "mode": "0o644",
+ "sha256": "83f48bb720a11c8e49165ac382e3a870fdcf6b380a0a95267f8c25211898c9eb",
+ "size": 1109
+ },
+ "key_bind_func.go": {
+ "mode": "0o644",
+ "sha256": "445bff5c0fdb0b52879c635322603c2fc75d265de3761cb8c3b980c798bf39af",
+ "size": 1219
+ },
+ "key_string.go": {
+ "mode": "0o644",
+ "sha256": "55c429dae227bb1659d5d5e2e906dbfa9c7f53b5105fa83fbe290529ff6f2317",
+ "size": 1359
+ },
+ "option.go": {
+ "mode": "0o644",
+ "sha256": "28cfcc1d08b3cf650483d977195458531b3b3913f8a5f357a3ec17ea5d73e215",
+ "size": 8737
+ },
+ "output.go": {
+ "mode": "0o644",
+ "sha256": "372876b0aa908479ed3b29de70a479f420d85e3666b8957c8b61eaed9b32c3f2",
+ "size": 4320
+ },
+ "output_posix.go": {
+ "mode": "0o644",
+ "sha256": "d46b1da307e8969b033e1ade2eb51a83c4c3d4f2a7e4aba35ec3a03991b89a0f",
+ "size": 1545
+ },
+ "output_vt100.go": {
+ "mode": "0o644",
+ "sha256": "9082c7e4619c1eb38030bc4994a4fbf66ef27b130751bf2eb9c25c01082e8605",
+ "size": 7453
+ },
+ "output_windows.go": {
+ "mode": "0o644",
+ "sha256": "571c5ae1ad051a701b426371efd79a3776c2226ca9e3c2e598fe5996dfa1b8e1",
+ "size": 1066
+ },
+ "prompt.go": {
+ "mode": "0o644",
+ "sha256": "6b3e2bbd90f40ad6a487f1a6ea7f5a6fb48cae6c8c246ecc77621fb3e7383ca7",
+ "size": 7062
+ },
+ "render.go": {
+ "mode": "0o644",
+ "sha256": "90fdd57a63e06f01940d10ee1a0be95ced7d6adc7faa255b3141556d7d316270",
+ "size": 8020
+ },
+ "shortcut.go": {
+ "mode": "0o644",
+ "sha256": "b4a097f466df7396049ebe8393f81c9b1200159d4e2be22bd6838c307ec156dc",
+ "size": 1120
+ },
+ "signal_posix.go": {
+ "mode": "0o644",
+ "sha256": "74f0bae5f290f3f7f82a5dd495e672f627a4ab4b63118f870e8c13c0a7024314",
+ "size": 881
+ },
+ "signal_windows.go": {
+ "mode": "0o644",
+ "sha256": "444f662a32e6997df2af8e2a9e7dbfe977414a6bfc0f54a7f10117f204648437",
+ "size": 757
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982",
+ "os": "linux",
+ "sha256": "0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982"
+ },
+ "context_inventory_sha256": "6b8f93086e81483ac1ce82f328d7f4b38b1b560dbad057ed6a2a30ff3cf0e13f",
+ "image": "registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "9d3b21cdacadfa4f3de9584d0cea973e5aa2ceedcd5ec9cbd3a63df22b313455",
+ "receipt_path": "production/runtime-images-extra-v1/resolutions/316e0e68930cd4ef/resolution.json",
+ "receipt_sha256": "697bb0619eddcdfdeba1c9144b033f564f2d7514be6e6a44dc520fa4e63ed8bc",
+ "registry_digest": "sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "source_image": "docker.io/swebench/swesmith.x86_64.c-bata_1776_go-prompt.82a91227@sha256:3daf51c74a01657e9ad8f326651fb6f5b796ffecdb90098e74a52a9560e0a1bb",
+ "source_receipt_sha256": "b450bea0e201cbe194b765ded4b51539144c85296122c8b642d7e94c889526f3",
+ "space_commit": "5ae654cd2e9d695f0de304bd4398835fc7cf45e0",
+ "space_id": "harness-hub/scale800-go-316e0e68930cd4ef-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "2ca8738754a7facb7ef828a309f60348b00b0a55f6117f965e1228db7e9cc304",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21",
+ "source_proof_sha256": "65f6a8e48cedbb05a8749330d318480e7322f520567702ce811bfe958dc08d6a",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:c-bata__go-prompt.82a91227.lm_modify__cyda491g",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "9992c59c25864ce1556e67b9e1501c93f6e7f9ff",
+ "instruction_sha256": "3aa489308074cbca0264bbc21616d194d40b91212e152027fd31f63331476f63",
+ "is_fork": true,
+ "learner_path": "tasks/51872cb48e06ae1912b06338/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/c-bata__go-prompt.82a91227/0c73250c389980239e60bab96f73d4a9c7528f3b/LICENSE"
+ },
+ "task_bundle": {
+ "basis": "Captured publisherMIT/train; exactsoftwarepermissionverifiedseparately",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "82a912274504477990ecf7c852eebb7c85291772",
+ "patch_sha256": "838b17a12bf44ae2e9de12ef70802e1d3bb6766fff8236d32ed7ec386960e650",
+ "provenance_path": "tasks/51872cb48e06ae1912b06338/source-proof.json",
+ "repository_lineage": [
+ "swesmith/c-bata__go-prompt.82a91227",
+ "c-bata/go-prompt"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "0c73250c389980239e60bab96f73d4a9c7528f3b",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "6442a4765035a53d37544f0ab80450f7c26da93b",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/c-bata__go-prompt.82a91227",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "c-bata__go-prompt.82a91227.lm_modify__cyda491g",
+ "task_sha256": "db3a01d858de33fbaced5e66b26e6d9898b8c03d5d800683ef66be96b9edb643",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "c-bata/go-prompt",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "730db66b3752a19b3b1d0bee34828b690a2f60086a73d72414c6915f9cf84da6",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.md",
+ "/testbed/.github/ISSUE_TEMPLATE/feature_request.md",
+ "/testbed/.gitignore",
+ "/testbed/CHANGELOG.md",
+ "/testbed/LICENSE",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/_example/README.md",
+ "/testbed/_example/build.sh",
+ "/testbed/_example/exec-command/main.go",
+ "/testbed/_example/http-prompt/api.py",
+ "/testbed/_example/http-prompt/main.go",
+ "/testbed/_example/live-prefix/main.go",
+ "/testbed/_example/simple-echo/cjk-cyrillic/main.go",
+ "/testbed/_example/simple-echo/main.go",
+ "/testbed/_tools/README.md",
+ "/testbed/_tools/complete_file/main.go",
+ "/testbed/_tools/sigwinch/main.go",
+ "/testbed/_tools/vt100_debug/main.go",
+ "/testbed/buffer.go",
+ "/testbed/completer/file.go",
+ "/testbed/completion.go",
+ "/testbed/document.go",
+ "/testbed/emacs.go",
+ "/testbed/filter.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum",
+ "/testbed/history.go",
+ "/testbed/input.go",
+ "/testbed/input_posix.go",
+ "/testbed/input_windows.go",
+ "/testbed/internal/bisect/bisect.go",
+ "/testbed/internal/debug/assert.go",
+ "/testbed/internal/debug/log.go",
+ "/testbed/internal/strings/strings.go",
+ "/testbed/internal/term/raw.go",
+ "/testbed/internal/term/term.go",
+ "/testbed/key.go",
+ "/testbed/key_bind.go",
+ "/testbed/key_bind_func.go",
+ "/testbed/key_string.go",
+ "/testbed/option.go",
+ "/testbed/output.go",
+ "/testbed/output_posix.go",
+ "/testbed/output_vt100.go",
+ "/testbed/output_windows.go",
+ "/testbed/prompt.go",
+ "/testbed/render.go",
+ "/testbed/shortcut.go",
+ "/testbed/signal_posix.go",
+ "/testbed/signal_windows.go"
+ ]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/solution/solve.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..1efd4330070144002a3073d405c313b6d73474b1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"completion.go": {"data": "cGFja2FnZSBwcm9tcHQKCmltcG9ydCAoCgkic3RyaW5ncyIKCgkiZ2l0aHViLmNvbS9jLWJhdGEvZ28tcHJvbXB0L2ludGVybmFsL2RlYnVnIgoJcnVuZXdpZHRoICJnaXRodWIuY29tL21hdHRuL2dvLXJ1bmV3aWR0aCIKKQoKY29uc3QgKAoJc2hvcnRlblN1ZmZpeCA9ICIuLi4iCglsZWZ0UHJlZml4ICAgID0gIiAiCglsZWZ0U3VmZml4ICAgID0gIiAiCglyaWdodFByZWZpeCAgID0gIiAiCglyaWdodFN1ZmZpeCAgID0gIiAiCikKCnZhciAoCglsZWZ0TWFyZ2luICAgICAgID0gcnVuZXdpZHRoLlN0cmluZ1dpZHRoKGxlZnRQcmVmaXggKyBsZWZ0U3VmZml4KQoJcmlnaHRNYXJnaW4gICAgICA9IHJ1bmV3aWR0aC5TdHJpbmdXaWR0aChyaWdodFByZWZpeCArIHJpZ2h0U3VmZml4KQoJY29tcGxldGlvbk1hcmdpbiA9IGxlZnRNYXJnaW4gKyByaWdodE1hcmdpbgopCgovLyBTdWdnZXN0IGlzIHByaW50ZWQgd2hlbiBjb21wbGV0aW5nLgp0eXBlIFN1Z2dlc3Qgc3RydWN0IHsKCVRleHQgICAgICAgIHN0cmluZwoJRGVzY3JpcHRpb24gc3RyaW5nCn0KCi8vIENvbXBsZXRpb25NYW5hZ2VyIG1hbmFnZXMgd2hpY2ggc3VnZ2VzdGlvbiBpcyBub3cgc2VsZWN0ZWQuCnR5cGUgQ29tcGxldGlvbk1hbmFnZXIgc3RydWN0IHsKCXNlbGVjdGVkICBpbnQgLy8gLTEgbWVhbnMgbm90aGluZyBvbmUgaXMgc2VsZWN0ZWQuCgl0bXAgICAgICAgW11TdWdnZXN0CgltYXggICAgICAgdWludDE2Cgljb21wbGV0ZXIgQ29tcGxldGVyCgoJdmVydGljYWxTY3JvbGwgaW50Cgl3b3JkU2VwYXJhdG9yICBzdHJpbmcKCXNob3dBdFN0YXJ0ICAgIGJvb2wKfQoKLy8gR2V0U2VsZWN0ZWRTdWdnZXN0aW9uIHJldHVybnMgdGhlIHNlbGVjdGVkIGl0ZW0uCmZ1bmMgKGMgKkNvbXBsZXRpb25NYW5hZ2VyKSBHZXRTZWxlY3RlZFN1Z2dlc3Rpb24oKSAocyBTdWdnZXN0LCBvayBib29sKSB7CglpZiBjLnNlbGVjdGVkID09IC0xIHsKCQlyZXR1cm4gU3VnZ2VzdHt9LCBmYWxzZQoJfSBlbHNlIGlmIGMuc2VsZWN0ZWQgPCAtMSB7CgkJZGVidWcuQXNzZXJ0KGZhbHNlLCAibXVzdCBub3QgcmVhY2ggaGVyZSIpCgkJYy5zZWxlY3RlZCA9IC0xCgkJcmV0dXJuIFN1Z2dlc3R7fSwgZmFsc2UKCX0KCXJldHVybiBjLnRtcFtjLnNlbGVjdGVkXSwgdHJ1ZQp9CgovLyBHZXRTdWdnZXN0aW9ucyByZXR1cm5zIHRoZSBsaXN0IG9mIHN1Z2dlc3Rpb24uCmZ1bmMgKGMgKkNvbXBsZXRpb25NYW5hZ2VyKSBHZXRTdWdnZXN0aW9ucygpIFtdU3VnZ2VzdCB7CglyZXR1cm4gYy50bXAKfQoKLy8gUmVzZXQgdG8gc2VsZWN0IG5vdGhpbmcuCmZ1bmMgKGMgKkNvbXBsZXRpb25NYW5hZ2VyKSBSZXNldCgpIHsKCWMuc2VsZWN0ZWQgPSAtMQoJYy52ZXJ0aWNhbFNjcm9sbCA9IDAKCWMuVXBkYXRlKCpOZXdEb2N1bWVudCgpKQp9CgovLyBVcGRhdGUgdG8gdXBkYXRlIHRoZSBzdWdnZXN0aW9ucy4KZnVuYyAoYyAqQ29tcGxldGlvbk1hbmFnZXIpIFVwZGF0ZShpbiBEb2N1bWVudCkgewoJYy50bXAgPSBjLmNvbXBsZXRlcihpbikKfQoKLy8gUHJldmlvdXMgdG8gc2VsZWN0IHRoZSBwcmV2aW91cyBzdWdnZXN0aW9uIGl0ZW0uCmZ1bmMgKGMgKkNvbXBsZXRpb25NYW5hZ2VyKSBQcmV2aW91cygpIHsKCWlmIGMudmVydGljYWxTY3JvbGwgPT0gYy5zZWxlY3RlZCAmJiBjLnNlbGVjdGVkID4gMCB7CgkJYy52ZXJ0aWNhbFNjcm9sbC0tCgl9CgljLnNlbGVjdGVkLS0KCWMudXBkYXRlKCkKfQoKLy8gTmV4dCB0byBzZWxlY3QgdGhlIG5leHQgc3VnZ2VzdGlvbiBpdGVtLgpmdW5jIChjICpDb21wbGV0aW9uTWFuYWdlcikgTmV4dCgpIHsKCWlmIGMudmVydGljYWxTY3JvbGwraW50KGMubWF4KS0xID09IGMuc2VsZWN0ZWQgewoJCWMudmVydGljYWxTY3JvbGwrKwoJfQoJYy5zZWxlY3RlZCsrCgljLnVwZGF0ZSgpCn0KCi8vIENvbXBsZXRpbmcgcmV0dXJucyB3aGV0aGVyIHRoZSBDb21wbGV0aW9uTWFuYWdlciBzZWxlY3RzIHNvbWV0aGluZyBvbmUuCmZ1bmMgKGMgKkNvbXBsZXRpb25NYW5hZ2VyKSBDb21wbGV0aW5nKCkgYm9vbCB7CglyZXR1cm4gYy5zZWxlY3RlZCAhPSAtMQp9CgpmdW5jIChjICpDb21wbGV0aW9uTWFuYWdlcikgdXBkYXRlKCkgewoJbWF4IDo9IGludChjLm1heCkKCWlmIGxlbihjLnRtcCkgPCBtYXggewoJCW1heCA9IGxlbihjLnRtcCkKCX0KCglpZiBjLnNlbGVjdGVkID49IGxlbihjLnRtcCkgewoJCWMuUmVzZXQoKQoJfSBlbHNlIGlmIGMuc2VsZWN0ZWQgPCAtMSB7CgkJYy5zZWxlY3RlZCA9IGxlbihjLnRtcCkgLSAxCgkJYy52ZXJ0aWNhbFNjcm9sbCA9IGxlbihjLnRtcCkgLSBtYXgKCX0KfQoKZnVuYyBkZWxldGVCcmVha0xpbmVDaGFyYWN0ZXJzKHMgc3RyaW5nKSBzdHJpbmcgewoJcyA9IHN0cmluZ3MuUmVwbGFjZShzLCAiXG4iLCAiIiwgLTEpCglzID0gc3RyaW5ncy5SZXBsYWNlKHMsICJcciIsICIiLCAtMSkKCXJldHVybiBzCn0KCmZ1bmMgZm9ybWF0VGV4dHMobyBbXXN0cmluZywgbWF4IGludCwgcHJlZml4LCBzdWZmaXggc3RyaW5nKSAobmV3IFtdc3RyaW5nLCB3aWR0aCBpbnQpIHsKCWwgOj0gbGVuKG8pCgluIDo9IG1ha2UoW11zdHJpbmcsIGwpCgoJbGVuUHJlZml4IDo9IHJ1bmV3aWR0aC5TdHJpbmdXaWR0aChwcmVmaXgpCglsZW5TdWZmaXggOj0gcnVuZXdpZHRoLlN0cmluZ1dpZHRoKHN1ZmZpeCkKCWxlblNob3J0ZW4gOj0gcnVuZXdpZHRoLlN0cmluZ1dpZHRoKHNob3J0ZW5TdWZmaXgpCgltaW4gOj0gbGVuUHJlZml4ICsgbGVuU3VmZml4ICsgbGVuU2hvcnRlbgoJZm9yIGkgOj0gMDsgaSA8IGw7IGkrKyB7CgkJb1tpXSA9IGRlbGV0ZUJyZWFrTGluZUNoYXJhY3RlcnMob1tpXSkKCgkJdyA6PSBydW5ld2lkdGguU3RyaW5nV2lkdGgob1tpXSkKCQlpZiB3aWR0aCA8IHcgewoJCQl3aWR0aCA9IHcKCQl9Cgl9CgoJaWYgd2lkdGggPT0gMCB7CgkJcmV0dXJuIG4sIDAKCX0KCWlmIG1pbiA+PSBtYXggewoJCXJldHVybiBuLCAwCgl9CglpZiBsZW5QcmVmaXgrd2lkdGgrbGVuU3VmZml4ID4gbWF4IHsKCQl3aWR0aCA9IG1heCAtIGxlblByZWZpeCAtIGxlblN1ZmZpeAoJfQoKCWZvciBpIDo9IDA7IGkgPCBsOyBpKysgewoJCXggOj0gcnVuZXdpZHRoLlN0cmluZ1dpZHRoKG9baV0pCgkJaWYgeCA8PSB3aWR0aCB7CgkJCXNwYWNlcyA6PSBzdHJpbmdzLlJlcGVhdCgiICIsIHdpZHRoLXgpCgkJCW5baV0gPSBwcmVmaXggKyBvW2ldICsgc3BhY2VzICsgc3VmZml4CgkJfSBlbHNlIGlmIHggPiB3aWR0aCB7CgkJCXggOj0gcnVuZXdpZHRoLlRydW5jYXRlKG9baV0sIHdpZHRoLCBzaG9ydGVuU3VmZml4KQoJCQkvLyBXaGVuIGNhbGxpbmcgcnVuZXdpZHRoLlRydW5jYXRlKCLmgqjlpb14eHjmgqjlpb14eHgiLCAxMSwgIi4uLiIpIHJldHVybnMgIuaCqOWlvXh4eC4uLiIKCQkJLy8gQnV0IHRoZSBsZW5ndGggb2YgdGhpcyByZXN1bHQgaXMgMTAuIFNvIHdlIG5lZWQgZmlsbCByaWdodCB1c2luZyBydW5ld2lkdGguRmlsbFJpZ2h0LgoJCQluW2ldID0gcHJlZml4ICsgcnVuZXdpZHRoLkZpbGxSaWdodCh4LCB3aWR0aCkgKyBzdWZmaXgKCQl9Cgl9CglyZXR1cm4gbiwgbGVuUHJlZml4ICsgd2lkdGggKyBsZW5TdWZmaXgKfQoKZnVuYyBmb3JtYXRTdWdnZXN0aW9ucyhzdWdnZXN0cyBbXVN1Z2dlc3QsIG1heCBpbnQpIChuZXcgW11TdWdnZXN0LCB3aWR0aCBpbnQpIHsKCW51bSA6PSBsZW4oc3VnZ2VzdHMpCgluZXcgPSBtYWtlKFtdU3VnZ2VzdCwgbnVtKQoKCWxlZnQgOj0gbWFrZShbXXN0cmluZywgbnVtKQoJZm9yIGkgOj0gMDsgaSA8IG51bTsgaSsrIHsKCQlsZWZ0W2ldID0gc3VnZ2VzdHNbaV0uVGV4dAoJfQoJcmlnaHQgOj0gbWFrZShbXXN0cmluZywgbnVtKQoJZm9yIGkgOj0gMDsgaSA8IG51bTsgaSsrIHsKCQlyaWdodFtpXSA9IHN1Z2dlc3RzW2ldLkRlc2NyaXB0aW9uCgl9CgoJbGVmdCwgbGVmdFdpZHRoIDo9IGZvcm1hdFRleHRzKGxlZnQsIG1heCwgbGVmdFByZWZpeCwgbGVmdFN1ZmZpeCkKCWlmIGxlZnRXaWR0aCA9PSAwIHsKCQlyZXR1cm4gW11TdWdnZXN0e30sIDAKCX0KCXJpZ2h0LCByaWdodFdpZHRoIDo9IGZvcm1hdFRleHRzKHJpZ2h0LCBtYXgtbGVmdFdpZHRoLCByaWdodFByZWZpeCwgcmlnaHRTdWZmaXgpCgoJZm9yIGkgOj0gMDsgaSA8IG51bTsgaSsrIHsKCQluZXdbaV0gPSBTdWdnZXN0e1RleHQ6IGxlZnRbaV0sIERlc2NyaXB0aW9uOiByaWdodFtpXX0KCX0KCXJldHVybiBuZXcsIGxlZnRXaWR0aCArIHJpZ2h0V2lkdGgKfQoKLy8gTmV3Q29tcGxldGlvbk1hbmFnZXIgcmV0dXJucyBpbml0aWFsaXplZCBDb21wbGV0aW9uTWFuYWdlciBvYmplY3QuCmZ1bmMgTmV3Q29tcGxldGlvbk1hbmFnZXIoY29tcGxldGVyIENvbXBsZXRlciwgbWF4IHVpbnQxNikgKkNvbXBsZXRpb25NYW5hZ2VyIHsKCXJldHVybiAmQ29tcGxldGlvbk1hbmFnZXJ7CgkJc2VsZWN0ZWQ6ICAtMSwKCQltYXg6ICAgICAgIG1heCwKCQljb21wbGV0ZXI6IGNvbXBsZXRlciwKCgkJdmVydGljYWxTY3JvbGw6IDAsCgl9Cn0K", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/task.toml b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..239eb93f4c894de60ad4e0a930314e8dc7800354
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/task.toml
@@ -0,0 +1,11 @@
+version = "1.0"
+[agent]
+timeout_sec = 300.0
+[verifier]
+timeout_sec = 300.0
+environment_mode = "shared"
+[environment]
+docker_image = "ghcr.io/younesbelkada/scale800@sha256:a0f3a8290edd8b6c2e09096bc6609d7367e4a97f0dbf4f4a533d15af2e190af1"
+cpus = 1
+memory_mb = 2048
+storage_mb = 4096
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..617e3afa3725653d6fbc39a335d5fe9705ac5bcc
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/manifest.json
@@ -0,0 +1,432 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CursorPositionRowAndCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorLeftPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorUpPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorDownPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorRightPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_Lines"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_LineCount"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateIndexToPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateRowColToIndex"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_OnLastLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetEndOfLinePosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestEmacsKeyBindings"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFilter"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFuzzyMatch"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryClear"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryAdd"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryOlder"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/escape"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/undefined"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWrite"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteRawStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatCompletion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBreakLineCallback"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionRow"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition_withJapanese"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/validation/canaries/partial-repair.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/validation/canaries/partial-repair.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f6bac73eac42ba87259fb87e5d908d9bb435ab30
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/validation/canaries/partial-repair.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"completion.go": {"data": "cGFja2FnZSBwcm9tcHQKCmltcG9ydCAoCgkic3RyaW5ncyIKCgkiZ2l0aHViLmNvbS9jLWJhdGEvZ28tcHJvbXB0L2ludGVybmFsL2RlYnVnIgoJcnVuZXdpZHRoICJnaXRodWIuY29tL21hdHRuL2dvLXJ1bmV3aWR0aCIKKQoKY29uc3QgKAoJc2hvcnRlblN1ZmZpeCA9ICIuLi4iCglsZWZ0UHJlZml4ICAgID0gIiAiCglsZWZ0U3VmZml4ICAgID0gIiAiCglyaWdodFByZWZpeCAgID0gIiAiCglyaWdodFN1ZmZpeCAgID0gIiAiCikKCnZhciAoCglsZWZ0TWFyZ2luICAgICAgID0gcnVuZXdpZHRoLlN0cmluZ1dpZHRoKGxlZnRQcmVmaXggKyBsZWZ0U3VmZml4KQoJcmlnaHRNYXJnaW4gICAgICA9IHJ1bmV3aWR0aC5TdHJpbmdXaWR0aChyaWdodFByZWZpeCArIHJpZ2h0U3VmZml4KQoJY29tcGxldGlvbk1hcmdpbiA9IGxlZnRNYXJnaW4gKyByaWdodE1hcmdpbgopCgovLyBTdWdnZXN0IGlzIHByaW50ZWQgd2hlbiBjb21wbGV0aW5nLgp0eXBlIFN1Z2dlc3Qgc3RydWN0IHsKCVRleHQgICAgICAgIHN0cmluZwoJRGVzY3JpcHRpb24gc3RyaW5nCn0KCi8vIENvbXBsZXRpb25NYW5hZ2VyIG1hbmFnZXMgd2hpY2ggc3VnZ2VzdGlvbiBpcyBub3cgc2VsZWN0ZWQuCnR5cGUgQ29tcGxldGlvbk1hbmFnZXIgc3RydWN0IHsKCXNlbGVjdGVkICBpbnQgLy8gLTEgbWVhbnMgbm90aGluZyBvbmUgaXMgc2VsZWN0ZWQuCgl0bXAgICAgICAgW11TdWdnZXN0CgltYXggICAgICAgdWludDE2Cgljb21wbGV0ZXIgQ29tcGxldGVyCgoJdmVydGljYWxTY3JvbGwgaW50Cgl3b3JkU2VwYXJhdG9yICBzdHJpbmcKCXNob3dBdFN0YXJ0ICAgIGJvb2wKfQoKLy8gR2V0U2VsZWN0ZWRTdWdnZXN0aW9uIHJldHVybnMgdGhlIHNlbGVjdGVkIGl0ZW0uCmZ1bmMgKGMgKkNvbXBsZXRpb25NYW5hZ2VyKSBHZXRTZWxlY3RlZFN1Z2dlc3Rpb24oKSAocyBTdWdnZXN0LCBvayBib29sKSB7CglpZiBjLnNlbGVjdGVkID09IC0xIHsKCQlyZXR1cm4gU3VnZ2VzdHt9LCBmYWxzZQoJfSBlbHNlIGlmIGMuc2VsZWN0ZWQgPCAtMSB7CgkJZGVidWcuQXNzZXJ0KGZhbHNlLCAibXVzdCBub3QgcmVhY2ggaGVyZSIpCgkJYy5zZWxlY3RlZCA9IC0xCgkJcmV0dXJuIFN1Z2dlc3R7fSwgZmFsc2UKCX0KCXJldHVybiBjLnRtcFtjLnNlbGVjdGVkXSwgdHJ1ZQp9CgovLyBHZXRTdWdnZXN0aW9ucyByZXR1cm5zIHRoZSBsaXN0IG9mIHN1Z2dlc3Rpb24uCmZ1bmMgKGMgKkNvbXBsZXRpb25NYW5hZ2VyKSBHZXRTdWdnZXN0aW9ucygpIFtdU3VnZ2VzdCB7CglyZXR1cm4gYy50bXAKfQoKLy8gUmVzZXQgdG8gc2VsZWN0IG5vdGhpbmcuCmZ1bmMgKGMgKkNvbXBsZXRpb25NYW5hZ2VyKSBSZXNldCgpIHsKCWMuc2VsZWN0ZWQgPSAtMQoJYy52ZXJ0aWNhbFNjcm9sbCA9IDAKCWMuVXBkYXRlKCpOZXdEb2N1bWVudCgpKQp9CgovLyBVcGRhdGUgdG8gdXBkYXRlIHRoZSBzdWdnZXN0aW9ucy4KZnVuYyAoYyAqQ29tcGxldGlvbk1hbmFnZXIpIFVwZGF0ZShpbiBEb2N1bWVudCkgewoJYy50bXAgPSBjLmNvbXBsZXRlcihpbikKfQoKLy8gUHJldmlvdXMgdG8gc2VsZWN0IHRoZSBwcmV2aW91cyBzdWdnZXN0aW9uIGl0ZW0uCmZ1bmMgKGMgKkNvbXBsZXRpb25NYW5hZ2VyKSBQcmV2aW91cygpIHsKCWlmIGMudmVydGljYWxTY3JvbGwgPT0gYy5zZWxlY3RlZCAmJiBjLnNlbGVjdGVkID4gMCB7CgkJYy52ZXJ0aWNhbFNjcm9sbC0tCgl9CgljLnNlbGVjdGVkLS0KCWMudXBkYXRlKCkKfQoKLy8gTmV4dCB0byBzZWxlY3QgdGhlIG5leHQgc3VnZ2VzdGlvbiBpdGVtLgpmdW5jIChjICpDb21wbGV0aW9uTWFuYWdlcikgTmV4dCgpIHsKCWlmIGMudmVydGljYWxTY3JvbGwraW50KGMubWF4KS0xID09IGMuc2VsZWN0ZWQgewoJCWMudmVydGljYWxTY3JvbGwrKwoJfQoJYy5zZWxlY3RlZCsrCgljLnVwZGF0ZSgpCn0KCi8vIENvbXBsZXRpbmcgcmV0dXJucyB3aGV0aGVyIHRoZSBDb21wbGV0aW9uTWFuYWdlciBzZWxlY3RzIHNvbWV0aGluZyBvbmUuCmZ1bmMgKGMgKkNvbXBsZXRpb25NYW5hZ2VyKSBDb21wbGV0aW5nKCkgYm9vbCB7CglyZXR1cm4gYy5zZWxlY3RlZCAhPSAtMQp9CgpmdW5jIChjICpDb21wbGV0aW9uTWFuYWdlcikgdXBkYXRlKCkgewoJbWF4IDo9IGludChjLm1heCkKCWlmIGxlbihjLnRtcCkgPCBtYXggewoJCW1heCA9IGxlbihjLnRtcCkKCX0KCglpZiBjLnNlbGVjdGVkID49IGxlbihjLnRtcCkgewoJCWMuUmVzZXQoKQoJfSBlbHNlIGlmIGMuc2VsZWN0ZWQgPCAtMSB7CgkJYy5zZWxlY3RlZCA9IGxlbihjLnRtcCkgLSAxCgkJYy52ZXJ0aWNhbFNjcm9sbCA9IGxlbihjLnRtcCkgLSBtYXgKCX0KfQoKZnVuYyBkZWxldGVCcmVha0xpbmVDaGFyYWN0ZXJzKHMgc3RyaW5nKSBzdHJpbmcgewoJcyA9IHN0cmluZ3MuUmVwbGFjZShzLCAiXG4iLCAiIiwgLTEpCglzID0gc3RyaW5ncy5SZXBsYWNlKHMsICJcciIsICIiLCAtMSkKCXJldHVybiBzCn0KCmZ1bmMgZm9ybWF0VGV4dHMobyBbXXN0cmluZywgbWF4IGludCwgcHJlZml4LCBzdWZmaXggc3RyaW5nKSAobmV3IFtdc3RyaW5nLCB3aWR0aCBpbnQpIHsKCWwgOj0gbGVuKG8pCgluIDo9IG1ha2UoW11zdHJpbmcsIGwpCgoJbGVuUHJlZml4IDo9IHJ1bmV3aWR0aC5TdHJpbmdXaWR0aChwcmVmaXgpCglsZW5TdWZmaXggOj0gcnVuZXdpZHRoLlN0cmluZ1dpZHRoKHN1ZmZpeCkKCWxlblNob3J0ZW4gOj0gcnVuZXdpZHRoLlN0cmluZ1dpZHRoKHNob3J0ZW5TdWZmaXgpCgltaW4gOj0gbGVuUHJlZml4ICsgbGVuU3VmZml4ICsgbGVuU2hvcnRlbgoJZm9yIGkgOj0gMDsgaSA8IGw7IGkrKyB7CgkJb1tpXSA9IGRlbGV0ZUJyZWFrTGluZUNoYXJhY3RlcnMob1tpXSkKCgkJdyA6PSBydW5ld2lkdGguU3RyaW5nV2lkdGgob1tpXSkKCQlpZiB3aWR0aCA8IHcgewoJCQl3aWR0aCA9IHcKCQl9Cgl9CgoJaWYgd2lkdGggPT0gMCB7CgkJcmV0dXJuIG4sIDAKCX0KCWlmIG1pbiA+PSBtYXggewoJCXJldHVybiBuLCAwCgl9CglpZiBsZW5QcmVmaXgrd2lkdGgrbGVuU3VmZml4ID4gbWF4IHsKCQl3aWR0aCA9IG1heCAtIGxlblByZWZpeCAtIGxlblN1ZmZpeCAtIDEKCX0KCglmb3IgaSA6PSAwOyBpIDwgbDsgaSsrIHsKCQl4IDo9IHJ1bmV3aWR0aC5TdHJpbmdXaWR0aChvW2ldKQoJCWlmIHggPD0gd2lkdGggewoJCQlzcGFjZXMgOj0gc3RyaW5ncy5SZXBlYXQoIiAiLCB3aWR0aC14KQoJCQluW2ldID0gcHJlZml4ICsgb1tpXSArIHNwYWNlcyArIHN1ZmZpeAoJCX0gZWxzZSBpZiB4ID4gd2lkdGggewoJCQl4IDo9IHJ1bmV3aWR0aC5UcnVuY2F0ZShvW2ldLCB3aWR0aCwgc2hvcnRlblN1ZmZpeCkKCQkJLy8gV2hlbiBjYWxsaW5nIHJ1bmV3aWR0aC5UcnVuY2F0ZSgi5oKo5aW9eHh45oKo5aW9eHh4IiwgMTEsICIuLi4iKSByZXR1cm5zICLmgqjlpb14eHguLi4iCgkJCS8vIEJ1dCB0aGUgbGVuZ3RoIG9mIHRoaXMgcmVzdWx0IGlzIDEwLiBTbyB3ZSBuZWVkIGZpbGwgcmlnaHQgdXNpbmcgcnVuZXdpZHRoLkZpbGxSaWdodC4KCQkJbltpXSA9IHByZWZpeCArIHJ1bmV3aWR0aC5GaWxsUmlnaHQoeCwgd2lkdGgpICsgc3VmZml4CgkJfQoJfQoJcmV0dXJuIG4sIGxlblByZWZpeCArIHdpZHRoICsgbGVuU3VmZml4Cn0KCmZ1bmMgZm9ybWF0U3VnZ2VzdGlvbnMoc3VnZ2VzdHMgW11TdWdnZXN0LCBtYXggaW50KSAobmV3IFtdU3VnZ2VzdCwgd2lkdGggaW50KSB7CgludW0gOj0gbGVuKHN1Z2dlc3RzKQoJbmV3ID0gbWFrZShbXVN1Z2dlc3QsIG51bSkKCglsZWZ0IDo9IG1ha2UoW11zdHJpbmcsIG51bSkKCWZvciBpIDo9IDA7IGkgPCBudW07IGkrKyB7CgkJbGVmdFtpXSA9IHN1Z2dlc3RzW2ldLlRleHQKCX0KCXJpZ2h0IDo9IG1ha2UoW11zdHJpbmcsIG51bSkKCWZvciBpIDo9IDA7IGkgPCBudW07IGkrKyB7CgkJcmlnaHRbaV0gPSBzdWdnZXN0c1tpXS5EZXNjcmlwdGlvbgoJfQoKCWxlZnQsIGxlZnRXaWR0aCA6PSBmb3JtYXRUZXh0cyhsZWZ0LCBtYXgsIGxlZnRQcmVmaXgsIGxlZnRTdWZmaXgpCglpZiBsZWZ0V2lkdGggPT0gMCB7CgkJcmV0dXJuIFtdU3VnZ2VzdHt9LCAwCgl9CglyaWdodCwgcmlnaHRXaWR0aCA6PSBmb3JtYXRUZXh0cyhyaWdodCwgbWF4LWxlZnRXaWR0aCwgcmlnaHRQcmVmaXgsIHJpZ2h0U3VmZml4KQoKCWZvciBpIDo9IDA7IGkgPCBudW07IGkrKyB7CgkJbmV3W2ldID0gU3VnZ2VzdHtUZXh0OiBsZWZ0W2ldLCBEZXNjcmlwdGlvbjogcmlnaHRbaV19Cgl9CglyZXR1cm4gbmV3LCBsZWZ0V2lkdGggKyByaWdodFdpZHRoCn0KCi8vIE5ld0NvbXBsZXRpb25NYW5hZ2VyIHJldHVybnMgaW5pdGlhbGl6ZWQgQ29tcGxldGlvbk1hbmFnZXIgb2JqZWN0LgpmdW5jIE5ld0NvbXBsZXRpb25NYW5hZ2VyKGNvbXBsZXRlciBDb21wbGV0ZXIsIG1heCB1aW50MTYpICpDb21wbGV0aW9uTWFuYWdlciB7CglyZXR1cm4gJkNvbXBsZXRpb25NYW5hZ2VyewoJCXNlbGVjdGVkOiAgLTEsCgkJbWF4OiAgICAgICBtYXgsCgkJY29tcGxldGVyOiBjb21wbGV0ZXIsCgoJCXZlcnRpY2FsU2Nyb2xsOiAwLAoJfQp9Cg==", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..331a5cac6c33f8bade2393d71836ccf8bb7cd509
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__cyda491g/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "f823e15dc4b473d6eed9d958b7fa04e68e2837d7ccf6ec2fa399eaaada780297",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/Dockerfile b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f35bf9e5393ee1086fe1b72c1b442f3b16e2bd5b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22
+WORKDIR /testbed
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c8c031d0f87fb9aea0aff433b1fcaeaac259c41
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: "Bug report"
+about: Create a bug report to improve go-prompt
+title: "[Bug]"
+labels: bug
+assignees: ''
+
+---
+
+# Bug reports
+
+*Please file a bug report here.*
+
+## Expected Behavior
+
+*Please describe the behavior you are expecting*
+
+## Current Behavior and Steps to Reproduce
+
+*What is the current behavior? Please provide detailed steps for reproducing the issue.*
+*A picture or gif animation tells a thousand words*
+
+## Context
+
+Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
+
+* Operating System:
+* Terminal Emulator: (i.e. iTerm2)
+* tag of go-prompt or commit revision:
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb816a2496376983781774cb5466fed8e1efc93b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,13 @@
+---
+name: "Feature request"
+about: Suggest an idea for new features in go-prompt.
+title: "[Feature Request]"
+labels: enhancement
+assignees: ''
+
+---
+
+# Feature Request
+
+*Please write your suggestion here.*
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/.gitignore b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..eba2b56abe0f7758a560d47dd19d8985b67ef327
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+bin/
+
+# Folders
+pkg/
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+# Glide
+vendor/
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/CHANGELOG.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..b9e21f1ef333b9ec13323bcd4a8f377322ed7e9f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/CHANGELOG.md
@@ -0,0 +1,79 @@
+# Change Log
+
+## v0.3.0 (2018/??/??)
+
+next release.
+
+## v0.2.3 (2018/10/25)
+
+### What's new?
+
+* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92).
+* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100).
+* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102).
+
+### Fixed
+
+* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details).
+* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details).
+* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details).
+
+### Removed or Deprecated
+
+* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`.
+
+## v0.2.2 (2018/06/28)
+
+### What's new?
+
+* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters.
+* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions.
+ * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details).
+* Add FilePathCompleter to complete file path on your system.
+* Add option to customize ascii code key bindings.
+* Add GetWordAfterCursor method in Document.
+
+### Removed or Deprecated
+
+* prompt.Choose shortcut function is deprecated.
+
+## v0.2.1 (2018/02/14)
+
+### What's New?
+
+* ~~It seems that windows support is almost perfect.~~
+ * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows.
+
+### Fixed
+
+* Fix a Shift+Tab handling on Windows.
+* Fix 4-dimension arrow keys handling on Windows.
+
+## v0.2.0 (2018/02/13)
+
+### What's New?
+
+* Supports scrollbar when there are too many matched suggestions
+* Windows support (but please caution because this is still not perfect).
+* Add OptionLivePrefix to update the prefix dynamically
+* Implement clear screen by `Ctrl+L`.
+
+### Fixed
+
+* Fix the behavior of `Ctrl+W` keybind.
+* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details).
+* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details).
+* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ).
+
+### News
+
+New core developers are joined (alphabetical order).
+
+* Nao Yonashiro (Github @orisano)
+* Ryoma Abe (Github @Allajah)
+* Yusuke Nakamura (Github @unasuke)
+
+
+## v0.1.0 (2017/08/15)
+
+Initial Release
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/LICENSE b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a86acaa7ab24fe61ea152a9afcadc21980020efb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Masashi SHIBATA
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/Makefile b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..505817c36f0b8a0bb643eed8680b8989af2b0920
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/Makefile
@@ -0,0 +1,46 @@
+.DEFAULT_GOAL := help
+
+SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
+
+GOIMPORTS ?= goimports
+GOCILINT ?= golangci-lint
+
+.PHONY: setup
+setup: ## Setup for required tools.
+ go get -u golang.org/x/tools/cmd/goimports
+ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+ go get -u golang.org/x/tools/cmd/stringer
+
+.PHONY: fmt
+fmt: $(SOURCES) ## Formatting source codes.
+ @$(GOIMPORTS) -w $^
+
+.PHONY: lint
+lint: ## Run golangci-lint.
+ @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
+
+.PHONY: test
+test: ## Run tests with race condition checking.
+ @go test -race ./...
+
+.PHONY: bench
+bench: ## Run benchmarks.
+ @go test -bench=. -run=- -benchmem ./...
+
+.PHONY: coverage
+cover: ## Run the tests.
+ @go test -coverprofile=coverage.o
+ @go tool cover -func=coverage.o
+
+.PHONY: generate
+generate: ## Run go generate
+ @go generate ./...
+
+.PHONY: build
+build: ## Build example command lines.
+ ./_example/build.sh
+
+.PHONY: help
+help: ## Show help text
+ @echo "Commands:"
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfcd7a399b4827d6b126d6a173cce34d36520481
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/README.md
@@ -0,0 +1,125 @@
+# go-prompt
+
+[](https://goreportcard.com/report/github.com/c-bata/go-prompt)
+
+[](https://godoc.org/github.com/c-bata/go-prompt)
+
+
+A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit),
+making it easier to build cross-platform command line tools using Go.
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func completer(d prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ }
+ return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ fmt.Println("Please select table.")
+ t := prompt.Input("> ", completer)
+ fmt.Println("You selected " + t)
+}
+```
+
+#### Projects using go-prompt
+
+* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt)
+* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli)
+* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn)
+* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli)
+* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans)
+* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit)
+* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go)
+* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS)
+* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs)
+* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli)
+* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt)
+* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh)
+* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell)
+* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt)
+* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim)
+* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron)
+* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl)
+* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl)
+* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit)
+* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.)
+
+## Features
+
+### Powerful auto-completion
+
+[](https://github.com/c-bata/kube-prompt)
+
+(This is a GIF animation of kube-prompt.)
+
+### Flexible options
+
+go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details.
+
+[](#flexible-options)
+
+### Keyboard Shortcuts
+
+Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell).
+You can customize and expand these shortcuts.
+
+[](#keyboard-shortcuts)
+
+Key Binding | Description
+---------------------|---------------------------------------------------------
+Ctrl + A | Go to the beginning of the line (Home)
+Ctrl + E | Go to the end of the line (End)
+Ctrl + P | Previous command (Up arrow)
+Ctrl + N | Next command (Down arrow)
+Ctrl + F | Forward one character
+Ctrl + B | Backward one character
+Ctrl + D | Delete character under the cursor
+Ctrl + H | Delete character before the cursor (Backspace)
+Ctrl + W | Cut the word before the cursor to the clipboard
+Ctrl + K | Cut the line after the cursor to the clipboard
+Ctrl + U | Cut the line before the cursor to the clipboard
+Ctrl + L | Clear the screen
+
+### History
+
+You can use Up arrow and Down arrow to walk through the history of commands executed.
+
+[](#history)
+
+### Multiple platform support
+
+We have confirmed go-prompt works fine in the following terminals:
+
+* iTerm2 (macOS)
+* Terminal.app (macOS)
+* Command Prompt (Windows)
+* gnome-terminal (Ubuntu)
+
+## Links
+
+* [Change Log](./CHANGELOG.md)
+* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt)
+* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt)
+
+## Author
+
+Masashi Shibata
+
+* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/)
+* Github: [@c-bata](https://github.com/c-bata/)
+
+## License
+
+This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..759b0e3f8acf1216b055e0f9458758a6c1e8950a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/README.md
@@ -0,0 +1,30 @@
+# Examples of go-prompt
+
+This directory includes some examples using go-prompt.
+These examples are useful to know the usage of go-prompt and check behavior for development.
+
+## simple-echo
+
+
+
+A simple echo example using `prompt.Input`.
+
+## http-prompt
+
+
+
+A simple [http-prompt](https://github.com/eliangcs/http-prompt) implementation using go-prompt in less than 200 lines of Go.
+
+## live-prefix
+
+
+
+A example application which changes a prefix string dynamically.
+This feature is used like [ktr0731/evans](https://github.com/ktr0731/evans) which is interactive gRPC client using go-prompt.
+
+## exec-command
+
+Run another CLI tool via `os/exec` package.
+More practical example is [a source code of kube-prompt](https://github.com/c-bata/kube-prompt).
+I recommend you to look this if you want to create tools like kube-prompt.
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/build.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c552afcfa69b2356ffcd484c867abcaaaaeeaff
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/build.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+export GO111MODULE=on
+DIR=$(cd $(dirname $0); pwd)
+BIN_DIR=$(cd $(dirname $(dirname $0)); pwd)/bin
+
+mkdir -p ${BIN_DIR}
+go build -o ${BIN_DIR}/exec-command ${DIR}/exec-command/main.go
+go build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.go
+go build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.go
+go build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.go
+go build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/exec-command/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/exec-command/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..838f756260df91569491def29a7ee05a7c9a98f7
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/exec-command/main.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "os/exec"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(t string) {
+ if t == "bash" {
+ cmd := exec.Command("bash")
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Run()
+ }
+ return
+}
+
+func completer(t prompt.Document) []prompt.Suggest {
+ return []prompt.Suggest{
+ {Text: "bash"},
+ }
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/http-prompt/api.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/http-prompt/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..08e7b1a489a2077f26f280fe39e3bd06efa52cd2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/http-prompt/api.py
@@ -0,0 +1,17 @@
+from bottle import route, run, request
+
+@route('/')
+def hello():
+ return "Hello World!"
+
+@route('/ping')
+def hello():
+ return "pong!"
+
+@route('/register', method='POST')
+def register():
+ name = request.json.get("name")
+ return "Hello %s!" % name
+
+if __name__ == "__main__":
+ run(host='localhost', port=8000, debug=True)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/http-prompt/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/http-prompt/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b372a3550c50121d6e500e2a08e641e168b8c00d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/http-prompt/main.go
@@ -0,0 +1,192 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+type RequestContext struct {
+ url *url.URL
+ header http.Header
+ client *http.Client
+}
+
+var ctx *RequestContext
+
+// See https://github.com/eliangcs/http-prompt/blob/master/http_prompt/completion.py
+var suggestions = []prompt.Suggest{
+ // Command
+ {"cd", "Change URL/path"},
+ {"exit", "Exit http-prompt"},
+
+ // HTTP Method
+ {"delete", "DELETE request"},
+ {"get", "GET request"},
+ {"patch", "GET request"},
+ {"post", "POST request"},
+ {"put", "PUT request"},
+
+ // HTTP Header
+ {"Accept", "Acceptable response media type"},
+ {"Accept-Charset", "Acceptable response charsets"},
+ {"Accept-Encoding", "Acceptable response content codings"},
+ {"Accept-Language", "Preferred natural languages in response"},
+ {"ALPN", "Application-layer protocol negotiation to use"},
+ {"Alt-Used", "Alternative host in use"},
+ {"Authorization", "Authentication information"},
+ {"Cache-Control", "Directives for caches"},
+ {"Connection", "Connection options"},
+ {"Content-Encoding", "Content codings"},
+ {"Content-Language", "Natural languages for content"},
+ {"Content-Length", "Anticipated size for payload body"},
+ {"Content-Location", "Where content was obtained"},
+ {"Content-MD5", "Base64-encoded MD5 sum of content"},
+ {"Content-Type", "Content media type"},
+ {"Cookie", "Stored cookies"},
+ {"Date", "Datetime when message was originated"},
+ {"Depth", "Applied only to resource or its members"},
+ {"DNT", "Do not track user"},
+ {"Expect", "Expected behaviors supported by server"},
+ {"Forwarded", "Proxies involved"},
+ {"From", "Sender email address"},
+ {"Host", "Target URI"},
+ {"HTTP2-Settings", "HTTP/2 connection parameters"},
+ {"If", "Request condition on state tokens and ETags"},
+ {"If-Match", "Request condition on target resource"},
+ {"If-Modified-Since", "Request condition on modification date"},
+ {"If-None-Match", "Request condition on target resource"},
+ {"If-Range", "Request condition on Range"},
+ {"If-Schedule-Tag-Match", "Request condition on Schedule-Tag"},
+ {"If-Unmodified-Since", "Request condition on modification date"},
+ {"Max-Forwards", "Max number of times forwarded by proxies"},
+ {"MIME-Version", "Version of MIME protocol"},
+ {"Origin", "Origin(s} issuing the request"},
+ {"Pragma", "Implementation-specific directives"},
+ {"Prefer", "Preferred server behaviors"},
+ {"Proxy-Authorization", "Proxy authorization credentials"},
+ {"Proxy-Connection", "Proxy connection options"},
+ {"Range", "Request transfer of only part of data"},
+ {"Referer", "Previous web page"},
+ {"TE", "Transfer codings willing to accept"},
+ {"Transfer-Encoding", "Transfer codings applied to payload body"},
+ {"Upgrade", "Invite server to upgrade to another protocol"},
+ {"User-Agent", "User agent string"},
+ {"Via", "Intermediate proxies"},
+ {"Warning", "Possible incorrectness with payload body"},
+ {"WWW-Authenticate", "Authentication scheme"},
+ {"X-Csrf-Token", "Prevent cross-site request forgery"},
+ {"X-CSRFToken", "Prevent cross-site request forgery"},
+ {"X-Forwarded-For", "Originating client IP address"},
+ {"X-Forwarded-Host", "Original host requested by client"},
+ {"X-Forwarded-Proto", "Originating protocol"},
+ {"X-Http-Method-Override", "Request method override"},
+ {"X-Requested-With", "Used to identify Ajax requests"},
+ {"X-XSRF-TOKEN", "Prevent cross-site request forgery"},
+}
+
+func livePrefix() (string, bool) {
+ if ctx.url.Path == "/" {
+ return "", false
+ }
+ return ctx.url.String() + "> ", true
+}
+
+func executor(in string) {
+ in = strings.TrimSpace(in)
+
+ var method, body string
+ blocks := strings.Split(in, " ")
+ switch blocks[0] {
+ case "exit":
+ fmt.Println("Bye!")
+ os.Exit(0)
+ case "cd":
+ if len(blocks) < 2 {
+ ctx.url.Path = "/"
+ } else {
+ ctx.url.Path = path.Join(ctx.url.Path, blocks[1])
+ }
+ return
+ case "get", "delete":
+ method = strings.ToUpper(blocks[0])
+ case "post", "put", "patch":
+ if len(blocks) < 2 {
+ fmt.Println("please set request body.")
+ return
+ }
+ body = strings.Join(blocks[1:], " ")
+ method = strings.ToUpper(blocks[0])
+ }
+ if method != "" {
+ req, err := http.NewRequest(method, ctx.url.String(), strings.NewReader(body))
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ req.Header = ctx.header
+ res, err := ctx.client.Do(req)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ result, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ fmt.Println("err: " + err.Error())
+ return
+ }
+ fmt.Printf("%s\n", result)
+ ctx.header = http.Header{}
+ return
+ }
+
+ if h := strings.Split(in, ":"); len(h) == 2 {
+ // Handling HTTP Header
+ ctx.header.Add(strings.TrimSpace(h[0]), strings.Trim(h[1], ` '"`))
+ } else {
+ fmt.Println("Sorry, I don't understand.")
+ }
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ w := in.GetWordBeforeCursor()
+ if w == "" {
+ return []prompt.Suggest{}
+ }
+ return prompt.FilterHasPrefix(suggestions, w, true)
+}
+
+func main() {
+ var baseURL = "http://localhost:8000/"
+ if len(os.Args) == 2 {
+ baseURL = os.Args[1]
+ if strings.HasSuffix(baseURL, "/") {
+ baseURL += "/"
+ }
+ }
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ ctx = &RequestContext{
+ url: u,
+ header: http.Header{},
+ client: &http.Client{},
+ }
+
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(u.String()+"> "),
+ prompt.OptionLivePrefix(livePrefix),
+ prompt.OptionTitle("http-prompt"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/live-prefix/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/live-prefix/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c7ced720592173e2a13f19f7cb543730192d3f8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/live-prefix/main.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+var LivePrefixState struct {
+ LivePrefix string
+ IsEnable bool
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+ if in == "" {
+ LivePrefixState.IsEnable = false
+ LivePrefixState.LivePrefix = in
+ return
+ }
+ LivePrefixState.LivePrefix = in + "> "
+ LivePrefixState.IsEnable = true
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func changeLivePrefix() (string, bool) {
+ return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionLivePrefix(changeLivePrefix),
+ prompt.OptionTitle("live-prefix-example"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/simple-echo/cjk-cyrillic/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/simple-echo/cjk-cyrillic/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e9e53adef1558e004f86ccbca2c2e2b83c1da39
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/simple-echo/cjk-cyrillic/main.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
+ {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
+ {Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
+ {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completer,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionTitle("sql-prompt for multi width characters"),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/simple-echo/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/simple-echo/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..12b1bb4fc189e6b369e889779418d7826a45db9d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_example/simple-echo/main.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "fmt"
+
+ prompt "github.com/c-bata/go-prompt"
+)
+
+func completer(in prompt.Document) []prompt.Suggest {
+ s := []prompt.Suggest{
+ {Text: "users", Description: "Store the username and age"},
+ {Text: "articles", Description: "Store the article text posted by user"},
+ {Text: "comments", Description: "Store the text commented to articles"},
+ {Text: "groups", Description: "Combine users with specific rules"},
+ }
+ return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
+}
+
+func main() {
+ in := prompt.Input(">>> ", completer,
+ prompt.OptionTitle("sql-prompt"),
+ prompt.OptionHistory([]string{"SELECT * FROM users;"}),
+ prompt.OptionPrefixTextColor(prompt.Yellow),
+ prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
+ prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
+ prompt.OptionSuggestionBGColor(prompt.DarkGray))
+ fmt.Println("Your input: " + in)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_tools/README.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..45bd2234f21ff32562984bec046316c8e52868fd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_tools/README.md
@@ -0,0 +1,10 @@
+## Tools of go-prompt
+
+### vt100_debug
+
+
+
+### sigwinch
+
+
+
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_tools/complete_file/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_tools/complete_file/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..41015cfab9b021fbc7df575bde87e3c510705496
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_tools/complete_file/main.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/completer"
+)
+
+var filePathCompleter = completer.FilePathCompleter{
+ IgnoreCase: true,
+ Filter: func(fi os.FileInfo) bool {
+ return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
+ },
+}
+
+func executor(in string) {
+ fmt.Println("Your input: " + in)
+}
+
+func completerFunc(d prompt.Document) []prompt.Suggest {
+ t := d.GetWordBeforeCursor()
+ if strings.HasPrefix(t, "--") {
+ return []prompt.Suggest{
+ {"--foo", ""},
+ {"--bar", ""},
+ {"--baz", ""},
+ }
+ }
+ return filePathCompleter.Complete(d)
+}
+
+func main() {
+ p := prompt.New(
+ executor,
+ completerFunc,
+ prompt.OptionPrefix(">>> "),
+ prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
+ )
+ p.Run()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_tools/sigwinch/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_tools/sigwinch/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..9608eb3b4a5e3c6942c140c41e08a36ab3adb33b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_tools/sigwinch/main.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "unsafe"
+)
+
+// Winsize is winsize struct got from the ioctl(2) system call.
+type Winsize struct {
+ Row uint16
+ Col uint16
+ X uint16 // pixel value
+ Y uint16 // pixel value
+}
+
+// GetWinSize returns winsize struct which is the response of ioctl(2).
+func GetWinSize(fd int) *Winsize {
+ ws := &Winsize{}
+ retCode, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ uintptr(fd),
+ uintptr(syscall.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(ws)))
+
+ if int(retCode) == -1 {
+ panic(errno)
+ }
+ return ws
+}
+
+func main() {
+ signalChan := make(chan os.Signal, 1)
+ signal.Notify(
+ signalChan,
+ syscall.SIGHUP,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ exitChan := make(chan int)
+ go func() {
+ for {
+ s := <-signalChan
+ switch s {
+ // kill -SIGHUP XXXX
+ case syscall.SIGHUP:
+ exitChan <- 0
+
+ // kill -SIGINT XXXX or Ctrl+c
+ case syscall.SIGINT:
+ exitChan <- 0
+
+ // kill -SIGTERM XXXX
+ case syscall.SIGTERM:
+ exitChan <- 0
+
+ // kill -SIGQUIT XXXX
+ case syscall.SIGQUIT:
+ exitChan <- 0
+
+ case syscall.SIGWINCH:
+ ws := GetWinSize(syscall.Stdin)
+ fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
+
+ default:
+ exitChan <- 1
+ }
+ }
+ }()
+
+ code := <-exitChan
+ os.Exit(code)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_tools/vt100_debug/main.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_tools/vt100_debug/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..c6036d45959febc739e287a3a7b631259d4ee7c1
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/_tools/vt100_debug/main.go
@@ -0,0 +1,47 @@
+// +build !windows
+
+package main
+
+import (
+ "fmt"
+ "syscall"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/term"
+)
+
+func main() {
+ if err := term.SetRaw(syscall.Stdin); err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer term.Restore()
+
+ bufCh := make(chan []byte, 128)
+ go readBuffer(bufCh)
+ fmt.Print("> ")
+
+ for {
+ b := <-bufCh
+ if key := prompt.GetKey(b); key == prompt.NotDefined {
+ fmt.Printf("Key '%s' data:'%#v'\n", string(b), b)
+ } else {
+ if key == prompt.ControlC {
+ fmt.Println("exit.")
+ return
+ }
+ fmt.Printf("Key '%s' data:'%#v'\n", key, b)
+ }
+ fmt.Print("> ")
+ }
+}
+
+func readBuffer(bufCh chan []byte) {
+ buf := make([]byte, 1024)
+
+ for {
+ if n, err := syscall.Read(syscall.Stdin, buf); err == nil {
+ bufCh <- buf[:n]
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/buffer.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..46efbbba8bfb75f4a064c83368b781d1d6dbbb29
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/buffer.go
@@ -0,0 +1,191 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Buffer emulates the console buffer.
+type Buffer struct {
+ workingLines []string // The working lines. Similar to history
+ workingIndex int
+ cursorPosition int
+ cacheDocument *Document
+ preferredColumn int // Remember the original column for the next up/down movement.
+ lastKeyStroke Key
+}
+
+// Text returns string of the current line.
+func (b *Buffer) Text() string {
+ return b.workingLines[b.workingIndex]
+}
+
+// Document method to return document instance from the current text and cursor position.
+func (b *Buffer) Document() (d *Document) {
+ if b.cacheDocument == nil ||
+ b.cacheDocument.Text != b.Text() ||
+ b.cacheDocument.cursorPosition != b.cursorPosition {
+ b.cacheDocument = &Document{
+ Text: b.Text(),
+ cursorPosition: b.cursorPosition,
+ }
+ }
+ b.cacheDocument.lastKey = b.lastKeyStroke
+ return b.cacheDocument
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (b *Buffer) DisplayCursorPosition() int {
+ return b.Document().DisplayCursorPosition()
+}
+
+// InsertText insert string from current line.
+func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
+ or := []rune(b.Text())
+ oc := b.cursorPosition
+
+ if overwrite {
+ overwritten := string(or[oc : oc+len(v)])
+ if strings.Contains(overwritten, "\n") {
+ i := strings.IndexAny(overwritten, "\n")
+ overwritten = overwritten[:i]
+ }
+ b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):]))
+ } else {
+ b.setText(string(or[:oc]) + v + string(or[oc:]))
+ }
+
+ if moveCursor {
+ b.cursorPosition += len([]rune(v))
+ }
+}
+
+// SetText method to set text and update cursorPosition.
+// (When doing this, make sure that the cursor_position is valid for this text.
+// text/cursor_position should be consistent at any time, otherwise set a Document instead.)
+func (b *Buffer) setText(v string) {
+ debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position")
+ b.workingLines[b.workingIndex] = v
+}
+
+// Set cursor position. Return whether it changed.
+func (b *Buffer) setCursorPosition(p int) {
+ if p > 0 {
+ b.cursorPosition = p
+ } else {
+ b.cursorPosition = 0
+ }
+}
+
+func (b *Buffer) setDocument(d *Document) {
+ b.cacheDocument = d
+ b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length.
+ b.setText(d.Text)
+}
+
+// CursorLeft move to left on the current line.
+func (b *Buffer) CursorLeft(count int) {
+ l := b.Document().GetCursorLeftPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorRight move to right on the current line.
+func (b *Buffer) CursorRight(count int) {
+ l := b.Document().GetCursorRightPosition(count)
+ b.cursorPosition += l
+}
+
+// CursorUp move cursor to the previous line.
+// (for multi-line edit).
+func (b *Buffer) CursorUp(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorUpPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// CursorDown move cursor to the next line.
+// (for multi-line edit).
+func (b *Buffer) CursorDown(count int) {
+ orig := b.preferredColumn
+ if b.preferredColumn == -1 { // -1 means nil
+ orig = b.Document().CursorPositionCol()
+ }
+ b.cursorPosition += b.Document().GetCursorDownPosition(count, orig)
+
+ // Remember the original column for the next up/down movement.
+ b.preferredColumn = orig
+}
+
+// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text.
+func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) {
+ debug.Assert(count >= 0, "count should be positive")
+ r := []rune(b.Text())
+
+ if b.cursorPosition > 0 {
+ start := b.cursorPosition - count
+ if start < 0 {
+ start = 0
+ }
+ deleted = string(r[start:b.cursorPosition])
+ b.setDocument(&Document{
+ Text: string(r[:start]) + string(r[b.cursorPosition:]),
+ cursorPosition: b.cursorPosition - len([]rune(deleted)),
+ })
+ }
+ return
+}
+
+// NewLine means CR.
+func (b *Buffer) NewLine(copyMargin bool) {
+ if copyMargin {
+ b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true)
+ } else {
+ b.InsertText("\n", false, true)
+ }
+}
+
+// Delete specified number of characters and Return the deleted text.
+func (b *Buffer) Delete(count int) (deleted string) {
+ r := []rune(b.Text())
+ if b.cursorPosition < len(r) {
+ deleted = b.Document().TextAfterCursor()[:count]
+ b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):]))
+ }
+ return
+}
+
+// JoinNextLine joins the next line to the current one by deleting the line ending after the current line.
+func (b *Buffer) JoinNextLine(separator string) {
+ if !b.Document().OnLastLine() {
+ b.cursorPosition += b.Document().GetEndOfLinePosition()
+ b.Delete(1)
+ // Remove spaces
+ b.setText(b.Document().TextBeforeCursor() + separator + strings.TrimLeft(b.Document().TextAfterCursor(), " "))
+ }
+}
+
+// SwapCharactersBeforeCursor swaps the last two characters before the cursor.
+func (b *Buffer) SwapCharactersBeforeCursor() {
+ if b.cursorPosition >= 2 {
+ x := b.Text()[b.cursorPosition-2 : b.cursorPosition-1]
+ y := b.Text()[b.cursorPosition-1 : b.cursorPosition]
+ b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:])
+ }
+}
+
+// NewBuffer is constructor of Buffer struct.
+func NewBuffer() (b *Buffer) {
+ b = &Buffer{
+ workingLines: []string{""},
+ workingIndex: 0,
+ preferredColumn: -1, // -1 means nil
+ }
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/completer/file.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/completer/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..59f2d8dec84214ccaa6e345a11ed51aa61a08199
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/completer/file.go
@@ -0,0 +1,90 @@
+package completer
+
+import (
+ "io/ioutil"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+
+ prompt "github.com/c-bata/go-prompt"
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+var (
+ // FilePathCompletionSeparator holds separate characters.
+ FilePathCompletionSeparator = string([]byte{' ', os.PathSeparator})
+)
+
+// FilePathCompleter is a completer for your local file system.
+// Please caution that you need to set OptionCompletionWordSeparator(completer.FilePathCompletionSeparator)
+// when you use this completer.
+type FilePathCompleter struct {
+ Filter func(fi os.FileInfo) bool
+ IgnoreCase bool
+ fileListCache map[string][]prompt.Suggest
+}
+
+func cleanFilePath(path string) (dir, base string, err error) {
+ if path == "" {
+ return ".", "", nil
+ }
+
+ var endsWithSeparator bool
+ if len(path) >= 1 && path[len(path)-1] == os.PathSeparator {
+ endsWithSeparator = true
+ }
+
+ if runtime.GOOS != "windows" && len(path) >= 2 && path[0:2] == "~/" {
+ me, err := user.Current()
+ if err != nil {
+ return "", "", err
+ }
+ path = filepath.Join(me.HomeDir, path[1:])
+ }
+ path = filepath.Clean(os.ExpandEnv(path))
+ dir = filepath.Dir(path)
+ base = filepath.Base(path)
+
+ if endsWithSeparator {
+ dir = path + string(os.PathSeparator) // Append slash(in POSIX) if path ends with slash.
+ base = "" // Set empty string if path ends with separator.
+ }
+ return dir, base, nil
+}
+
+// Complete returns suggestions from your local file system.
+func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest {
+ if c.fileListCache == nil {
+ c.fileListCache = make(map[string][]prompt.Suggest, 4)
+ }
+
+ path := d.GetWordBeforeCursor()
+ dir, base, err := cleanFilePath(path)
+ if err != nil {
+ debug.Log("completer: cannot get current user:" + err.Error())
+ return nil
+ }
+
+ if cached, ok := c.fileListCache[dir]; ok {
+ return prompt.FilterHasPrefix(cached, base, c.IgnoreCase)
+ }
+
+ files, err := ioutil.ReadDir(dir)
+ if err != nil && os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ debug.Log("completer: cannot read directory items:" + err.Error())
+ return nil
+ }
+
+ suggests := make([]prompt.Suggest, 0, len(files))
+ for _, f := range files {
+ if c.Filter != nil && !c.Filter(f) {
+ continue
+ }
+ suggests = append(suggests, prompt.Suggest{Text: f.Name()})
+ }
+ c.fileListCache[dir] = suggests
+ return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/completion.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/completion.go
new file mode 100644
index 0000000000000000000000000000000000000000..57e82eefc0f50e9561214704e770a2ad313a3659
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/completion.go
@@ -0,0 +1,190 @@
+package prompt
+
+import (
+ "strings"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+const (
+ shortenSuffix = "..."
+ leftPrefix = " "
+ leftSuffix = " "
+ rightPrefix = " "
+ rightSuffix = " "
+)
+
+var (
+ leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix)
+ rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix)
+ completionMargin = leftMargin + rightMargin
+)
+
+// Suggest is printed when completing.
+type Suggest struct {
+ Text string
+ Description string
+}
+
+// CompletionManager manages which suggestion is now selected.
+type CompletionManager struct {
+ selected int // -1 means nothing one is selected.
+ tmp []Suggest
+ max uint16
+ completer Completer
+
+ verticalScroll int
+ wordSeparator string
+ showAtStart bool
+}
+
+// GetSelectedSuggestion returns the selected item.
+func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) {
+ if c.selected == -1 {
+ return Suggest{}, false
+ } else if c.selected < -1 {
+ debug.Assert(false, "must not reach here")
+ c.selected = -1
+ return Suggest{}, false
+ }
+ return c.tmp[c.selected], true
+}
+
+// GetSuggestions returns the list of suggestion.
+func (c *CompletionManager) GetSuggestions() []Suggest {
+ return c.tmp
+}
+
+// Reset to select nothing.
+func (c *CompletionManager) Reset() {
+ c.selected = -1
+ c.verticalScroll = 0
+ c.Update(*NewDocument())
+}
+
+// Update to update the suggestions.
+func (c *CompletionManager) Update(in Document) {
+ c.tmp = c.completer(in)
+}
+
+// Previous to select the previous suggestion item.
+func (c *CompletionManager) Previous() {
+ if c.verticalScroll == c.selected && c.selected > 0 {
+ c.verticalScroll--
+ }
+ c.selected--
+ c.update()
+}
+
+// Next to select the next suggestion item.
+func (c *CompletionManager) Next() {
+ if c.verticalScroll+int(c.max)-1 == c.selected {
+ c.verticalScroll++
+ }
+ c.selected++
+ c.update()
+}
+
+// Completing returns whether the CompletionManager selects something one.
+func (c *CompletionManager) Completing() bool {
+ return c.selected != -1
+}
+
+func (c *CompletionManager) update() {
+ max := int(c.max)
+ if len(c.tmp) < max {
+ max = len(c.tmp)
+ }
+
+ if c.selected >= len(c.tmp) {
+ c.Reset()
+ } else if c.selected < -1 {
+ c.selected = len(c.tmp) - 1
+ c.verticalScroll = len(c.tmp) - max
+ }
+}
+
+func deleteBreakLineCharacters(s string) string {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, "\r", "", -1)
+ return s
+}
+
+func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) {
+ l := len(o)
+ n := make([]string, l)
+
+ lenPrefix := runewidth.StringWidth(prefix)
+ lenSuffix := runewidth.StringWidth(suffix)
+ lenShorten := runewidth.StringWidth(shortenSuffix)
+ min := lenPrefix + lenSuffix + lenShorten
+ for i := 0; i < l; i++ {
+ o[i] = deleteBreakLineCharacters(o[i])
+
+ w := runewidth.StringWidth(o[i])
+ if width < w {
+ width = w
+ }
+ }
+
+ if width == 0 {
+ return n, 0
+ }
+ if min >= max {
+ return n, 0
+ }
+ if lenPrefix+width+lenSuffix > max {
+ width = max - lenPrefix - lenSuffix
+ }
+
+ for i := 0; i < l; i++ {
+ x := runewidth.StringWidth(o[i])
+ if x <= width {
+ spaces := strings.Repeat(" ", width-x)
+ n[i] = prefix + o[i] + spaces + suffix
+ } else if x > width {
+ x := runewidth.Truncate(o[i], width, shortenSuffix)
+ // When calling runewidth.Truncate("您好xxx您好xxx", 11, "...") returns "您好xxx..."
+ // But the length of this result is 10. So we need fill right using runewidth.FillRight.
+ n[i] = prefix + runewidth.FillRight(x, width) + suffix
+ }
+ }
+ return n, lenPrefix + width + lenSuffix
+}
+
+func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) {
+ num := len(suggests)
+ new = make([]Suggest, num)
+
+ left := make([]string, num)
+ for i := 0; i < num; i++ {
+ left[i] = suggests[i].Text
+ }
+ right := make([]string, num)
+ for i := 0; i < num; i++ {
+ right[i] = suggests[i].Description
+ }
+
+ left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix)
+ if leftWidth == 0 {
+ return []Suggest{}, 0
+ }
+ right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix)
+
+ for i := 0; i < num; i++ {
+ new[i] = Suggest{Text: left[i], Description: right[i]}
+ }
+ return new, leftWidth + rightWidth
+}
+
+// NewCompletionManager returns initialized CompletionManager object.
+func NewCompletionManager(completer Completer, max uint16) *CompletionManager {
+ return &CompletionManager{
+ selected: -1,
+ max: max,
+ completer: completer,
+
+ verticalScroll: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/document.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/document.go
new file mode 100644
index 0000000000000000000000000000000000000000..46df25daaa03dfc9b0025916ed877032972a1290
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/document.go
@@ -0,0 +1,441 @@
+package prompt
+
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+ istrings "github.com/c-bata/go-prompt/internal/strings"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Document has text displayed in terminal and cursor position.
+type Document struct {
+ Text string
+ // This represents a index in a rune array of Document.Text.
+ // So if Document is "日本(cursor)語", cursorPosition is 2.
+ // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+ cursorPosition int
+ lastKey Key
+}
+
+// NewDocument return the new empty document.
+func NewDocument() *Document {
+ return &Document{
+ Text: "",
+ cursorPosition: 0,
+ }
+}
+
+// LastKeyStroke return the last key pressed in this document.
+func (d *Document) LastKeyStroke() Key {
+ return d.lastKey
+}
+
+// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators.
+// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters.
+func (d *Document) DisplayCursorPosition() int {
+ var position int
+ runes := []rune(d.Text)[:d.cursorPosition]
+ for i := range runes {
+ position += runewidth.RuneWidth(runes[i])
+ }
+ return position
+}
+
+// GetCharRelativeToCursor return character relative to cursor position, or empty string
+func (d *Document) GetCharRelativeToCursor(offset int) (r rune) {
+ s := d.Text
+ cnt := 0
+
+ for len(s) > 0 {
+ cnt++
+ r, size := utf8.DecodeRuneInString(s)
+ if cnt == d.cursorPosition+offset {
+ return r
+ }
+ s = s[size:]
+ }
+ return 0
+}
+
+// TextBeforeCursor returns the text before the cursor.
+func (d *Document) TextBeforeCursor() string {
+ r := []rune(d.Text)
+ return string(r[:d.cursorPosition])
+}
+
+// TextAfterCursor returns the text after the cursor.
+func (d *Document) TextAfterCursor() string {
+ r := []rune(d.Text)
+ return string(r[d.cursorPosition:])
+}
+
+// GetWordBeforeCursor returns the word before the cursor.
+// If we have whitespace before the cursor this returns an empty string.
+func (d *Document) GetWordBeforeCursor() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWord():]
+}
+
+// GetWordAfterCursor returns the word after the cursor.
+// If we have whitespace after the cursor this returns an empty string.
+func (d *Document) GetWordAfterCursor() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWord()]
+}
+
+// GetWordBeforeCursorWithSpace returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorWithSpace() string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordWithSpace():]
+}
+
+// GetWordAfterCursorWithSpace returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorWithSpace() string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordWithSpace()]
+}
+
+// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
+func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparator(sep):]
+}
+
+// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
+func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparator(sep)]
+}
+
+// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor.
+// Unlike GetWordBeforeCursor, it returns string containing space
+func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextBeforeCursor()
+ return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep)+1:]
+}
+
+// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor.
+// Unlike GetWordAfterCursor, it returns string containing space
+func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string {
+ x := d.TextAfterCursor()
+ return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)]
+}
+
+// FindStartOfPreviousWord returns an index relative to the cursor position
+// pointing to the start of the previous word. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWord() int {
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexByte(x, ' ')
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindStartOfPreviousWordWithSpace() int {
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotByte(x, ' ')
+ if end == -1 {
+ return 0
+ }
+
+ start := strings.LastIndexByte(x[:end], ' ')
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWord()
+ }
+
+ x := d.TextBeforeCursor()
+ i := strings.LastIndexAny(x, sep)
+ if i != -1 {
+ return i + 1
+ }
+ return 0
+}
+
+// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindStartOfPreviousWordWithSpace()
+ }
+
+ x := d.TextBeforeCursor()
+ end := istrings.LastIndexNotAny(x, sep)
+ if end == -1 {
+ return 0
+ }
+ start := strings.LastIndexAny(x[:end], sep)
+ if start == -1 {
+ return 0
+ }
+ return start + 1
+}
+
+// FindEndOfCurrentWord returns an index relative to the cursor position.
+// pointing to the end of the current word. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWord() int {
+ x := d.TextAfterCursor()
+ i := strings.IndexByte(x, ' ')
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord.
+// The only difference is to ignore contiguous spaces.
+func (d *Document) FindEndOfCurrentWordWithSpace() int {
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotByte(x, ' ')
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexByte(x[start:], ' ')
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWord()
+ }
+
+ x := d.TextAfterCursor()
+ i := strings.IndexAny(x, sep)
+ if i != -1 {
+ return i
+ }
+ return len(x)
+}
+
+// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace.
+// But this can specify Separator. Return 0 if nothing was found.
+func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int {
+ if sep == "" {
+ return d.FindEndOfCurrentWordWithSpace()
+ }
+
+ x := d.TextAfterCursor()
+
+ start := istrings.IndexNotAny(x, sep)
+ if start == -1 {
+ return len(x)
+ }
+
+ end := strings.IndexAny(x[start:], sep)
+ if end == -1 {
+ return len(x)
+ }
+
+ return start + end
+}
+
+// CurrentLineBeforeCursor returns the text from the start of the line until the cursor.
+func (d *Document) CurrentLineBeforeCursor() string {
+ s := strings.Split(d.TextBeforeCursor(), "\n")
+ return s[len(s)-1]
+}
+
+// CurrentLineAfterCursor returns the text from the cursor until the end of the line.
+func (d *Document) CurrentLineAfterCursor() string {
+ return strings.Split(d.TextAfterCursor(), "\n")[0]
+}
+
+// CurrentLine return the text on the line where the cursor is. (when the input
+// consists of just one line, it equals `text`.
+func (d *Document) CurrentLine() string {
+ return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor()
+}
+
+// Array pointing to the start indexes of all the lines.
+func (d *Document) lineStartIndexes() []int {
+ // TODO: Cache, because this is often reused.
+ // (If it is used, it's often used many times.
+ // And this has to be fast for editing big documents!)
+ lc := d.LineCount()
+ lengths := make([]int, lc)
+ for i, l := range d.Lines() {
+ lengths[i] = len(l)
+ }
+
+ // Calculate cumulative sums.
+ indexes := make([]int, lc+1)
+ indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189
+ pos := 0
+ for i, l := range lengths {
+ pos += l + 1
+ indexes[i+1] = pos
+ }
+ if lc > 1 {
+ // Pop the last item. (This is not a new line.)
+ indexes = indexes[:lc]
+ }
+ return indexes
+}
+
+// For the index of a character at a certain line, calculate the index of
+// the first character on that line.
+func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) {
+ indexes := d.lineStartIndexes()
+ pos = bisect.Right(indexes, index) - 1
+ lineStartIndex = indexes[pos]
+ return
+}
+
+// CursorPositionRow returns the current row. (0-based.)
+func (d *Document) CursorPositionRow() (row int) {
+ row, _ = d.findLineStartIndex(d.cursorPosition)
+ return
+}
+
+// CursorPositionCol returns the current column. (0-based.)
+func (d *Document) CursorPositionCol() (col int) {
+ // Don't use self.text_before_cursor to calculate this. Creating substrings
+ // and splitting is too expensive for getting the cursor position.
+ _, index := d.findLineStartIndex(d.cursorPosition)
+ col = d.cursorPosition - index
+ return
+}
+
+// GetCursorLeftPosition returns the relative position for cursor left.
+func (d *Document) GetCursorLeftPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorRightPosition(-count)
+ }
+ if d.CursorPositionCol() > count {
+ return -count
+ }
+ return -d.CursorPositionCol()
+}
+
+// GetCursorRightPosition returns relative position for cursor right.
+func (d *Document) GetCursorRightPosition(count int) int {
+ if count < 0 {
+ return d.GetCursorLeftPosition(-count)
+ }
+ if len(d.CurrentLineAfterCursor()) > count {
+ return count
+ }
+ return len(d.CurrentLineAfterCursor())
+}
+
+// GetCursorUpPosition return the relative cursor position (character index) where we would be
+// if the user pressed the arrow-up button.
+func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+
+ row := d.CursorPositionRow() - count
+ if row < 0 {
+ row = 0
+ }
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// GetCursorDownPosition return the relative cursor position (character index) where we would be if the
+// user pressed the arrow-down button.
+func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int {
+ var col int
+ if preferredColumn == -1 { // -1 means nil
+ col = d.CursorPositionCol()
+ } else {
+ col = preferredColumn
+ }
+ row := d.CursorPositionRow() + count
+ return d.TranslateRowColToIndex(row, col) - d.cursorPosition
+}
+
+// Lines returns the array of all the lines.
+func (d *Document) Lines() []string {
+ // TODO: Cache, because this one is reused very often.
+ return strings.Split(d.Text, "\n")
+}
+
+// LineCount return the number of lines in this document. If the document ends
+// with a trailing \n, that counts as the beginning of a new line.
+func (d *Document) LineCount() int {
+ return len(d.Lines())
+}
+
+// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple.
+// (0-based. Returns (0, 0) for index=0.)
+func (d *Document) TranslateIndexToPosition(index int) (row int, col int) {
+ row, rowIndex := d.findLineStartIndex(index)
+ col = index - rowIndex
+ return
+}
+
+// TranslateRowColToIndex given a (row, col), return the corresponding index.
+// (Row and col params are 0-based.)
+func (d *Document) TranslateRowColToIndex(row int, column int) (index int) {
+ indexes := d.lineStartIndexes()
+ if row < 0 {
+ row = 0
+ } else if row > len(indexes) {
+ row = len(indexes) - 1
+ }
+ index = indexes[row]
+ line := d.Lines()[row]
+
+ // python) result += max(0, min(col, len(line)))
+ if column > 0 || len(line) > 0 {
+ if column > len(line) {
+ index += len(line)
+ } else {
+ index += column
+ }
+ }
+
+ // Keep in range. (len(self.text) is included, because the cursor can be
+ // right after the end of the text as well.)
+ // python) result = max(0, min(result, len(self.text)))
+ if index > len(d.Text) {
+ index = len(d.Text)
+ }
+ if index < 0 {
+ index = 0
+ }
+ return index
+}
+
+// OnLastLine returns true when we are at the last line.
+func (d *Document) OnLastLine() bool {
+ return d.CursorPositionRow() == (d.LineCount() - 1)
+}
+
+// GetEndOfLinePosition returns relative position for the end of this line.
+func (d *Document) GetEndOfLinePosition() int {
+ return len([]rune(d.CurrentLineAfterCursor()))
+}
+
+func (d *Document) leadingWhitespaceInCurrentLine() (margin string) {
+ trimmed := strings.TrimSpace(d.CurrentLine())
+ margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)]
+ return
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/emacs.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/emacs.go
new file mode 100644
index 0000000000000000000000000000000000000000..632f96321f2577cdb7e8cffe639f1518a65d5e0f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/emacs.go
@@ -0,0 +1,120 @@
+package prompt
+
+import "github.com/c-bata/go-prompt/internal/debug"
+
+/*
+
+========
+PROGRESS
+========
+
+Moving the cursor
+-----------------
+
+* [x] Ctrl + a Go to the beginning of the line (Home)
+* [x] Ctrl + e Go to the End of the line (End)
+* [x] Ctrl + p Previous command (Up arrow)
+* [x] Ctrl + n Next command (Down arrow)
+* [x] Ctrl + f Forward one character
+* [x] Ctrl + b Backward one character
+* [x] Ctrl + xx Toggle between the start of line and current cursor position
+
+Editing
+-------
+
+* [x] Ctrl + L Clear the Screen, similar to the clear command
+* [x] Ctrl + d Delete character under the cursor
+* [x] Ctrl + h Delete character before the cursor (Backspace)
+
+* [x] Ctrl + w Cut the Word before the cursor to the clipboard.
+* [x] Ctrl + k Cut the Line after the cursor to the clipboard.
+* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard.
+
+* [ ] Ctrl + t Swap the last two characters before the cursor (typo).
+* [ ] Esc + t Swap the last two words before the cursor.
+
+* [ ] ctrl + y Paste the last thing to be cut (yank)
+* [ ] ctrl + _ Undo
+
+*/
+
+var emacsKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: ControlE,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+ },
+ },
+ // Go to the beginning of the line
+ {
+ Key: ControlA,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+ },
+ },
+ // Cut the Line after the cursor
+ {
+ Key: ControlK,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.Delete(len(x))
+ },
+ },
+ // Cut/delete the Line before the cursor
+ {
+ Key: ControlU,
+ Fn: func(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.DeleteBeforeCursor(len(x))
+ },
+ },
+ // Delete character under the cursor
+ {
+ Key: ControlD,
+ Fn: func(buf *Buffer) {
+ if buf.Text() != "" {
+ buf.Delete(1)
+ }
+ },
+ },
+ // Backspace
+ {
+ Key: ControlH,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+ },
+ },
+ // Right allow: Forward one character
+ {
+ Key: ControlF,
+ Fn: func(buf *Buffer) {
+ buf.CursorRight(1)
+ },
+ },
+ // Left allow: Backward one character
+ {
+ Key: ControlB,
+ Fn: func(buf *Buffer) {
+ buf.CursorLeft(1)
+ },
+ },
+ // Cut the Word before the cursor.
+ {
+ Key: ControlW,
+ Fn: func(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace())))
+ },
+ },
+ // Clear the Screen, similar to the clear command
+ {
+ Key: ControlL,
+ Fn: func(buf *Buffer) {
+ consoleWriter.EraseScreen()
+ consoleWriter.CursorGoTo(0, 0)
+ debug.AssertNoError(consoleWriter.Flush())
+ },
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/filter.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/filter.go
new file mode 100644
index 0000000000000000000000000000000000000000..61c17ed7f436a069563f520512bd25e4d81af0de
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/filter.go
@@ -0,0 +1,71 @@
+package prompt
+
+import "strings"
+
+// Filter is the type to filter the prompt.Suggestion array.
+type Filter func([]Suggest, string, bool) []Suggest
+
+// FilterHasPrefix checks whether the string completions.Text begins with sub.
+func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
+}
+
+// FilterHasSuffix checks whether the completion.Text ends with sub.
+func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
+}
+
+// FilterContains checks whether the completion.Text contains sub.
+func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
+}
+
+// FilterFuzzy checks whether the completion.Text fuzzy matches sub.
+// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
+// would match, for example, "Good food is gone"
+// ^ ^ ^
+func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
+ return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
+}
+
+func fuzzyMatch(s, sub string) bool {
+ sChars := []rune(s)
+ sIdx := 0
+
+ // https://staticcheck.io/docs/checks#S1029
+ for _, c := range sub {
+ found := false
+ for ; sIdx < len(sChars); sIdx++ {
+ if sChars[sIdx] == c {
+ found = true
+ sIdx++
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
+
+func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
+ if sub == "" {
+ return suggestions
+ }
+ if ignoreCase {
+ sub = strings.ToUpper(sub)
+ }
+
+ ret := make([]Suggest, 0, len(suggestions))
+ for i := range suggestions {
+ c := suggestions[i].Text
+ if ignoreCase {
+ c = strings.ToUpper(c)
+ }
+ if function(c, sub) {
+ ret = append(ret, suggestions[i])
+ }
+ }
+ return ret
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/go.mod b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..30bc6d39a39c328341ca7153d3391352be5baa63
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/go.mod
@@ -0,0 +1,11 @@
+module github.com/c-bata/go-prompt
+
+go 1.14
+
+require (
+ github.com/mattn/go-colorable v0.1.7
+ github.com/mattn/go-runewidth v0.0.9
+ github.com/mattn/go-tty v0.0.3
+ github.com/pkg/term v1.2.0-beta.2
+ golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/go.sum b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..768bf93619a68e1b334c13e7b93ec84fa465598e
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/go.sum
@@ -0,0 +1,23 @@
+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
+github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
+github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
+github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
+github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
+github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
+github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff h1:1CPUrky56AcgSpxz/KfgzQWzfG09u5YOL8MvPYBlrL8=
+golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/history.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/history.go
new file mode 100644
index 0000000000000000000000000000000000000000..e75c64592d82142bf4826ceb8c613ac72ca24d9c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/history.go
@@ -0,0 +1,61 @@
+package prompt
+
+// History stores the texts that are entered.
+type History struct {
+ histories []string
+ tmp []string
+ selected int
+}
+
+// Add to add text in history.
+func (h *History) Add(input string) {
+ h.histories = append(h.histories, input)
+ h.Clear()
+}
+
+// Clear to clear the history.
+func (h *History) Clear() {
+ h.tmp = make([]string, len(h.histories))
+ for i := range h.histories {
+ h.tmp[i] = h.histories[i]
+ }
+ h.tmp = append(h.tmp, "")
+ h.selected = len(h.tmp) - 1
+}
+
+// Older saves a buffer of current line and get a buffer of previous line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) {
+ if len(h.tmp) == 1 || h.selected == 0 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected--
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// Newer saves a buffer of current line and get a buffer of next line by up-arrow.
+// The changes of line buffers are stored until new history is created.
+func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {
+ if h.selected >= len(h.tmp)-1 {
+ return buf, false
+ }
+ h.tmp[h.selected] = buf.Text()
+
+ h.selected++
+ new = NewBuffer()
+ new.InsertText(h.tmp[h.selected], false, true)
+ return new, true
+}
+
+// NewHistory returns new history object.
+func NewHistory() *History {
+ return &History{
+ histories: []string{},
+ tmp: []string{""},
+ selected: 0,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/input.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/input.go
new file mode 100644
index 0000000000000000000000000000000000000000..307e747190c2b27bf888b379644fc4f3cdd489a2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/input.go
@@ -0,0 +1,169 @@
+package prompt
+
+import "bytes"
+
+// WinSize represents the width and height of terminal.
+type WinSize struct {
+ Row uint16
+ Col uint16
+}
+
+// ConsoleParser is an interface to abstract input layer.
+type ConsoleParser interface {
+ // Setup should be called before starting input
+ Setup() error
+ // TearDown should be called after stopping input
+ TearDown() error
+ // GetWinSize returns WinSize object to represent width and height of terminal.
+ GetWinSize() *WinSize
+ // Read returns byte array.
+ Read() ([]byte, error)
+}
+
+// GetKey returns Key correspond to input byte codes.
+func GetKey(b []byte) Key {
+ for _, k := range ASCIISequences {
+ if bytes.Equal(k.ASCIICode, b) {
+ return k.Key
+ }
+ }
+ return NotDefined
+}
+
+// ASCIISequences holds mappings of the key and byte array.
+var ASCIISequences = []*ASCIICode{
+ {Key: Escape, ASCIICode: []byte{0x1b}},
+
+ {Key: ControlSpace, ASCIICode: []byte{0x00}},
+ {Key: ControlA, ASCIICode: []byte{0x1}},
+ {Key: ControlB, ASCIICode: []byte{0x2}},
+ {Key: ControlC, ASCIICode: []byte{0x3}},
+ {Key: ControlD, ASCIICode: []byte{0x4}},
+ {Key: ControlE, ASCIICode: []byte{0x5}},
+ {Key: ControlF, ASCIICode: []byte{0x6}},
+ {Key: ControlG, ASCIICode: []byte{0x7}},
+ {Key: ControlH, ASCIICode: []byte{0x8}},
+ //{Key: ControlI, ASCIICode: []byte{0x9}},
+ //{Key: ControlJ, ASCIICode: []byte{0xa}},
+ {Key: ControlK, ASCIICode: []byte{0xb}},
+ {Key: ControlL, ASCIICode: []byte{0xc}},
+ {Key: ControlM, ASCIICode: []byte{0xd}},
+ {Key: ControlN, ASCIICode: []byte{0xe}},
+ {Key: ControlO, ASCIICode: []byte{0xf}},
+ {Key: ControlP, ASCIICode: []byte{0x10}},
+ {Key: ControlQ, ASCIICode: []byte{0x11}},
+ {Key: ControlR, ASCIICode: []byte{0x12}},
+ {Key: ControlS, ASCIICode: []byte{0x13}},
+ {Key: ControlT, ASCIICode: []byte{0x14}},
+ {Key: ControlU, ASCIICode: []byte{0x15}},
+ {Key: ControlV, ASCIICode: []byte{0x16}},
+ {Key: ControlW, ASCIICode: []byte{0x17}},
+ {Key: ControlX, ASCIICode: []byte{0x18}},
+ {Key: ControlY, ASCIICode: []byte{0x19}},
+ {Key: ControlZ, ASCIICode: []byte{0x1a}},
+
+ {Key: ControlBackslash, ASCIICode: []byte{0x1c}},
+ {Key: ControlSquareClose, ASCIICode: []byte{0x1d}},
+ {Key: ControlCircumflex, ASCIICode: []byte{0x1e}},
+ {Key: ControlUnderscore, ASCIICode: []byte{0x1f}},
+ {Key: Backspace, ASCIICode: []byte{0x7f}},
+
+ {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}},
+
+ {Key: Enter, ASCIICode: []byte{0xa}},
+ {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}},
+ {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+ {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}},
+ {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}},
+ {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}},
+ {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}},
+ {Key: Tab, ASCIICode: []byte{0x9}},
+ {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}},
+ {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}},
+ {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}},
+ {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}},
+ {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}},
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console
+
+ {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode
+ {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode
+ {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode
+ {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode
+
+ {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}},
+ {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}},
+ {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}},
+ {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}},
+ {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}},
+ {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}},
+ {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}},
+ {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}},
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}},
+ {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}},
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}},
+
+ // Xterm
+ {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}},
+ {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}},
+ // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response
+ {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}},
+ {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}},
+ {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}},
+ {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}},
+ {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}},
+ {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}},
+ {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}},
+ {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}},
+ {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}},
+
+ {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}},
+ {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}},
+ {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}},
+ {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}},
+
+ // Tmux sends following keystrokes when control+arrow is pressed, but for
+ // Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ // it a normal arrow press, because that's more important.
+ {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}},
+ {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}},
+ {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}},
+ {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}},
+
+ {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}},
+ {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}},
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}},
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}},
+
+ {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt
+ {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt
+
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm
+ {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/input_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/input_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f10430318be0e797c841eba8e08ab1cf5277be27
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/input_posix.go
@@ -0,0 +1,77 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/term"
+ "golang.org/x/sys/unix"
+)
+
+const maxReadBytes = 1024
+
+// PosixParser is a ConsoleParser implementation for POSIX environment.
+type PosixParser struct {
+ fd int
+ origTermios syscall.Termios
+}
+
+// Setup should be called before starting input
+func (t *PosixParser) Setup() error {
+ // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
+ if err := syscall.SetNonblock(t.fd, true); err != nil {
+ return err
+ }
+ if err := term.SetRaw(t.fd); err != nil {
+ return err
+ }
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (t *PosixParser) TearDown() error {
+ if err := syscall.SetNonblock(t.fd, false); err != nil {
+ return err
+ }
+ if err := term.Restore(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Read returns byte array.
+func (t *PosixParser) Read() ([]byte, error) {
+ buf := make([]byte, maxReadBytes)
+ n, err := syscall.Read(t.fd, buf)
+ if err != nil {
+ return []byte{}, err
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (t *PosixParser) GetWinSize() *WinSize {
+ ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: ws.Row,
+ Col: ws.Col,
+ }
+}
+
+var _ ConsoleParser = &PosixParser{}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *PosixParser {
+ in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ return &PosixParser{
+ fd: in,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/input_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/input_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..11b7679d4c4bc8b924a5b6c863ca1f6d6880570d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/input_windows.go
@@ -0,0 +1,83 @@
+// +build windows
+
+package prompt
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf8"
+ "unsafe"
+
+ tty "github.com/mattn/go-tty"
+)
+
+const maxReadBytes = 1024
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents")
+
+// WindowsParser is a ConsoleParser implementation for Win32 console.
+type WindowsParser struct {
+ tty *tty.TTY
+}
+
+// Setup should be called before starting input
+func (p *WindowsParser) Setup() error {
+ t, err := tty.Open()
+ if err != nil {
+ return err
+ }
+ p.tty = t
+ return nil
+}
+
+// TearDown should be called after stopping input
+func (p *WindowsParser) TearDown() error {
+ return p.tty.Close()
+}
+
+// Read returns byte array.
+func (p *WindowsParser) Read() ([]byte, error) {
+ var ev uint32
+ r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev)))
+ if r0 == 0 {
+ return nil, err
+ }
+ if ev == 0 {
+ return nil, errors.New("EAGAIN")
+ }
+
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, maxReadBytes)
+ n := utf8.EncodeRune(buf[:], r)
+ for p.tty.Buffered() && n < maxReadBytes {
+ r, err := p.tty.ReadRune()
+ if err != nil {
+ break
+ }
+ n += utf8.EncodeRune(buf[n:], r)
+ }
+ return buf[:n], nil
+}
+
+// GetWinSize returns WinSize object to represent width and height of terminal.
+func (p *WindowsParser) GetWinSize() *WinSize {
+ w, h, err := p.tty.Size()
+ if err != nil {
+ panic(err)
+ }
+ return &WinSize{
+ Row: uint16(h),
+ Col: uint16(w),
+ }
+}
+
+// NewStandardInputParser returns ConsoleParser object to read from stdin.
+func NewStandardInputParser() *WindowsParser {
+ return &WindowsParser{}
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/bisect/bisect.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/bisect/bisect.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe162fa8c4873302e25702081b629a445d43415
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/bisect/bisect.go
@@ -0,0 +1,15 @@
+package bisect
+
+import "sort"
+
+// Right to locate the insertion point for v in a to maintain sorted order.
+func Right(a []int, v int) int {
+ return bisectRightRange(a, v, 0, len(a))
+}
+
+func bisectRightRange(a []int, v int, lo, hi int) int {
+ s := a[lo:hi]
+ return sort.Search(len(s), func(i int) bool {
+ return s[i] > v
+ })
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/debug/assert.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/debug/assert.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f648ac93c44e1e021cdf581a68f03b548534d9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/debug/assert.go
@@ -0,0 +1,55 @@
+package debug
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
+)
+
+var (
+ enableAssert bool
+)
+
+func init() {
+ if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
+ enableAssert = true
+ }
+}
+
+// Assert ensures expected condition.
+func Assert(cond bool, msg interface{}) {
+ if cond {
+ return
+ }
+ if enableAssert {
+ panic(msg)
+ }
+ writeWithSync(2, "[ASSERT] "+toString(msg))
+}
+
+func toString(v interface{}) string {
+ switch a := v.(type) {
+ case func() string:
+ return a()
+ case string:
+ return a
+ case fmt.Stringer:
+ return a.String()
+ default:
+ return fmt.Sprintf("unexpected type, %t", v)
+ }
+}
+
+// AssertNoError ensures err is nil.
+func AssertNoError(err error) {
+ if err == nil {
+ return
+ }
+ if enableAssert {
+ panic(err)
+ }
+ writeWithSync(2, "[ASSERT] "+err.Error())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/debug/log.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/debug/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..516378627a34ead9063ab7ce6c445b23c77b7cb4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/debug/log.go
@@ -0,0 +1,52 @@
+package debug
+
+import (
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+const (
+ envEnableLog = "GO_PROMPT_ENABLE_LOG"
+ logFileName = "go-prompt.log"
+)
+
+var (
+ logfile *os.File
+ logger *log.Logger
+)
+
+func init() {
+ if e := os.Getenv(envEnableLog); e == "true" || e == "1" {
+ var err error
+ logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
+ if err == nil {
+ logger = log.New(logfile, "", log.Llongfile)
+ return
+ }
+ }
+ logger = log.New(ioutil.Discard, "", log.Llongfile)
+}
+
+// Teardown to close logfile
+func Teardown() {
+ if logfile == nil {
+ return
+ }
+ _ = logfile.Close()
+}
+
+func writeWithSync(calldepth int, msg string) {
+ calldepth++
+ if logfile == nil {
+ return
+ }
+ _ = logger.Output(calldepth, msg)
+ _ = logfile.Sync() // immediately write msg
+}
+
+// Log to output message
+func Log(msg string) {
+ calldepth := 2
+ writeWithSync(calldepth, msg)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/strings/strings.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/strings/strings.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7d1886ae03a7d541c66dffca921e2d040e6d5eb
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/strings/strings.go
@@ -0,0 +1,102 @@
+package strings
+
+import "unicode/utf8"
+
+// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior.
+func IndexNotByte(s string, c byte) int {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior.
+func LastIndexNotByte(s string, c byte) int {
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] != c {
+ return i
+ }
+ }
+ return -1
+}
+
+type asciiSet [8]uint32
+
+func (as *asciiSet) notContains(c byte) bool {
+ return (as[c>>5] & (1 << uint(c&31))) == 0
+}
+
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c>>5] |= 1 << uint(c&31)
+ }
+ return as, true
+}
+
+// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior.
+func IndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := 0; i < len(s); i++ {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+
+ LabelFirstLoop:
+ for i, c := range s {
+ for j, m := range chars {
+ if c != m && j == len(chars)-1 {
+ return i
+ } else if c != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior.
+func LastIndexNotAny(s, chars string) int {
+ if len(chars) > 0 {
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.notContains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ LabelFirstLoop:
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRuneInString(s[:i])
+ i -= size
+ for j, m := range chars {
+ if r != m && j == len(chars)-1 {
+ return i
+ } else if r != m {
+ continue
+ } else {
+ continue LabelFirstLoop
+ }
+ }
+ }
+ }
+ return -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/term/raw.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/term/raw.go
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3ed8d04023558cf386a98080815d661248b85
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/term/raw.go
@@ -0,0 +1,29 @@
+// +build !windows
+
+package term
+
+import (
+ "syscall"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+// SetRaw put terminal into a raw mode
+func SetRaw(fd int) error {
+ n, err := getOriginalTermios(fd)
+ if err != nil {
+ return err
+ }
+
+ n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK |
+ syscall.ISTRIP | syscall.INLCR | syscall.IGNCR |
+ syscall.ICRNL | syscall.IXON
+ n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL
+ n.Cflag &^= syscall.CSIZE | syscall.PARENB
+ n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters.
+ n.Cc[syscall.VMIN] = 1
+ n.Cc[syscall.VTIME] = 0
+
+ return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n))
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/term/term.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/term/term.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f3a53c059ae60c0348ec01689babef4b13a2ecd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/internal/term/term.go
@@ -0,0 +1,34 @@
+// +build !windows
+
+package term
+
+import (
+ "sync"
+
+ "github.com/pkg/term/termios"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ saveTermios *unix.Termios
+ saveTermiosFD int
+ saveTermiosOnce sync.Once
+)
+
+func getOriginalTermios(fd int) (*unix.Termios, error) {
+ var err error
+ saveTermiosOnce.Do(func() {
+ saveTermiosFD = fd
+ saveTermios, err = termios.Tcgetattr(uintptr(fd))
+ })
+ return saveTermios, err
+}
+
+// Restore terminal's mode.
+func Restore() error {
+ o, err := getOriginalTermios(saveTermiosFD)
+ if err != nil {
+ return err
+ }
+ return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/key.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ba569c2dd20a8ae3b3dd79ff3695bf0b6c1bd09
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/key.go
@@ -0,0 +1,128 @@
+// Code generated by hand; DO NOT EDIT.
+// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment.
+
+package prompt
+
+// Key is the type express the key inserted from user.
+//go:generate stringer -type=Key
+type Key int
+
+// ASCIICode is the type contains Key and it's ascii byte array.
+type ASCIICode struct {
+ Key Key
+ ASCIICode []byte
+}
+
+const (
+ Escape Key = iota
+
+ ControlA
+ ControlB
+ ControlC
+ ControlD
+ ControlE
+ ControlF
+ ControlG
+ ControlH
+ ControlI
+ ControlJ
+ ControlK
+ ControlL
+ ControlM
+ ControlN
+ ControlO
+ ControlP
+ ControlQ
+ ControlR
+ ControlS
+ ControlT
+ ControlU
+ ControlV
+ ControlW
+ ControlX
+ ControlY
+ ControlZ
+
+ ControlSpace
+ ControlBackslash
+ ControlSquareClose
+ ControlCircumflex
+ ControlUnderscore
+ ControlLeft
+ ControlRight
+ ControlUp
+ ControlDown
+
+ Up
+ Down
+ Right
+ Left
+
+ ShiftLeft
+ ShiftUp
+ ShiftDown
+ ShiftRight
+
+ Home
+ End
+ Delete
+ ShiftDelete
+ ControlDelete
+ PageUp
+ PageDown
+ BackTab
+ Insert
+ Backspace
+
+ // Aliases.
+ Tab
+ Enter
+ // Actually Enter equals ControlM, not ControlJ,
+ // However, in prompt_toolkit, we made the mistake of translating
+ // \r into \n during the input, so everyone is now handling the
+ // enter key by binding ControlJ.
+
+ // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere,
+ // because that's future compatible, and will still work when we
+ // stop replacing \r by \n.
+
+ F1
+ F2
+ F3
+ F4
+ F5
+ F6
+ F7
+ F8
+ F9
+ F10
+ F11
+ F12
+ F13
+ F14
+ F15
+ F16
+ F17
+ F18
+ F19
+ F20
+ F21
+ F22
+ F23
+ F24
+
+ // Matches any key.
+ Any
+
+ // Special
+ CPRResponse
+ Vt100MouseEvent
+ WindowsMouseEvent
+ BracketedPaste
+
+ // Key which is ignored. (The key binding for this key should not do anything.)
+ Ignore
+
+ // Key is not defined
+ NotDefined
+)
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/key_bind.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/key_bind.go
new file mode 100644
index 0000000000000000000000000000000000000000..42669e7f942efc4d92f896388daede90b96b55dd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/key_bind.go
@@ -0,0 +1,59 @@
+package prompt
+
+// KeyBindFunc receives buffer and processed it.
+type KeyBindFunc func(*Buffer)
+
+// KeyBind represents which key should do what operation.
+type KeyBind struct {
+ Key Key
+ Fn KeyBindFunc
+}
+
+// ASCIICodeBind represents which []byte should do what operation
+type ASCIICodeBind struct {
+ ASCIICode []byte
+ Fn KeyBindFunc
+}
+
+// KeyBindMode to switch a key binding flexibly.
+type KeyBindMode string
+
+const (
+ // CommonKeyBind is a mode without any keyboard shortcut
+ CommonKeyBind KeyBindMode = "common"
+ // EmacsKeyBind is a mode to use emacs-like keyboard shortcut
+ EmacsKeyBind KeyBindMode = "emacs"
+)
+
+var commonKeyBindings = []KeyBind{
+ // Go to the End of the line
+ {
+ Key: End,
+ Fn: GoLineEnd,
+ },
+ // Go to the beginning of the line
+ {
+ Key: Home,
+ Fn: GoLineBeginning,
+ },
+ // Delete character under the cursor
+ {
+ Key: Delete,
+ Fn: DeleteChar,
+ },
+ // Backspace
+ {
+ Key: Backspace,
+ Fn: DeleteBeforeChar,
+ },
+ // Right allow: Forward one character
+ {
+ Key: Right,
+ Fn: GoRightChar,
+ },
+ // Left allow: Backward one character
+ {
+ Key: Left,
+ Fn: GoLeftChar,
+ },
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/key_bind_func.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/key_bind_func.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b2ecdf63179dbfdbcb0d71bfa436bb36d62d230
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/key_bind_func.go
@@ -0,0 +1,48 @@
+package prompt
+
+// GoLineEnd Go to the End of the line
+func GoLineEnd(buf *Buffer) {
+ x := []rune(buf.Document().TextAfterCursor())
+ buf.CursorRight(len(x))
+}
+
+// GoLineBeginning Go to the beginning of the line
+func GoLineBeginning(buf *Buffer) {
+ x := []rune(buf.Document().TextBeforeCursor())
+ buf.CursorLeft(len(x))
+}
+
+// DeleteChar Delete character under the cursor
+func DeleteChar(buf *Buffer) {
+ buf.Delete(1)
+}
+
+// DeleteWord Delete word before the cursor
+func DeleteWord(buf *Buffer) {
+ buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
+
+// DeleteBeforeChar Go to Backspace
+func DeleteBeforeChar(buf *Buffer) {
+ buf.DeleteBeforeCursor(1)
+}
+
+// GoRightChar Forward one character
+func GoRightChar(buf *Buffer) {
+ buf.CursorRight(1)
+}
+
+// GoLeftChar Backward one character
+func GoLeftChar(buf *Buffer) {
+ buf.CursorLeft(1)
+}
+
+// GoRightWord Forward one word
+func GoRightWord(buf *Buffer) {
+ buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
+}
+
+// GoLeftWord Backward one word
+func GoLeftWord(buf *Buffer) {
+ buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/key_string.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/key_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..fce6ea31c502b3e763451cb47757ae1b49c32814
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/key_string.go
@@ -0,0 +1,16 @@
+// Code generated by "stringer -type=Key"; DO NOT EDIT.
+
+package prompt
+
+import "strconv"
+
+const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined"
+
+var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607}
+
+func (i Key) String() string {
+ if i < 0 || i >= Key(len(_Key_index)-1) {
+ return "Key(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _Key_name[_Key_index[i]:_Key_index[i+1]]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/option.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/option.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd6806cc1dbccf8c4ddb048080fde615c59088
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/option.go
@@ -0,0 +1,310 @@
+package prompt
+
+// Option is the type to replace default parameters.
+// prompt.New accepts any number of options (this is functional option pattern).
+type Option func(prompt *Prompt) error
+
+// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
+func OptionParser(x ConsoleParser) Option {
+ return func(p *Prompt) error {
+ p.in = x
+ return nil
+ }
+}
+
+// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
+func OptionWriter(x ConsoleWriter) Option {
+ return func(p *Prompt) error {
+ registerConsoleWriter(x)
+ p.renderer.out = x
+ return nil
+ }
+}
+
+// OptionTitle to set title displayed at the header bar of terminal.
+func OptionTitle(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.title = x
+ return nil
+ }
+}
+
+// OptionPrefix to set prefix string.
+func OptionPrefix(x string) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefix = x
+ return nil
+ }
+}
+
+// OptionInitialBufferText to set the initial buffer text
+func OptionInitialBufferText(x string) Option {
+ return func(p *Prompt) error {
+ p.buf.InsertText(x, false, true)
+ return nil
+ }
+}
+
+// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
+func OptionCompletionWordSeparator(x string) Option {
+ return func(p *Prompt) error {
+ p.completion.wordSeparator = x
+ return nil
+ }
+}
+
+// OptionLivePrefix to change the prefix dynamically by callback function
+func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
+ return func(p *Prompt) error {
+ p.renderer.livePrefixCallback = f
+ return nil
+ }
+}
+
+// OptionPrefixTextColor change a text color of prefix string
+func OptionPrefixTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixTextColor = x
+ return nil
+ }
+}
+
+// OptionPrefixBackgroundColor to change a background color of prefix string
+func OptionPrefixBackgroundColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.prefixBGColor = x
+ return nil
+ }
+}
+
+// OptionInputTextColor to change a color of text which is input by user
+func OptionInputTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputTextColor = x
+ return nil
+ }
+}
+
+// OptionInputBGColor to change a color of background which is input by user
+func OptionInputBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.inputBGColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionTextColor to change a text color which is completed
+func OptionPreviewSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionPreviewSuggestionBGColor to change a background color which is completed
+func OptionPreviewSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.previewSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionTextColor to change a text color in drop down suggestions.
+func OptionSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSuggestionBGColor change a background color in drop down suggestions.
+func OptionSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.suggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
+func OptionSelectedSuggestionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedSuggestionBGColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
+func OptionDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.descriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionTextColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionTextColor = x
+ return nil
+ }
+}
+
+// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
+func OptionSelectedDescriptionBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.selectedDescriptionBGColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarThumbColor to change a thumb color on scrollbar.
+func OptionScrollbarThumbColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarThumbColor = x
+ return nil
+ }
+}
+
+// OptionScrollbarBGColor to change a background color of scrollbar.
+func OptionScrollbarBGColor(x Color) Option {
+ return func(p *Prompt) error {
+ p.renderer.scrollbarBGColor = x
+ return nil
+ }
+}
+
+// OptionMaxSuggestion specify the max number of displayed suggestions.
+func OptionMaxSuggestion(x uint16) Option {
+ return func(p *Prompt) error {
+ p.completion.max = x
+ return nil
+ }
+}
+
+// OptionHistory to set history expressed by string array.
+func OptionHistory(x []string) Option {
+ return func(p *Prompt) error {
+ p.history.histories = x
+ p.history.Clear()
+ return nil
+ }
+}
+
+// OptionSwitchKeyBindMode set a key bind mode.
+func OptionSwitchKeyBindMode(m KeyBindMode) Option {
+ return func(p *Prompt) error {
+ p.keyBindMode = m
+ return nil
+ }
+}
+
+// OptionCompletionOnDown allows for Down arrow key to trigger completion.
+func OptionCompletionOnDown() Option {
+ return func(p *Prompt) error {
+ p.completionOnDown = true
+ return nil
+ }
+}
+
+// SwitchKeyBindMode to set a key bind mode.
+// Deprecated: Please use OptionSwitchKeyBindMode.
+var SwitchKeyBindMode = OptionSwitchKeyBindMode
+
+// OptionAddKeyBind to set a custom key bind.
+func OptionAddKeyBind(b ...KeyBind) Option {
+ return func(p *Prompt) error {
+ p.keyBindings = append(p.keyBindings, b...)
+ return nil
+ }
+}
+
+// OptionAddASCIICodeBind to set a custom key bind.
+func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option {
+ return func(p *Prompt) error {
+ p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...)
+ return nil
+ }
+}
+
+// OptionShowCompletionAtStart to set completion window is open at start.
+func OptionShowCompletionAtStart() Option {
+ return func(p *Prompt) error {
+ p.completion.showAtStart = true
+ return nil
+ }
+}
+
+// OptionBreakLineCallback to run a callback at every break line
+func OptionBreakLineCallback(fn func(*Document)) Option {
+ return func(p *Prompt) error {
+ p.renderer.breakLineCallback = fn
+ return nil
+ }
+}
+
+// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop
+func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
+ return func(p *Prompt) error {
+ p.exitChecker = fn
+ return nil
+ }
+}
+
+// New returns a Prompt with powerful auto-completion.
+func New(executor Executor, completer Completer, opts ...Option) *Prompt {
+ defaultWriter := NewStdoutWriter()
+ registerConsoleWriter(defaultWriter)
+
+ pt := &Prompt{
+ in: NewStandardInputParser(),
+ renderer: &Render{
+ prefix: "> ",
+ out: defaultWriter,
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ },
+ buf: NewBuffer(),
+ executor: executor,
+ history: NewHistory(),
+ completion: NewCompletionManager(completer, 6),
+ keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting
+ }
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/output.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/output.go
new file mode 100644
index 0000000000000000000000000000000000000000..42531b412f1ed027c2fff5b85bc273e53e569b3a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/output.go
@@ -0,0 +1,161 @@
+package prompt
+
+import "sync"
+
+var (
+ consoleWriterMu sync.Mutex
+ consoleWriter ConsoleWriter
+)
+
+func registerConsoleWriter(f ConsoleWriter) {
+ consoleWriterMu.Lock()
+ defer consoleWriterMu.Unlock()
+ consoleWriter = f
+}
+
+// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on.
+type DisplayAttribute int
+
+const (
+ // DisplayReset reset all display attributes.
+ DisplayReset DisplayAttribute = iota
+ // DisplayBold set bold or increases intensity.
+ DisplayBold
+ // DisplayLowIntensity decreases intensity. Not widely supported.
+ DisplayLowIntensity
+ // DisplayItalic set italic. Not widely supported.
+ DisplayItalic
+ // DisplayUnderline set underline
+ DisplayUnderline
+ // DisplayBlink set blink (less than 150 per minute).
+ DisplayBlink
+ // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported.
+ DisplayRapidBlink
+ // DisplayReverse swap foreground and background colors.
+ DisplayReverse
+ // DisplayInvisible set invisible. Not widely supported.
+ DisplayInvisible
+ // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported.
+ DisplayCrossedOut
+ // DisplayDefaultFont set primary(default) font
+ DisplayDefaultFont
+)
+
+// Color represents color on terminal.
+type Color int
+
+const (
+ // DefaultColor represents a default color.
+ DefaultColor Color = iota
+
+ // Low intensity
+
+ // Black represents a black.
+ Black
+ // DarkRed represents a dark red.
+ DarkRed
+ // DarkGreen represents a dark green.
+ DarkGreen
+ // Brown represents a brown.
+ Brown
+ // DarkBlue represents a dark blue.
+ DarkBlue
+ // Purple represents a purple.
+ Purple
+ // Cyan represents a cyan.
+ Cyan
+ // LightGray represents a light gray.
+ LightGray
+
+ // High intensity
+
+ // DarkGray represents a dark gray.
+ DarkGray
+ // Red represents a red.
+ Red
+ // Green represents a green.
+ Green
+ // Yellow represents a yellow.
+ Yellow
+ // Blue represents a blue.
+ Blue
+ // Fuchsia represents a fuchsia.
+ Fuchsia
+ // Turquoise represents a turquoise.
+ Turquoise
+ // White represents a white.
+ White
+)
+
+// ConsoleWriter is an interface to abstract output layer.
+type ConsoleWriter interface {
+ /* Write */
+
+ // WriteRaw to write raw byte array.
+ WriteRaw(data []byte)
+ // Write to write safety byte array by removing control sequences.
+ Write(data []byte)
+ // WriteStr to write raw string.
+ WriteRawStr(data string)
+ // WriteStr to write safety string by removing control sequences.
+ WriteStr(data string)
+ // Flush to flush buffer.
+ Flush() error
+
+ /* Erasing */
+
+ // EraseScreen erases the screen with the background colour and moves the cursor to home.
+ EraseScreen()
+ // EraseUp erases the screen from the current line up to the top of the screen.
+ EraseUp()
+ // EraseDown erases the screen from the current line down to the bottom of the screen.
+ EraseDown()
+ // EraseStartOfLine erases from the current cursor position to the start of the current line.
+ EraseStartOfLine()
+ // EraseEndOfLine erases from the current cursor position to the end of the current line.
+ EraseEndOfLine()
+ // EraseLine erases the entire current line.
+ EraseLine()
+
+ /* Cursor */
+
+ // ShowCursor stops blinking cursor and show.
+ ShowCursor()
+ // HideCursor hides cursor.
+ HideCursor()
+ // CursorGoTo sets the cursor position where subsequent text will begin.
+ CursorGoTo(row, col int)
+ // CursorUp moves the cursor up by 'n' rows; the default count is 1.
+ CursorUp(n int)
+ // CursorDown moves the cursor down by 'n' rows; the default count is 1.
+ CursorDown(n int)
+ // CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+ CursorForward(n int)
+ // CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+ CursorBackward(n int)
+ // AskForCPR asks for a cursor position report (CPR).
+ AskForCPR()
+ // SaveCursor saves current cursor position.
+ SaveCursor()
+ // UnSaveCursor restores cursor position after a Save Cursor.
+ UnSaveCursor()
+
+ /* Scrolling */
+
+ // ScrollDown scrolls display down one line.
+ ScrollDown()
+ // ScrollUp scroll display up one line.
+ ScrollUp()
+
+ /* Title */
+
+ // SetTitle sets a title of terminal window.
+ SetTitle(title string)
+ // ClearTitle clears a title of terminal window.
+ ClearTitle()
+
+ /* Font */
+
+ // SetColor sets text and background colors. and specify whether text is bold.
+ SetColor(fg, bg Color, bold bool)
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/output_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/output_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..26c770cc152a7b126be43915d60b8ba000ad0e38
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/output_posix.go
@@ -0,0 +1,67 @@
+// +build !windows
+
+package prompt
+
+import (
+ "syscall"
+)
+
+const flushMaxRetryCount = 3
+
+// PosixWriter is a ConsoleWriter implementation for POSIX environment.
+// To control terminal emulator, this outputs VT100 escape sequences.
+type PosixWriter struct {
+ VT100Writer
+ fd int
+}
+
+// Flush to flush buffer
+func (w *PosixWriter) Flush() error {
+ l := len(w.buffer)
+ offset := 0
+ retry := 0
+ for {
+ n, err := syscall.Write(w.fd, w.buffer[offset:])
+ if err != nil {
+ if retry < flushMaxRetryCount {
+ retry++
+ continue
+ }
+ return err
+ }
+ offset += n
+ if offset == l {
+ break
+ }
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &PosixWriter{}
+
+var (
+ // NewStandardOutputWriter returns ConsoleWriter object to write to stdout.
+ // This generates VT100 escape sequences because almost terminal emulators
+ // in POSIX OS built on top of a VT100 specification.
+ // Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStdoutWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stdout,
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates VT100 escape sequences because almost terminal emulators
+// in POSIX OS built on top of a VT100 specification.
+func NewStderrWriter() ConsoleWriter {
+ return &PosixWriter{
+ fd: syscall.Stderr,
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/output_vt100.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/output_vt100.go
new file mode 100644
index 0000000000000000000000000000000000000000..20850fead883c4cd9802928b5de3f935fbbeb047
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/output_vt100.go
@@ -0,0 +1,310 @@
+package prompt
+
+import (
+ "bytes"
+ "strconv"
+)
+
+// VT100Writer generates VT100 escape sequences.
+type VT100Writer struct {
+ buffer []byte
+}
+
+// WriteRaw to write raw byte array
+func (w *VT100Writer) WriteRaw(data []byte) {
+ w.buffer = append(w.buffer, data...)
+}
+
+// Write to write safety byte array by removing control sequences.
+func (w *VT100Writer) Write(data []byte) {
+ w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1))
+}
+
+// WriteRawStr to write raw string
+func (w *VT100Writer) WriteRawStr(data string) {
+ w.WriteRaw([]byte(data))
+}
+
+// WriteStr to write safety string by removing control sequences.
+func (w *VT100Writer) WriteStr(data string) {
+ w.Write([]byte(data))
+}
+
+/* Erase */
+
+// EraseScreen erases the screen with the background colour and moves the cursor to home.
+func (w *VT100Writer) EraseScreen() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'J'})
+}
+
+// EraseUp erases the screen from the current line up to the top of the screen.
+func (w *VT100Writer) EraseUp() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'J'})
+}
+
+// EraseDown erases the screen from the current line down to the bottom of the screen.
+func (w *VT100Writer) EraseDown() {
+ w.WriteRaw([]byte{0x1b, '[', 'J'})
+}
+
+// EraseStartOfLine erases from the current cursor position to the start of the current line.
+func (w *VT100Writer) EraseStartOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', '1', 'K'})
+}
+
+// EraseEndOfLine erases from the current cursor position to the end of the current line.
+func (w *VT100Writer) EraseEndOfLine() {
+ w.WriteRaw([]byte{0x1b, '[', 'K'})
+}
+
+// EraseLine erases the entire current line.
+func (w *VT100Writer) EraseLine() {
+ w.WriteRaw([]byte{0x1b, '[', '2', 'K'})
+}
+
+/* Cursor */
+
+// ShowCursor stops blinking cursor and show.
+func (w *VT100Writer) ShowCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'})
+}
+
+// HideCursor hides cursor.
+func (w *VT100Writer) HideCursor() {
+ w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'})
+}
+
+// CursorGoTo sets the cursor position where subsequent text will begin.
+func (w *VT100Writer) CursorGoTo(row, col int) {
+ if row == 0 && col == 0 {
+ // If no row/column parameters are provided (ie. [H), the cursor will move to the home position.
+ w.WriteRaw([]byte{0x1b, '[', 'H'})
+ return
+ }
+ r := strconv.Itoa(row)
+ c := strconv.Itoa(col)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(r))
+ w.WriteRaw([]byte{';'})
+ w.WriteRaw([]byte(c))
+ w.WriteRaw([]byte{'H'})
+}
+
+// CursorUp moves the cursor up by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorUp(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorDown(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'A'})
+}
+
+// CursorDown moves the cursor down by 'n' rows; the default count is 1.
+func (w *VT100Writer) CursorDown(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorUp(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'B'})
+}
+
+// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorForward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorBackward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'C'})
+}
+
+// CursorBackward moves the cursor backward by 'n' columns; the default count is 1.
+func (w *VT100Writer) CursorBackward(n int) {
+ if n == 0 {
+ return
+ } else if n < 0 {
+ w.CursorForward(-n)
+ return
+ }
+ s := strconv.Itoa(n)
+ w.WriteRaw([]byte{0x1b, '['})
+ w.WriteRaw([]byte(s))
+ w.WriteRaw([]byte{'D'})
+}
+
+// AskForCPR asks for a cursor position report (CPR).
+func (w *VT100Writer) AskForCPR() {
+ // CPR: Cursor Position Request.
+ w.WriteRaw([]byte{0x1b, '[', '6', 'n'})
+}
+
+// SaveCursor saves current cursor position.
+func (w *VT100Writer) SaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 's'})
+}
+
+// UnSaveCursor restores cursor position after a Save Cursor.
+func (w *VT100Writer) UnSaveCursor() {
+ w.WriteRaw([]byte{0x1b, '[', 'u'})
+}
+
+/* Scrolling */
+
+// ScrollDown scrolls display down one line.
+func (w *VT100Writer) ScrollDown() {
+ w.WriteRaw([]byte{0x1b, 'D'})
+}
+
+// ScrollUp scroll display up one line.
+func (w *VT100Writer) ScrollUp() {
+ w.WriteRaw([]byte{0x1b, 'M'})
+}
+
+/* Title */
+
+// SetTitle sets a title of terminal window.
+func (w *VT100Writer) SetTitle(title string) {
+ titleBytes := []byte(title)
+ patterns := []struct {
+ from []byte
+ to []byte
+ }{
+ {
+ from: []byte{0x13},
+ to: []byte{},
+ },
+ {
+ from: []byte{0x07},
+ to: []byte{},
+ },
+ }
+ for i := range patterns {
+ titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1)
+ }
+
+ w.WriteRaw([]byte{0x1b, ']', '2', ';'})
+ w.WriteRaw(titleBytes)
+ w.WriteRaw([]byte{0x07})
+}
+
+// ClearTitle clears a title of terminal window.
+func (w *VT100Writer) ClearTitle() {
+ w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07})
+}
+
+/* Font */
+
+// SetColor sets text and background colors. and specify whether text is bold.
+func (w *VT100Writer) SetColor(fg, bg Color, bold bool) {
+ if bold {
+ w.SetDisplayAttributes(fg, bg, DisplayBold)
+ } else {
+ // If using `DisplayDefualt`, it will be broken in some environment.
+ // Details are https://github.com/c-bata/go-prompt/pull/85
+ w.SetDisplayAttributes(fg, bg, DisplayReset)
+ }
+}
+
+// SetDisplayAttributes to set VT100 display attributes.
+func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) {
+ w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer
+ defer w.WriteRaw([]byte{'m'}) // final character
+
+ var separator byte = ';'
+ for i := range attrs {
+ p, ok := displayAttributeParameters[attrs[i]]
+ if !ok {
+ continue
+ }
+ w.WriteRaw(p)
+ w.WriteRaw([]byte{separator})
+ }
+
+ f, ok := foregroundANSIColors[fg]
+ if !ok {
+ f = foregroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(f)
+ w.WriteRaw([]byte{separator})
+ b, ok := backgroundANSIColors[bg]
+ if !ok {
+ b = backgroundANSIColors[DefaultColor]
+ }
+ w.WriteRaw(b)
+}
+
+var displayAttributeParameters = map[DisplayAttribute][]byte{
+ DisplayReset: {'0'},
+ DisplayBold: {'1'},
+ DisplayLowIntensity: {'2'},
+ DisplayItalic: {'3'},
+ DisplayUnderline: {'4'},
+ DisplayBlink: {'5'},
+ DisplayRapidBlink: {'6'},
+ DisplayReverse: {'7'},
+ DisplayInvisible: {'8'},
+ DisplayCrossedOut: {'9'},
+ DisplayDefaultFont: {'1', '0'},
+}
+
+var foregroundANSIColors = map[Color][]byte{
+ DefaultColor: {'3', '9'},
+
+ // Low intensity.
+ Black: {'3', '0'},
+ DarkRed: {'3', '1'},
+ DarkGreen: {'3', '2'},
+ Brown: {'3', '3'},
+ DarkBlue: {'3', '4'},
+ Purple: {'3', '5'},
+ Cyan: {'3', '6'},
+ LightGray: {'3', '7'},
+
+ // High intensity.
+ DarkGray: {'9', '0'},
+ Red: {'9', '1'},
+ Green: {'9', '2'},
+ Yellow: {'9', '3'},
+ Blue: {'9', '4'},
+ Fuchsia: {'9', '5'},
+ Turquoise: {'9', '6'},
+ White: {'9', '7'},
+}
+
+var backgroundANSIColors = map[Color][]byte{
+ DefaultColor: {'4', '9'},
+
+ // Low intensity.
+ Black: {'4', '0'},
+ DarkRed: {'4', '1'},
+ DarkGreen: {'4', '2'},
+ Brown: {'4', '3'},
+ DarkBlue: {'4', '4'},
+ Purple: {'4', '5'},
+ Cyan: {'4', '6'},
+ LightGray: {'4', '7'},
+
+ // High intensity
+ DarkGray: {'1', '0', '0'},
+ Red: {'1', '0', '1'},
+ Green: {'1', '0', '2'},
+ Yellow: {'1', '0', '3'},
+ Blue: {'1', '0', '4'},
+ Fuchsia: {'1', '0', '5'},
+ Turquoise: {'1', '0', '6'},
+ White: {'1', '0', '7'},
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/output_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/output_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b9c2769fc2d64cfcfcc5b99c915591ec625bd5f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/output_windows.go
@@ -0,0 +1,49 @@
+// +build windows
+
+package prompt
+
+import (
+ "io"
+
+ colorable "github.com/mattn/go-colorable"
+)
+
+// WindowsWriter is a ConsoleWriter implementation for Win32 console.
+// Output is converted from VT100 escape sequences by mattn/go-colorable.
+type WindowsWriter struct {
+ VT100Writer
+ out io.Writer
+}
+
+// Flush to flush buffer
+func (w *WindowsWriter) Flush() error {
+ _, err := w.out.Write(w.buffer)
+ if err != nil {
+ return err
+ }
+ w.buffer = []byte{}
+ return nil
+}
+
+var _ ConsoleWriter = &WindowsWriter{}
+
+var (
+ // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter
+ NewStandardOutputWriter = NewStdoutWriter
+)
+
+// NewStdoutWriter returns ConsoleWriter object to write to stdout.
+// This generates win32 control sequences.
+func NewStdoutWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStdout(),
+ }
+}
+
+// NewStderrWriter returns ConsoleWriter object to write to stderr.
+// This generates win32 control sequences.
+func NewStderrWriter() ConsoleWriter {
+ return &WindowsWriter{
+ out: colorable.NewColorableStderr(),
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/prompt.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/prompt.go
new file mode 100644
index 0000000000000000000000000000000000000000..173cd517c40cde212433e399978641ceff1d1a43
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/prompt.go
@@ -0,0 +1,296 @@
+package prompt
+
+import (
+ "bytes"
+ "os"
+ "time"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+// Executor is called when user input something text.
+type Executor func(string)
+
+// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
+// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
+// - immediate exit (if breakline is false) without executor called
+// - exit after typing (meaning breakline is true), and the executor is called first, before exit.
+// Exit means exit go-prompt (not the overall Go program)
+type ExitChecker func(in string, breakline bool) bool
+
+// Completer should return the suggest item from Document.
+type Completer func(Document) []Suggest
+
+// Prompt is core struct of go-prompt.
+type Prompt struct {
+ in ConsoleParser
+ buf *Buffer
+ renderer *Render
+ executor Executor
+ history *History
+ completion *CompletionManager
+ keyBindings []KeyBind
+ ASCIICodeBindings []ASCIICodeBind
+ keyBindMode KeyBindMode
+ completionOnDown bool
+ exitChecker ExitChecker
+ skipTearDown bool
+}
+
+// Exec is the struct contains user input context.
+type Exec struct {
+ input string
+}
+
+// Run starts prompt.
+func (p *Prompt) Run() {
+ p.skipTearDown = false
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ exitCh := make(chan int)
+ winSizeCh := make(chan *WinSize)
+ stopHandleSignalCh := make(chan struct{})
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+ return
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ stopHandleSignalCh <- struct{}{}
+
+ // Unset raw mode
+ // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
+ debug.AssertNoError(p.in.TearDown())
+ p.executor(e.input)
+
+ p.completion.Update(*p.buf.Document())
+
+ p.renderer.Render(p.buf, p.completion)
+
+ if p.exitChecker != nil && p.exitChecker(e.input, true) {
+ p.skipTearDown = true
+ return
+ }
+ // Set raw mode
+ debug.AssertNoError(p.in.Setup())
+ go p.readBuffer(bufCh, stopReadBufCh)
+ go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ case w := <-winSizeCh:
+ p.renderer.UpdateWinSize(w)
+ p.renderer.Render(p.buf, p.completion)
+ case code := <-exitCh:
+ p.renderer.BreakLine(p.buf)
+ p.tearDown()
+ os.Exit(code)
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
+ key := GetKey(b)
+ p.buf.lastKeyStroke = key
+ // completion
+ completing := p.completion.Completing()
+ p.handleCompletionKeyBinding(key, completing)
+
+ switch key {
+ case Enter, ControlJ, ControlM:
+ p.renderer.BreakLine(p.buf)
+
+ exec = &Exec{input: p.buf.Text()}
+ p.buf = NewBuffer()
+ if exec.input != "" {
+ p.history.Add(exec.input)
+ }
+ case ControlC:
+ p.renderer.BreakLine(p.buf)
+ p.buf = NewBuffer()
+ p.history.Clear()
+ case Up, ControlP:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Older(p.buf); changed {
+ p.buf = newBuf
+ }
+ }
+ case Down, ControlN:
+ if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1.
+ if newBuf, changed := p.history.Newer(p.buf); changed {
+ p.buf = newBuf
+ }
+ return
+ }
+ case ControlD:
+ if p.buf.Text() == "" {
+ shouldExit = true
+ return
+ }
+ case NotDefined:
+ if p.handleASCIICodeBinding(b) {
+ return
+ }
+ p.buf.InsertText(string(b), false, true)
+ }
+
+ shouldExit = p.handleKeyBinding(key)
+ return
+}
+
+func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
+ switch key {
+ case Down:
+ if completing || p.completionOnDown {
+ p.completion.Next()
+ }
+ case Tab, ControlI:
+ p.completion.Next()
+ case Up:
+ if completing {
+ p.completion.Previous()
+ }
+ case BackTab:
+ p.completion.Previous()
+ default:
+ if s, ok := p.completion.GetSelectedSuggestion(); ok {
+ w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator)
+ if w != "" {
+ p.buf.DeleteBeforeCursor(len([]rune(w)))
+ }
+ p.buf.InsertText(s.Text, false, true)
+ }
+ p.completion.Reset()
+ }
+}
+
+func (p *Prompt) handleKeyBinding(key Key) bool {
+ shouldExit := false
+ for i := range commonKeyBindings {
+ kb := commonKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+
+ if p.keyBindMode == EmacsKeyBind {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ }
+
+ // Custom key bindings
+ for i := range p.keyBindings {
+ kb := p.keyBindings[i]
+ if kb.Key == key {
+ kb.Fn(p.buf)
+ }
+ }
+ if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
+ shouldExit = true
+ }
+ return shouldExit
+}
+
+func (p *Prompt) handleASCIICodeBinding(b []byte) bool {
+ checked := false
+ for _, kb := range p.ASCIICodeBindings {
+ if bytes.Equal(kb.ASCIICode, b) {
+ kb.Fn(p.buf)
+ checked = true
+ }
+ }
+ return checked
+}
+
+// Input just returns user input text.
+func (p *Prompt) Input() string {
+ defer debug.Teardown()
+ debug.Log("start prompt")
+ p.setUp()
+ defer p.tearDown()
+
+ if p.completion.showAtStart {
+ p.completion.Update(*p.buf.Document())
+ }
+
+ p.renderer.Render(p.buf, p.completion)
+ bufCh := make(chan []byte, 128)
+ stopReadBufCh := make(chan struct{})
+ go p.readBuffer(bufCh, stopReadBufCh)
+
+ for {
+ select {
+ case b := <-bufCh:
+ if shouldExit, e := p.feed(b); shouldExit {
+ p.renderer.BreakLine(p.buf)
+ stopReadBufCh <- struct{}{}
+ return ""
+ } else if e != nil {
+ // Stop goroutine to run readBuffer function
+ stopReadBufCh <- struct{}{}
+ return e.input
+ } else {
+ p.completion.Update(*p.buf.Document())
+ p.renderer.Render(p.buf, p.completion)
+ }
+ default:
+ time.Sleep(10 * time.Millisecond)
+ }
+ }
+}
+
+func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) {
+ debug.Log("start reading buffer")
+ for {
+ select {
+ case <-stopCh:
+ debug.Log("stop reading buffer")
+ return
+ default:
+ if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) {
+ bufCh <- b
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (p *Prompt) setUp() {
+ debug.AssertNoError(p.in.Setup())
+ p.renderer.Setup()
+ p.renderer.UpdateWinSize(p.in.GetWinSize())
+}
+
+func (p *Prompt) tearDown() {
+ if !p.skipTearDown {
+ debug.AssertNoError(p.in.TearDown())
+ }
+ p.renderer.TearDown()
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/render.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/render.go
new file mode 100644
index 0000000000000000000000000000000000000000..299ac48b6254b9752ea16516aaedcd41acca6515
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/render.go
@@ -0,0 +1,287 @@
+package prompt
+
+import (
+ "runtime"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+ runewidth "github.com/mattn/go-runewidth"
+)
+
+// Render to render prompt information from state of Buffer.
+type Render struct {
+ out ConsoleWriter
+ prefix string
+ livePrefixCallback func() (prefix string, useLivePrefix bool)
+ breakLineCallback func(*Document)
+ title string
+ row uint16
+ col uint16
+
+ previousCursor int
+
+ // colors,
+ prefixTextColor Color
+ prefixBGColor Color
+ inputTextColor Color
+ inputBGColor Color
+ previewSuggestionTextColor Color
+ previewSuggestionBGColor Color
+ suggestionTextColor Color
+ suggestionBGColor Color
+ selectedSuggestionTextColor Color
+ selectedSuggestionBGColor Color
+ descriptionTextColor Color
+ descriptionBGColor Color
+ selectedDescriptionTextColor Color
+ selectedDescriptionBGColor Color
+ scrollbarThumbColor Color
+ scrollbarBGColor Color
+}
+
+// Setup to initialize console output.
+func (r *Render) Setup() {
+ if r.title != "" {
+ r.out.SetTitle(r.title)
+ debug.AssertNoError(r.out.Flush())
+ }
+}
+
+// getCurrentPrefix to get current prefix.
+// If live-prefix is enabled, return live-prefix.
+func (r *Render) getCurrentPrefix() string {
+ if prefix, ok := r.livePrefixCallback(); ok {
+ return prefix
+ }
+ return r.prefix
+}
+
+func (r *Render) renderPrefix() {
+ r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
+ r.out.WriteStr(r.getCurrentPrefix())
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// TearDown to clear title and erasing.
+func (r *Render) TearDown() {
+ r.out.ClearTitle()
+ r.out.EraseDown()
+ debug.AssertNoError(r.out.Flush())
+}
+
+func (r *Render) prepareArea(lines int) {
+ for i := 0; i < lines; i++ {
+ r.out.ScrollDown()
+ }
+ for i := 0; i < lines; i++ {
+ r.out.ScrollUp()
+ }
+}
+
+// UpdateWinSize called when window size is changed.
+func (r *Render) UpdateWinSize(ws *WinSize) {
+ r.row = ws.Row
+ r.col = ws.Col
+}
+
+func (r *Render) renderWindowTooSmall() {
+ r.out.CursorGoTo(0, 0)
+ r.out.EraseScreen()
+ r.out.SetColor(DarkRed, White, false)
+ r.out.WriteStr("Your console window is too small...")
+}
+
+func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) {
+ suggestions := completions.GetSuggestions()
+ if len(completions.GetSuggestions()) == 0 {
+ return
+ }
+ prefix := r.getCurrentPrefix()
+ formatted, width := formatSuggestions(
+ suggestions,
+ int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar
+ )
+ // +1 means a width of scrollbar.
+ width++
+
+ windowHeight := len(formatted)
+ if windowHeight > int(completions.max) {
+ windowHeight = int(completions.max)
+ }
+ formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
+ r.prepareArea(windowHeight)
+
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor())
+ x, _ := r.toPos(cursor)
+ if x+width >= int(r.col) {
+ cursor = r.backward(cursor, x+width-int(r.col))
+ }
+
+ contentHeight := len(completions.tmp)
+
+ fractionVisible := float64(windowHeight) / float64(contentHeight)
+ fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
+
+ scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
+ scrollbarTop := int(float64(windowHeight) * fractionAbove)
+
+ isScrollThumb := func(row int) bool {
+ return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
+ }
+
+ selected := completions.selected - completions.verticalScroll
+ r.out.SetColor(White, Cyan, false)
+ for i := 0; i < windowHeight; i++ {
+ r.out.CursorDown(1)
+ if i == selected {
+ r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
+ } else {
+ r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Text)
+
+ if i == selected {
+ r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
+ } else {
+ r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
+ }
+ r.out.WriteStr(formatted[i].Description)
+
+ if isScrollThumb(i) {
+ r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
+ } else {
+ r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
+ }
+ r.out.WriteStr(" ")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+
+ r.lineWrap(cursor + width)
+ r.backward(cursor+width, width)
+ }
+
+ if x+width >= int(r.col) {
+ r.out.CursorForward(x + width - int(r.col))
+ }
+
+ r.out.CursorUp(windowHeight)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+}
+
+// Render renders to the console.
+func (r *Render) Render(buffer *Buffer, completion *CompletionManager) {
+ // In situations where a pseudo tty is allocated (e.g. within a docker container),
+ // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
+ if r.col == 0 {
+ return
+ }
+ defer func() { debug.AssertNoError(r.out.Flush()) }()
+ r.move(r.previousCursor, 0)
+
+ line := buffer.Text()
+ prefix := r.getCurrentPrefix()
+ cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line)
+
+ // prepare area
+ _, y := r.toPos(cursor)
+
+ h := y + 1 + int(completion.max)
+ if h > int(r.row) || completionMargin > int(r.col) {
+ r.renderWindowTooSmall()
+ return
+ }
+
+ // Rendering
+ r.out.HideCursor()
+ defer r.out.ShowCursor()
+
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(line)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ r.lineWrap(cursor)
+
+ r.out.EraseDown()
+
+ cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition())
+
+ r.renderCompletion(buffer, completion)
+ if suggest, ok := completion.GetSelectedSuggestion(); ok {
+ cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator)))
+
+ r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false)
+ r.out.WriteStr(suggest.Text)
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ cursor += runewidth.StringWidth(suggest.Text)
+
+ rest := buffer.Document().TextAfterCursor()
+ r.out.WriteStr(rest)
+ cursor += runewidth.StringWidth(rest)
+ r.lineWrap(cursor)
+
+ cursor = r.backward(cursor, runewidth.StringWidth(rest))
+ }
+ r.previousCursor = cursor
+}
+
+// BreakLine to break line.
+func (r *Render) BreakLine(buffer *Buffer) {
+ // Erasing and Render
+ cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix())
+ r.clear(cursor)
+ r.renderPrefix()
+ r.out.SetColor(r.inputTextColor, r.inputBGColor, false)
+ r.out.WriteStr(buffer.Document().Text + "\n")
+ r.out.SetColor(DefaultColor, DefaultColor, false)
+ debug.AssertNoError(r.out.Flush())
+ if r.breakLineCallback != nil {
+ r.breakLineCallback(buffer.Document())
+ }
+
+ r.previousCursor = 0
+}
+
+// clear erases the screen from a beginning of input
+// even if there is line break which means input length exceeds a window's width.
+func (r *Render) clear(cursor int) {
+ r.move(cursor, 0)
+ r.out.EraseDown()
+}
+
+// backward moves cursor to backward from a current cursor position
+// regardless there is a line break.
+func (r *Render) backward(from, n int) int {
+ return r.move(from, from-n)
+}
+
+// move moves cursor to specified position from the beginning of input
+// even if there is a line break.
+func (r *Render) move(from, to int) int {
+ fromX, fromY := r.toPos(from)
+ toX, toY := r.toPos(to)
+
+ r.out.CursorUp(fromY - toY)
+ r.out.CursorBackward(fromX - toX)
+ return to
+}
+
+// toPos returns the relative position from the beginning of the string.
+func (r *Render) toPos(cursor int) (x, y int) {
+ col := int(r.col)
+ return cursor % col, cursor / col
+}
+
+func (r *Render) lineWrap(cursor int) {
+ if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 {
+ r.out.WriteRaw([]byte{'\n'})
+ }
+}
+
+func clamp(high, low, x float64) float64 {
+ switch {
+ case high < x:
+ return high
+ case x < low:
+ return low
+ default:
+ return x
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/shortcut.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/shortcut.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8d4282700c0bdb30e4decfb9c9ac91f27af251
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/shortcut.go
@@ -0,0 +1,43 @@
+package prompt
+
+func dummyExecutor(in string) {}
+
+// Input get the input data from the user and return it.
+func Input(prefix string, completer Completer, opts ...Option) string {
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+// Choose to the shortcut of input function to select from string array.
+// Deprecated: Maybe anyone want to use this.
+func Choose(prefix string, choices []string, opts ...Option) string {
+ completer := newChoiceCompleter(choices, FilterHasPrefix)
+ pt := New(dummyExecutor, completer)
+ pt.renderer.prefixTextColor = DefaultColor
+ pt.renderer.prefix = prefix
+
+ for _, opt := range opts {
+ if err := opt(pt); err != nil {
+ panic(err)
+ }
+ }
+ return pt.Input()
+}
+
+func newChoiceCompleter(choices []string, filter Filter) Completer {
+ s := make([]Suggest, len(choices))
+ for i := range choices {
+ s[i] = Suggest{Text: choices[i]}
+ }
+ return func(x Document) []Suggest {
+ return filter(s, x.GetWordBeforeCursor(), true)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/signal_posix.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/signal_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3150df5d85e7612c42c2a889dbefee3b524bef6
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/signal_posix.go
@@ -0,0 +1,49 @@
+// +build !windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ in := p.in
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ syscall.SIGWINCH,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+
+ case syscall.SIGWINCH:
+ debug.Log("Catch SIGWINCH")
+ winSizeCh <- in.GetWinSize()
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/signal_windows.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/signal_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a427c79ec0414540f8f40694731b2565ea80c13
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/environment/source/signal_windows.go
@@ -0,0 +1,44 @@
+// +build windows
+
+package prompt
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/c-bata/go-prompt/internal/debug"
+)
+
+func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) {
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(
+ sigCh,
+ syscall.SIGINT,
+ syscall.SIGTERM,
+ syscall.SIGQUIT,
+ )
+
+ for {
+ select {
+ case <-stop:
+ debug.Log("stop handleSignals")
+ return
+ case s := <-sigCh:
+ switch s {
+
+ case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c
+ debug.Log("Catch SIGINT")
+ exitCh <- 0
+
+ case syscall.SIGTERM: // kill -SIGTERM XXXX
+ debug.Log("Catch SIGTERM")
+ exitCh <- 1
+
+ case syscall.SIGQUIT: // kill -SIGQUIT XXXX
+ debug.Log("Catch SIGQUIT")
+ exitCh <- 0
+ }
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/instruction.md b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..7c032b0b3b756ba30612f9eff9a2319befb64835
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/instruction.md
@@ -0,0 +1,43 @@
+GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns incorrect substring
+
+#### Description
+
+The `GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor` method is returning an incorrect substring that's missing the first character. When called on a document, it should return the complete word before the cursor but it's cutting off the first character.
+
+#### Steps/Code to Reproduce
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/c-bata/go-prompt"
+)
+
+func main() {
+ // Create a document with cursor positioned after "i am c-bata"
+ doc := &prompt.Document{
+ Text: "i am c-bata, go-prompt is awesome library.",
+ cursor: 11, // cursor after "i am c-bata"
+ }
+
+ result := doc.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(",")
+ fmt.Printf("Got: '%s'\n", result)
+ fmt.Printf("Expected: 'i am c-bata'\n")
+}
+```
+
+Expected output:
+```
+Got: 'i am c-bata'
+Expected: 'i am c-bata'
+```
+
+Actual output:
+```
+Got: 'am c-bata'
+Expected: 'i am c-bata'
+```
+
+The method is missing the first character of the word sequence before the cursor.
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/provenance.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..8dbf6c23859a309a072e747f23a4d4ad8f0e301f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/provenance.json
@@ -0,0 +1,477 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt",
+ "original-bug": "task-specific unchanged semantic bug",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only",
+ "extra_semantic_repair_coverage": false,
+ "original_patch_hunks": 1
+ },
+ "private_frozen_files": {
+ "buffer_test.go": {
+ "mode": "0o644",
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098",
+ "size": 4965
+ },
+ "completion_test.go": {
+ "mode": "0o644",
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d",
+ "size": 7010
+ },
+ "document_test.go": {
+ "mode": "0o644",
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284",
+ "size": 28938
+ },
+ "emacs_test.go": {
+ "mode": "0o644",
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095",
+ "size": 741
+ },
+ "filter_test.go": {
+ "mode": "0o644",
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247",
+ "size": 3339
+ },
+ "history_test.go": {
+ "mode": "0o644",
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327",
+ "size": 1319
+ },
+ "input_test.go": {
+ "mode": "0o644",
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922",
+ "size": 533
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": "0o644",
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf",
+ "size": 1075
+ },
+ "internal/strings/strings_test.go": {
+ "mode": "0o644",
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6",
+ "size": 981
+ },
+ "output_vt100_test.go": {
+ "mode": "0o644",
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee",
+ "size": 1349
+ },
+ "render_test.go": {
+ "mode": "0o644",
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb",
+ "size": 2890
+ }
+ },
+ "public_files": {
+ ".github/ISSUE_TEMPLATE/bug_report.md": {
+ "mode": "0o644",
+ "sha256": "89d3492ca8533a3d31e4de49a23828a322f75d2a1ec4236327c4a76c7c51ada6",
+ "size": 684
+ },
+ ".github/ISSUE_TEMPLATE/feature_request.md": {
+ "mode": "0o644",
+ "sha256": "d82e14e6b4d021d0007eeef4f5ca489fc6c8e8e4d7479ee30e74fe82afd3b08f",
+ "size": 206
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "3239b94a1a41c05eff5dc086ef1378cf1e289fad0203420b5cb4c78e3c5c239b",
+ "size": 270
+ },
+ "CHANGELOG.md": {
+ "mode": "0o644",
+ "sha256": "1f88f92d3247e1b52af0f0de7ad1263a59807edb17238c7a0211554f8080e51c",
+ "size": 2895
+ },
+ "LICENSE": {
+ "mode": "0o644",
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "size": 1072
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "9425a0d4c15747863625f647348962a9b0f81a0971a7e0184ee722bf34a60ba2",
+ "size": 1177
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "ce56df51a1a9a5b5c5b056429bbee006a260fb0730af63b1d0fe91755e574cc4",
+ "size": 6185
+ },
+ "_example/README.md": {
+ "mode": "0o644",
+ "sha256": "155951bafd778493bd41ae57dcc0ba6b8eca821fcbe2ffe770960ac2780d3d09",
+ "size": 1102
+ },
+ "_example/build.sh": {
+ "mode": "0o755",
+ "sha256": "de2fb330b665691cd75b990236cd6a5df0058608de0dfc6194da30d4041a1e29",
+ "size": 469
+ },
+ "_example/exec-command/main.go": {
+ "mode": "0o644",
+ "sha256": "0e96493b6e6d446b2e691d4834ff8a55834caa410ead970cb611a63ba84f174a",
+ "size": 429
+ },
+ "_example/http-prompt/api.py": {
+ "mode": "0o644",
+ "sha256": "2c2bca9acb07a84c65a4482c61c9ade253a574477a8e461307568ea1f9a342c8",
+ "size": 335
+ },
+ "_example/http-prompt/main.go": {
+ "mode": "0o644",
+ "sha256": "6994b190c4165068e69ed44eb61698af69a15a7690179ce46e3c1c5d8c211643",
+ "size": 5484
+ },
+ "_example/live-prefix/main.go": {
+ "mode": "0o644",
+ "sha256": "20268f9cb6f3b82a52eddc33cbf8082adaa46092e2063df279499e05e25a228c",
+ "size": 1103
+ },
+ "_example/simple-echo/cjk-cyrillic/main.go": {
+ "mode": "0o644",
+ "sha256": "8fb10807d4085ebc4b345bc0ccfef9217e21e49a888bfe3192e8ddfdfa01e89c",
+ "size": 800
+ },
+ "_example/simple-echo/main.go": {
+ "mode": "0o644",
+ "sha256": "e46563ddaa932831fe9ede870b10efb5222c0d54a86f4b4f5197c9cf20942a24",
+ "size": 902
+ },
+ "_tools/README.md": {
+ "mode": "0o644",
+ "sha256": "96dc2343bc5cde642fd449ddc366462753a2e17b6a78adfa015bf991e9dac241",
+ "size": 234
+ },
+ "_tools/complete_file/main.go": {
+ "mode": "0o644",
+ "sha256": "e5dd823f9d6415614a8238ce106d26e9ded1db9b308c121d7f48bb1df003effc",
+ "size": 803
+ },
+ "_tools/sigwinch/main.go": {
+ "mode": "0o644",
+ "sha256": "a806b4e45298f5003c95432d8dd3c40c9c096335f19f1a4160afcdb64fa727e3",
+ "size": 1386
+ },
+ "_tools/vt100_debug/main.go": {
+ "mode": "0o644",
+ "sha256": "7f72eba3cc7037fcf39c9b56a96c578c157e5fb235cb626ab1e83cbef0dc290b",
+ "size": 794
+ },
+ "buffer.go": {
+ "mode": "0o644",
+ "sha256": "10188d96a450fe13ba1e9ec00c89603eb2a2860536965d980d1e4abf4374b018",
+ "size": 5781
+ },
+ "completer/file.go": {
+ "mode": "0o644",
+ "sha256": "6181ed9e39028236c5c93fbe219331fc1492ecfd6af2df764cc42b5455c9bb96",
+ "size": 2401
+ },
+ "completion.go": {
+ "mode": "0o644",
+ "sha256": "b90bd9628534cfb343a592775430e17a1999b1de500fb2a8f1507c030a432eae",
+ "size": 4491
+ },
+ "document.go": {
+ "mode": "0o644",
+ "sha256": "cdf957b86eac51dc5f94c2d622a41d988fa8a21e5b201a61e26e8588c7c85c53",
+ "size": 13099
+ },
+ "emacs.go": {
+ "mode": "0o644",
+ "sha256": "53f0df0016ef9d9695a797b19286681666cf0c7e5a866c393b194aae915f2664",
+ "size": 2675
+ },
+ "filter.go": {
+ "mode": "0o644",
+ "sha256": "dc5922bad6ecb32ecdaf20bd6035dddc7ce8c14f15dbd4d49192c2354cb8a038",
+ "size": 2005
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "97413fa2a2ed68170496f2289a2dca6fb0a192dcd020fc0ca48a5d106e60d55e",
+ "size": 253
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "88ea0a91babaa54b67cc6d5f6f7f47fa4be798fe523324ea568d8926eed2024c",
+ "size": 2183
+ },
+ "history.go": {
+ "mode": "0o644",
+ "sha256": "4ce80ba067cfc72c56a3ee3353ec75cd6bb2f5d82097515c591e3c7c773c51cd",
+ "size": 1488
+ },
+ "input.go": {
+ "mode": "0o644",
+ "sha256": "73461cc4f57d68b66e2a9e196239aaef942539134593beac0d0023743832e0e1",
+ "size": 7630
+ },
+ "input_posix.go": {
+ "mode": "0o644",
+ "sha256": "c7e5a4dfc3910f178f0685ef99f2e47d481a91c4cf9af50f92fc4266aed634df",
+ "size": 1648
+ },
+ "input_windows.go": {
+ "mode": "0o644",
+ "sha256": "f763250d309fb88d9536f77da1d1285c04bc6defe859506f1501e10f7743da9e",
+ "size": 1679
+ },
+ "internal/bisect/bisect.go": {
+ "mode": "0o644",
+ "sha256": "c4de2adfa2e08a77f902661d67325467f89013634dbcef22d24dc6f34d26624a",
+ "size": 327
+ },
+ "internal/debug/assert.go": {
+ "mode": "0o644",
+ "sha256": "1a3050ec58991b62c7ea352d19505e3080ac9760bdb091544f0ecf5aba35969c",
+ "size": 815
+ },
+ "internal/debug/log.go": {
+ "mode": "0o644",
+ "sha256": "2ce968e275558de61c6d83793e85561f7a8dd69c95ec7902ccd2cc3fb169aa82",
+ "size": 875
+ },
+ "internal/strings/strings.go": {
+ "mode": "0o644",
+ "sha256": "b97f08157c3baf1f94fea4bb2237691d8270bd5380b4311709ecd59b84cf4b7b",
+ "size": 2018
+ },
+ "internal/term/raw.go": {
+ "mode": "0o644",
+ "sha256": "177a1a20ae8d71b56857383a5797754560f7f6404ea86778d5f01e9a1c1b4f9f",
+ "size": 747
+ },
+ "internal/term/term.go": {
+ "mode": "0o644",
+ "sha256": "abe6fa965fa15b999b2010135903f598830d4c885a52ef9b067fd5ebbf6e373f",
+ "size": 606
+ },
+ "key.go": {
+ "mode": "0o644",
+ "sha256": "03a43283e07de7a4ea6fed32692d86325f73e98fd89a296f19c171e0bc780999",
+ "size": 1746
+ },
+ "key_bind.go": {
+ "mode": "0o644",
+ "sha256": "83f48bb720a11c8e49165ac382e3a870fdcf6b380a0a95267f8c25211898c9eb",
+ "size": 1109
+ },
+ "key_bind_func.go": {
+ "mode": "0o644",
+ "sha256": "445bff5c0fdb0b52879c635322603c2fc75d265de3761cb8c3b980c798bf39af",
+ "size": 1219
+ },
+ "key_string.go": {
+ "mode": "0o644",
+ "sha256": "55c429dae227bb1659d5d5e2e906dbfa9c7f53b5105fa83fbe290529ff6f2317",
+ "size": 1359
+ },
+ "option.go": {
+ "mode": "0o644",
+ "sha256": "28cfcc1d08b3cf650483d977195458531b3b3913f8a5f357a3ec17ea5d73e215",
+ "size": 8737
+ },
+ "output.go": {
+ "mode": "0o644",
+ "sha256": "372876b0aa908479ed3b29de70a479f420d85e3666b8957c8b61eaed9b32c3f2",
+ "size": 4320
+ },
+ "output_posix.go": {
+ "mode": "0o644",
+ "sha256": "d46b1da307e8969b033e1ade2eb51a83c4c3d4f2a7e4aba35ec3a03991b89a0f",
+ "size": 1545
+ },
+ "output_vt100.go": {
+ "mode": "0o644",
+ "sha256": "9082c7e4619c1eb38030bc4994a4fbf66ef27b130751bf2eb9c25c01082e8605",
+ "size": 7453
+ },
+ "output_windows.go": {
+ "mode": "0o644",
+ "sha256": "571c5ae1ad051a701b426371efd79a3776c2226ca9e3c2e598fe5996dfa1b8e1",
+ "size": 1066
+ },
+ "prompt.go": {
+ "mode": "0o644",
+ "sha256": "6b3e2bbd90f40ad6a487f1a6ea7f5a6fb48cae6c8c246ecc77621fb3e7383ca7",
+ "size": 7062
+ },
+ "render.go": {
+ "mode": "0o644",
+ "sha256": "90fdd57a63e06f01940d10ee1a0be95ced7d6adc7faa255b3141556d7d316270",
+ "size": 8020
+ },
+ "shortcut.go": {
+ "mode": "0o644",
+ "sha256": "b4a097f466df7396049ebe8393f81c9b1200159d4e2be22bd6838c307ec156dc",
+ "size": 1120
+ },
+ "signal_posix.go": {
+ "mode": "0o644",
+ "sha256": "74f0bae5f290f3f7f82a5dd495e672f627a4ab4b63118f870e8c13c0a7024314",
+ "size": 881
+ },
+ "signal_windows.go": {
+ "mode": "0o644",
+ "sha256": "444f662a32e6997df2af8e2a9e7dbfe977414a6bfc0f54a7f10117f204648437",
+ "size": 757
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982",
+ "os": "linux",
+ "sha256": "0a138f6e1b16914c4b254c75ccec4f66d24f2313d2a248c0d78de914d5efa982"
+ },
+ "context_inventory_sha256": "6b8f93086e81483ac1ce82f328d7f4b38b1b560dbad057ed6a2a30ff3cf0e13f",
+ "image": "registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "9d3b21cdacadfa4f3de9584d0cea973e5aa2ceedcd5ec9cbd3a63df22b313455",
+ "receipt_path": "production/runtime-images-extra-v1/resolutions/316e0e68930cd4ef/resolution.json",
+ "receipt_sha256": "697bb0619eddcdfdeba1c9144b033f564f2d7514be6e6a44dc520fa4e63ed8bc",
+ "registry_digest": "sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22",
+ "source_image": "docker.io/swebench/swesmith.x86_64.c-bata_1776_go-prompt.82a91227@sha256:3daf51c74a01657e9ad8f326651fb6f5b796ffecdb90098e74a52a9560e0a1bb",
+ "source_receipt_sha256": "b450bea0e201cbe194b765ded4b51539144c85296122c8b642d7e94c889526f3",
+ "space_commit": "5ae654cd2e9d695f0de304bd4398835fc7cf45e0",
+ "space_id": "harness-hub/scale800-go-316e0e68930cd4ef-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "b27f568055b1dd82afc8c38240cc625597e2c6df01a0c2ce41696e95f5005902",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21",
+ "source_proof_sha256": "6f84d69332c16f2667483cf14f395f88a4ccf86252df29124b5ef8b73138a0cd",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:c-bata__go-prompt.82a91227.lm_modify__dnaspfcb",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "9992c59c25864ce1556e67b9e1501c93f6e7f9ff",
+ "instruction_sha256": "38c49f59cb02b351283c2bd355682afb8cd12ea6303762c56288fef0de373544",
+ "is_fork": true,
+ "learner_path": "tasks/b2dd0db3da632c1649daef1a/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "6983c377893cff108f75364bbe3f4397a99efb83317f748f783468dc23f53acd",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/c-bata__go-prompt.82a91227/0e6ee297a346ac30b8e1f01b864936008b0de8b8/LICENSE"
+ },
+ "task_bundle": {
+ "basis": "Captured publisherMIT/train; exactsoftwarepermissionverifiedseparately",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "82a912274504477990ecf7c852eebb7c85291772",
+ "patch_sha256": "18db42379719764014a68f2ef1d829d1a3a3f325359f90569b7eecaf80d01c27",
+ "provenance_path": "tasks/b2dd0db3da632c1649daef1a/source-proof.json",
+ "repository_lineage": [
+ "swesmith/c-bata__go-prompt.82a91227",
+ "c-bata/go-prompt"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "0e6ee297a346ac30b8e1f01b864936008b0de8b8",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "d5e7954053dc39f3d67b9c752686673bf1c7c541",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/c-bata__go-prompt.82a91227",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "c-bata__go-prompt.82a91227.lm_modify__dnaspfcb",
+ "task_sha256": "3d9f42ef33bc7d58006d85cbc9dd01f5b9239cb9aaa46db226c5bac4e44ecb07",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "c-bata/go-prompt",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "c8c0bf77ea27ffa0d316905d1592025cd05e11b6734f7fc6db3b7c7a463b5fda",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.md",
+ "/testbed/.github/ISSUE_TEMPLATE/feature_request.md",
+ "/testbed/.gitignore",
+ "/testbed/CHANGELOG.md",
+ "/testbed/LICENSE",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/_example/README.md",
+ "/testbed/_example/build.sh",
+ "/testbed/_example/exec-command/main.go",
+ "/testbed/_example/http-prompt/api.py",
+ "/testbed/_example/http-prompt/main.go",
+ "/testbed/_example/live-prefix/main.go",
+ "/testbed/_example/simple-echo/cjk-cyrillic/main.go",
+ "/testbed/_example/simple-echo/main.go",
+ "/testbed/_tools/README.md",
+ "/testbed/_tools/complete_file/main.go",
+ "/testbed/_tools/sigwinch/main.go",
+ "/testbed/_tools/vt100_debug/main.go",
+ "/testbed/buffer.go",
+ "/testbed/completer/file.go",
+ "/testbed/completion.go",
+ "/testbed/document.go",
+ "/testbed/emacs.go",
+ "/testbed/filter.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum",
+ "/testbed/history.go",
+ "/testbed/input.go",
+ "/testbed/input_posix.go",
+ "/testbed/input_windows.go",
+ "/testbed/internal/bisect/bisect.go",
+ "/testbed/internal/debug/assert.go",
+ "/testbed/internal/debug/log.go",
+ "/testbed/internal/strings/strings.go",
+ "/testbed/internal/term/raw.go",
+ "/testbed/internal/term/term.go",
+ "/testbed/key.go",
+ "/testbed/key_bind.go",
+ "/testbed/key_bind_func.go",
+ "/testbed/key_string.go",
+ "/testbed/option.go",
+ "/testbed/output.go",
+ "/testbed/output_posix.go",
+ "/testbed/output_vt100.go",
+ "/testbed/output_windows.go",
+ "/testbed/prompt.go",
+ "/testbed/render.go",
+ "/testbed/shortcut.go",
+ "/testbed/signal_posix.go",
+ "/testbed/signal_windows.go"
+ ]
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/solution/solve.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..00d1a533519e8abc9def758862da6b859247bfe5
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"document.go": {"data": "cGFja2FnZSBwcm9tcHQKCmltcG9ydCAoCgkic3RyaW5ncyIKCSJ1bmljb2RlL3V0ZjgiCgoJImdpdGh1Yi5jb20vYy1iYXRhL2dvLXByb21wdC9pbnRlcm5hbC9iaXNlY3QiCglpc3RyaW5ncyAiZ2l0aHViLmNvbS9jLWJhdGEvZ28tcHJvbXB0L2ludGVybmFsL3N0cmluZ3MiCglydW5ld2lkdGggImdpdGh1Yi5jb20vbWF0dG4vZ28tcnVuZXdpZHRoIgopCgovLyBEb2N1bWVudCBoYXMgdGV4dCBkaXNwbGF5ZWQgaW4gdGVybWluYWwgYW5kIGN1cnNvciBwb3NpdGlvbi4KdHlwZSBEb2N1bWVudCBzdHJ1Y3QgewoJVGV4dCBzdHJpbmcKCS8vIFRoaXMgcmVwcmVzZW50cyBhIGluZGV4IGluIGEgcnVuZSBhcnJheSBvZiBEb2N1bWVudC5UZXh0LgoJLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgY3Vyc29yUG9zaXRpb24gaXMgMi4KCS8vIEJ1dCBEaXNwbGF5ZWRDdXJzb3JQb3NpdGlvbiByZXR1cm5zIDQgYmVjYXVzZSAn5pelJyBhbmQgJ+acrCcgYXJlIGRvdWJsZSB3aWR0aCBjaGFyYWN0ZXJzLgoJY3Vyc29yUG9zaXRpb24gaW50CglsYXN0S2V5ICAgICAgICBLZXkKfQoKLy8gTmV3RG9jdW1lbnQgcmV0dXJuIHRoZSBuZXcgZW1wdHkgZG9jdW1lbnQuCmZ1bmMgTmV3RG9jdW1lbnQoKSAqRG9jdW1lbnQgewoJcmV0dXJuICZEb2N1bWVudHsKCQlUZXh0OiAgICAgICAgICAgIiIsCgkJY3Vyc29yUG9zaXRpb246IDAsCgl9Cn0KCi8vIExhc3RLZXlTdHJva2UgcmV0dXJuIHRoZSBsYXN0IGtleSBwcmVzc2VkIGluIHRoaXMgZG9jdW1lbnQuCmZ1bmMgKGQgKkRvY3VtZW50KSBMYXN0S2V5U3Ryb2tlKCkgS2V5IHsKCXJldHVybiBkLmxhc3RLZXkKfQoKLy8gRGlzcGxheUN1cnNvclBvc2l0aW9uIHJldHVybnMgdGhlIGN1cnNvciBwb3NpdGlvbiBvbiByZW5kZXJlZCB0ZXh0IG9uIHRlcm1pbmFsIGVtdWxhdG9ycy4KLy8gU28gaWYgRG9jdW1lbnQgaXMgIuaXpeacrChjdXJzb3Ip6KqeIiwgRGlzcGxheWVkQ3Vyc29yUG9zaXRpb24gcmV0dXJucyA0IGJlY2F1c2UgJ+aXpScgYW5kICfmnKwnIGFyZSBkb3VibGUgd2lkdGggY2hhcmFjdGVycy4KZnVuYyAoZCAqRG9jdW1lbnQpIERpc3BsYXlDdXJzb3JQb3NpdGlvbigpIGludCB7Cgl2YXIgcG9zaXRpb24gaW50CglydW5lcyA6PSBbXXJ1bmUoZC5UZXh0KVs6ZC5jdXJzb3JQb3NpdGlvbl0KCWZvciBpIDo9IHJhbmdlIHJ1bmVzIHsKCQlwb3NpdGlvbiArPSBydW5ld2lkdGguUnVuZVdpZHRoKHJ1bmVzW2ldKQoJfQoJcmV0dXJuIHBvc2l0aW9uCn0KCi8vIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yIHJldHVybiBjaGFyYWN0ZXIgcmVsYXRpdmUgdG8gY3Vyc29yIHBvc2l0aW9uLCBvciBlbXB0eSBzdHJpbmcKZnVuYyAoZCAqRG9jdW1lbnQpIEdldENoYXJSZWxhdGl2ZVRvQ3Vyc29yKG9mZnNldCBpbnQpIChyIHJ1bmUpIHsKCXMgOj0gZC5UZXh0CgljbnQgOj0gMAoKCWZvciBsZW4ocykgPiAwIHsKCQljbnQrKwoJCXIsIHNpemUgOj0gdXRmOC5EZWNvZGVSdW5lSW5TdHJpbmcocykKCQlpZiBjbnQgPT0gZC5jdXJzb3JQb3NpdGlvbitvZmZzZXQgewoJCQlyZXR1cm4gcgoJCX0KCQlzID0gc1tzaXplOl0KCX0KCXJldHVybiAwCn0KCi8vIFRleHRCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJciA6PSBbXXJ1bmUoZC5UZXh0KQoJcmV0dXJuIHN0cmluZyhyWzpkLmN1cnNvclBvc2l0aW9uXSkKfQoKLy8gVGV4dEFmdGVyQ3Vyc29yIHJldHVybnMgdGhlIHRleHQgYWZ0ZXIgdGhlIGN1cnNvci4KZnVuYyAoZCAqRG9jdW1lbnQpIFRleHRBZnRlckN1cnNvcigpIHN0cmluZyB7CglyIDo9IFtdcnVuZShkLlRleHQpCglyZXR1cm4gc3RyaW5nKHJbZC5jdXJzb3JQb3NpdGlvbjpdKQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYmVmb3JlIHRoZSBjdXJzb3IuCi8vIElmIHdlIGhhdmUgd2hpdGVzcGFjZSBiZWZvcmUgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcigpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBJZiB3ZSBoYXZlIHdoaXRlc3BhY2UgYWZ0ZXIgdGhlIGN1cnNvciB0aGlzIHJldHVybnMgYW4gZW1wdHkgc3RyaW5nLgpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yKCkgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmQoKV0KfQoKLy8gR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvcldpdGhTcGFjZSgpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UgcmV0dXJucyB0aGUgd29yZCBhZnRlciB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEFmdGVyQ3Vyc29yLCBpdCByZXR1cm5zIHN0cmluZyBjb250YWluaW5nIHNwYWNlCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JXaXRoU3BhY2UoKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpXQp9CgovLyBHZXRXb3JkQmVmb3JlQ3Vyc29yVW50aWxTZXBhcmF0b3IgcmV0dXJucyB0aGUgdGV4dCBiZWZvcmUgdGhlIGN1cnNvciB1bnRpbCBuZXh0IHNlcGFyYXRvci4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJcmV0dXJuIHhbZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFVudGlsU2VwYXJhdG9yKHNlcCk6XQp9CgovLyBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvciByZXR1cm5zIHRoZSB0ZXh0IGFmdGVyIHRoZSBjdXJzb3IgdW50aWwgbmV4dCBzZXBhcmF0b3IuCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRXb3JkQWZ0ZXJDdXJzb3JVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBzdHJpbmcgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglyZXR1cm4geFs6ZC5GaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCldCn0KCi8vIEdldFdvcmRCZWZvcmVDdXJzb3JVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvciByZXR1cm5zIHRoZSB3b3JkIGJlZm9yZSB0aGUgY3Vyc29yLgovLyBVbmxpa2UgR2V0V29yZEJlZm9yZUN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEJlZm9yZUN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yKHNlcCBzdHJpbmcpIHN0cmluZyB7Cgl4IDo9IGQuVGV4dEJlZm9yZUN1cnNvcigpCglyZXR1cm4geFtkLkZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwKTpdCn0KCi8vIEdldFdvcmRBZnRlckN1cnNvclVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIHJldHVybnMgdGhlIHdvcmQgYWZ0ZXIgdGhlIGN1cnNvci4KLy8gVW5saWtlIEdldFdvcmRBZnRlckN1cnNvciwgaXQgcmV0dXJucyBzdHJpbmcgY29udGFpbmluZyBzcGFjZQpmdW5jIChkICpEb2N1bWVudCkgR2V0V29yZEFmdGVyQ3Vyc29yVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgc3RyaW5nIHsKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoJcmV0dXJuIHhbOmQuRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXApXQp9CgovLyBGaW5kU3RhcnRPZlByZXZpb3VzV29yZCByZXR1cm5zIGFuIGluZGV4IHJlbGF0aXZlIHRvIHRoZSBjdXJzb3IgcG9zaXRpb24KLy8gcG9pbnRpbmcgdG8gdGhlIHN0YXJ0IG9mIHRoZSBwcmV2aW91cyB3b3JkLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5MYXN0SW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpICsgMQoJfQoJcmV0dXJuIDAKfQoKLy8gRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRXaXRoU3BhY2UgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBUaGUgb25seSBkaWZmZXJlbmNlIGlzIHRvIGlnbm9yZSBjb250aWd1b3VzIHNwYWNlcy4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlKCkgaW50IHsKCXggOj0gZC5UZXh0QmVmb3JlQ3Vyc29yKCkKCWVuZCA6PSBpc3RyaW5ncy5MYXN0SW5kZXhOb3RCeXRlKHgsICcgJykKCWlmIGVuZCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEJ5dGUoeFs6ZW5kXSwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiAwCgl9CglyZXR1cm4gc3RhcnQgKyAxCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZCgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJaSA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaSArIDEKCX0KCXJldHVybiAwCn0KCi8vIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3IgaXMgYWxtb3N0IHRoZSBzYW1lIGFzIEZpbmRTdGFydE9mUHJldmlvdXNXb3JkV2l0aFNwYWNlLgovLyBCdXQgdGhpcyBjYW4gc3BlY2lmeSBTZXBhcmF0b3IuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZFN0YXJ0T2ZQcmV2aW91c1dvcmRVbnRpbFNlcGFyYXRvcklnbm9yZU5leHRUb0N1cnNvcihzZXAgc3RyaW5nKSBpbnQgewoJaWYgc2VwID09ICIiIHsKCQlyZXR1cm4gZC5GaW5kU3RhcnRPZlByZXZpb3VzV29yZFdpdGhTcGFjZSgpCgl9CgoJeCA6PSBkLlRleHRCZWZvcmVDdXJzb3IoKQoJZW5kIDo9IGlzdHJpbmdzLkxhc3RJbmRleE5vdEFueSh4LCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiAwCgl9CglzdGFydCA6PSBzdHJpbmdzLkxhc3RJbmRleEFueSh4WzplbmRdLCBzZXApCglpZiBzdGFydCA9PSAtMSB7CgkJcmV0dXJuIDAKCX0KCXJldHVybiBzdGFydCArIDEKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmQgcmV0dXJucyBhbiBpbmRleCByZWxhdGl2ZSB0byB0aGUgY3Vyc29yIHBvc2l0aW9uLgovLyBwb2ludGluZyB0byB0aGUgZW5kIG9mIHRoZSBjdXJyZW50IHdvcmQuIFJldHVybiAwIGlmIG5vdGhpbmcgd2FzIGZvdW5kLgpmdW5jIChkICpEb2N1bWVudCkgRmluZEVuZE9mQ3VycmVudFdvcmQoKSBpbnQgewoJeCA6PSBkLlRleHRBZnRlckN1cnNvcigpCglpIDo9IHN0cmluZ3MuSW5kZXhCeXRlKHgsICcgJykKCWlmIGkgIT0gLTEgewoJCXJldHVybiBpCgl9CglyZXR1cm4gbGVuKHgpCn0KCi8vIEZpbmRFbmRPZkN1cnJlbnRXb3JkV2l0aFNwYWNlIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZC4KLy8gVGhlIG9ubHkgZGlmZmVyZW5jZSBpcyB0byBpZ25vcmUgY29udGlndW91cyBzcGFjZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZSgpIGludCB7Cgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCglzdGFydCA6PSBpc3RyaW5ncy5JbmRleE5vdEJ5dGUoeCwgJyAnKQoJaWYgc3RhcnQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCgllbmQgOj0gc3RyaW5ncy5JbmRleEJ5dGUoeFtzdGFydDpdLCAnICcpCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gRmluZEVuZE9mQ3VycmVudFdvcmRVbnRpbFNlcGFyYXRvciBpcyBhbG1vc3QgdGhlIHNhbWUgYXMgRmluZEVuZE9mQ3VycmVudFdvcmQuCi8vIEJ1dCB0aGlzIGNhbiBzcGVjaWZ5IFNlcGFyYXRvci4gUmV0dXJuIDAgaWYgbm90aGluZyB3YXMgZm91bmQuCmZ1bmMgKGQgKkRvY3VtZW50KSBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9yKHNlcCBzdHJpbmcpIGludCB7CglpZiBzZXAgPT0gIiIgewoJCXJldHVybiBkLkZpbmRFbmRPZkN1cnJlbnRXb3JkKCkKCX0KCgl4IDo9IGQuVGV4dEFmdGVyQ3Vyc29yKCkKCWkgOj0gc3RyaW5ncy5JbmRleEFueSh4LCBzZXApCglpZiBpICE9IC0xIHsKCQlyZXR1cm4gaQoJfQoJcmV0dXJuIGxlbih4KQp9CgovLyBGaW5kRW5kT2ZDdXJyZW50V29yZFVudGlsU2VwYXJhdG9ySWdub3JlTmV4dFRvQ3Vyc29yIGlzIGFsbW9zdCB0aGUgc2FtZSBhcyBGaW5kRW5kT2ZDdXJyZW50V29yZFdpdGhTcGFjZS4KLy8gQnV0IHRoaXMgY2FuIHNwZWNpZnkgU2VwYXJhdG9yLiBSZXR1cm4gMCBpZiBub3RoaW5nIHdhcyBmb3VuZC4KZnVuYyAoZCAqRG9jdW1lbnQpIEZpbmRFbmRPZkN1cnJlbnRXb3JkVW50aWxTZXBhcmF0b3JJZ25vcmVOZXh0VG9DdXJzb3Ioc2VwIHN0cmluZykgaW50IHsKCWlmIHNlcCA9PSAiIiB7CgkJcmV0dXJuIGQuRmluZEVuZE9mQ3VycmVudFdvcmRXaXRoU3BhY2UoKQoJfQoKCXggOj0gZC5UZXh0QWZ0ZXJDdXJzb3IoKQoKCXN0YXJ0IDo9IGlzdHJpbmdzLkluZGV4Tm90QW55KHgsIHNlcCkKCWlmIHN0YXJ0ID09IC0xIHsKCQlyZXR1cm4gbGVuKHgpCgl9CgoJZW5kIDo9IHN0cmluZ3MuSW5kZXhBbnkoeFtzdGFydDpdLCBzZXApCglpZiBlbmQgPT0gLTEgewoJCXJldHVybiBsZW4oeCkKCX0KCglyZXR1cm4gc3RhcnQgKyBlbmQKfQoKLy8gQ3VycmVudExpbmVCZWZvcmVDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBzdGFydCBvZiB0aGUgbGluZSB1bnRpbCB0aGUgY3Vyc29yLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSBzdHJpbmcgewoJcyA6PSBzdHJpbmdzLlNwbGl0KGQuVGV4dEJlZm9yZUN1cnNvcigpLCAiXG4iKQoJcmV0dXJuIHNbbGVuKHMpLTFdCn0KCi8vIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IgcmV0dXJucyB0aGUgdGV4dCBmcm9tIHRoZSBjdXJzb3IgdW50aWwgdGhlIGVuZCBvZiB0aGUgbGluZS4KZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSBzdHJpbmcgewoJcmV0dXJuIHN0cmluZ3MuU3BsaXQoZC5UZXh0QWZ0ZXJDdXJzb3IoKSwgIlxuIilbMF0KfQoKLy8gQ3VycmVudExpbmUgcmV0dXJuIHRoZSB0ZXh0IG9uIHRoZSBsaW5lIHdoZXJlIHRoZSBjdXJzb3IgaXMuICh3aGVuIHRoZSBpbnB1dAovLyBjb25zaXN0cyBvZiBqdXN0IG9uZSBsaW5lLCBpdCBlcXVhbHMgYHRleHRgLgpmdW5jIChkICpEb2N1bWVudCkgQ3VycmVudExpbmUoKSBzdHJpbmcgewoJcmV0dXJuIGQuQ3VycmVudExpbmVCZWZvcmVDdXJzb3IoKSArIGQuQ3VycmVudExpbmVBZnRlckN1cnNvcigpCn0KCi8vIEFycmF5IHBvaW50aW5nIHRvIHRoZSBzdGFydCBpbmRleGVzIG9mIGFsbCB0aGUgbGluZXMuCmZ1bmMgKGQgKkRvY3VtZW50KSBsaW5lU3RhcnRJbmRleGVzKCkgW11pbnQgewoJLy8gVE9ETzogQ2FjaGUsIGJlY2F1c2UgdGhpcyBpcyBvZnRlbiByZXVzZWQuCgkvLyAoSWYgaXQgaXMgdXNlZCwgaXQncyBvZnRlbiB1c2VkIG1hbnkgdGltZXMuCgkvLyBBbmQgdGhpcyBoYXMgdG8gYmUgZmFzdCBmb3IgZWRpdGluZyBiaWcgZG9jdW1lbnRzISkKCWxjIDo9IGQuTGluZUNvdW50KCkKCWxlbmd0aHMgOj0gbWFrZShbXWludCwgbGMpCglmb3IgaSwgbCA6PSByYW5nZSBkLkxpbmVzKCkgewoJCWxlbmd0aHNbaV0gPSBsZW4obCkKCX0KCgkvLyBDYWxjdWxhdGUgY3VtdWxhdGl2ZSBzdW1zLgoJaW5kZXhlcyA6PSBtYWtlKFtdaW50LCBsYysxKQoJaW5kZXhlc1swXSA9IDAgLy8gaHR0cHM6Ly9naXRodWIuY29tL2pvbmF0aGFuc2xlbmRlcnMvcHl0aG9uLXByb21wdC10b29sa2l0L2Jsb2IvbWFzdGVyL3Byb21wdF90b29sa2l0L2RvY3VtZW50LnB5I0wxODkKCXBvcyA6PSAwCglmb3IgaSwgbCA6PSByYW5nZSBsZW5ndGhzIHsKCQlwb3MgKz0gbCArIDEKCQlpbmRleGVzW2krMV0gPSBwb3MKCX0KCWlmIGxjID4gMSB7CgkJLy8gUG9wIHRoZSBsYXN0IGl0ZW0uIChUaGlzIGlzIG5vdCBhIG5ldyBsaW5lLikKCQlpbmRleGVzID0gaW5kZXhlc1s6bGNdCgl9CglyZXR1cm4gaW5kZXhlcwp9CgovLyBGb3IgdGhlIGluZGV4IG9mIGEgY2hhcmFjdGVyIGF0IGEgY2VydGFpbiBsaW5lLCBjYWxjdWxhdGUgdGhlIGluZGV4IG9mCi8vIHRoZSBmaXJzdCBjaGFyYWN0ZXIgb24gdGhhdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgZmluZExpbmVTdGFydEluZGV4KGluZGV4IGludCkgKHBvcyBpbnQsIGxpbmVTdGFydEluZGV4IGludCkgewoJaW5kZXhlcyA6PSBkLmxpbmVTdGFydEluZGV4ZXMoKQoJcG9zID0gYmlzZWN0LlJpZ2h0KGluZGV4ZXMsIGluZGV4KSAtIDEKCWxpbmVTdGFydEluZGV4ID0gaW5kZXhlc1twb3NdCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Sb3cgcmV0dXJucyB0aGUgY3VycmVudCByb3cuICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uUm93KCkgKHJvdyBpbnQpIHsKCXJvdywgXyA9IGQuZmluZExpbmVTdGFydEluZGV4KGQuY3Vyc29yUG9zaXRpb24pCglyZXR1cm4KfQoKLy8gQ3Vyc29yUG9zaXRpb25Db2wgcmV0dXJucyB0aGUgY3VycmVudCBjb2x1bW4uICgwLWJhc2VkLikKZnVuYyAoZCAqRG9jdW1lbnQpIEN1cnNvclBvc2l0aW9uQ29sKCkgKGNvbCBpbnQpIHsKCS8vIERvbid0IHVzZSBzZWxmLnRleHRfYmVmb3JlX2N1cnNvciB0byBjYWxjdWxhdGUgdGhpcy4gQ3JlYXRpbmcgc3Vic3RyaW5ncwoJLy8gYW5kIHNwbGl0dGluZyBpcyB0b28gZXhwZW5zaXZlIGZvciBnZXR0aW5nIHRoZSBjdXJzb3IgcG9zaXRpb24uCglfLCBpbmRleCA6PSBkLmZpbmRMaW5lU3RhcnRJbmRleChkLmN1cnNvclBvc2l0aW9uKQoJY29sID0gZC5jdXJzb3JQb3NpdGlvbiAtIGluZGV4CglyZXR1cm4KfQoKLy8gR2V0Q3Vyc29yTGVmdFBvc2l0aW9uIHJldHVybnMgdGhlIHJlbGF0aXZlIHBvc2l0aW9uIGZvciBjdXJzb3IgbGVmdC4KZnVuYyAoZCAqRG9jdW1lbnQpIEdldEN1cnNvckxlZnRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvclJpZ2h0UG9zaXRpb24oLWNvdW50KQoJfQoJaWYgZC5DdXJzb3JQb3NpdGlvbkNvbCgpID4gY291bnQgewoJCXJldHVybiAtY291bnQKCX0KCXJldHVybiAtZC5DdXJzb3JQb3NpdGlvbkNvbCgpCn0KCi8vIEdldEN1cnNvclJpZ2h0UG9zaXRpb24gcmV0dXJucyByZWxhdGl2ZSBwb3NpdGlvbiBmb3IgY3Vyc29yIHJpZ2h0LgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yUmlnaHRQb3NpdGlvbihjb3VudCBpbnQpIGludCB7CglpZiBjb3VudCA8IDAgewoJCXJldHVybiBkLkdldEN1cnNvckxlZnRQb3NpdGlvbigtY291bnQpCgl9CglpZiBsZW4oZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpID4gY291bnQgewoJCXJldHVybiBjb3VudAoJfQoJcmV0dXJuIGxlbihkLkN1cnJlbnRMaW5lQWZ0ZXJDdXJzb3IoKSkKfQoKLy8gR2V0Q3Vyc29yVXBQb3NpdGlvbiByZXR1cm4gdGhlIHJlbGF0aXZlIGN1cnNvciBwb3NpdGlvbiAoY2hhcmFjdGVyIGluZGV4KSB3aGVyZSB3ZSB3b3VsZCBiZQovLyBpZiB0aGUgdXNlciBwcmVzc2VkIHRoZSBhcnJvdy11cCBidXR0b24uCmZ1bmMgKGQgKkRvY3VtZW50KSBHZXRDdXJzb3JVcFBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9CgoJcm93IDo9IGQuQ3Vyc29yUG9zaXRpb25Sb3coKSAtIGNvdW50CglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9CglyZXR1cm4gZC5UcmFuc2xhdGVSb3dDb2xUb0luZGV4KHJvdywgY29sKSAtIGQuY3Vyc29yUG9zaXRpb24KfQoKLy8gR2V0Q3Vyc29yRG93blBvc2l0aW9uIHJldHVybiB0aGUgcmVsYXRpdmUgY3Vyc29yIHBvc2l0aW9uIChjaGFyYWN0ZXIgaW5kZXgpIHdoZXJlIHdlIHdvdWxkIGJlIGlmIHRoZQovLyB1c2VyIHByZXNzZWQgdGhlIGFycm93LWRvd24gYnV0dG9uLgpmdW5jIChkICpEb2N1bWVudCkgR2V0Q3Vyc29yRG93blBvc2l0aW9uKGNvdW50IGludCwgcHJlZmVycmVkQ29sdW1uIGludCkgaW50IHsKCXZhciBjb2wgaW50CglpZiBwcmVmZXJyZWRDb2x1bW4gPT0gLTEgeyAvLyAtMSBtZWFucyBuaWwKCQljb2wgPSBkLkN1cnNvclBvc2l0aW9uQ29sKCkKCX0gZWxzZSB7CgkJY29sID0gcHJlZmVycmVkQ29sdW1uCgl9Cglyb3cgOj0gZC5DdXJzb3JQb3NpdGlvblJvdygpICsgY291bnQKCXJldHVybiBkLlRyYW5zbGF0ZVJvd0NvbFRvSW5kZXgocm93LCBjb2wpIC0gZC5jdXJzb3JQb3NpdGlvbgp9CgovLyBMaW5lcyByZXR1cm5zIHRoZSBhcnJheSBvZiBhbGwgdGhlIGxpbmVzLgpmdW5jIChkICpEb2N1bWVudCkgTGluZXMoKSBbXXN0cmluZyB7CgkvLyBUT0RPOiBDYWNoZSwgYmVjYXVzZSB0aGlzIG9uZSBpcyByZXVzZWQgdmVyeSBvZnRlbi4KCXJldHVybiBzdHJpbmdzLlNwbGl0KGQuVGV4dCwgIlxuIikKfQoKLy8gTGluZUNvdW50IHJldHVybiB0aGUgbnVtYmVyIG9mIGxpbmVzIGluIHRoaXMgZG9jdW1lbnQuIElmIHRoZSBkb2N1bWVudCBlbmRzCi8vIHdpdGggYSB0cmFpbGluZyBcbiwgdGhhdCBjb3VudHMgYXMgdGhlIGJlZ2lubmluZyBvZiBhIG5ldyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgTGluZUNvdW50KCkgaW50IHsKCXJldHVybiBsZW4oZC5MaW5lcygpKQp9CgovLyBUcmFuc2xhdGVJbmRleFRvUG9zaXRpb24gZ2l2ZW4gYW4gaW5kZXggZm9yIHRoZSB0ZXh0LCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgKHJvdywgY29sKSB0dXBsZS4KLy8gKDAtYmFzZWQuIFJldHVybnMgKDAsIDApIGZvciBpbmRleD0wLikKZnVuYyAoZCAqRG9jdW1lbnQpIFRyYW5zbGF0ZUluZGV4VG9Qb3NpdGlvbihpbmRleCBpbnQpIChyb3cgaW50LCBjb2wgaW50KSB7Cglyb3csIHJvd0luZGV4IDo9IGQuZmluZExpbmVTdGFydEluZGV4KGluZGV4KQoJY29sID0gaW5kZXggLSByb3dJbmRleAoJcmV0dXJuCn0KCi8vIFRyYW5zbGF0ZVJvd0NvbFRvSW5kZXggZ2l2ZW4gYSAocm93LCBjb2wpLCByZXR1cm4gdGhlIGNvcnJlc3BvbmRpbmcgaW5kZXguCi8vIChSb3cgYW5kIGNvbCBwYXJhbXMgYXJlIDAtYmFzZWQuKQpmdW5jIChkICpEb2N1bWVudCkgVHJhbnNsYXRlUm93Q29sVG9JbmRleChyb3cgaW50LCBjb2x1bW4gaW50KSAoaW5kZXggaW50KSB7CglpbmRleGVzIDo9IGQubGluZVN0YXJ0SW5kZXhlcygpCglpZiByb3cgPCAwIHsKCQlyb3cgPSAwCgl9IGVsc2UgaWYgcm93ID4gbGVuKGluZGV4ZXMpIHsKCQlyb3cgPSBsZW4oaW5kZXhlcykgLSAxCgl9CglpbmRleCA9IGluZGV4ZXNbcm93XQoJbGluZSA6PSBkLkxpbmVzKClbcm93XQoKCS8vIHB5dGhvbikgcmVzdWx0ICs9IG1heCgwLCBtaW4oY29sLCBsZW4obGluZSkpKQoJaWYgY29sdW1uID4gMCB8fCBsZW4obGluZSkgPiAwIHsKCQlpZiBjb2x1bW4gPiBsZW4obGluZSkgewoJCQlpbmRleCArPSBsZW4obGluZSkKCQl9IGVsc2UgewoJCQlpbmRleCArPSBjb2x1bW4KCQl9Cgl9CgoJLy8gS2VlcCBpbiByYW5nZS4gKGxlbihzZWxmLnRleHQpIGlzIGluY2x1ZGVkLCBiZWNhdXNlIHRoZSBjdXJzb3IgY2FuIGJlCgkvLyByaWdodCBhZnRlciB0aGUgZW5kIG9mIHRoZSB0ZXh0IGFzIHdlbGwuKQoJLy8gcHl0aG9uKSByZXN1bHQgPSBtYXgoMCwgbWluKHJlc3VsdCwgbGVuKHNlbGYudGV4dCkpKQoJaWYgaW5kZXggPiBsZW4oZC5UZXh0KSB7CgkJaW5kZXggPSBsZW4oZC5UZXh0KQoJfQoJaWYgaW5kZXggPCAwIHsKCQlpbmRleCA9IDAKCX0KCXJldHVybiBpbmRleAp9CgovLyBPbkxhc3RMaW5lIHJldHVybnMgdHJ1ZSB3aGVuIHdlIGFyZSBhdCB0aGUgbGFzdCBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgT25MYXN0TGluZSgpIGJvb2wgewoJcmV0dXJuIGQuQ3Vyc29yUG9zaXRpb25Sb3coKSA9PSAoZC5MaW5lQ291bnQoKSAtIDEpCn0KCi8vIEdldEVuZE9mTGluZVBvc2l0aW9uIHJldHVybnMgcmVsYXRpdmUgcG9zaXRpb24gZm9yIHRoZSBlbmQgb2YgdGhpcyBsaW5lLgpmdW5jIChkICpEb2N1bWVudCkgR2V0RW5kT2ZMaW5lUG9zaXRpb24oKSBpbnQgewoJcmV0dXJuIGxlbihbXXJ1bmUoZC5DdXJyZW50TGluZUFmdGVyQ3Vyc29yKCkpKQp9CgpmdW5jIChkICpEb2N1bWVudCkgbGVhZGluZ1doaXRlc3BhY2VJbkN1cnJlbnRMaW5lKCkgKG1hcmdpbiBzdHJpbmcpIHsKCXRyaW1tZWQgOj0gc3RyaW5ncy5UcmltU3BhY2UoZC5DdXJyZW50TGluZSgpKQoJbWFyZ2luID0gZC5DdXJyZW50TGluZSgpWzpsZW4oZC5DdXJyZW50TGluZSgpKS1sZW4odHJpbW1lZCldCglyZXR1cm4KfQo=", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/task.toml b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..054c6c096dd946ee11ab22c5518928102b9841b8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/task.toml
@@ -0,0 +1,11 @@
+version = "1.0"
+[agent]
+timeout_sec = 300.0
+[verifier]
+timeout_sec = 300.0
+environment_mode = "shared"
+[environment]
+docker_image = "ghcr.io/younesbelkada/scale800@sha256:941c3a84e45c4f0dffb059a437eb22326fc7ff84ec4b1e45f3951fd0152c6c35"
+cpus = 1
+memory_mb = 2048
+storage_mb = 4096
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/buffer_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dceb3ce6aa7f5de6cc187bfe9ee3466f09cbe163
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/buffer_test.go
@@ -0,0 +1,198 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNewBuffer(t *testing.T) {
+ b := NewBuffer()
+ if b.workingIndex != 0 {
+ t.Errorf("workingIndex should be %#v, got %#v", 0, b.workingIndex)
+ }
+ if !reflect.DeepEqual(b.workingLines, []string{""}) {
+ t.Errorf("workingLines should be %#v, got %#v", []string{""}, b.workingLines)
+ }
+}
+
+func TestBuffer_InsertText(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ if b.Text() != "some_text" {
+ t.Errorf("Text should be %#v, got %#v", "some_text", b.Text())
+ }
+
+ if b.cursorPosition != len("some_text") {
+ t.Errorf("cursorPosition should be %#v, got %#v", len("some_text"), b.cursorPosition)
+ }
+}
+
+func TestBuffer_CursorMovement(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+
+ b.CursorLeft(1)
+ b.CursorLeft(2)
+ b.CursorRight(1)
+ b.InsertText("A", false, true)
+ if b.Text() != "some_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("some_teA") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // Moving over left character counts.
+ b.CursorLeft(100)
+ b.InsertText("A", false, true)
+ if b.Text() != "Asome_teAxt" {
+ t.Errorf("Text should be %#v, got %#v", "some_teAxt", b.Text())
+ }
+ if b.cursorPosition != len("A") {
+ t.Errorf("Text should be %#v, got %#v", len("some_teA"), b.cursorPosition)
+ }
+
+ // TODO: Going right already at right end.
+}
+
+func TestBuffer_CursorMovement_WithMultiByte(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("あいうえお", false, true)
+ b.CursorLeft(1)
+ if l := b.Document().TextAfterCursor(); l != "お" {
+ t.Errorf("Should be 'お', but got %s", l)
+ }
+}
+
+func TestBuffer_CursorUp(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("long line1\nline2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up when already at the top.
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+
+ // Going up to a line that's shorter.
+ b.setDocument(&Document{})
+ b.InsertText("line1\nlong line2", false, true)
+ b.CursorUp(1)
+ if b.Document().cursorPosition != 5 {
+ t.Errorf("Should be %#v, got %#v", 5, b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_CursorDown(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2", false, true)
+ b.cursorPosition = 3
+
+ // Normally going down
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("line1\nlin") {
+ t.Errorf("Should be %#v, got %#v", len("line1\nlin"), b.Document().cursorPosition)
+ }
+
+ // Going down to a line that's storter.
+ b = NewBuffer()
+ b.InsertText("long line1\na\nb", false, true)
+ b.cursorPosition = 3
+ b.CursorDown(1)
+ if b.Document().cursorPosition != len("long line1\na") {
+ t.Errorf("Should be %#v, got %#v", len("long line1\na"), b.Document().cursorPosition)
+ }
+}
+
+func TestBuffer_DeleteBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("some_text", false, true)
+ b.CursorLeft(2)
+ deleted := b.DeleteBeforeCursor(1)
+
+ if b.Text() != "some_txt" {
+ t.Errorf("Should be %#v, got %#v", "some_txt", b.Text())
+ }
+ if deleted != "e" {
+ t.Errorf("Should be %#v, got %#v", deleted, "e")
+ }
+ if b.cursorPosition != len("some_t") {
+ t.Errorf("Should be %#v, got %#v", len("some_t"), b.cursorPosition)
+ }
+
+ // Delete over the characters length before cursor.
+ deleted = b.DeleteBeforeCursor(100)
+ if deleted != "some_t" {
+ t.Errorf("Should be %#v, got %#v", "some_t", deleted)
+ }
+ if b.Text() != "xt" {
+ t.Errorf("Should be %#v, got %#v", "xt", b.Text())
+ }
+
+ // If cursor position is a beginning of line, it has no effect.
+ deleted = b.DeleteBeforeCursor(1)
+ if deleted != "" {
+ t.Errorf("Should be empty, got %#v", deleted)
+ }
+}
+
+func TestBuffer_NewLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(false)
+ ac := b.Text()
+ ex := " hello\n"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ b = NewBuffer()
+ b.InsertText(" hello", false, true)
+ b.NewLine(true)
+ ac = b.Text()
+ ex = " hello\n "
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_JoinNextLine(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("line1\nline2\nline3", false, true)
+ b.CursorUp(1)
+ b.JoinNextLine(" ")
+
+ ac := b.Text()
+ ex := "line1\nline2 line3"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ // Test when there is no '\n' in the text
+ b = NewBuffer()
+ b.InsertText("line1", false, true)
+ b.cursorPosition = 0
+ b.JoinNextLine(" ")
+ ac = b.Text()
+ ex = "line1"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestBuffer_SwapCharactersBeforeCursor(t *testing.T) {
+ b := NewBuffer()
+ b.InsertText("hello world", false, true)
+ b.CursorLeft(2)
+ b.SwapCharactersBeforeCursor()
+ ac := b.Text()
+ ex := "hello wrold"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/completion_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/completion_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b66347a9c4479380dffab1cb08aeb09c1a087c2
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/completion_test.go
@@ -0,0 +1,206 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFormatShortSuggestion(t *testing.T) {
+ var scenarioTable = []struct {
+ in []Suggest
+ expected []Suggest
+ max int
+ exWidth int
+ }{
+ {
+ in: []Suggest{
+ {Text: "foo"},
+ {Text: "bar"},
+ {Text: "fuga"},
+ },
+ expected: []Suggest{
+ {Text: " foo "},
+ {Text: " bar "},
+ {Text: " fuga "},
+ },
+ max: 100,
+ exWidth: 6,
+ },
+ {
+ in: []Suggest{
+ {Text: "apple", Description: "This is apple."},
+ {Text: "banana", Description: "This is banana."},
+ {Text: "coconut", Description: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " apple ", Description: " This is apple. "},
+ {Text: " banana ", Description: " This is banana. "},
+ {Text: " coconut ", Description: " This is coconut. "},
+ },
+ max: 100,
+ exWidth: len(" apple " + " This is apple. "),
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ {Text: " Thi... "},
+ },
+ max: 8,
+ exWidth: 8,
+ },
+ {
+ in: []Suggest{
+ {Text: "This is apple."},
+ {Text: "This is banana."},
+ {Text: "This is coconut."},
+ },
+ expected: []Suggest{},
+ max: 3,
+ exWidth: 0,
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "-------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--allow-missing-template-keys", Description: "-----------------------------------------------------------------------------------------------------------------------------------------------"},
+ {Text: "--export", Description: "----------------------------------------------------------------------------------------------------------"},
+ {Text: "-f", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--filename", Description: "-----------------------------------------------------------------------------------"},
+ {Text: "--include-extended-apis", Description: "------------------------------------------------------------------------------------"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " --------------... "},
+ {Text: " --allow-missing-template-keys ", Description: " --------------... "},
+ {Text: " --export ", Description: " --------------... "},
+ {Text: " -f ", Description: " --------------... "},
+ {Text: " --filename ", Description: " --------------... "},
+ {Text: " --include-extended-apis ", Description: " --------------... "},
+ },
+ max: 50,
+ exWidth: len(" --include-extended-apis " + " ---------------..."),
+ },
+ {
+ in: []Suggest{
+ {Text: "--all-namespaces", Description: "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace."},
+ {Text: "--allow-missing-template-keys", Description: "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats."},
+ {Text: "--export", Description: "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information."},
+ {Text: "-f", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--filename", Description: "Filename, directory, or URL to files identifying the resource to get from a server."},
+ {Text: "--include-extended-apis", Description: "If true, include definitions of new APIs via calls to the API server. [default true]"},
+ },
+ expected: []Suggest{
+ {Text: " --all-namespaces ", Description: " If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. "},
+ {Text: " --allow-missing-template-keys ", Description: " If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. "},
+ {Text: " --export ", Description: " If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. "},
+ {Text: " -f ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --filename ", Description: " Filename, directory, or URL to files identifying the resource to get from a server. "},
+ {Text: " --include-extended-apis ", Description: " If true, include definitions of new APIs via calls to the API server. [default true] "},
+ },
+ max: 500,
+ exWidth: len(" --include-extended-apis " + " If true, include definitions of new APIs via calls to the API server. [default true] "),
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatSuggestions(s.in, s.max)
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
+
+func TestFormatText(t *testing.T) {
+ var scenarioTable = []struct {
+ in []string
+ expected []string
+ max int
+ exWidth int
+ }{
+ {
+ in: []string{
+ "",
+ "",
+ },
+ expected: []string{
+ "",
+ "",
+ },
+ max: 10,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: 2,
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ "",
+ "",
+ "",
+ },
+ max: len(" " + " " + shortenSuffix),
+ exWidth: 0,
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " apple ",
+ " banana ",
+ " coconut ",
+ },
+ max: 100,
+ exWidth: len(" coconut "),
+ },
+ {
+ in: []string{
+ "apple",
+ "banana",
+ "coconut",
+ },
+ expected: []string{
+ " a... ",
+ " b... ",
+ " c... ",
+ },
+ max: 6,
+ exWidth: 6,
+ },
+ }
+
+ for i, s := range scenarioTable {
+ actual, width := formatTexts(s.in, s.max, " ", " ")
+ if width != s.exWidth {
+ t.Errorf("[scenario %d] Want %d but got %d\n", i, s.exWidth, width)
+ }
+ if !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("[scenario %d] Want %#v, but got %#v\n", i, s.expected, actual)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/document_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/document_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f273b7b6d5caccd3a32d882c24a94dc3a6cc8b0
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/document_test.go
@@ -0,0 +1,1255 @@
+package prompt
+
+import (
+ "fmt"
+ "reflect"
+ "testing"
+ "unicode/utf8"
+)
+
+func ExampleDocument_CurrentLine() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLine())
+ // Output:
+ // This is a example of Document component.
+}
+
+func ExampleDocument_DisplayCursorPosition() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.`,
+ cursorPosition: len(`Hello`),
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 5
+}
+
+func ExampleDocument_CursorPositionRow() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionRow", d.CursorPositionRow())
+ // Output:
+ // CursorPositionRow 1
+}
+
+func ExampleDocument_CursorPositionCol() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println("CursorPositionCol", d.CursorPositionCol())
+ // Output:
+ // CursorPositionCol 14
+}
+
+func ExampleDocument_TextBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextBeforeCursor())
+ // Output:
+ // Hello! my name is c-bata.
+ // This is a exam
+}
+
+func ExampleDocument_TextAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.TextAfterCursor())
+ // Output:
+ // ple of Document component.
+ // This component has texts displayed in terminal and cursor position.
+}
+
+func ExampleDocument_DisplayCursorPosition_withJapanese() {
+ d := &Document{
+ Text: `こんにちは、芝田 将です。`,
+ cursorPosition: 3,
+ }
+ fmt.Println("DisplayCursorPosition", d.DisplayCursorPosition())
+ // Output:
+ // DisplayCursorPosition 6
+}
+
+func ExampleDocument_CurrentLineBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineBeforeCursor())
+ // Output:
+ // This is a exam
+}
+
+func ExampleDocument_CurrentLineAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+This component has texts displayed in terminal and cursor position.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.CurrentLineAfterCursor())
+ // Output:
+ // ple of Document component.
+}
+
+func ExampleDocument_GetWordBeforeCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordBeforeCursor())
+ // Output:
+ // exam
+}
+
+func ExampleDocument_GetWordAfterCursor() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a exam`),
+ }
+ fmt.Println(d.GetWordAfterCursor())
+ // Output:
+ // ple
+}
+
+func ExampleDocument_GetWordBeforeCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a example `),
+ }
+ fmt.Println(d.GetWordBeforeCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordAfterCursorWithSpace() {
+ d := &Document{
+ Text: `Hello! my name is c-bata.
+This is a example of Document component.
+`,
+ cursorPosition: len(`Hello! my name is c-bata.
+This is a`),
+ }
+ fmt.Println(d.GetWordAfterCursorWithSpace())
+ // Output:
+ // example
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata`,
+ cursorPosition: len(`hello,i am c`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparator(","))
+ // Output:
+ // i am c
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparator() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i a`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparator(","))
+ // Output:
+ // m c-bata
+}
+
+func ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello,i am c-bata,`),
+ }
+ fmt.Println(d.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // i am c-bata,
+}
+
+func ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor() {
+ d := &Document{
+ Text: `hello,i am c-bata,thank you for using go-prompt`,
+ cursorPosition: len(`hello`),
+ }
+ fmt.Println(d.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(","))
+ // Output:
+ // ,i am c-bata
+}
+
+func TestDocument_DisplayCursorPosition(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected int
+ }{
+ {
+ document: &Document{
+ Text: "hello",
+ cursorPosition: 2,
+ },
+ expected: 2,
+ },
+ {
+ document: &Document{
+ Text: "こんにちは",
+ cursorPosition: 2,
+ },
+ expected: 4,
+ },
+ {
+ // If you're facing test failure on this test case and your terminal is iTerm2,
+ // please check 'Profile -> Text' configuration. 'Use Unicode version 9 widths'
+ // must be checked.
+ // https://github.com/c-bata/go-prompt/pull/99
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, p := range patterns {
+ ac := p.document.DisplayCursorPosition()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetCharRelativeToCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len([]rune("line 1\n" + "lin")),
+ },
+ expected: "e",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "く",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "н",
+ },
+ }
+
+ for i, p := range patterns {
+ ac := p.document.GetCharRelativeToCursor(1)
+ ex, _ := utf8.DecodeRuneInString(p.expected)
+ if ac != ex {
+ t.Errorf("[%d] Should be %s, got %s", i, string(ex), string(ac))
+ }
+ }
+}
+
+func TestDocument_TextBeforeCursor(t *testing.T) {
+ patterns := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "line 1\nlin",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "あいうえお\nかき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "Добрый\nде",
+ },
+ }
+ for i, p := range patterns {
+ ac := p.document.TextBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %s, got %s", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_TextAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ }{
+ {
+ document: &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ },
+ expected: "e 2\nline 3\nline 4\n",
+ },
+ {
+ document: &Document{
+ Text: "",
+ cursorPosition: 0,
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n",
+ cursorPosition: 8,
+ },
+ expected: "くけこ\nさしすせそ\nたちつてと\n",
+ },
+ {
+ document: &Document{
+ Text: "Добрый\nдень\nДобрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь\nДобрый день",
+ },
+ }
+
+ for i, p := range pattern {
+ ac := p.document.TextAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: "foo.json",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple banana orange",
+ cursorPosition: len("apple ba"),
+ },
+ expected: "ba",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "fi",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "かき",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "де",
+ },
+ }
+
+ for i, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", i, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordBeforeCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: "bana ",
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to/file/",
+ cursorPosition: len("apply -f /path/to/file/"),
+ },
+ expected: "file/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: "apple ",
+ },
+ {
+ document: &Document{
+ Text: "path/",
+ cursorPosition: len("path/"),
+ },
+ expected: "path/",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12,
+ },
+ expected: "かきくけこ ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: "день ",
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordBeforeCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./file/foo.json"),
+ },
+ expected: len("apply -f ./file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("apply -f ./"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8, // between 'き' and 'く'
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWord()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindStartOfPreviousWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana ",
+ cursorPosition: len("apple bana "),
+ },
+ expected: len("apple "),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo/",
+ cursorPosition: len("apply -f /file/foo/"),
+ },
+ expected: len("apply -f /file/"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple ",
+ cursorPosition: len("apple "),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "file/",
+ cursorPosition: len("file/"),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ ",
+ cursorPosition: 12, // cursor points to last
+ },
+ expected: len("あいうえお "), // this function returns index byte in string
+ },
+ {
+ document: &Document{
+ Text: "Добрый день ",
+ cursorPosition: 12,
+ },
+ expected: len("Добрый "), // this function returns index byte in string
+ },
+ }
+
+ for _, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindStartOfPreviousWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ ac = p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("Should be %#v, got %#v", p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursor(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./fi"),
+ },
+ expected: "le",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: "",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 8,
+ },
+ expected: "くけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 9,
+ },
+ expected: "нь",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursor()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_GetWordAfterCursorWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected string
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: "",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: "bana",
+ },
+ {
+ document: &Document{
+ Text: "/path/to",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "/path/to/file",
+ cursorPosition: len("/path/"),
+ },
+ expected: "to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: " bana",
+ },
+ {
+ document: &Document{
+ Text: "path/to",
+ cursorPosition: len("path"),
+ },
+ expected: "/to",
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: "ple",
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ さしすせそ",
+ cursorPosition: 5,
+ },
+ expected: " かきくけこ",
+ },
+ {
+ document: &Document{
+ Text: "Добрый день Добрый день",
+ cursorPosition: 6,
+ },
+ expected: " день",
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.GetWordAfterCursorWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWord(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ./"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apply -f ./file/foo.json",
+ cursorPosition: len("apply -f ."),
+ },
+ expected: len(""),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ // りん(cursor)ご ばなな
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 2,
+ },
+ expected: len("ご"),
+ },
+ {
+ document: &Document{
+ Text: "りんご ばなな",
+ cursorPosition: 3,
+ },
+ expected: 0,
+ },
+ {
+ // Доб(cursor)рый день
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 3,
+ },
+ expected: len("рый"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWord()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparator("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparator(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_FindEndOfCurrentWordWithSpace(t *testing.T) {
+ pattern := []struct {
+ document *Document
+ expected int
+ sep string
+ }{
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple bana"),
+ },
+ expected: len(""),
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple "),
+ },
+ expected: len("bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /file/foo.json",
+ cursorPosition: len("apply -f /"),
+ },
+ expected: len("file"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("apple"),
+ },
+ expected: len(" bana"),
+ },
+ {
+ document: &Document{
+ Text: "apply -f /path/to",
+ cursorPosition: len("apply -f /path"),
+ },
+ expected: len("/to"),
+ sep: " /",
+ },
+ {
+ document: &Document{
+ Text: "apple bana",
+ cursorPosition: len("ap"),
+ },
+ expected: len("ple"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 6,
+ },
+ expected: len("かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "あいうえお かきくけこ",
+ cursorPosition: 5,
+ },
+ expected: len(" かきくけこ"),
+ },
+ {
+ document: &Document{
+ Text: "Добрый день",
+ cursorPosition: 6,
+ },
+ expected: len(" день"),
+ },
+ }
+
+ for k, p := range pattern {
+ if p.sep == "" {
+ ac := p.document.FindEndOfCurrentWordWithSpace()
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ ac = p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor("")
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ } else {
+ ac := p.document.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(p.sep)
+ if ac != p.expected {
+ t.Errorf("[%d] Should be %#v, got %#v", k, p.expected, ac)
+ }
+ }
+ }
+}
+
+func TestDocument_CurrentLineBeforeCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineBeforeCursor()
+ ex := "lin"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLineAfterCursor(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLineAfterCursor()
+ ex := "e 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CurrentLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.CurrentLine()
+ ex := "line 2"
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_CursorPositionRowAndCol(t *testing.T) {
+ var cursorPositionTests = []struct {
+ document *Document
+ expectedRow int
+ expectedCol int
+ }{
+ {
+ document: &Document{Text: "line 1\nline 2\nline 3\n", cursorPosition: len("line 1\n" + "lin")},
+ expectedRow: 1,
+ expectedCol: 3,
+ },
+ {
+ document: &Document{Text: "", cursorPosition: 0},
+ expectedRow: 0,
+ expectedCol: 0,
+ },
+ }
+ for _, test := range cursorPositionTests {
+ ac := test.document.CursorPositionRow()
+ if ac != test.expectedRow {
+ t.Errorf("Should be %#v, got %#v", test.expectedRow, ac)
+ }
+ ac = test.document.CursorPositionCol()
+ if ac != test.expectedCol {
+ t.Errorf("Should be %#v, got %#v", test.expectedCol, ac)
+ }
+ }
+}
+
+func TestDocument_GetCursorLeftPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorLeftPosition(2)
+ ex := -2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorLeftPosition(10)
+ ex = -3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorUpPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorUpPosition(2, -1)
+ ex := len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorUpPosition(100, -1)
+ ex = len("lin") - len("line 1\n"+"line 2\n"+"lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorDownPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("lin"),
+ }
+ ac := d.GetCursorDownPosition(2, -1)
+ ex := len("line 1\n"+"line 2\n"+"lin") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+
+ ac = d.GetCursorDownPosition(100, -1)
+ ex = len("line 1\n"+"line 2\n"+"line 3\n"+"line 4\n") - len("lin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_GetCursorRightPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "line 2\n" + "lin"),
+ }
+ ac := d.GetCursorRightPosition(2)
+ ex := 2
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.GetCursorRightPosition(10)
+ ex = 3
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_Lines(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.Lines()
+ ex := []string{"line 1", "line 2", "line 3", "line 4", ""}
+ if !reflect.DeepEqual(ac, ex) {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_LineCount(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.LineCount()
+ ex := 5
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_TranslateIndexToPosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ row, col := d.TranslateIndexToPosition(len("line 1\nline 2\nlin"))
+ if row != 2 {
+ t.Errorf("Should be %#v, got %#v", 2, row)
+ }
+ if col != 3 {
+ t.Errorf("Should be %#v, got %#v", 3, col)
+ }
+ row, col = d.TranslateIndexToPosition(0)
+ if row != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, row)
+ }
+ if col != 0 {
+ t.Errorf("Should be %#v, got %#v", 0, col)
+ }
+}
+
+func TestDocument_TranslateRowColToIndex(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3\nline 4\n",
+ cursorPosition: len("line 1\n" + "lin"),
+ }
+ ac := d.TranslateRowColToIndex(2, 3)
+ ex := len("line 1\nline 2\nlin")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+ ac = d.TranslateRowColToIndex(0, 0)
+ ex = 0
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
+
+func TestDocument_OnLastLine(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nline"),
+ }
+ ac := d.OnLastLine()
+ if ac {
+ t.Errorf("Should be %#v, got %#v", false, ac)
+ }
+ d.cursorPosition = len("line 1\nline 2\nline")
+ ac = d.OnLastLine()
+ if !ac {
+ t.Errorf("Should be %#v, got %#v", true, ac)
+ }
+}
+
+func TestDocument_GetEndOfLinePosition(t *testing.T) {
+ d := &Document{
+ Text: "line 1\nline 2\nline 3",
+ cursorPosition: len("line 1\nli"),
+ }
+ ac := d.GetEndOfLinePosition()
+ ex := len("ne 2")
+ if ac != ex {
+ t.Errorf("Should be %#v, got %#v", ex, ac)
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/emacs_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/emacs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfda59e6034e5d31ff65bc4aec4d4f13957bd3c4
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/emacs_test.go
@@ -0,0 +1,32 @@
+package prompt
+
+import "testing"
+
+func TestEmacsKeyBindings(t *testing.T) {
+ buf := NewBuffer()
+ buf.InsertText("abcde", false, true)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+
+ // Go to the beginning of the line
+ applyEmacsKeyBind(buf, ControlA)
+ if buf.cursorPosition != 0 {
+ t.Errorf("Want %d, but got %d", 0, buf.cursorPosition)
+ }
+
+ // Go to the end of the line
+ applyEmacsKeyBind(buf, ControlE)
+ if buf.cursorPosition != len("abcde") {
+ t.Errorf("Want %d, but got %d", len("abcde"), buf.cursorPosition)
+ }
+}
+
+func applyEmacsKeyBind(buf *Buffer, key Key) {
+ for i := range emacsKeyBindings {
+ kb := emacsKeyBindings[i]
+ if kb.Key == key {
+ kb.Fn(buf)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/filter_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/filter_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e111a9e4cd6da8b526d0a1be70a37294e59d94a8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/filter_test.go
@@ -0,0 +1,164 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilter(t *testing.T) {
+ var scenarioTable = []struct {
+ scenario string
+ filter Filter
+ list []Suggest
+ substr string
+ ignoreCase bool
+ expected []Suggest
+ }{
+ {
+ scenario: "Contains don't ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Contains ignore case",
+ filter: FilterContains,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "cd",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasPrefix don't ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fghij"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasPrefix ignore case",
+ filter: FilterHasPrefix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fabcj"},
+ {Text: "ABCDE"},
+ },
+ substr: "abc",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "HasSuffix don't ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "HasSuffix ignore case",
+ filter: FilterHasSuffix,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "cde",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ {
+ scenario: "Fuzzy don't ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: false,
+ expected: []Suggest{
+ {Text: "abcde"},
+ },
+ },
+ {
+ scenario: "Fuzzy ignore case",
+ filter: FilterFuzzy,
+ list: []Suggest{
+ {Text: "abcde"},
+ {Text: "fcdej"},
+ {Text: "ABCDE"},
+ },
+ substr: "ae",
+ ignoreCase: true,
+ expected: []Suggest{
+ {Text: "abcde"},
+ {Text: "ABCDE"},
+ },
+ },
+ }
+
+ for _, s := range scenarioTable {
+ if actual := s.filter(s.list, s.substr, s.ignoreCase); !reflect.DeepEqual(actual, s.expected) {
+ t.Errorf("%s: Should be %#v, but got %#v", s.scenario, s.expected, actual)
+ }
+ }
+}
+
+func TestFuzzyMatch(t *testing.T) {
+ tests := []struct {
+ s string
+ sub string
+ match bool
+ }{
+ {"dog house", "dog", true},
+ {"dog house", "", true},
+ {"", "", true},
+ {"this is much longer", "hhg", true},
+ {"this is much longer", "hhhg", false},
+ {"long", "longer", false},
+ {"can we do unicode 文字 with this 今日", "文字今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字tt今日", true},
+ {"can we do unicode 文字 with this 今日", "d文字ttt今日", false},
+ }
+
+ for _, test := range tests {
+ if fuzzyMatch(test.s, test.sub) != test.match {
+ t.Errorf("fuzzymatch, %s in %s: expected %v, got %v", test.sub, test.s, test.match, !test.match)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/history_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/history_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf638699d7e2e9d96c03253986b04c9aa71e49c8
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/history_test.go
@@ -0,0 +1,62 @@
+package prompt
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestHistoryClear(t *testing.T) {
+ h := NewHistory()
+ h.Add("foo")
+ h.Clear()
+ expected := &History{
+ histories: []string{"foo"},
+ tmp: []string{"foo", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(expected, h) {
+ t.Errorf("Should be %#v, but got %#v", expected, h)
+ }
+}
+
+func TestHistoryAdd(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+ expected := &History{
+ histories: []string{"echo 1"},
+ tmp: []string{"echo 1", ""},
+ selected: 1,
+ }
+ if !reflect.DeepEqual(h, expected) {
+ t.Errorf("Should be %v, but got %v", expected, h)
+ }
+}
+
+func TestHistoryOlder(t *testing.T) {
+ h := NewHistory()
+ h.Add("echo 1")
+
+ // Prepare buffer
+ buf := NewBuffer()
+ buf.InsertText("echo 2", false, true)
+
+ // [1 time] Call Older function
+ buf1, changed := h.Older(buf)
+ if !changed {
+ t.Error("Should be changed history but not changed.")
+ }
+ if buf1.Text() != "echo 1" {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text())
+ }
+
+ // [2 times] Call Older function
+ buf = NewBuffer()
+ buf.InsertText("echo 1", false, true)
+ buf2, changed := h.Older(buf)
+ if changed {
+ t.Error("Should be not changed history but changed.")
+ }
+ if !reflect.DeepEqual("echo 1", buf2.Text()) {
+ t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text())
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/input_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/input_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf064a5c5c660542be74c8e36de57657133b50c9
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/input_test.go
@@ -0,0 +1,33 @@
+package prompt
+
+import (
+ "testing"
+)
+
+func TestPosixParserGetKey(t *testing.T) {
+ scenarioTable := []struct {
+ name string
+ input []byte
+ expected Key
+ }{
+ {
+ name: "escape",
+ input: []byte{0x1b},
+ expected: Escape,
+ },
+ {
+ name: "undefined",
+ input: []byte{'a'},
+ expected: NotDefined,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ t.Run(s.name, func(t *testing.T) {
+ key := GetKey(s.input)
+ if key != s.expected {
+ t.Errorf("Should be %s, but got %s", key, s.expected)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/internal/bisect/bisect_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/internal/bisect/bisect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d52a298e2579b433de32d268cce2c301b5df811
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/internal/bisect/bisect_test.go
@@ -0,0 +1,50 @@
+package bisect_test
+
+import (
+ "fmt"
+ "math/rand"
+ "testing"
+
+ "github.com/c-bata/go-prompt/internal/bisect"
+)
+
+func Example() {
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+ fmt.Println("Insertion position for 0 in the slice is", bisect.Right(in, 0))
+ fmt.Println("Insertion position for 4 in the slice is", bisect.Right(in, 4))
+
+ // Output:
+ // Insertion position for 0 in the slice is 0
+ // Insertion position for 4 in the slice is 5
+}
+
+func TestBisectRight(t *testing.T) {
+ // Thanks!! https://play.golang.org/p/y9NRj_XVIW
+ in := []int{1, 2, 3, 3, 3, 6, 7}
+
+ r := bisect.Right(in, 0)
+ if r != 0 {
+ t.Errorf("number 0 should inserted at 0 position, but got %d", r)
+ }
+
+ r = bisect.Right(in, 4)
+ if r != 5 {
+ t.Errorf("number 4 should inserted at 5 position, but got %d", r)
+ }
+}
+
+func BenchmarkRight(b *testing.B) {
+ rand.Seed(0)
+
+ for _, l := range []int{10, 1e2, 1e3, 1e4} {
+ x := rand.Perm(l)
+ insertion := rand.Int()
+
+ b.Run(fmt.Sprintf("arrayLength=%d", l), func(b *testing.B) {
+ b.ResetTimer()
+ for n := 0; n < b.N; n++ {
+ bisect.Right(x, insertion)
+ }
+ })
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/internal/strings/strings_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/internal/strings/strings_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9bc9cede6c4fc7299f762ad2cd2e301b00f26
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/internal/strings/strings_test.go
@@ -0,0 +1,47 @@
+package strings_test
+
+import (
+ "fmt"
+
+ "github.com/c-bata/go-prompt/internal/strings"
+)
+
+func ExampleIndexNotByte() {
+ fmt.Println(strings.IndexNotByte("golang", 'g'))
+ fmt.Println(strings.IndexNotByte("golang", 'x'))
+ fmt.Println(strings.IndexNotByte("gggggg", 'g'))
+ // Output:
+ // 1
+ // 0
+ // -1
+}
+
+func ExampleLastIndexNotByte() {
+ fmt.Println(strings.LastIndexNotByte("golang", 'g'))
+ fmt.Println(strings.LastIndexNotByte("golang", 'x'))
+ fmt.Println(strings.LastIndexNotByte("gggggg", 'g'))
+ // Output:
+ // 4
+ // 5
+ // -1
+}
+
+func ExampleIndexNotAny() {
+ fmt.Println(strings.IndexNotAny("golang", "glo"))
+ fmt.Println(strings.IndexNotAny("golang", "gl"))
+ fmt.Println(strings.IndexNotAny("golang", "golang"))
+ // Output:
+ // 3
+ // 1
+ // -1
+}
+
+func ExampleLastIndexNotAny() {
+ fmt.Println(strings.LastIndexNotAny("golang", "agn"))
+ fmt.Println(strings.LastIndexNotAny("golang", "an"))
+ fmt.Println(strings.LastIndexNotAny("golang", "golang"))
+ // Output:
+ // 2
+ // 5
+ // -1
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/output_vt100_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/output_vt100_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591607ca5dfe57551df981f9fbf5343bb07ad85a
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/output_vt100_test.go
@@ -0,0 +1,81 @@
+package prompt
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestVT100WriterWrite(t *testing.T) {
+ scenarioTable := []struct {
+ input []byte
+ expected []byte
+ }{
+ {
+ input: []byte{0x1b},
+ expected: []byte{'?'},
+ },
+ {
+ input: []byte{'a'},
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.Write(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{'?'},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
+
+func TestVT100WriterWriteRawStr(t *testing.T) {
+ scenarioTable := []struct {
+ input string
+ expected []byte
+ }{
+ {
+ input: "\x1b",
+ expected: []byte{0x1b},
+ },
+ {
+ input: "a",
+ expected: []byte{'a'},
+ },
+ }
+
+ for _, s := range scenarioTable {
+ pw := &VT100Writer{}
+ pw.WriteRawStr(s.input)
+
+ if !bytes.Equal(pw.buffer, s.expected) {
+ t.Errorf("Should be %+#v, but got %+#v", pw.buffer, s.expected)
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/render_test.go b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/render_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0d9fa8a349a34820d463ecfd68cab4558ee3b8cd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/frozen/render_test.go
@@ -0,0 +1,115 @@
+// +build !windows
+
+package prompt
+
+import (
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestFormatCompletion(t *testing.T) {
+ scenarioTable := []struct {
+ scenario string
+ completions []Suggest
+ prefix string
+ suffix string
+ expected []Suggest
+ maxWidth int
+ expectedWidth int
+ }{
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select"},
+ {Text: "from"},
+ {Text: "insert"},
+ {Text: "where"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select "},
+ {Text: " from "},
+ {Text: " insert "},
+ {Text: " where "},
+ },
+ maxWidth: 20,
+ expectedWidth: 8,
+ },
+ {
+ scenario: "",
+ completions: []Suggest{
+ {Text: "select", Description: "select description"},
+ {Text: "from", Description: "from description"},
+ {Text: "insert", Description: "insert description"},
+ {Text: "where", Description: "where description"},
+ },
+ prefix: " ",
+ suffix: " ",
+ expected: []Suggest{
+ {Text: " select ", Description: " select description "},
+ {Text: " from ", Description: " from description "},
+ {Text: " insert ", Description: " insert description "},
+ {Text: " where ", Description: " where description "},
+ },
+ maxWidth: 40,
+ expectedWidth: 28,
+ },
+ }
+
+ for _, s := range scenarioTable {
+ ac, width := formatSuggestions(s.completions, s.maxWidth)
+ if !reflect.DeepEqual(ac, s.expected) {
+ t.Errorf("Should be %#v, but got %#v", s.expected, ac)
+ }
+ if width != s.expectedWidth {
+ t.Errorf("Should be %#v, but got %#v", s.expectedWidth, width)
+ }
+ }
+}
+
+func TestBreakLineCallback(t *testing.T) {
+ var i int
+ r := &Render{
+ prefix: "> ",
+ out: &PosixWriter{
+ fd: syscall.Stdin, // "write" to stdin just so we don't mess with the output of the tests
+ },
+ livePrefixCallback: func() (string, bool) { return "", false },
+ prefixTextColor: Blue,
+ prefixBGColor: DefaultColor,
+ inputTextColor: DefaultColor,
+ inputBGColor: DefaultColor,
+ previewSuggestionTextColor: Green,
+ previewSuggestionBGColor: DefaultColor,
+ suggestionTextColor: White,
+ suggestionBGColor: Cyan,
+ selectedSuggestionTextColor: Black,
+ selectedSuggestionBGColor: Turquoise,
+ descriptionTextColor: Black,
+ descriptionBGColor: Turquoise,
+ selectedDescriptionTextColor: White,
+ selectedDescriptionBGColor: Cyan,
+ scrollbarThumbColor: DarkGray,
+ scrollbarBGColor: Cyan,
+ col: 1,
+ }
+ b := NewBuffer()
+ r.BreakLine(b)
+
+ if i != 0 {
+ t.Errorf("i should initially be 0, before applying a break line callback")
+ }
+
+ r.breakLineCallback = func(doc *Document) {
+ i++
+ }
+ r.BreakLine(b)
+ r.BreakLine(b)
+ r.BreakLine(b)
+
+ if i != 3 {
+ t.Errorf("BreakLine callback not called, i should be 3")
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/grade.py b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/grade.py
@@ -0,0 +1,157 @@
+"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
+
+import hashlib
+import json
+import os
+import selectors
+import signal
+import subprocess
+import time
+from pathlib import Path, PurePosixPath
+
+
+def assess(events, expected, returncode):
+ required = [(row["package"], row["test"]) for row in expected]
+ if not required or len(set(required)) != len(required):
+ raise ValueError("Required Go identities must be nonempty and unique")
+ runs, passes, package_passes, bad = {}, {}, set(), []
+ malformed = 0
+ for line in events.splitlines():
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ malformed += 1
+ continue
+ if not isinstance(event, dict) or not isinstance(event.get("Package"), str):
+ malformed += 1
+ continue
+ package, name, action = event["Package"], event.get("Test"), event.get("Action")
+ if name is None:
+ if action == "pass":
+ package_passes.add(package)
+ elif action == "fail":
+ bad.append([package, None, action])
+ continue
+ if not isinstance(name, str):
+ malformed += 1
+ continue
+ key = (package, name)
+ if action == "run":
+ runs[key] = runs.get(key, 0) + 1
+ elif action == "pass":
+ passes[key] = passes.get(key, 0) + 1
+ elif action in {"fail", "skip"}:
+ bad.append([package, name, action])
+ # Never parse Output strings as event records.
+ missing = [
+ list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1
+ ]
+ passed = (
+ returncode == 0
+ and not missing
+ and not bad
+ and not malformed
+ and all(package in package_passes for package, _ in required)
+ )
+ return {
+ "passed": passed,
+ "reward": int(passed),
+ "required": len(required),
+ "missing_or_duplicate": missing,
+ "failed_or_skipped": bad,
+ "malformed_lines": malformed,
+ "exit_code": returncode,
+ }
+
+
+def bounded_run(argv, cwd, seconds):
+ process = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ output, deadline = bytearray(), time.monotonic() + seconds
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ while selector.get_map():
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Go verifier deadline exceeded")
+ for key, _ in selector.select(min(1, deadline - time.monotonic())):
+ chunk = os.read(key.fileobj.fileno(), 65536)
+ if not chunk:
+ selector.unregister(key.fileobj)
+ else:
+ output.extend(chunk)
+ if len(output) > 4 * 1024 * 1024:
+ raise ValueError("Go verifier output bound exceeded")
+ return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes(
+ output
+ )
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+
+
+def main():
+ private, workspace, output = (
+ Path(__file__).resolve().parent,
+ Path("/testbed"),
+ Path("/logs/verifier"),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ reward = output / "reward.txt"
+ reward.unlink(missing_ok=True)
+ try:
+ manifest = json.loads((private / "manifest.json").read_bytes())
+ fixtures = {}
+ for name, item in manifest["frozen_files"].items():
+ path = PurePosixPath(name)
+ if path.is_absolute() or path.as_posix() != name or ".." in path.parts:
+ raise ValueError("Unsafe frozen fixture path")
+ raw = (private / "frozen" / name).read_bytes()
+ if hashlib.sha256(raw).hexdigest() != item["sha256"]:
+ raise ValueError("Frozen fixture hash mismatch")
+ fixtures[name] = raw
+ if (workspace / ".git").exists():
+ raise ValueError("Task Git history is unsupported")
+ for path in workspace.rglob("*_test.go"):
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Unsafe submitted test path")
+ path.unlink()
+ for name, raw in fixtures.items():
+ target = workspace / name
+ if target.is_symlink() or any(p.is_symlink() for p in target.parents):
+ raise ValueError("Unsafe fixture destination")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(raw)
+ target.chmod(manifest["frozen_files"][name]["mode"])
+ code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30)
+ if code:
+ raise ValueError("Offline dependency verification failed")
+ code, raw = bounded_run(manifest["command"], workspace, 240)
+ if code not in {0, 1}:
+ raise ValueError("Go verifier terminated unexpectedly")
+ result = assess(raw.decode("utf-8"), manifest["expected"], code)
+ (output / "test-result.json").write_text(
+ json.dumps(result, sort_keys=True) + "\n"
+ )
+ reward.write_text(str(result["reward"]) + "\n")
+ return 0
+ except Exception as error:
+ (output / "infrastructure-error.json").write_text(
+ json.dumps({"error_type": type(error).__name__}) + "\n"
+ )
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/manifest.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..022ff699c86932054061fc3fd40cb72236e08abd
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/manifest.json
@@ -0,0 +1,432 @@
+{
+ "command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "expected": [
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "FAIL_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestNewBuffer"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_InsertText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorMovement_WithMultiByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorUp"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_CursorDown"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_DeleteBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_NewLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_JoinNextLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBuffer_SwapCharactersBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatShortSuggestion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatText"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCharRelativeToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindStartOfPreviousWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWord"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_FindEndOfCurrentWordWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_CursorPositionRowAndCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorLeftPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorUpPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorDownPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetCursorRightPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_Lines"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_LineCount"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateIndexToPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_TranslateRowColToIndex"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_OnLastLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestDocument_GetEndOfLinePosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestEmacsKeyBindings"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFilter"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFuzzyMatch"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryClear"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryAdd"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestHistoryOlder"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/escape"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestPosixParserGetKey/undefined"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWrite"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestVT100WriterWriteRawStr"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestFormatCompletion"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "TestBreakLineCallback"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLine"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionRow"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CursorPositionCol"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_TextAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_DisplayCursorPosition_withJapanese"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_CurrentLineAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorWithSpace"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordBeforeCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparator"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt",
+ "test": "ExampleDocument_GetWordAfterCursorUntilSeparatorIgnoreNextToCursor"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "TestBisectRight"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/bisect",
+ "test": "Example"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotByte"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleIndexNotAny"
+ },
+ {
+ "group": "PASS_TO_PASS",
+ "package": "github.com/c-bata/go-prompt/internal/strings",
+ "test": "ExampleLastIndexNotAny"
+ }
+ ],
+ "frozen_files": {
+ "buffer_test.go": {
+ "mode": 420,
+ "sha256": "9279faf32d7656e0c8ac1aea079e5fdcce018a3f0f17211f8222cca67311c098"
+ },
+ "completion_test.go": {
+ "mode": 420,
+ "sha256": "769f5fad95dc5df5be036e8871426bf21f51299f59cab620941b7d80658d592d"
+ },
+ "document_test.go": {
+ "mode": 420,
+ "sha256": "5007fe0936c5e4a4124ccf2981a82024724de4b0c82e4feb64d7eb72a4aed284"
+ },
+ "emacs_test.go": {
+ "mode": 420,
+ "sha256": "f614396f75e72febebc52b573a25091f2a85214b3d0f2615a22d144ba9126095"
+ },
+ "filter_test.go": {
+ "mode": 420,
+ "sha256": "5154c518d32c2b67f4877c8659f5c23ad2aece7971d47c3039d97d5f5bf08247"
+ },
+ "history_test.go": {
+ "mode": 420,
+ "sha256": "310b91f5738f3acc2b96f40e04ced993b3ce0fd9491c5c6812e60c8651753327"
+ },
+ "input_test.go": {
+ "mode": 420,
+ "sha256": "6d58e0f8572f6643f17fcb3765edbcdad49a6c03ee58b75599fdf5c5bd0ee922"
+ },
+ "internal/bisect/bisect_test.go": {
+ "mode": 420,
+ "sha256": "f12d632334c42c9e09411fe96ee39f42ccff76d206aa10be29b763feec350aaf"
+ },
+ "internal/strings/strings_test.go": {
+ "mode": 420,
+ "sha256": "88d835bb9f5b7098ad6a11f1419130178961fcd9fb2fe87dfb151394622f56c6"
+ },
+ "output_vt100_test.go": {
+ "mode": 420,
+ "sha256": "7f7d56d1066009d53127f9ae90464e8f31aafa20510553862e5d2a598cddeaee"
+ },
+ "render_test.go": {
+ "mode": 420,
+ "sha256": "392c028e8ca5478ece684b85aeeeab3222372377541c62393b92810054f252bb"
+ }
+ }
+}
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/test.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+exec /usr/local/bin/python -I /tests/grade.py
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/validation/canaries/delete-tests.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/validation/canaries/delete-tests.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/validation/canaries/delete-tests.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+find /testbed -name '*_test.go' -type f -delete
+printf 'PASS\nok forged-package 0.001s\n'
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/validation/canaries/original-bug.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/validation/canaries/original-bug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/validation/canaries/original-bug.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+set -eu
+:
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/validation/canaries/stale-reward.sh b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/validation/canaries/stale-reward.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/validation/canaries/stale-reward.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -eu
+mkdir -p /logs/verifier
+printf '1\n' > /logs/verifier/reward.txt
diff --git a/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/validation/openenv.json b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/validation/openenv.json
new file mode 100644
index 0000000000000000000000000000000000000000..6a37150d7d6b4160094383da97da3e4f244daf1b
--- /dev/null
+++ b/tasks/c-bata__go-prompt.82a91227.lm_modify__dnaspfcb/validation/openenv.json
@@ -0,0 +1,28 @@
+{
+ "canaries": "validation/canaries",
+ "original_source_digest": "45a499e5d89e0a1dd5071cddb7af502d815c28279f72d8c4fa14b7e968e39b42",
+ "profile": "harbor-semantic-v1",
+ "requires_credentials": false,
+ "resources": {
+ "cpu": 1,
+ "disk_mb": 4096,
+ "episode_timeout_s": 600,
+ "memory_mb": 2048
+ },
+ "reward": {
+ "floor_margin": 0.1,
+ "oracle_tolerance": 0,
+ "range": [
+ 0,
+ 1
+ ]
+ },
+ "reward_key": "reward",
+ "types": {
+ "tags": [
+ "swe",
+ "go",
+ "repository-repair"
+ ]
+ }
+}
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/Dockerfile b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..284db3252ecd4ce9f81ebe88d1db21299cdfd9d1
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/Dockerfile
@@ -0,0 +1,2 @@
+FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-11a67b0f935a27b1-starter-v1@sha256:4ee00ee1d2e8d73fc91bd8adc004c943c4b3b4cf08c09f46a8ffa24dab68de93
+WORKDIR /testbed
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.editorconfig b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.editorconfig
new file mode 100644
index 0000000000000000000000000000000000000000..0d3bd399bcdd67a92637f05f00982dd46c21e602
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.editorconfig
@@ -0,0 +1,28 @@
+[*]
+charset = utf-8
+end_of_line = lf
+trim_trailing_whitespace = true
+max_line_length = 120
+
+[{go.mod,go.sum,*.go}]
+insert_final_newline = true
+indent_size = tab
+indent_style = tab
+tab_width = 4
+
+[Makefile]
+max_line_length = off
+insert_final_newline = true
+indent_size = tab
+indent_style = tab
+tab_width = 4
+
+[*.md]
+max_line_length = off
+trim_trailing_whitespace = false
+indent_size = tab
+indent_style = space
+tab_width = 2
+
+[.mailmap]
+max_line_length = off
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.github/FUNDING.yml b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.github/FUNDING.yml
new file mode 100644
index 0000000000000000000000000000000000000000..f87b4ac224f8acc976fa9021ebaf91d83bf82505
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.github/FUNDING.yml
@@ -0,0 +1 @@
+github: [caarlos0]
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.github/dependabot.yml b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.github/dependabot.yml
new file mode 100644
index 0000000000000000000000000000000000000000..92b0ef8b8325a19a823e6a71638cee93d8b37a62
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.github/dependabot.yml
@@ -0,0 +1,16 @@
+version: 2
+updates:
+ - package-ecosystem: "gomod"
+ directory: "/"
+ schedule:
+ interval: "daily"
+ time: "08:00"
+ labels:
+ - "dependencies"
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "daily"
+ time: "08:00"
+ labels:
+ - "dependencies"
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.gitignore b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..9eea1c980a29eafe8de09dff5633198d2021876d
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.gitignore
@@ -0,0 +1,5 @@
+coverage.txt
+bin
+card.png
+dist
+codecov*
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.golangci.yml b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.golangci.yml
new file mode 100644
index 0000000000000000000000000000000000000000..8e51bdccdae50b402d090d3fee9b54d1e9e5bb4d
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.golangci.yml
@@ -0,0 +1,32 @@
+linters-settings:
+ gocritic:
+ enabled-checks:
+ - emptyStringTest
+ - evalOrder
+ - paramTypeCombine
+ - preferStringWriter
+ - sprintfQuotedString
+ - stringConcatSimplify
+ - yodaStyleExpr
+ revive:
+ rules:
+ - name: line-length-limit
+ arguments: [120]
+
+issues:
+ exclude-rules:
+ - path: _test\.go
+ linters:
+ - revive
+ text: "line-length-limit:"
+
+linters:
+ enable:
+ - thelper
+ - gofumpt
+ - gocritic
+ - tparallel
+ - unconvert
+ - unparam
+ - wastedassign
+ - revive
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.goreleaser.yml b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.goreleaser.yml
new file mode 100644
index 0000000000000000000000000000000000000000..a5b7d4d2720d8bbd937de95ddd92fa632f79e202
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.goreleaser.yml
@@ -0,0 +1,5 @@
+# yaml-language-server: $schema=https://goreleaser.com/static/schema-pro.json
+version: 2
+includes:
+ - from_url:
+ url: https://raw.githubusercontent.com/caarlos0/.goreleaserfiles/main/lib.yml
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.mailmap b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.mailmap
new file mode 100644
index 0000000000000000000000000000000000000000..eeeee60107e92c845937861d35711936c0f5fadc
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/.mailmap
@@ -0,0 +1,7 @@
+Carlos Alexandro Becker Carlos A Becker
+Carlos Alexandro Becker Carlos A Becker
+Carlos Alexandro Becker Carlos Alexandro Becker
+Carlos Alexandro Becker Carlos Alexandro Becker
+Carlos Alexandro Becker Carlos Becker
+dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
+actions-user github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/LICENSE.md b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/LICENSE.md
new file mode 100644
index 0000000000000000000000000000000000000000..28463401b71766f5a945c529dbb1e9391ab8bc2c
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/LICENSE.md
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2015-2024 Carlos Alexandro Becker
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/Makefile b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..da8595fb9a7c28fb33a78c0d831d5ec2c19118a2
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/Makefile
@@ -0,0 +1,37 @@
+SOURCE_FILES?=./...
+TEST_PATTERN?=.
+
+export GO111MODULE := on
+
+setup:
+ go mod tidy
+.PHONY: setup
+
+build:
+ go build
+.PHONY: build
+
+test:
+ go test -v -failfast -race -coverpkg=./... -covermode=atomic -coverprofile=coverage.txt $(SOURCE_FILES) -run $(TEST_PATTERN) -timeout=2m
+.PHONY: test
+
+cover: test
+ go tool cover -html=coverage.txt
+.PHONY: cover
+
+fmt:
+ gofumpt -w -l .
+.PHONY: fmt
+
+lint:
+ golangci-lint run ./...
+.PHONY: lint
+
+ci: build test
+.PHONY: ci
+
+card:
+ wget -O card.png -c "https://og.caarlos0.dev/**env**: parse envs to structs.png?theme=light&md=1&fontSize=100px&images=https://github.com/caarlos0.png"
+.PHONY: card
+
+.DEFAULT_GOAL := ci
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/README.md b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..de6f8249d15a777ca469072419f3c4968140eb11
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/README.md
@@ -0,0 +1,156 @@
+
+
+
A simple, zero-dependencies library to parse environment variables into structs.
+
+
+###### Installation
+
+```bash
+go get github.com/caarlos0/env/v11
+```
+
+###### Getting started
+
+```go
+type config struct {
+ Home string `env:"HOME"`
+}
+
+// parse
+var cfg config
+err := env.Parse(&cfg)
+
+// parse with generics
+cfg, err := env.ParseAs[config]()
+```
+
+You can see the full documentation and list of examples at [pkg.go.dev](https://pkg.go.dev/github.com/caarlos0/env/v11).
+
+---
+
+## Used and supported by
+
+
+
+
+
+
+
+ Encore – the platform for building Go-based cloud backends.
+
+
+
+## Usage
+
+### Caveats
+
+> [!CAUTION]
+>
+> _Unexported fields_ will be **ignored** by `env`.
+> This is by design and will not change.
+
+### Functions
+
+- `Parse`: parse the current environment into a type
+- `ParseAs`: parse the current environment into a type using generics
+- `ParseWithOptions`: parse the current environment into a type with custom options
+- `ParseAsWithOptions`: parse the current environment into a type with custom options and using generics
+- `Must`: can be used to wrap `Parse.*` calls to panic on error
+- `GetFieldParams`: get the `env` parsed options for a type
+- `GetFieldParamsWithOptions`: get the `env` parsed options for a type with custom options
+
+### Supported types
+
+Out of the box all built-in types are supported, plus a few others that are commonly used.
+
+Complete list:
+
+- `bool`
+- `float32`
+- `float64`
+- `int16`
+- `int32`
+- `int64`
+- `int8`
+- `int`
+- `string`
+- `uint16`
+- `uint32`
+- `uint64`
+- `uint8`
+- `uint`
+- `time.Duration`
+- `time.Location`
+- `encoding.TextUnmarshaler`
+- `url.URL`
+
+Pointers, slices and slices of pointers, and maps of those types are also supported.
+
+You may also add custom parsers for your types.
+
+### Tags
+
+The following tags are provided:
+
+- `env`: sets the environment variable name and optionally takes the tag options described below
+- `envDefault`: sets the default value for the field
+- `envPrefix`: can be used in a field that is a complex type to set a prefix to all environment variables used in it
+- `envSeparator`: sets the character to be used to separate items in slices and maps (default: `,`)
+- `envKeyValSeparator`: sets the character to be used to separate keys and their values in maps (default: `:`)
+
+### `env` tag options
+
+Here are all the options available for the `env` tag:
+
+- `,expand`: expands environment variables, e.g. `FOO_${BAR}`
+- `,file`: instructs that the content of the variable is a path to a file that should be read
+- `,init`: initialize nil pointers
+- `,notEmpty`: make the field errors if the environment variable is empty
+- `,required`: make the field errors if the environment variable is not set
+- `,unset`: unset the environment variable after use
+
+### Parse Options
+
+There are a few options available in the functions that end with `WithOptions`:
+
+- `Environment`: keys and values to be used instead of `os.Environ()`
+- `TagName`: specifies another tag name to use rather than the default `env`
+- `PrefixTagName`: specifies another prefix tag name to use rather than the default `envPrefix`
+- `DefaultValueTagName`: specifies another default tag name to use rather than the default `envDefault`
+- `RequiredIfNoDef`: set all `env` fields as required if they do not declare `envDefault`
+- `OnSet`: allows to hook into the `env` parsing and do something when a value is set
+- `Prefix`: prefix to be used in all environment variables
+- `UseFieldNameByDefault`: defines whether or not `env` should use the field name by default if the `env` key is missing
+- `FuncMap`: custom parse functions for custom types
+
+### Documentation and examples
+
+Examples are live in [pkg.go.dev](https://pkg.go.dev/github.com/caarlos0/env/v11),
+and also in the [example test file](./example_test.go).
+
+## Current state
+
+`env` is considered feature-complete.
+
+I do not intent to add any new features unless they really make sense, and are
+requested by many people.
+
+Eventual bug fixes will keep being merged.
+
+## Badges
+
+[](https://github.com/goreleaser/goreleaser/releases/latest)
+[](/LICENSE.md)
+[](https://github.com/caarlos0/env/actions?workflow=build)
+[](https://codecov.io/gh/caarlos0/env)
+[](http://godoc.org/github.com/caarlos0/env/v11)
+[](https://github.com/goreleaser)
+[](https://conventionalcommits.org)
+
+## Related projects
+
+- [envdoc](https://github.com/g4s8/envdoc) - generate documentation for environment variables from `env` tags
+
+## Stargazers over time
+
+[](https://starchart.cc/caarlos0/env)
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/env.go b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/env.go
new file mode 100644
index 0000000000000000000000000000000000000000..fed420c50d518159f5e7ed597cdb9e0b68121deb
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/env.go
@@ -0,0 +1,856 @@
+// Package env is a simple, zero-dependencies library to parse environment
+// variables into structs.
+//
+// Example:
+//
+// type config struct {
+// Home string `env:"HOME"`
+// }
+// // parse
+// var cfg config
+// err := env.Parse(&cfg)
+// // or parse with generics
+// cfg, err := env.ParseAs[config]()
+//
+// Check the examples and README for more detailed usage.
+package env
+
+import (
+ "encoding"
+ "fmt"
+ "net/url"
+ "os"
+ "reflect"
+ "strconv"
+ "strings"
+ "time"
+ "unicode"
+)
+
+// nolint: gochecknoglobals
+var (
+ defaultBuiltInParsers = map[reflect.Kind]ParserFunc{
+ reflect.Bool: func(v string) (interface{}, error) {
+ return strconv.ParseBool(v)
+ },
+ reflect.String: func(v string) (interface{}, error) {
+ return v, nil
+ },
+ reflect.Int: func(v string) (interface{}, error) {
+ i, err := strconv.ParseInt(v, 10, 32)
+ return int(i), err
+ },
+ reflect.Int16: func(v string) (interface{}, error) {
+ i, err := strconv.ParseInt(v, 10, 16)
+ return int16(i), err
+ },
+ reflect.Int32: func(v string) (interface{}, error) {
+ i, err := strconv.ParseInt(v, 10, 32)
+ return int32(i), err
+ },
+ reflect.Int64: func(v string) (interface{}, error) {
+ return strconv.ParseInt(v, 10, 64)
+ },
+ reflect.Int8: func(v string) (interface{}, error) {
+ i, err := strconv.ParseInt(v, 10, 8)
+ return int8(i), err
+ },
+ reflect.Uint: func(v string) (interface{}, error) {
+ i, err := strconv.ParseUint(v, 10, 32)
+ return uint(i), err
+ },
+ reflect.Uint16: func(v string) (interface{}, error) {
+ i, err := strconv.ParseUint(v, 10, 16)
+ return uint16(i), err
+ },
+ reflect.Uint32: func(v string) (interface{}, error) {
+ i, err := strconv.ParseUint(v, 10, 32)
+ return uint32(i), err
+ },
+ reflect.Uint64: func(v string) (interface{}, error) {
+ i, err := strconv.ParseUint(v, 10, 64)
+ return i, err
+ },
+ reflect.Uint8: func(v string) (interface{}, error) {
+ i, err := strconv.ParseUint(v, 10, 8)
+ return uint8(i), err
+ },
+ reflect.Float64: func(v string) (interface{}, error) {
+ return strconv.ParseFloat(v, 64)
+ },
+ reflect.Float32: func(v string) (interface{}, error) {
+ f, err := strconv.ParseFloat(v, 32)
+ return float32(f), err
+ },
+ }
+)
+
+func defaultTypeParsers() map[reflect.Type]ParserFunc {
+ return map[reflect.Type]ParserFunc{
+ reflect.TypeOf(url.URL{}): parseURL,
+ reflect.TypeOf(time.Nanosecond): parseDuration,
+ reflect.TypeOf(time.Location{}): parseLocation,
+ }
+}
+
+func parseURL(v string) (interface{}, error) {
+ u, err := url.Parse(v)
+ if err != nil {
+ return nil, newParseValueError("unable to parse URL", err)
+ }
+ return *u, nil
+}
+
+func parseDuration(v string) (interface{}, error) {
+ d, err := time.ParseDuration(v)
+ if err != nil {
+ return nil, newParseValueError("unable to parse duration", err)
+ }
+ return d, err
+}
+
+func parseLocation(v string) (interface{}, error) {
+ loc, err := time.LoadLocation(v)
+ if err != nil {
+ return nil, newParseValueError("unable to parse location", err)
+ }
+ return *loc, nil
+}
+
+// ParserFunc defines the signature of a function that can be used within
+// `Options`' `FuncMap`.
+type ParserFunc func(v string) (interface{}, error)
+
+// OnSetFn is a hook that can be run when a value is set.
+type OnSetFn func(tag string, value interface{}, isDefault bool)
+
+// processFieldFn is a function which takes all information about a field and processes it.
+type processFieldFn func(
+ refField reflect.Value,
+ refTypeField reflect.StructField,
+ opts Options,
+ fieldParams FieldParams,
+) error
+
+// Options for the parser.
+type Options struct {
+ // Environment keys and values that will be accessible for the service.
+ Environment map[string]string
+
+ // TagName specifies another tag name to use rather than the default 'env'.
+ TagName string
+
+ // PrefixTagName specifies another prefix tag name to use rather than the default 'envPrefix'.
+ PrefixTagName string
+
+ // DefaultValueTagName specifies another default tag name to use rather than the default 'envDefault'.
+ DefaultValueTagName string
+
+ // RequiredIfNoDef automatically sets all fields as required if they do not
+ // declare 'envDefault'.
+ RequiredIfNoDef bool
+
+ // OnSet allows to run a function when a value is set.
+ OnSet OnSetFn
+
+ // Prefix define a prefix for every key.
+ Prefix string
+
+ // UseFieldNameByDefault defines whether or not `env` should use the field
+ // name by default if the `env` key is missing.
+ // Note that the field name will be "converted" to conform with environment
+ // variable names conventions.
+ UseFieldNameByDefault bool
+
+ // SetDefaultsForZeroValuesOnly defines whether to set defaults for zero values
+ // If the `env` variable for the value is not set
+ // and `envDefault` is set
+ // and the value is not a zero value for the the type
+ // and SetDefaultsForZeroValuesOnly=true
+ // the value from `envDefault` will be ignored
+ // Usefull for mixing default values from `envDefault` and struct initialization
+ SetDefaultsForZeroValuesOnly bool
+
+ // Custom parse functions for different types.
+ FuncMap map[reflect.Type]ParserFunc
+
+ // Used internally. maps the env variable key to its resolved string value.
+ // (for env var expansion)
+ rawEnvVars map[string]string
+}
+
+func (opts *Options) getRawEnv(s string) string {
+ val := opts.rawEnvVars[s]
+ if val == "" {
+ val = opts.Environment[s]
+ }
+ return os.Expand(val, opts.getRawEnv)
+}
+
+func defaultOptions() Options {
+ return Options{
+ TagName: "env",
+ PrefixTagName: "envPrefix",
+ DefaultValueTagName: "envDefault",
+ Environment: toMap(os.Environ()),
+ FuncMap: defaultTypeParsers(),
+ rawEnvVars: make(map[string]string),
+ }
+}
+
+func mergeOptions[T any](target, source *T) {
+ targetPtr := reflect.ValueOf(target).Elem()
+ sourcePtr := reflect.ValueOf(source).Elem()
+
+ targetType := targetPtr.Type()
+ for i := 0; i < targetPtr.NumField(); i++ {
+ fieldName := targetType.Field(i).Name
+ targetField := targetPtr.Field(i)
+ sourceField := sourcePtr.FieldByName(fieldName)
+
+ if targetField.CanSet() && !isZero(sourceField) {
+ // FuncMaps are being merged, while Environments must be overwritten
+ if fieldName == "FuncMap" {
+ if !sourceField.IsZero() {
+ iter := sourceField.MapRange()
+ for iter.Next() {
+ targetField.SetMapIndex(iter.Key(), iter.Value())
+ }
+ }
+ } else {
+ targetField.Set(sourceField)
+ }
+ }
+ }
+}
+
+func isZero(v reflect.Value) bool {
+ switch v.Kind() {
+ case reflect.Func, reflect.Map, reflect.Slice:
+ return v.IsNil()
+ default:
+ zero := reflect.Zero(v.Type())
+ return v.Interface() == zero.Interface()
+ }
+}
+
+func customOptions(opts Options) Options {
+ defOpts := defaultOptions()
+ mergeOptions(&defOpts, &opts)
+ return defOpts
+}
+
+func optionsWithSliceEnvPrefix(opts Options, index int) Options {
+ return Options{
+ Environment: opts.Environment,
+ TagName: opts.TagName,
+ PrefixTagName: opts.PrefixTagName,
+ DefaultValueTagName: opts.DefaultValueTagName,
+ RequiredIfNoDef: opts.RequiredIfNoDef,
+ OnSet: opts.OnSet,
+ Prefix: fmt.Sprintf("%s%d_", opts.Prefix, index),
+ UseFieldNameByDefault: opts.UseFieldNameByDefault,
+ SetDefaultsForZeroValuesOnly: opts.SetDefaultsForZeroValuesOnly,
+ FuncMap: opts.FuncMap,
+ rawEnvVars: opts.rawEnvVars,
+ }
+}
+
+func optionsWithEnvPrefix(field reflect.StructField, opts Options) Options {
+ return Options{
+ Environment: opts.Environment,
+ TagName: opts.TagName,
+ PrefixTagName: opts.PrefixTagName,
+ DefaultValueTagName: opts.DefaultValueTagName,
+ RequiredIfNoDef: opts.RequiredIfNoDef,
+ OnSet: opts.OnSet,
+ Prefix: opts.Prefix + field.Tag.Get(opts.PrefixTagName),
+ UseFieldNameByDefault: opts.UseFieldNameByDefault,
+ SetDefaultsForZeroValuesOnly: opts.SetDefaultsForZeroValuesOnly,
+ FuncMap: opts.FuncMap,
+ rawEnvVars: opts.rawEnvVars,
+ }
+}
+
+// Parse parses a struct containing `env` tags and loads its values from
+// environment variables.
+func Parse(v interface{}) error {
+ return parseInternal(v, setField, defaultOptions())
+}
+
+// ParseWithOptions parses a struct containing `env` tags and loads its values from
+// environment variables.
+func ParseWithOptions(v interface{}, opts Options) error {
+ return parseInternal(v, setField, customOptions(opts))
+}
+
+// ParseAs parses the given struct type containing `env` tags and loads its
+// values from environment variables.
+func ParseAs[T any]() (T, error) {
+ var t T
+ err := Parse(&t)
+ return t, err
+}
+
+// ParseWithOptions parses the given struct type containing `env` tags and
+// loads its values from environment variables.
+func ParseAsWithOptions[T any](opts Options) (T, error) {
+ var t T
+ err := ParseWithOptions(&t, opts)
+ return t, err
+}
+
+// Must panic is if err is not nil, and returns t otherwise.
+func Must[T any](t T, err error) T {
+ if err != nil {
+ panic(err)
+ }
+ return t
+}
+
+// GetFieldParams parses a struct containing `env` tags and returns information about
+// tags it found.
+func GetFieldParams(v interface{}) ([]FieldParams, error) {
+ return GetFieldParamsWithOptions(v, defaultOptions())
+}
+
+// GetFieldParamsWithOptions parses a struct containing `env` tags and returns information about
+// tags it found.
+func GetFieldParamsWithOptions(v interface{}, opts Options) ([]FieldParams, error) {
+ var result []FieldParams
+ err := parseInternal(
+ v,
+ func(_ reflect.Value, _ reflect.StructField, _ Options, fieldParams FieldParams) error {
+ if fieldParams.OwnKey != "" {
+ result = append(result, fieldParams)
+ }
+ return nil
+ },
+ customOptions(opts),
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ return result, nil
+}
+
+func parseInternal(v interface{}, processField processFieldFn, opts Options) error {
+ ptrRef := reflect.ValueOf(v)
+ if ptrRef.Kind() != reflect.Ptr {
+ return newAggregateError(NotStructPtrError{})
+ }
+ ref := ptrRef.Elem()
+ if ref.Kind() != reflect.Struct {
+ return newAggregateError(NotStructPtrError{})
+ }
+
+ return doParse(ref, processField, opts)
+}
+
+func doParse(ref reflect.Value, processField processFieldFn, opts Options) error {
+ refType := ref.Type()
+
+ var agrErr AggregateError
+
+ for i := 0; i < refType.NumField(); i++ {
+ refField := ref.Field(i)
+ refTypeField := refType.Field(i)
+
+ if err := doParseField(refField, refTypeField, processField, opts); err != nil {
+ if val, ok := err.(AggregateError); ok {
+ agrErr.Errors = append(agrErr.Errors, val.Errors...)
+ } else {
+ agrErr.Errors = append(agrErr.Errors, err)
+ }
+ }
+ }
+
+ if len(agrErr.Errors) == 0 {
+ return nil
+ }
+
+ return agrErr
+}
+
+func doParseField(
+ refField reflect.Value,
+ refTypeField reflect.StructField,
+ processField processFieldFn,
+ opts Options,
+) error {
+ if !refField.CanSet() {
+ return nil
+ }
+ if refField.Kind() == reflect.Ptr && refField.Elem().Kind() == reflect.Struct && !refField.IsNil() {
+ return parseInternal(refField.Interface(), processField, optionsWithEnvPrefix(refTypeField, opts))
+ }
+ if refField.Kind() == reflect.Struct && refField.CanAddr() && refField.Type().Name() == "" {
+ return parseInternal(refField.Addr().Interface(), processField, optionsWithEnvPrefix(refTypeField, opts))
+ }
+
+ params, err := parseFieldParams(refTypeField, opts)
+ if err != nil {
+ return err
+ }
+
+ if params.Ignored {
+ return nil
+ }
+
+ if err := processField(refField, refTypeField, opts, params); err != nil {
+ return err
+ }
+
+ if params.Init && isInvalidPtr(refField) {
+ refField.Set(reflect.New(refField.Type().Elem()))
+ refField = refField.Elem()
+ }
+
+ if refField.Kind() == reflect.Struct {
+ return doParse(refField, processField, optionsWithEnvPrefix(refTypeField, opts))
+ }
+
+ if isSliceOfStructs(refTypeField) {
+ return doParseSlice(refField, processField, optionsWithEnvPrefix(refTypeField, opts))
+ }
+
+ return nil
+}
+
+func isSliceOfStructs(refTypeField reflect.StructField) bool {
+ field := refTypeField.Type
+
+ // *[]struct
+ if field.Kind() == reflect.Ptr {
+ field = field.Elem()
+ if field.Kind() == reflect.Slice && field.Elem().Kind() == reflect.Struct {
+ return true
+ }
+ }
+
+ // []struct{}
+ if field.Kind() == reflect.Slice && field.Elem().Kind() == reflect.Struct {
+ return true
+ }
+
+ return false
+}
+
+func doParseSlice(ref reflect.Value, processField processFieldFn, opts Options) error {
+ if opts.Prefix != "" && !strings.HasSuffix(opts.Prefix, string(underscore)) {
+ opts.Prefix += string(underscore)
+ }
+
+ var environments []string
+ for environment := range opts.Environment {
+ if strings.HasPrefix(environment, opts.Prefix) {
+ environments = append(environments, environment)
+ }
+ }
+
+ if len(environments) > 0 {
+ counter := 0
+ for finished := false; !finished; {
+ finished = true
+ prefix := fmt.Sprintf("%s%d%c", opts.Prefix, counter, underscore)
+ for _, variable := range environments {
+ if strings.HasPrefix(variable, prefix) {
+ counter++
+ finished = false
+ break
+ }
+ }
+ }
+
+ sliceType := ref.Type()
+ var initialized int
+ if reflect.Ptr == ref.Kind() {
+ initialized = ref.Len()
+ } else {
+ sliceType = sliceType.Elem()
+ // Due to the rest of code the pre-initialized slice has no chance for this situation
+ initialized = 0
+ }
+
+ var capacity int
+ if capacity = initialized; counter > initialized {
+ capacity = counter
+ }
+ result := reflect.MakeSlice(sliceType, capacity, capacity)
+ for i := 0; i < capacity; i++ {
+ item := result.Index(i)
+ if i < initialized {
+ item.Set(ref.Index(i))
+ }
+ if err := doParse(item, processField, optionsWithSliceEnvPrefix(opts, i)); err != nil {
+ return err
+ }
+ }
+
+ if result.Len() > 0 {
+ if reflect.Ptr == ref.Kind() {
+ resultPtr := reflect.New(sliceType)
+ resultPtr.Elem().Set(result)
+ result = resultPtr
+ }
+ ref.Set(result)
+ }
+ }
+
+ return nil
+}
+
+func setField(refField reflect.Value, refTypeField reflect.StructField, opts Options, fieldParams FieldParams) error {
+ value, err := get(fieldParams, opts)
+ if err != nil {
+ return err
+ }
+
+ if value != "" && (!opts.SetDefaultsForZeroValuesOnly || refField.IsZero()) {
+ return set(refField, refTypeField, value, opts.FuncMap)
+ }
+
+ return nil
+}
+
+const underscore rune = '_'
+
+func toEnvName(input string) string {
+ var output []rune
+ for i, c := range input {
+ if c == underscore {
+ continue
+ }
+ if len(output) > 0 && unicode.IsUpper(c) {
+ if len(input) > i+1 {
+ peek := rune(input[i+1])
+ if unicode.IsLower(peek) || unicode.IsLower(rune(input[i-1])) {
+ output = append(output, underscore)
+ }
+ }
+ }
+ output = append(output, unicode.ToUpper(c))
+ }
+ return string(output)
+}
+
+// FieldParams contains information about parsed field tags.
+type FieldParams struct {
+ OwnKey string
+ Key string
+ DefaultValue string
+ HasDefaultValue bool
+ Required bool
+ LoadFile bool
+ Unset bool
+ NotEmpty bool
+ Expand bool
+ Init bool
+ Ignored bool
+}
+
+func parseFieldParams(field reflect.StructField, opts Options) (FieldParams, error) {
+ ownKey, tags := parseKeyForOption(field.Tag.Get(opts.TagName))
+ if ownKey == "" && opts.UseFieldNameByDefault {
+ ownKey = toEnvName(field.Name)
+ }
+
+ defaultValue, hasDefaultValue := field.Tag.Lookup(opts.DefaultValueTagName)
+
+ result := FieldParams{
+ OwnKey: ownKey,
+ Key: opts.Prefix + ownKey,
+ Required: opts.RequiredIfNoDef,
+ DefaultValue: defaultValue,
+ HasDefaultValue: hasDefaultValue,
+ Ignored: ownKey == "-",
+ }
+
+ for _, tag := range tags {
+ switch tag {
+ case "":
+ continue
+ case "file":
+ result.LoadFile = true
+ case "required":
+ result.Required = true
+ case "unset":
+ result.Unset = true
+ case "notEmpty":
+ result.NotEmpty = true
+ case "expand":
+ result.Expand = true
+ case "init":
+ result.Init = true
+ case "-":
+ result.Ignored = true
+ default:
+ return FieldParams{}, newNoSupportedTagOptionError(tag)
+ }
+ }
+
+ return result, nil
+}
+
+func get(fieldParams FieldParams, opts Options) (val string, err error) {
+ var exists, isDefault bool
+
+ val, exists, isDefault = getOr(
+ fieldParams.Key,
+ fieldParams.DefaultValue,
+ fieldParams.HasDefaultValue,
+ opts.Environment,
+ )
+
+ if fieldParams.Expand {
+ val = os.Expand(val, opts.getRawEnv)
+ }
+
+ opts.rawEnvVars[fieldParams.OwnKey] = val
+
+ if fieldParams.Unset {
+ defer os.Unsetenv(fieldParams.Key)
+ }
+
+ if fieldParams.Required && !exists && fieldParams.OwnKey != "" {
+ return "", newVarIsNotSetError(fieldParams.Key)
+ }
+
+ if fieldParams.NotEmpty && val == "" {
+ return "", newEmptyVarError(fieldParams.Key)
+ }
+
+ if fieldParams.LoadFile && val != "" {
+ filename := val
+ val, err = getFromFile(filename)
+ if err != nil {
+ return "", newLoadFileContentError(filename, fieldParams.Key, err)
+ }
+ }
+
+ if opts.OnSet != nil {
+ if fieldParams.OwnKey != "" {
+ opts.OnSet(fieldParams.Key, val, isDefault)
+ }
+ }
+ return val, err
+}
+
+// split the env tag's key into the expected key and desired option, if any.
+func parseKeyForOption(key string) (string, []string) {
+ opts := strings.Split(key, ",")
+ return opts[0], opts[1:]
+}
+
+func getFromFile(filename string) (value string, err error) {
+ b, err := os.ReadFile(filename)
+ return string(b), err
+}
+
+func getOr(key, defaultValue string, defExists bool, envs map[string]string) (val string, exists, isDefault bool) {
+ value, exists := envs[key]
+ switch {
+ case (!exists || key == "") && defExists:
+ return defaultValue, true, true
+ case exists && value == "" && defExists:
+ return defaultValue, true, true
+ case !exists:
+ return "", false, false
+ }
+
+ return value, true, false
+}
+
+func set(field reflect.Value, sf reflect.StructField, value string, funcMap map[reflect.Type]ParserFunc) error {
+ if tm := asTextUnmarshaler(field); tm != nil {
+ if err := tm.UnmarshalText([]byte(value)); err != nil {
+ return newParseError(sf, err)
+ }
+ return nil
+ }
+
+ typee := sf.Type
+ fieldee := field
+ if typee.Kind() == reflect.Ptr {
+ typee = typee.Elem()
+ fieldee = field.Elem()
+ }
+
+ parserFunc, ok := funcMap[typee]
+ if ok {
+ val, err := parserFunc(value)
+ if err != nil {
+ return newParseError(sf, err)
+ }
+
+ fieldee.Set(reflect.ValueOf(val))
+ return nil
+ }
+
+ parserFunc, ok = defaultBuiltInParsers[typee.Kind()]
+ if ok {
+ val, err := parserFunc(value)
+ if err != nil {
+ return newParseError(sf, err)
+ }
+
+ fieldee.Set(reflect.ValueOf(val).Convert(typee))
+ return nil
+ }
+
+ switch field.Kind() {
+ case reflect.Slice:
+ return handleSlice(field, value, sf, funcMap)
+ case reflect.Map:
+ return handleMap(field, value, sf, funcMap)
+ }
+
+ return newNoParserError(sf)
+}
+
+func handleSlice(field reflect.Value, value string, sf reflect.StructField, funcMap map[reflect.Type]ParserFunc) error {
+ separator := sf.Tag.Get("envSeparator")
+ if separator == "" {
+ separator = ","
+ }
+ parts := strings.Split(value, separator)
+
+ typee := sf.Type.Elem()
+ if typee.Kind() == reflect.Ptr {
+ typee = typee.Elem()
+ }
+
+ if _, ok := reflect.New(typee).Interface().(encoding.TextUnmarshaler); ok {
+ return parseTextUnmarshalers(field, parts, sf)
+ }
+
+ parserFunc, ok := funcMap[typee]
+ if !ok {
+ parserFunc, ok = defaultBuiltInParsers[typee.Kind()]
+ if !ok {
+ return newNoParserError(sf)
+ }
+ }
+
+ result := reflect.MakeSlice(sf.Type, 0, len(parts))
+ for _, part := range parts {
+ r, err := parserFunc(part)
+ if err != nil {
+ return newParseError(sf, err)
+ }
+ v := reflect.ValueOf(r).Convert(typee)
+ if sf.Type.Elem().Kind() == reflect.Ptr {
+ v = reflect.New(typee)
+ v.Elem().Set(reflect.ValueOf(r).Convert(typee))
+ }
+ result = reflect.Append(result, v)
+ }
+ field.Set(result)
+ return nil
+}
+
+func handleMap(field reflect.Value, value string, sf reflect.StructField, funcMap map[reflect.Type]ParserFunc) error {
+ keyType := sf.Type.Key()
+ keyParserFunc, ok := funcMap[keyType]
+ if !ok {
+ keyParserFunc, ok = defaultBuiltInParsers[keyType.Kind()]
+ if !ok {
+ return newNoParserError(sf)
+ }
+ }
+
+ elemType := sf.Type.Elem()
+ elemParserFunc, ok := funcMap[elemType]
+ if !ok {
+ elemParserFunc, ok = defaultBuiltInParsers[elemType.Kind()]
+ if !ok {
+ return newNoParserError(sf)
+ }
+ }
+
+ separator := sf.Tag.Get("envSeparator")
+ if separator == "" {
+ separator = ","
+ }
+
+ keyValSeparator := sf.Tag.Get("envKeyValSeparator")
+ if keyValSeparator == "" {
+ keyValSeparator = ":"
+ }
+
+ result := reflect.MakeMap(sf.Type)
+ for _, part := range strings.Split(value, separator) {
+ pairs := strings.SplitN(part, keyValSeparator, 2)
+ if len(pairs) != 2 {
+ return newParseError(sf, fmt.Errorf(`%q should be in "key%svalue" format`, part, keyValSeparator))
+ }
+
+ key, err := keyParserFunc(pairs[0])
+ if err != nil {
+ return newParseError(sf, err)
+ }
+
+ elem, err := elemParserFunc(pairs[1])
+ if err != nil {
+ return newParseError(sf, err)
+ }
+
+ result.SetMapIndex(reflect.ValueOf(key).Convert(keyType), reflect.ValueOf(elem).Convert(elemType))
+ }
+
+ field.Set(result)
+ return nil
+}
+
+func asTextUnmarshaler(field reflect.Value) encoding.TextUnmarshaler {
+ if field.Kind() == reflect.Ptr {
+ if field.IsNil() {
+ field.Set(reflect.New(field.Type().Elem()))
+ }
+ } else if field.CanAddr() {
+ field = field.Addr()
+ }
+
+ tm, ok := field.Interface().(encoding.TextUnmarshaler)
+ if !ok {
+ return nil
+ }
+ return tm
+}
+
+func parseTextUnmarshalers(field reflect.Value, data []string, sf reflect.StructField) error {
+ s := len(data)
+ elemType := field.Type().Elem()
+ slice := reflect.MakeSlice(reflect.SliceOf(elemType), s, s)
+ for i, v := range data {
+ sv := slice.Index(i)
+ kind := sv.Kind()
+ if kind == reflect.Ptr {
+ sv = reflect.New(elemType.Elem())
+ } else {
+ sv = sv.Addr()
+ }
+ tm := sv.Interface().(encoding.TextUnmarshaler)
+ if err := tm.UnmarshalText([]byte(v)); err != nil {
+ return newParseError(sf, err)
+ }
+ if kind == reflect.Ptr {
+ slice.Index(i).Set(sv)
+ }
+ }
+
+ field.Set(slice)
+
+ return nil
+}
+
+// ToMap Converts list of env vars as provided by os.Environ() to map you
+// can use as Options.Environment field
+func ToMap(env []string) map[string]string {
+ return toMap(env)
+}
+
+func isInvalidPtr(v reflect.Value) bool {
+ return reflect.Ptr == v.Kind() && v.Elem().Kind() == reflect.Invalid
+}
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/env_tomap.go b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/env_tomap.go
new file mode 100644
index 0000000000000000000000000000000000000000..aece2ae9af27d7ee5825b941e3239af06a25da2b
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/env_tomap.go
@@ -0,0 +1,16 @@
+//go:build !windows
+
+package env
+
+import "strings"
+
+func toMap(env []string) map[string]string {
+ r := map[string]string{}
+ for _, e := range env {
+ p := strings.SplitN(e, "=", 2)
+ if len(p) == 2 {
+ r[p[0]] = p[1]
+ }
+ }
+ return r
+}
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/env_tomap_windows.go b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/env_tomap_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..04ce66f577f4ae8fd4e0defd64f81e89947dd9af
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/env_tomap_windows.go
@@ -0,0 +1,29 @@
+//go:build windows
+
+package env
+
+import "strings"
+
+func toMap(env []string) map[string]string {
+ r := map[string]string{}
+ for _, e := range env {
+ p := strings.SplitN(e, "=", 2)
+
+ // On Windows, environment variables can start with '='. If so, Split at next character.
+ // See env_windows.go in the Go source: https://github.com/golang/go/blob/master/src/syscall/env_windows.go#L58
+ prefixEqualSign := false
+ if len(e) > 0 && e[0] == '=' {
+ e = e[1:]
+ prefixEqualSign = true
+ }
+ p = strings.SplitN(e, "=", 2)
+ if prefixEqualSign {
+ p[0] = "=" + p[0]
+ }
+
+ if len(p) == 2 {
+ r[p[0]] = p[1]
+ }
+ }
+ return r
+}
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/error.go b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/error.go
new file mode 100644
index 0000000000000000000000000000000000000000..d615912c4878e7b8e1352a1a797b0ae5660e5a6d
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/error.go
@@ -0,0 +1,173 @@
+package env
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+)
+
+// An aggregated error wrapper to combine gathered errors.
+// This allows either to display all errors or convert them individually
+// List of the available errors
+// ParseError
+// NotStructPtrError
+// NoParserError
+// NoSupportedTagOptionError
+// VarIsNotSetError
+// EmptyVarError
+// LoadFileContentError
+// ParseValueError
+type AggregateError struct {
+ Errors []error
+}
+
+func newAggregateError(initErr error) error {
+ return AggregateError{
+ []error{
+ initErr,
+ },
+ }
+}
+
+func (e AggregateError) Error() string {
+ var sb strings.Builder
+
+ sb.WriteString("env:")
+
+ for _, err := range e.Errors {
+ sb.WriteString(fmt.Sprintf(" %v;", err.Error()))
+ }
+
+ return strings.TrimRight(sb.String(), ";")
+}
+
+// Unwrap implements std errors.Join go1.20 compatibility
+func (e AggregateError) Unwrap() []error {
+ return e.Errors
+}
+
+// Is conforms with errors.Is.
+func (e AggregateError) Is(err error) bool {
+ for _, ie := range e.Errors {
+ if reflect.TypeOf(ie) == reflect.TypeOf(err) {
+ return true
+ }
+ }
+ return false
+}
+
+// The error occurs when it's impossible to convert the value for given type.
+type ParseError struct {
+ Name string
+ Type reflect.Type
+ Err error
+}
+
+func newParseError(sf reflect.StructField, err error) error {
+ return ParseError{sf.Name, sf.Type, err}
+}
+
+func (e ParseError) Error() string {
+ return fmt.Sprintf("parse error on field %q of type %q: %v", e.Name, e.Type, e.Err)
+}
+
+// The error occurs when pass something that is not a pointer to a struct to Parse
+type NotStructPtrError struct{}
+
+func (e NotStructPtrError) Error() string {
+ return "expected a pointer to a Struct"
+}
+
+// This error occurs when there is no parser provided for given type.
+type NoParserError struct {
+ Name string
+ Type reflect.Type
+}
+
+func newNoParserError(sf reflect.StructField) error {
+ return NoParserError{sf.Name, sf.Type}
+}
+
+func (e NoParserError) Error() string {
+ return fmt.Sprintf("no parser found for field %q of type %q", e.Name, e.Type)
+}
+
+// This error occurs when the given tag is not supported.
+// Built-in supported tags: "", "file", "required", "unset", "notEmpty",
+// "expand", "envDefault", and "envSeparator".
+type NoSupportedTagOptionError struct {
+ Tag string
+}
+
+func newNoSupportedTagOptionError(tag string) error {
+ return NoSupportedTagOptionError{tag}
+}
+
+func (e NoSupportedTagOptionError) Error() string {
+ return fmt.Sprintf("tag option %q not supported", e.Tag)
+}
+
+// This error occurs when the required variable is not set.
+//
+// Deprecated: use VarIsNotSetError.
+type EnvVarIsNotSetError = VarIsNotSetError
+
+// This error occurs when the required variable is not set.
+type VarIsNotSetError struct {
+ Key string
+}
+
+func newVarIsNotSetError(key string) error {
+ return VarIsNotSetError{key}
+}
+
+func (e VarIsNotSetError) Error() string {
+ return fmt.Sprintf(`required environment variable %q is not set`, e.Key)
+}
+
+// This error occurs when the variable which must be not empty is existing but has an empty value
+//
+// Deprecated: use EmptyVarError.
+type EmptyEnvVarError = EmptyVarError
+
+// This error occurs when the variable which must be not empty is existing but has an empty value
+type EmptyVarError struct {
+ Key string
+}
+
+func newEmptyVarError(key string) error {
+ return EmptyVarError{key}
+}
+
+func (e EmptyVarError) Error() string {
+ return fmt.Sprintf("environment variable %q should not be empty", e.Key)
+}
+
+// This error occurs when it's impossible to load the value from the file.
+type LoadFileContentError struct {
+ Filename string
+ Key string
+ Err error
+}
+
+func newLoadFileContentError(filename, key string, err error) error {
+ return LoadFileContentError{filename, key, err}
+}
+
+func (e LoadFileContentError) Error() string {
+ return fmt.Sprintf("could not load content of file %q from variable %s: %v", e.Filename, e.Key, e.Err)
+}
+
+// This error occurs when it's impossible to convert value using given parser.
+type ParseValueError struct {
+ Msg string
+ Err error
+}
+
+func newParseValueError(message string, err error) error {
+ return ParseValueError{message, err}
+}
+
+func (e ParseValueError) Error() string {
+ return fmt.Sprintf("%s: %v", e.Msg, e.Err)
+}
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/go.mod b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..23c7f133d6f951132ce144dfcffd9e4f13dc2408
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/go.mod
@@ -0,0 +1,13 @@
+module github.com/caarlos0/env/v11
+
+// v11.0.1 accidentally introduced a breaking change regarding the behavior of nil pointers.
+// You can now chose to auto-initialize them by setting the `init` tag option.
+retract v11.0.1
+
+// v11.2.0 accidentally introduced a breaking change regarding the behavior of nil slices of complex types.
+retract v11.2.0
+
+// v11.3.0 merges OS environment variables with environments set with Options instead of overriding them.
+retract v11.3.0
+
+go 1.18
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/go.sum b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/environment/source/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/instruction.md b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..608e05e41ea7b632459aa0d59958150af60f2ee2
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/instruction.md
@@ -0,0 +1,41 @@
+Slice parsing fails with panic when using pointer to slice
+
+#### Description
+
+When parsing environment variables into a pointer to slice field, the code panics with "reflect.MakeSlice of non-slice type". This appears to be related to incorrect type handling when the field is a pointer to a slice rather than a direct slice.
+
+#### Steps/Code to Reproduce
+
+```go
+package main
+
+import (
+ "fmt"
+ "os"
+ "github.com/caarlos0/env/v11"
+)
+
+type Config struct {
+ Items *[]string `env:"ITEMS" envSeparator:","`
+}
+
+func main() {
+ os.Setenv("ITEMS", "item1,item2,item3")
+
+ cfg := Config{}
+ if err := env.Parse(&cfg); err != nil {
+ fmt.Printf("Error: %v\n", err)
+ return
+ }
+
+ fmt.Printf("Items: %v\n", *cfg.Items)
+}
+```
+
+Running this code results in a panic:
+```
+panic: reflect.MakeSlice of non-slice type
+```
+
+The expected behavior would be to successfully parse the comma-separated values into the slice pointed to by the Items field.
+Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled.
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/provenance.json b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/provenance.json
new file mode 100644
index 0000000000000000000000000000000000000000..bccfcb5d282bb45bece5b84ca0f8b39ad72a7c9b
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/provenance.json
@@ -0,0 +1,232 @@
+{
+ "cloud_launch_ready": false,
+ "execution_command": [
+ "/usr/local/go/bin/go",
+ "test",
+ "-json",
+ "-count=1",
+ "./..."
+ ],
+ "execution_profile": "harbor-semantic-jobs-v1",
+ "full_rfc008": false,
+ "generated_reference": false,
+ "native_validation_performed": false,
+ "negative_classes": {
+ "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt",
+ "original-bug": "task-specific unchanged semantic bug",
+ "stale-reward": "same wrong implementation with stale reward spoof attempt"
+ },
+ "new_arbitrary_files_supported": false,
+ "partial_hunk_control": {
+ "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only",
+ "extra_semantic_repair_coverage": false,
+ "original_patch_hunks": 1
+ },
+ "private_frozen_files": {
+ "env_test.go": {
+ "mode": "0o644",
+ "sha256": "0d608693b75598978bbbf9c7a34099f3c9f93dfc37f7aac7356979aa7687770f",
+ "size": 63961
+ },
+ "env_tomap_test.go": {
+ "mode": "0o644",
+ "sha256": "dbc4b0ad9ae44a571dcaf85643e2d9f01bb6f8cec137c3e2ec361aaaf9ecf36d",
+ "size": 352
+ },
+ "env_tomap_windows_test.go": {
+ "mode": "0o644",
+ "sha256": "1713984775c2109257a234f68381b2accac55bfc075e638d1379a648a81dc7f2",
+ "size": 563
+ },
+ "example_test.go": {
+ "mode": "0o644",
+ "sha256": "4567ba2c384d1d776a647cf2de0a60fa580159229ad5930d1354b437227f9313",
+ "size": 11860
+ }
+ },
+ "public_files": {
+ ".editorconfig": {
+ "mode": "0o644",
+ "sha256": "f886f56c21aba6215c957ce4d4606356c137d40ea0e82fc5680cba109b8ff04a",
+ "size": 457
+ },
+ ".github/FUNDING.yml": {
+ "mode": "0o644",
+ "sha256": "4ab2626e3eec3a31e5efbe07fb89362070697e9e92118206608074f292910483",
+ "size": 19
+ },
+ ".github/dependabot.yml": {
+ "mode": "0o644",
+ "sha256": "45451fbbd7ae6582f5002434ba7f315c97d6addcd652628a8c30521f4ea066d7",
+ "size": 315
+ },
+ ".gitignore": {
+ "mode": "0o644",
+ "sha256": "710b245f7a0f5cc6c9b0c9a37538c09367219fd180d168b58524e5d13e942a07",
+ "size": 40
+ },
+ ".golangci.yml": {
+ "mode": "0o644",
+ "sha256": "4298d79cc4dd26f11436abc6f27087c5c26d698a5b06a2ee9fc56d32f0f114b6",
+ "size": 555
+ },
+ ".goreleaser.yml": {
+ "mode": "0o644",
+ "sha256": "00df4f1c403533d47a74e663bba12dd4e01164a36760e8047c267e9afc8f0d98",
+ "size": 197
+ },
+ ".mailmap": {
+ "mode": "0o644",
+ "sha256": "9d70f3f1c2d252495bfa29a8a96af08933fe10a731fa7d5434eee42cf20af15f",
+ "size": 791
+ },
+ "LICENSE.md": {
+ "mode": "0o644",
+ "sha256": "657225b6c683571763995299113fe46677f110c70df88e95e75fa67a8772f5fa",
+ "size": 1095
+ },
+ "Makefile": {
+ "mode": "0o644",
+ "sha256": "e6088fe61c4ccc6130fe101a14a5f78d0f79c96279048c15b1005683acd7b9ca",
+ "size": 649
+ },
+ "README.md": {
+ "mode": "0o644",
+ "sha256": "44b96c6f24f218cb42b99179657786e8e2d2cc79547b36037c1ef3a3f540a269",
+ "size": 5592
+ },
+ "env.go": {
+ "mode": "0o644",
+ "sha256": "b9c46f0a7c58e54c90090eab519bc2b40e9feaee4cce894842f957a7fbaa3389",
+ "size": 22201
+ },
+ "env_tomap.go": {
+ "mode": "0o644",
+ "sha256": "bac0ff6897a67d7723a9137a6ae9bd1bceb48ba2f7f259d288505701cc57c717",
+ "size": 237
+ },
+ "env_tomap_windows.go": {
+ "mode": "0o644",
+ "sha256": "8dcbbe1e94e246fe8bdaa23ec044a0be26267a71e056c554818956d445cabdad",
+ "size": 626
+ },
+ "error.go": {
+ "mode": "0o644",
+ "sha256": "f6355aaf02f27f0a3c1ff5b0f9ab5d449760aa953e0620ff859408fc22340097",
+ "size": 4167
+ },
+ "go.mod": {
+ "mode": "0o644",
+ "sha256": "a6ba06a482d3ec54f8af25460dfe0ff19f14b96e501433fa07744368604ba610",
+ "size": 481
+ },
+ "go.sum": {
+ "mode": "0o644",
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+ "size": 0
+ }
+ },
+ "reference_kind": "provided_healthy_parent_changed_implementation",
+ "runtime": {
+ "clean_runtime_qualified": false,
+ "config": {
+ "architecture": "amd64",
+ "digest": "sha256:69569999a79422f5f3277caf4b318650012da112846a5d9eb210146079ad3493",
+ "os": "linux",
+ "sha256": "69569999a79422f5f3277caf4b318650012da112846a5d9eb210146079ad3493"
+ },
+ "context_inventory_sha256": "2892073257a6b52aee4a3762a138096e3d8a0a419e532cf48ba4d31d682a3b50",
+ "image": "registry.hf.space/harness-hub-scale800-11a67b0f935a27b1-starter-v1@sha256:4ee00ee1d2e8d73fc91bd8adc004c943c4b3b4cf08c09f46a8ffa24dab68de93",
+ "image_pull_qualified": false,
+ "provider_image_source_attestation": false,
+ "publication_receipt_sha256": "f5c9cff05fa74ff72cc52870951435cf6e3f748692f35793e2ef6240cd0e6dcf",
+ "receipt_path": "resolutions/11a67b0f935a27b1/resolution.json",
+ "receipt_sha256": "9583a4c043c9e6333ff2946a0df1e9870879d7a0d44d4e811d3ebe87d0c016cb",
+ "registry_digest": "sha256:4ee00ee1d2e8d73fc91bd8adc004c943c4b3b4cf08c09f46a8ffa24dab68de93",
+ "source_image": "docker.io/swebench/swesmith.x86_64.caarlos0_1776_env.56a09d29@sha256:ddb461183d1a3ba39a9f28922c4b5015d4a1e19a369d10228544507d99252263",
+ "source_receipt_sha256": "2e19cd335650f29b99354852192b9ad6b900201ec6ab5c03bd757e5cd145f552",
+ "space_commit": "67fe69712e700b549297ab0537fb95fcf88ae53f",
+ "space_id": "harness-hub/scale800-11a67b0f935a27b1-starter-v1",
+ "status": "registry_resolved_paused_unqualified"
+ },
+ "schema": "scale800-go-jobs-transform-v1",
+ "source_completion_sha256": "327398dc84377443263d183a9f1aeda61eed4b97a9fa1acf58998e82ecd4fd78",
+ "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f",
+ "source_inventory_verified": true,
+ "source_manifest_sha256": null,
+ "source_proof_sha256": "66730099742f97a3750901160f1fb93f816a3708fbfe7b9a0141aee17b184644",
+ "source_record": {
+ "anti_training_canary": false,
+ "anti_training_reviewed": true,
+ "candidate_id": "swesmith-go:caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6",
+ "cloud_launch_ready": false,
+ "healthy_mirror_commit": "90205ddc6b2cdf7716612ad4be788eaad92260fb",
+ "instruction_sha256": "611649b9abfda22499337fbf869c8c7e451016b8b5c0ac9afaccc0754ac77d66",
+ "is_fork": true,
+ "learner_path": "tasks/0d0f86444ad40f8dc747a035/learner",
+ "license_evidence": {
+ "source_code": {
+ "reviewed": true,
+ "sha256": "657225b6c683571763995299113fe46677f110c70df88e95e75fa67a8772f5fa",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://raw.githubusercontent.com/swesmith/caarlos0__env.56a09d29/b09fd86c069568ee8c0812c1390fb3c79ed9d08c/LICENSE.md"
+ },
+ "task_bundle": {
+ "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source",
+ "reviewed": true,
+ "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f",
+ "spdx": "MIT",
+ "training_allowed": true,
+ "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015"
+ }
+ },
+ "original_source_commit": "56a09d295d9321b1f3b537fd23df1527011cd83d",
+ "patch_sha256": "c3bbe2effdd3d15e01b374ae9eb4e33343a345046f3720da36275c0f52bdff9b",
+ "provenance_path": "tasks/0d0f86444ad40f8dc747a035/source-proof.json",
+ "repository_lineage": [
+ "swesmith/caarlos0__env.56a09d29",
+ "caarlos0/env"
+ ],
+ "rfc008_complete": false,
+ "runtime_qualified": false,
+ "runtime_test_identity_status": "pending_runtime_test_identity_resolution",
+ "semantic_nonoverlap_established": false,
+ "source_commit": "b09fd86c069568ee8c0812c1390fb3c79ed9d08c",
+ "source_dataset": "SWE-bench/SWE-smith-go",
+ "source_head_commit": "4e3d738f40a3ce6d7baf6a3fff5ba3dfc4fec25a",
+ "source_kind": "mutation",
+ "source_repo": "swesmith/caarlos0__env.56a09d29",
+ "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015",
+ "source_split": "train",
+ "target_model_calibrated": false,
+ "task_id": "caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6",
+ "task_sha256": "4eecf1372a25534383093d1c49aff8e39225441e567bf7a13955a90bb4d96330",
+ "training_admissible": false,
+ "upstream_identity_reviewed": true,
+ "upstream_repo": "caarlos0/env",
+ "usage": "quarantine_only"
+ },
+ "source_row_sha256": "669b6c8462e4fcdc6ab511e4d3cbf01d64c70f42a3a69ebc11d6c5be260dd2f3",
+ "source_test_command": "go test -v ./...",
+ "target_model_calibrated": false,
+ "training_admissible": false,
+ "transfer_allowlist": [
+ "/testbed/.editorconfig",
+ "/testbed/.github/FUNDING.yml",
+ "/testbed/.github/dependabot.yml",
+ "/testbed/.gitignore",
+ "/testbed/.golangci.yml",
+ "/testbed/.goreleaser.yml",
+ "/testbed/.mailmap",
+ "/testbed/LICENSE.md",
+ "/testbed/Makefile",
+ "/testbed/README.md",
+ "/testbed/env.go",
+ "/testbed/env_tomap.go",
+ "/testbed/env_tomap_windows.go",
+ "/testbed/error.go",
+ "/testbed/go.mod",
+ "/testbed/go.sum"
+ ]
+}
diff --git a/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/solution/solve.sh b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..06cd40cce003e413b6a3fa533f95872a96409599
--- /dev/null
+++ b/tasks/caarlos0__env.56a09d29.func_pm_ctrl_invert_if__f1cdiaa6/solution/solve.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+/usr/local/bin/python -I - <<'OPENENV_REFERENCE'
+import base64,json
+from pathlib import Path
+files=json.loads('{"env.go": {"data": "Ly8gUGFja2FnZSBlbnYgaXMgYSBzaW1wbGUsIHplcm8tZGVwZW5kZW5jaWVzIGxpYnJhcnkgdG8gcGFyc2UgZW52aXJvbm1lbnQKLy8gdmFyaWFibGVzIGludG8gc3RydWN0cy4KLy8KLy8gRXhhbXBsZToKLy8KLy8JdHlwZSBjb25maWcgc3RydWN0IHsKLy8JCUhvbWUgc3RyaW5nIGBlbnY6IkhPTUUiYAovLwl9Ci8vCS8vIHBhcnNlCi8vCXZhciBjZmcgY29uZmlnCi8vCWVyciA6PSBlbnYuUGFyc2UoJmNmZykKLy8JLy8gb3IgcGFyc2Ugd2l0aCBnZW5lcmljcwovLwljZmcsIGVyciA6PSBlbnYuUGFyc2VBc1tjb25maWddKCkKLy8KLy8gQ2hlY2sgdGhlIGV4YW1wbGVzIGFuZCBSRUFETUUgZm9yIG1vcmUgZGV0YWlsZWQgdXNhZ2UuCnBhY2thZ2UgZW52CgppbXBvcnQgKAoJImVuY29kaW5nIgoJImZtdCIKCSJuZXQvdXJsIgoJIm9zIgoJInJlZmxlY3QiCgkic3RyY29udiIKCSJzdHJpbmdzIgoJInRpbWUiCgkidW5pY29kZSIKKQoKLy8gbm9saW50OiBnb2NoZWNrbm9nbG9iYWxzCnZhciAoCglkZWZhdWx0QnVpbHRJblBhcnNlcnMgPSBtYXBbcmVmbGVjdC5LaW5kXVBhcnNlckZ1bmN7CgkJcmVmbGVjdC5Cb29sOiBmdW5jKHYgc3RyaW5nKSAoaW50ZXJmYWNle30sIGVycm9yKSB7CgkJCXJldHVybiBzdHJjb252LlBhcnNlQm9vbCh2KQoJCX0sCgkJcmVmbGVjdC5TdHJpbmc6IGZ1bmModiBzdHJpbmcpIChpbnRlcmZhY2V7fSwgZXJyb3IpIHsKCQkJcmV0dXJuIHYsIG5pbAoJCX0sCgkJcmVmbGVjdC5JbnQ6IGZ1bmModiBzdHJpbmcpIChpbnRlcmZhY2V7fSwgZXJyb3IpIHsKCQkJaSwgZXJyIDo9IHN0cmNvbnYuUGFyc2VJbnQodiwgMTAsIDMyKQoJCQlyZXR1cm4gaW50KGkpLCBlcnIKCQl9LAoJCXJlZmxlY3QuSW50MTY6IGZ1bmModiBzdHJpbmcpIChpbnRlcmZhY2V7fSwgZXJyb3IpIHsKCQkJaSwgZXJyIDo9IHN0cmNvbnYuUGFyc2VJbnQodiwgMTAsIDE2KQoJCQlyZXR1cm4gaW50MTYoaSksIGVycgoJCX0sCgkJcmVmbGVjdC5JbnQzMjogZnVuYyh2IHN0cmluZykgKGludGVyZmFjZXt9LCBlcnJvcikgewoJCQlpLCBlcnIgOj0gc3RyY29udi5QYXJzZUludCh2LCAxMCwgMzIpCgkJCXJldHVybiBpbnQzMihpKSwgZXJyCgkJfSwKCQlyZWZsZWN0LkludDY0OiBmdW5jKHYgc3RyaW5nKSAoaW50ZXJmYWNle30sIGVycm9yKSB7CgkJCXJldHVybiBzdHJjb252LlBhcnNlSW50KHYsIDEwLCA2NCkKCQl9LAoJCXJlZmxlY3QuSW50ODogZnVuYyh2IHN0cmluZykgKGludGVyZmFjZXt9LCBlcnJvcikgewoJCQlpLCBlcnIgOj0gc3RyY29udi5QYXJzZUludCh2LCAxMCwgOCkKCQkJcmV0dXJuIGludDgoaSksIGVycgoJCX0sCgkJcmVmbGVjdC5VaW50OiBmdW5jKHYgc3RyaW5nKSAoaW50ZXJmYWNle30sIGVycm9yKSB7CgkJCWksIGVyciA6PSBzdHJjb252LlBhcnNlVWludCh2LCAxMCwgMzIpCgkJCXJldHVybiB1aW50KGkpLCBlcnIKCQl9LAoJCXJlZmxlY3QuVWludDE2OiBmdW5jKHYgc3RyaW5nKSAoaW50ZXJmYWNle30sIGVycm9yKSB7CgkJCWksIGVyciA6PSBzdHJjb252LlBhcnNlVWludCh2LCAxMCwgMTYpCgkJCXJldHVybiB1aW50MTYoaSksIGVycgoJCX0sCgkJcmVmbGVjdC5VaW50MzI6IGZ1bmModiBzdHJpbmcpIChpbnRlcmZhY2V7fSwgZXJyb3IpIHsKCQkJaSwgZXJyIDo9IHN0cmNvbnYuUGFyc2VVaW50KHYsIDEwLCAzMikKCQkJcmV0dXJuIHVpbnQzMihpKSwgZXJyCgkJfSwKCQlyZWZsZWN0LlVpbnQ2NDogZnVuYyh2IHN0cmluZykgKGludGVyZmFjZXt9LCBlcnJvcikgewoJCQlpLCBlcnIgOj0gc3RyY29udi5QYXJzZVVpbnQodiwgMTAsIDY0KQoJCQlyZXR1cm4gaSwgZXJyCgkJfSwKCQlyZWZsZWN0LlVpbnQ4OiBmdW5jKHYgc3RyaW5nKSAoaW50ZXJmYWNle30sIGVycm9yKSB7CgkJCWksIGVyciA6PSBzdHJjb252LlBhcnNlVWludCh2LCAxMCwgOCkKCQkJcmV0dXJuIHVpbnQ4KGkpLCBlcnIKCQl9LAoJCXJlZmxlY3QuRmxvYXQ2NDogZnVuYyh2IHN0cmluZykgKGludGVyZmFjZXt9LCBlcnJvcikgewoJCQlyZXR1cm4gc3RyY29udi5QYXJzZUZsb2F0KHYsIDY0KQoJCX0sCgkJcmVmbGVjdC5GbG9hdDMyOiBmdW5jKHYgc3RyaW5nKSAoaW50ZXJmYWNle30sIGVycm9yKSB7CgkJCWYsIGVyciA6PSBzdHJjb252LlBhcnNlRmxvYXQodiwgMzIpCgkJCXJldHVybiBmbG9hdDMyKGYpLCBlcnIKCQl9LAoJfQopCgpmdW5jIGRlZmF1bHRUeXBlUGFyc2VycygpIG1hcFtyZWZsZWN0LlR5cGVdUGFyc2VyRnVuYyB7CglyZXR1cm4gbWFwW3JlZmxlY3QuVHlwZV1QYXJzZXJGdW5jewoJCXJlZmxlY3QuVHlwZU9mKHVybC5VUkx7fSk6ICAgICAgIHBhcnNlVVJMLAoJCXJlZmxlY3QuVHlwZU9mKHRpbWUuTmFub3NlY29uZCk6IHBhcnNlRHVyYXRpb24sCgkJcmVmbGVjdC5UeXBlT2YodGltZS5Mb2NhdGlvbnt9KTogcGFyc2VMb2NhdGlvbiwKCX0KfQoKZnVuYyBwYXJzZVVSTCh2IHN0cmluZykgKGludGVyZmFjZXt9LCBlcnJvcikgewoJdSwgZXJyIDo9IHVybC5QYXJzZSh2KQoJaWYgZXJyICE9IG5pbCB7CgkJcmV0dXJuIG5pbCwgbmV3UGFyc2VWYWx1ZUVycm9yKCJ1bmFibGUgdG8gcGFyc2UgVVJMIiwgZXJyKQoJfQoJcmV0dXJuICp1LCBuaWwKfQoKZnVuYyBwYXJzZUR1cmF0aW9uKHYgc3RyaW5nKSAoaW50ZXJmYWNle30sIGVycm9yKSB7CglkLCBlcnIgOj0gdGltZS5QYXJzZUR1cmF0aW9uKHYpCglpZiBlcnIgIT0gbmlsIHsKCQlyZXR1cm4gbmlsLCBuZXdQYXJzZVZhbHVlRXJyb3IoInVuYWJsZSB0byBwYXJzZSBkdXJhdGlvbiIsIGVycikKCX0KCXJldHVybiBkLCBlcnIKfQoKZnVuYyBwYXJzZUxvY2F0aW9uKHYgc3RyaW5nKSAoaW50ZXJmYWNle30sIGVycm9yKSB7Cglsb2MsIGVyciA6PSB0aW1lLkxvYWRMb2NhdGlvbih2KQoJaWYgZXJyICE9IG5pbCB7CgkJcmV0dXJuIG5pbCwgbmV3UGFyc2VWYWx1ZUVycm9yKCJ1bmFibGUgdG8gcGFyc2UgbG9jYXRpb24iLCBlcnIpCgl9CglyZXR1cm4gKmxvYywgbmlsCn0KCi8vIFBhcnNlckZ1bmMgZGVmaW5lcyB0aGUgc2lnbmF0dXJlIG9mIGEgZnVuY3Rpb24gdGhhdCBjYW4gYmUgdXNlZCB3aXRoaW4KLy8gYE9wdGlvbnNgJyBgRnVuY01hcGAuCnR5cGUgUGFyc2VyRnVuYyBmdW5jKHYgc3RyaW5nKSAoaW50ZXJmYWNle30sIGVycm9yKQoKLy8gT25TZXRGbiBpcyBhIGhvb2sgdGhhdCBjYW4gYmUgcnVuIHdoZW4gYSB2YWx1ZSBpcyBzZXQuCnR5cGUgT25TZXRGbiBmdW5jKHRhZyBzdHJpbmcsIHZhbHVlIGludGVyZmFjZXt9LCBpc0RlZmF1bHQgYm9vbCkKCi8vIHByb2Nlc3NGaWVsZEZuIGlzIGEgZnVuY3Rpb24gd2hpY2ggdGFrZXMgYWxsIGluZm9ybWF0aW9uIGFib3V0IGEgZmllbGQgYW5kIHByb2Nlc3NlcyBpdC4KdHlwZSBwcm9jZXNzRmllbGRGbiBmdW5jKAoJcmVmRmllbGQgcmVmbGVjdC5WYWx1ZSwKCXJlZlR5cGVGaWVsZCByZWZsZWN0LlN0cnVjdEZpZWxkLAoJb3B0cyBPcHRpb25zLAoJZmllbGRQYXJhbXMgRmllbGRQYXJhbXMsCikgZXJyb3IKCi8vIE9wdGlvbnMgZm9yIHRoZSBwYXJzZXIuCnR5cGUgT3B0aW9ucyBzdHJ1Y3QgewoJLy8gRW52aXJvbm1lbnQga2V5cyBhbmQgdmFsdWVzIHRoYXQgd2lsbCBiZSBhY2Nlc3NpYmxlIGZvciB0aGUgc2VydmljZS4KCUVudmlyb25tZW50IG1hcFtzdHJpbmddc3RyaW5nCgoJLy8gVGFnTmFtZSBzcGVjaWZpZXMgYW5vdGhlciB0YWcgbmFtZSB0byB1c2UgcmF0aGVyIHRoYW4gdGhlIGRlZmF1bHQgJ2VudicuCglUYWdOYW1lIHN0cmluZwoKCS8vIFByZWZpeFRhZ05hbWUgc3BlY2lmaWVzIGFub3RoZXIgcHJlZml4IHRhZyBuYW1lIHRvIHVzZSByYXRoZXIgdGhhbiB0aGUgZGVmYXVsdCAnZW52UHJlZml4Jy4KCVByZWZpeFRhZ05hbWUgc3RyaW5nCgoJLy8gRGVmYXVsdFZhbHVlVGFnTmFtZSBzcGVjaWZpZXMgYW5vdGhlciBkZWZhdWx0IHRhZyBuYW1lIHRvIHVzZSByYXRoZXIgdGhhbiB0aGUgZGVmYXVsdCAnZW52RGVmYXVsdCcuCglEZWZhdWx0VmFsdWVUYWdOYW1lIHN0cmluZwoKCS8vIFJlcXVpcmVkSWZOb0RlZiBhdXRvbWF0aWNhbGx5IHNldHMgYWxsIGZpZWxkcyBhcyByZXF1aXJlZCBpZiB0aGV5IGRvIG5vdAoJLy8gZGVjbGFyZSAnZW52RGVmYXVsdCcuCglSZXF1aXJlZElmTm9EZWYgYm9vbAoKCS8vIE9uU2V0IGFsbG93cyB0byBydW4gYSBmdW5jdGlvbiB3aGVuIGEgdmFsdWUgaXMgc2V0LgoJT25TZXQgT25TZXRGbgoKCS8vIFByZWZpeCBkZWZpbmUgYSBwcmVmaXggZm9yIGV2ZXJ5IGtleS4KCVByZWZpeCBzdHJpbmcKCgkvLyBVc2VGaWVsZE5hbWVCeURlZmF1bHQgZGVmaW5lcyB3aGV0aGVyIG9yIG5vdCBgZW52YCBzaG91bGQgdXNlIHRoZSBmaWVsZAoJLy8gbmFtZSBieSBkZWZhdWx0IGlmIHRoZSBgZW52YCBrZXkgaXMgbWlzc2luZy4KCS8vIE5vdGUgdGhhdCB0aGUgZmllbGQgbmFtZSB3aWxsIGJlICJjb252ZXJ0ZWQiIHRvIGNvbmZvcm0gd2l0aCBlbnZpcm9ubWVudAoJLy8gdmFyaWFibGUgbmFtZXMgY29udmVudGlvbnMuCglVc2VGaWVsZE5hbWVCeURlZmF1bHQgYm9vbAoKCS8vIFNldERlZmF1bHRzRm9yWmVyb1ZhbHVlc09ubHkgZGVmaW5lcyB3aGV0aGVyIHRvIHNldCBkZWZhdWx0cyBmb3IgemVybyB2YWx1ZXMKCS8vIElmIHRoZSBgZW52YCB2YXJpYWJsZSBmb3IgdGhlIHZhbHVlIGlzIG5vdCBzZXQKCS8vIGFuZCBgZW52RGVmYXVsdGAgaXMgc2V0CgkvLyBhbmQgdGhlIHZhbHVlIGlzIG5vdCBhIHplcm8gdmFsdWUgZm9yIHRoZSB0aGUgdHlwZQoJLy8gYW5kIFNldERlZmF1bHRzRm9yWmVyb1ZhbHVlc09ubHk9dHJ1ZQoJLy8gdGhlIHZhbHVlIGZyb20gYGVudkRlZmF1bHRgIHdpbGwgYmUgaWdub3JlZAoJLy8gVXNlZnVsbCBmb3IgbWl4aW5nIGRlZmF1bHQgdmFsdWVzIGZyb20gYGVudkRlZmF1bHRgIGFuZCBzdHJ1Y3QgaW5pdGlhbGl6YXRpb24KCVNldERlZmF1bHRzRm9yWmVyb1ZhbHVlc09ubHkgYm9vbAoKCS8vIEN1c3RvbSBwYXJzZSBmdW5jdGlvbnMgZm9yIGRpZmZlcmVudCB0eXBlcy4KCUZ1bmNNYXAgbWFwW3JlZmxlY3QuVHlwZV1QYXJzZXJGdW5jCgoJLy8gVXNlZCBpbnRlcm5hbGx5LiBtYXBzIHRoZSBlbnYgdmFyaWFibGUga2V5IHRvIGl0cyByZXNvbHZlZCBzdHJpbmcgdmFsdWUuCgkvLyAoZm9yIGVudiB2YXIgZXhwYW5zaW9uKQoJcmF3RW52VmFycyBtYXBbc3RyaW5nXXN0cmluZwp9CgpmdW5jIChvcHRzICpPcHRpb25zKSBnZXRSYXdFbnYocyBzdHJpbmcpIHN0cmluZyB7Cgl2YWwgOj0gb3B0cy5yYXdFbnZWYXJzW3NdCglpZiB2YWwgPT0gIiIgewoJCXZhbCA9IG9wdHMuRW52aXJvbm1lbnRbc10KCX0KCXJldHVybiBvcy5FeHBhbmQodmFsLCBvcHRzLmdldFJhd0VudikKfQoKZnVuYyBkZWZhdWx0T3B0aW9ucygpIE9wdGlvbnMgewoJcmV0dXJuIE9wdGlvbnN7CgkJVGFnTmFtZTogICAgICAgICAgICAgImVudiIsCgkJUHJlZml4VGFnTmFtZTogICAgICAgImVudlByZWZpeCIsCgkJRGVmYXVsdFZhbHVlVGFnTmFtZTogImVudkRlZmF1bHQiLAoJCUVudmlyb25tZW50OiAgICAgICAgIHRvTWFwKG9zLkVudmlyb24oKSksCgkJRnVuY01hcDogICAgICAgICAgICAgZGVmYXVsdFR5cGVQYXJzZXJzKCksCgkJcmF3RW52VmFyczogICAgICAgICAgbWFrZShtYXBbc3RyaW5nXXN0cmluZyksCgl9Cn0KCmZ1bmMgbWVyZ2VPcHRpb25zW1QgYW55XSh0YXJnZXQsIHNvdXJjZSAqVCkgewoJdGFyZ2V0UHRyIDo9IHJlZmxlY3QuVmFsdWVPZih0YXJnZXQpLkVsZW0oKQoJc291cmNlUHRyIDo9IHJlZmxlY3QuVmFsdWVPZihzb3VyY2UpLkVsZW0oKQoKCXRhcmdldFR5cGUgOj0gdGFyZ2V0UHRyLlR5cGUoKQoJZm9yIGkgOj0gMDsgaSA8IHRhcmdldFB0ci5OdW1GaWVsZCgpOyBpKysgewoJCWZpZWxkTmFtZSA6PSB0YXJnZXRUeXBlLkZpZWxkKGkpLk5hbWUKCQl0YXJnZXRGaWVsZCA6PSB0YXJnZXRQdHIuRmllbGQoaSkKCQlzb3VyY2VGaWVsZCA6PSBzb3VyY2VQdHIuRmllbGRCeU5hbWUoZmllbGROYW1lKQoKCQlpZiB0YXJnZXRGaWVsZC5DYW5TZXQoKSAmJiAhaXNaZXJvKHNvdXJjZUZpZWxkKSB7CgkJCS8vIEZ1bmNNYXBzIGFyZSBiZWluZyBtZXJnZWQsIHdoaWxlIEVudmlyb25tZW50cyBtdXN0IGJlIG92ZXJ3cml0dGVuCgkJCWlmIGZpZWxkTmFtZSA9PSAiRnVuY01hcCIgewoJCQkJaWYgIXNvdXJjZUZpZWxkLklzWmVybygpIHsKCQkJCQlpdGVyIDo9IHNvdXJjZUZpZWxkLk1hcFJhbmdlKCkKCQkJCQlmb3IgaXRlci5OZXh0KCkgewoJCQkJCQl0YXJnZXRGaWVsZC5TZXRNYXBJbmRleChpdGVyLktleSgpLCBpdGVyLlZhbHVlKCkpCgkJCQkJfQoJCQkJfQoJCQl9IGVsc2UgewoJCQkJdGFyZ2V0RmllbGQuU2V0KHNvdXJjZUZpZWxkKQoJCQl9CgkJfQoJfQp9CgpmdW5jIGlzWmVybyh2IHJlZmxlY3QuVmFsdWUpIGJvb2wgewoJc3dpdGNoIHYuS2luZCgpIHsKCWNhc2UgcmVmbGVjdC5GdW5jLCByZWZsZWN0Lk1hcCwgcmVmbGVjdC5TbGljZToKCQlyZXR1cm4gdi5Jc05pbCgpCglkZWZhdWx0OgoJCXplcm8gOj0gcmVmbGVjdC5aZXJvKHYuVHlwZSgpKQoJCXJldHVybiB2LkludGVyZmFjZSgpID09IHplcm8uSW50ZXJmYWNlKCkKCX0KfQoKZnVuYyBjdXN0b21PcHRpb25zKG9wdHMgT3B0aW9ucykgT3B0aW9ucyB7CglkZWZPcHRzIDo9IGRlZmF1bHRPcHRpb25zKCkKCW1lcmdlT3B0aW9ucygmZGVmT3B0cywgJm9wdHMpCglyZXR1cm4gZGVmT3B0cwp9CgpmdW5jIG9wdGlvbnNXaXRoU2xpY2VFbnZQcmVmaXgob3B0cyBPcHRpb25zLCBpbmRleCBpbnQpIE9wdGlvbnMgewoJcmV0dXJuIE9wdGlvbnN7CgkJRW52aXJvbm1lbnQ6ICAgICAgICAgICAgICAgICAgb3B0cy5FbnZpcm9ubWVudCwKCQlUYWdOYW1lOiAgICAgICAgICAgICAgICAgICAgICBvcHRzLlRhZ05hbWUsCgkJUHJlZml4VGFnTmFtZTogICAgICAgICAgICAgICAgb3B0cy5QcmVmaXhUYWdOYW1lLAoJCURlZmF1bHRWYWx1ZVRhZ05hbWU6ICAgICAgICAgIG9wdHMuRGVmYXVsdFZhbHVlVGFnTmFtZSwKCQlSZXF1aXJlZElmTm9EZWY6ICAgICAgICAgICAgICBvcHRzLlJlcXVpcmVkSWZOb0RlZiwKCQlPblNldDogICAgICAgICAgICAgICAgICAgICAgICBvcHRzLk9uU2V0LAoJCVByZWZpeDogICAgICAgICAgICAgICAgICAgICAgIGZtdC5TcHJpbnRmKCIlcyVkXyIsIG9wdHMuUHJlZml4LCBpbmRleCksCgkJVXNlRmllbGROYW1lQnlEZWZhdWx0OiAgICAgICAgb3B0cy5Vc2VGaWVsZE5hbWVCeURlZmF1bHQsCgkJU2V0RGVmYXVsdHNGb3JaZXJvVmFsdWVzT25seTogb3B0cy5TZXREZWZhdWx0c0Zvclplcm9WYWx1ZXNPbmx5LAoJCUZ1bmNNYXA6ICAgICAgICAgICAgICAgICAgICAgIG9wdHMuRnVuY01hcCwKCQlyYXdFbnZWYXJzOiAgICAgICAgICAgICAgICAgICBvcHRzLnJhd0VudlZhcnMsCgl9Cn0KCmZ1bmMgb3B0aW9uc1dpdGhFbnZQcmVmaXgoZmllbGQgcmVmbGVjdC5TdHJ1Y3RGaWVsZCwgb3B0cyBPcHRpb25zKSBPcHRpb25zIHsKCXJldHVybiBPcHRpb25zewoJCUVudmlyb25tZW50OiAgICAgICAgICAgICAgICAgIG9wdHMuRW52aXJvbm1lbnQsCgkJVGFnTmFtZTogICAgICAgICAgICAgICAgICAgICAgb3B0cy5UYWdOYW1lLAoJCVByZWZpeFRhZ05hbWU6ICAgICAgICAgICAgICAgIG9wdHMuUHJlZml4VGFnTmFtZSwKCQlEZWZhdWx0VmFsdWVUYWdOYW1lOiAgICAgICAgICBvcHRzLkRlZmF1bHRWYWx1ZVRhZ05hbWUsCgkJUmVxdWlyZWRJZk5vRGVmOiAgICAgICAgICAgICAgb3B0cy5SZXF1aXJlZElmTm9EZWYsCgkJT25TZXQ6ICAgICAgICAgICAgICAgICAgICAgICAgb3B0cy5PblNldCwKCQlQcmVmaXg6ICAgICAgICAgICAgICAgICAgICAgICBvcHRzLlByZWZpeCArIGZpZWxkLlRhZy5HZXQob3B0cy5QcmVmaXhUYWdOYW1lKSwKCQlVc2VGaWVsZE5hbWVCeURlZmF1bHQ6ICAgICAgICBvcHRzLlVzZUZpZWxkTmFtZUJ5RGVmYXVsdCwKCQlTZXREZWZhdWx0c0Zvclplcm9WYWx1ZXNPbmx5OiBvcHRzLlNldERlZmF1bHRzRm9yWmVyb1ZhbHVlc09ubHksCgkJRnVuY01hcDogICAgICAgICAgICAgICAgICAgICAgb3B0cy5GdW5jTWFwLAoJCXJhd0VudlZhcnM6ICAgICAgICAgICAgICAgICAgIG9wdHMucmF3RW52VmFycywKCX0KfQoKLy8gUGFyc2UgcGFyc2VzIGEgc3RydWN0IGNvbnRhaW5pbmcgYGVudmAgdGFncyBhbmQgbG9hZHMgaXRzIHZhbHVlcyBmcm9tCi8vIGVudmlyb25tZW50IHZhcmlhYmxlcy4KZnVuYyBQYXJzZSh2IGludGVyZmFjZXt9KSBlcnJvciB7CglyZXR1cm4gcGFyc2VJbnRlcm5hbCh2LCBzZXRGaWVsZCwgZGVmYXVsdE9wdGlvbnMoKSkKfQoKLy8gUGFyc2VXaXRoT3B0aW9ucyBwYXJzZXMgYSBzdHJ1Y3QgY29udGFpbmluZyBgZW52YCB0YWdzIGFuZCBsb2FkcyBpdHMgdmFsdWVzIGZyb20KLy8gZW52aXJvbm1lbnQgdmFyaWFibGVzLgpmdW5jIFBhcnNlV2l0aE9wdGlvbnModiBpbnRlcmZhY2V7fSwgb3B0cyBPcHRpb25zKSBlcnJvciB7CglyZXR1cm4gcGFyc2VJbnRlcm5hbCh2LCBzZXRGaWVsZCwgY3VzdG9tT3B0aW9ucyhvcHRzKSkKfQoKLy8gUGFyc2VBcyBwYXJzZXMgdGhlIGdpdmVuIHN0cnVjdCB0eXBlIGNvbnRhaW5pbmcgYGVudmAgdGFncyBhbmQgbG9hZHMgaXRzCi8vIHZhbHVlcyBmcm9tIGVudmlyb25tZW50IHZhcmlhYmxlcy4KZnVuYyBQYXJzZUFzW1QgYW55XSgpIChULCBlcnJvcikgewoJdmFyIHQgVAoJZXJyIDo9IFBhcnNlKCZ0KQoJcmV0dXJuIHQsIGVycgp9CgovLyBQYXJzZVdpdGhPcHRpb25zIHBhcnNlcyB0aGUgZ2l2ZW4gc3RydWN0IHR5cGUgY29udGFpbmluZyBgZW52YCB0YWdzIGFuZAovLyBsb2FkcyBpdHMgdmFsdWVzIGZyb20gZW52aXJvbm1lbnQgdmFyaWFibGVzLgpmdW5jIFBhcnNlQXNXaXRoT3B0aW9uc1tUIGFueV0ob3B0cyBPcHRpb25zKSAoVCwgZXJyb3IpIHsKCXZhciB0IFQKCWVyciA6PSBQYXJzZVdpdGhPcHRpb25zKCZ0LCBvcHRzKQoJcmV0dXJuIHQsIGVycgp9CgovLyBNdXN0IHBhbmljIGlzIGlmIGVyciBpcyBub3QgbmlsLCBhbmQgcmV0dXJucyB0IG90aGVyd2lzZS4KZnVuYyBNdXN0W1QgYW55XSh0IFQsIGVyciBlcnJvcikgVCB7CglpZiBlcnIgIT0gbmlsIHsKCQlwYW5pYyhlcnIpCgl9CglyZXR1cm4gdAp9CgovLyBHZXRGaWVsZFBhcmFtcyBwYXJzZXMgYSBzdHJ1Y3QgY29udGFpbmluZyBgZW52YCB0YWdzIGFuZCByZXR1cm5zIGluZm9ybWF0aW9uIGFib3V0Ci8vIHRhZ3MgaXQgZm91bmQuCmZ1bmMgR2V0RmllbGRQYXJhbXModiBpbnRlcmZhY2V7fSkgKFtdRmllbGRQYXJhbXMsIGVycm9yKSB7CglyZXR1cm4gR2V0RmllbGRQYXJhbXNXaXRoT3B0aW9ucyh2LCBkZWZhdWx0T3B0aW9ucygpKQp9CgovLyBHZXRGaWVsZFBhcmFtc1dpdGhPcHRpb25zIHBhcnNlcyBhIHN0cnVjdCBjb250YWluaW5nIGBlbnZgIHRhZ3MgYW5kIHJldHVybnMgaW5mb3JtYXRpb24gYWJvdXQKLy8gdGFncyBpdCBmb3VuZC4KZnVuYyBHZXRGaWVsZFBhcmFtc1dpdGhPcHRpb25zKHYgaW50ZXJmYWNle30sIG9wdHMgT3B0aW9ucykgKFtdRmllbGRQYXJhbXMsIGVycm9yKSB7Cgl2YXIgcmVzdWx0IFtdRmllbGRQYXJhbXMKCWVyciA6PSBwYXJzZUludGVybmFsKAoJCXYsCgkJZnVuYyhfIHJlZmxlY3QuVmFsdWUsIF8gcmVmbGVjdC5TdHJ1Y3RGaWVsZCwgXyBPcHRpb25zLCBmaWVsZFBhcmFtcyBGaWVsZFBhcmFtcykgZXJyb3IgewoJCQlpZiBmaWVsZFBhcmFtcy5Pd25LZXkgIT0gIiIgewoJCQkJcmVzdWx0ID0gYXBwZW5kKHJlc3VsdCwgZmllbGRQYXJhbXMpCgkJCX0KCQkJcmV0dXJuIG5pbAoJCX0sCgkJY3VzdG9tT3B0aW9ucyhvcHRzKSwKCSkKCWlmIGVyciAhPSBuaWwgewoJCXJldHVybiBuaWwsIGVycgoJfQoKCXJldHVybiByZXN1bHQsIG5pbAp9CgpmdW5jIHBhcnNlSW50ZXJuYWwodiBpbnRlcmZhY2V7fSwgcHJvY2Vzc0ZpZWxkIHByb2Nlc3NGaWVsZEZuLCBvcHRzIE9wdGlvbnMpIGVycm9yIHsKCXB0clJlZiA6PSByZWZsZWN0LlZhbHVlT2YodikKCWlmIHB0clJlZi5LaW5kKCkgIT0gcmVmbGVjdC5QdHIgewoJCXJldHVybiBuZXdBZ2dyZWdhdGVFcnJvcihOb3RTdHJ1Y3RQdHJFcnJvcnt9KQoJfQoJcmVmIDo9IHB0clJlZi5FbGVtKCkKCWlmIHJlZi5LaW5kKCkgIT0gcmVmbGVjdC5TdHJ1Y3QgewoJCXJldHVybiBuZXdBZ2dyZWdhdGVFcnJvcihOb3RTdHJ1Y3RQdHJFcnJvcnt9KQoJfQoKCXJldHVybiBkb1BhcnNlKHJlZiwgcHJvY2Vzc0ZpZWxkLCBvcHRzKQp9CgpmdW5jIGRvUGFyc2UocmVmIHJlZmxlY3QuVmFsdWUsIHByb2Nlc3NGaWVsZCBwcm9jZXNzRmllbGRGbiwgb3B0cyBPcHRpb25zKSBlcnJvciB7CglyZWZUeXBlIDo9IHJlZi5UeXBlKCkKCgl2YXIgYWdyRXJyIEFnZ3JlZ2F0ZUVycm9yCgoJZm9yIGkgOj0gMDsgaSA8IHJlZlR5cGUuTnVtRmllbGQoKTsgaSsrIHsKCQlyZWZGaWVsZCA6PSByZWYuRmllbGQoaSkKCQlyZWZUeXBlRmllbGQgOj0gcmVmVHlwZS5GaWVsZChpKQoKCQlpZiBlcnIgOj0gZG9QYXJzZUZpZWxkKHJlZkZpZWxkLCByZWZUeXBlRmllbGQsIHByb2Nlc3NGaWVsZCwgb3B0cyk7IGVyciAhPSBuaWwgewoJCQlpZiB2YWwsIG9rIDo9IGVyci4oQWdncmVnYXRlRXJyb3IpOyBvayB7CgkJCQlhZ3JFcnIuRXJyb3JzID0gYXBwZW5kKGFnckVyci5FcnJvcnMsIHZhbC5FcnJvcnMuLi4pCgkJCX0gZWxzZSB7CgkJCQlhZ3JFcnIuRXJyb3JzID0gYXBwZW5kKGFnckVyci5FcnJvcnMsIGVycikKCQkJfQoJCX0KCX0KCglpZiBsZW4oYWdyRXJyLkVycm9ycykgPT0gMCB7CgkJcmV0dXJuIG5pbAoJfQoKCXJldHVybiBhZ3JFcnIKfQoKZnVuYyBkb1BhcnNlRmllbGQoCglyZWZGaWVsZCByZWZsZWN0LlZhbHVlLAoJcmVmVHlwZUZpZWxkIHJlZmxlY3QuU3RydWN0RmllbGQsCglwcm9jZXNzRmllbGQgcHJvY2Vzc0ZpZWxkRm4sCglvcHRzIE9wdGlvbnMsCikgZXJyb3IgewoJaWYgIXJlZkZpZWxkLkNhblNldCgpIHsKCQlyZXR1cm4gbmlsCgl9CglpZiByZWZGaWVsZC5LaW5kKCkgPT0gcmVmbGVjdC5QdHIgJiYgcmVmRmllbGQuRWxlbSgpLktpbmQoKSA9PSByZWZsZWN0LlN0cnVjdCAmJiAhcmVmRmllbGQuSXNOaWwoKSB7CgkJcmV0dXJuIHBhcnNlSW50ZXJuYWwocmVmRmllbGQuSW50ZXJmYWNlKCksIHByb2Nlc3NGaWVsZCwgb3B0aW9uc1dpdGhFbnZQcmVmaXgocmVmVHlwZUZpZWxkLCBvcHRzKSkKCX0KCWlmIHJlZkZpZWxkLktpbmQoKSA9PSByZWZsZWN0LlN0cnVjdCAmJiByZWZGaWVsZC5DYW5BZGRyKCkgJiYgcmVmRmllbGQuVHlwZSgpLk5hbWUoKSA9PSAiIiB7CgkJcmV0dXJuIHBhcnNlSW50ZXJuYWwocmVmRmllbGQuQWRkcigpLkludGVyZmFjZSgpLCBwcm9jZXNzRmllbGQsIG9wdGlvbnNXaXRoRW52UHJlZml4KHJlZlR5cGVGaWVsZCwgb3B0cykpCgl9CgoJcGFyYW1zLCBlcnIgOj0gcGFyc2VGaWVsZFBhcmFtcyhyZWZUeXBlRmllbGQsIG9wdHMpCglpZiBlcnIgIT0gbmlsIHsKCQlyZXR1cm4gZXJyCgl9CgoJaWYgcGFyYW1zLklnbm9yZWQgewoJCXJldHVybiBuaWwKCX0KCglpZiBlcnIgOj0gcHJvY2Vzc0ZpZWxkKHJlZkZpZWxkLCByZWZUeXBlRmllbGQsIG9wdHMsIHBhcmFtcyk7IGVyciAhPSBuaWwgewoJCXJldHVybiBlcnIKCX0KCglpZiBwYXJhbXMuSW5pdCAmJiBpc0ludmFsaWRQdHIocmVmRmllbGQpIHsKCQlyZWZGaWVsZC5TZXQocmVmbGVjdC5OZXcocmVmRmllbGQuVHlwZSgpLkVsZW0oKSkpCgkJcmVmRmllbGQgPSByZWZGaWVsZC5FbGVtKCkKCX0KCglpZiByZWZGaWVsZC5LaW5kKCkgPT0gcmVmbGVjdC5TdHJ1Y3QgewoJCXJldHVybiBkb1BhcnNlKHJlZkZpZWxkLCBwcm9jZXNzRmllbGQsIG9wdGlvbnNXaXRoRW52UHJlZml4KHJlZlR5cGVGaWVsZCwgb3B0cykpCgl9CgoJaWYgaXNTbGljZU9mU3RydWN0cyhyZWZUeXBlRmllbGQpIHsKCQlyZXR1cm4gZG9QYXJzZVNsaWNlKHJlZkZpZWxkLCBwcm9jZXNzRmllbGQsIG9wdGlvbnNXaXRoRW52UHJlZml4KHJlZlR5cGVGaWVsZCwgb3B0cykpCgl9CgoJcmV0dXJuIG5pbAp9CgpmdW5jIGlzU2xpY2VPZlN0cnVjdHMocmVmVHlwZUZpZWxkIHJlZmxlY3QuU3RydWN0RmllbGQpIGJvb2wgewoJZmllbGQgOj0gcmVmVHlwZUZpZWxkLlR5cGUKCgkvLyAqW11zdHJ1Y3QKCWlmIGZpZWxkLktpbmQoKSA9PSByZWZsZWN0LlB0ciB7CgkJZmllbGQgPSBmaWVsZC5FbGVtKCkKCQlpZiBmaWVsZC5LaW5kKCkgPT0gcmVmbGVjdC5TbGljZSAmJiBmaWVsZC5FbGVtKCkuS2luZCgpID09IHJlZmxlY3QuU3RydWN0IHsKCQkJcmV0dXJuIHRydWUKCQl9Cgl9CgoJLy8gW11zdHJ1Y3R7fQoJaWYgZmllbGQuS2luZCgpID09IHJlZmxlY3QuU2xpY2UgJiYgZmllbGQuRWxlbSgpLktpbmQoKSA9PSByZWZsZWN0LlN0cnVjdCB7CgkJcmV0dXJuIHRydWUKCX0KCglyZXR1cm4gZmFsc2UKfQoKZnVuYyBkb1BhcnNlU2xpY2UocmVmIHJlZmxlY3QuVmFsdWUsIHByb2Nlc3NGaWVsZCBwcm9jZXNzRmllbGRGbiwgb3B0cyBPcHRpb25zKSBlcnJvciB7CglpZiBvcHRzLlByZWZpeCAhPSAiIiAmJiAhc3RyaW5ncy5IYXNTdWZmaXgob3B0cy5QcmVmaXgsIHN0cmluZyh1bmRlcnNjb3JlKSkgewoJCW9wdHMuUHJlZml4ICs9IHN0cmluZyh1bmRlcnNjb3JlKQoJfQoKCXZhciBlbnZpcm9ubWVudHMgW11zdHJpbmcKCWZvciBlbnZpcm9ubWVudCA6PSByYW5nZSBvcHRzLkVudmlyb25tZW50IHsKCQlpZiBzdHJpbmdzLkhhc1ByZWZpeChlbnZpcm9ubWVudCwgb3B0cy5QcmVmaXgpIHsKCQkJZW52aXJvbm1lbnRzID0gYXBwZW5kKGVudmlyb25tZW50cywgZW52aXJvbm1lbnQpCgkJfQoJfQoKCWlmIGxlbihlbnZpcm9ubWVudHMpID4gMCB7CgkJY291bnRlciA6PSAwCgkJZm9yIGZpbmlzaGVkIDo9IGZhbHNlOyAhZmluaXNoZWQ7IHsKCQkJZmluaXNoZWQgPSB0cnVlCgkJCXByZWZpeCA6PSBmbXQuU3ByaW50ZigiJXMlZCVjIiwgb3B0cy5QcmVmaXgsIGNvdW50ZXIsIHVuZGVyc2NvcmUpCgkJCWZvciBfLCB2YXJpYWJsZSA6PSByYW5nZSBlbnZpcm9ubWVudHMgewoJCQkJaWYgc3RyaW5ncy5IYXNQcmVmaXgodmFyaWFibGUsIHByZWZpeCkgewoJCQkJCWNvdW50ZXIrKwoJCQkJCWZpbmlzaGVkID0gZmFsc2UKCQkJCQlicmVhawoJCQkJfQoJCQl9CgkJfQoKCQlzbGljZVR5cGUgOj0gcmVmLlR5cGUoKQoJCXZhciBpbml0aWFsaXplZCBpbnQKCQlpZiByZWZsZWN0LlB0ciA9PSByZWYuS2luZCgpIHsKCQkJc2xpY2VUeXBlID0gc2xpY2VUeXBlLkVsZW0oKQoJCQkvLyBEdWUgdG8gdGhlIHJlc3Qgb2YgY29kZSB0aGUgcHJlLWluaXRpYWxpemVkIHNsaWNlIGhhcyBubyBjaGFuY2UgZm9yIHRoaXMgc2l0dWF0aW9uCgkJCWluaXRpYWxpemVkID0gMAoJCX0gZWxzZSB7CgkJCWluaXRpYWxpemVkID0gcmVmLkxlbigpCgkJfQoKCQl2YXIgY2FwYWNpdHkgaW50CgkJaWYgY2FwYWNpdHkgPSBpbml0aWFsaXplZDsgY291bnRlciA+IGluaXRpYWxpemVkIHsKCQkJY2FwYWNpdHkgPSBjb3VudGVyCgkJfQoJCXJlc3VsdCA6PSByZWZsZWN0Lk1ha2VTbGljZShzbGljZVR5cGUsIGNhcGFjaXR5LCBjYXBhY2l0eSkKCQlmb3IgaSA6PSAwOyBpIDwgY2FwYWNpdHk7IGkrKyB7CgkJCWl0ZW0gOj0gcmVzdWx0LkluZGV4KGkpCgkJCWlmIGkgPCBpbml0aWFsaXplZCB7CgkJCQlpdGVtLlNldChyZWYuSW5kZXgoaSkpCgkJCX0KCQkJaWYgZXJyIDo9IGRvUGFyc2UoaXRlbSwgcHJvY2Vzc0ZpZWxkLCBvcHRpb25zV2l0aFNsaWNlRW52UHJlZml4KG9wdHMsIGkpKTsgZXJyICE9IG5pbCB7CgkJCQlyZXR1cm4gZXJyCgkJCX0KCQl9CgoJCWlmIHJlc3VsdC5MZW4oKSA+IDAgewoJCQlpZiByZWZsZWN0LlB0ciA9PSByZWYuS2luZCgpIHsKCQkJCXJlc3VsdFB0ciA6PSByZWZsZWN0Lk5ldyhzbGljZVR5cGUpCgkJCQlyZXN1bHRQdHIuRWxlbSgpLlNldChyZXN1bHQpCgkJCQlyZXN1bHQgPSByZXN1bHRQdHIKCQkJfQoJCQlyZWYuU2V0KHJlc3VsdCkKCQl9Cgl9CgoJcmV0dXJuIG5pbAp9CgpmdW5jIHNldEZpZWxkKHJlZkZpZWxkIHJlZmxlY3QuVmFsdWUsIHJlZlR5cGVGaWVsZCByZWZsZWN0LlN0cnVjdEZpZWxkLCBvcHRzIE9wdGlvbnMsIGZpZWxkUGFyYW1zIEZpZWxkUGFyYW1zKSBlcnJvciB7Cgl2YWx1ZSwgZXJyIDo9IGdldChmaWVsZFBhcmFtcywgb3B0cykKCWlmIGVyciAhPSBuaWwgewoJCXJldHVybiBlcnIKCX0KCglpZiB2YWx1ZSAhPSAiIiAmJiAoIW9wdHMuU2V0RGVmYXVsdHNGb3JaZXJvVmFsdWVzT25seSB8fCByZWZGaWVsZC5Jc1plcm8oKSkgewoJCXJldHVybiBzZXQocmVmRmllbGQsIHJlZlR5cGVGaWVsZCwgdmFsdWUsIG9wdHMuRnVuY01hcCkKCX0KCglyZXR1cm4gbmlsCn0KCmNvbnN0IHVuZGVyc2NvcmUgcnVuZSA9ICdfJwoKZnVuYyB0b0Vudk5hbWUoaW5wdXQgc3RyaW5nKSBzdHJpbmcgewoJdmFyIG91dHB1dCBbXXJ1bmUKCWZvciBpLCBjIDo9IHJhbmdlIGlucHV0IHsKCQlpZiBjID09IHVuZGVyc2NvcmUgewoJCQljb250aW51ZQoJCX0KCQlpZiBsZW4ob3V0cHV0KSA+IDAgJiYgdW5pY29kZS5Jc1VwcGVyKGMpIHsKCQkJaWYgbGVuKGlucHV0KSA+IGkrMSB7CgkJCQlwZWVrIDo9IHJ1bmUoaW5wdXRbaSsxXSkKCQkJCWlmIHVuaWNvZGUuSXNMb3dlcihwZWVrKSB8fCB1bmljb2RlLklzTG93ZXIocnVuZShpbnB1dFtpLTFdKSkgewoJCQkJCW91dHB1dCA9IGFwcGVuZChvdXRwdXQsIHVuZGVyc2NvcmUpCgkJCQl9CgkJCX0KCQl9CgkJb3V0cHV0ID0gYXBwZW5kKG91dHB1dCwgdW5pY29kZS5Ub1VwcGVyKGMpKQoJfQoJcmV0dXJuIHN0cmluZyhvdXRwdXQpCn0KCi8vIEZpZWxkUGFyYW1zIGNvbnRhaW5zIGluZm9ybWF0aW9uIGFib3V0IHBhcnNlZCBmaWVsZCB0YWdzLgp0eXBlIEZpZWxkUGFyYW1zIHN0cnVjdCB7CglPd25LZXkgICAgICAgICAgc3RyaW5nCglLZXkgICAgICAgICAgICAgc3RyaW5nCglEZWZhdWx0VmFsdWUgICAgc3RyaW5nCglIYXNEZWZhdWx0VmFsdWUgYm9vbAoJUmVxdWlyZWQgICAgICAgIGJvb2wKCUxvYWRGaWxlICAgICAgICBib29sCglVbnNldCAgICAgICAgICAgYm9vbAoJTm90RW1wdHkgICAgICAgIGJvb2wKCUV4cGFuZCAgICAgICAgICBib29sCglJbml0ICAgICAgICAgICAgYm9vbAoJSWdub3JlZCAgICAgICAgIGJvb2wKfQoKZnVuYyBwYXJzZUZpZWxkUGFyYW1zKGZpZWxkIHJlZmxlY3QuU3RydWN0RmllbGQsIG9wdHMgT3B0aW9ucykgKEZpZWxkUGFyYW1zLCBlcnJvcikgewoJb3duS2V5LCB0YWdzIDo9IHBhcnNlS2V5Rm9yT3B0aW9uKGZpZWxkLlRhZy5HZXQob3B0cy5UYWdOYW1lKSkKCWlmIG93bktleSA9PSAiIiAmJiBvcHRzLlVzZUZpZWxkTmFtZUJ5RGVmYXVsdCB7CgkJb3duS2V5ID0gdG9FbnZOYW1lKGZpZWxkLk5hbWUpCgl9CgoJZGVmYXVsdFZhbHVlLCBoYXNEZWZhdWx0VmFsdWUgOj0gZmllbGQuVGFnLkxvb2t1cChvcHRzLkRlZmF1bHRWYWx1ZVRhZ05hbWUpCgoJcmVzdWx0IDo9IEZpZWxkUGFyYW1zewoJCU93bktleTogICAgICAgICAgb3duS2V5LAoJCUtleTogICAgICAgICAgICAgb3B0cy5QcmVmaXggKyBvd25LZXksCgkJUmVxdWlyZWQ6ICAgICAgICBvcHRzLlJlcXVpcmVkSWZOb0RlZiwKCQlEZWZhdWx0VmFsdWU6ICAgIGRlZmF1bHRWYWx1ZSwKCQlIYXNEZWZhdWx0VmFsdWU6IGhhc0RlZmF1bHRWYWx1ZSwKCQlJZ25vcmVkOiAgICAgICAgIG93bktleSA9PSAiLSIsCgl9CgoJZm9yIF8sIHRhZyA6PSByYW5nZSB0YWdzIHsKCQlzd2l0Y2ggdGFnIHsKCQljYXNlICIiOgoJCQljb250aW51ZQoJCWNhc2UgImZpbGUiOgoJCQlyZXN1bHQuTG9hZEZpbGUgPSB0cnVlCgkJY2FzZSAicmVxdWlyZWQiOgoJCQlyZXN1bHQuUmVxdWlyZWQgPSB0cnVlCgkJY2FzZSAidW5zZXQiOgoJCQlyZXN1bHQuVW5zZXQgPSB0cnVlCgkJY2FzZSAibm90RW1wdHkiOgoJCQlyZXN1bHQuTm90RW1wdHkgPSB0cnVlCgkJY2FzZSAiZXhwYW5kIjoKCQkJcmVzdWx0LkV4cGFuZCA9IHRydWUKCQljYXNlICJpbml0IjoKCQkJcmVzdWx0LkluaXQgPSB0cnVlCgkJY2FzZSAiLSI6CgkJCXJlc3VsdC5JZ25vcmVkID0gdHJ1ZQoJCWRlZmF1bHQ6CgkJCXJldHVybiBGaWVsZFBhcmFtc3t9LCBuZXdOb1N1cHBvcnRlZFRhZ09wdGlvbkVycm9yKHRhZykKCQl9Cgl9CgoJcmV0dXJuIHJlc3VsdCwgbmlsCn0KCmZ1bmMgZ2V0KGZpZWxkUGFyYW1zIEZpZWxkUGFyYW1zLCBvcHRzIE9wdGlvbnMpICh2YWwgc3RyaW5nLCBlcnIgZXJyb3IpIHsKCXZhciBleGlzdHMsIGlzRGVmYXVsdCBib29sCgoJdmFsLCBleGlzdHMsIGlzRGVmYXVsdCA9IGdldE9yKAoJCWZpZWxkUGFyYW1zLktleSwKCQlmaWVsZFBhcmFtcy5EZWZhdWx0VmFsdWUsCgkJZmllbGRQYXJhbXMuSGFzRGVmYXVsdFZhbHVlLAoJCW9wdHMuRW52aXJvbm1lbnQsCgkpCgoJaWYgZmllbGRQYXJhbXMuRXhwYW5kIHsKCQl2YWwgPSBvcy5FeHBhbmQodmFsLCBvcHRzLmdldFJhd0VudikKCX0KCglvcHRzLnJhd0VudlZhcnNbZmllbGRQYXJhbXMuT3duS2V5XSA9IHZhbAoKCWlmIGZpZWxkUGFyYW1zLlVuc2V0IHsKCQlkZWZlciBvcy5VbnNldGVudihmaWVsZFBhcmFtcy5LZXkpCgl9CgoJaWYgZmllbGRQYXJhbXMuUmVxdWlyZWQgJiYgIWV4aXN0cyAmJiBmaWVsZFBhcmFtcy5Pd25LZXkgIT0gIiIgewoJCXJldHVybiAiIiwgbmV3VmFySXNOb3RTZXRFcnJvcihmaWVsZFBhcmFtcy5LZXkpCgl9CgoJaWYgZmllbGRQYXJhbXMuTm90RW1wdHkgJiYgdmFsID09ICIiIHsKCQlyZXR1cm4gIiIsIG5ld0VtcHR5VmFyRXJyb3IoZmllbGRQYXJhbXMuS2V5KQoJfQoKCWlmIGZpZWxkUGFyYW1zLkxvYWRGaWxlICYmIHZhbCAhPSAiIiB7CgkJZmlsZW5hbWUgOj0gdmFsCgkJdmFsLCBlcnIgPSBnZXRGcm9tRmlsZShmaWxlbmFtZSkKCQlpZiBlcnIgIT0gbmlsIHsKCQkJcmV0dXJuICIiLCBuZXdMb2FkRmlsZUNvbnRlbnRFcnJvcihmaWxlbmFtZSwgZmllbGRQYXJhbXMuS2V5LCBlcnIpCgkJfQoJfQoKCWlmIG9wdHMuT25TZXQgIT0gbmlsIHsKCQlpZiBmaWVsZFBhcmFtcy5Pd25LZXkgIT0gIiIgewoJCQlvcHRzLk9uU2V0KGZpZWxkUGFyYW1zLktleSwgdmFsLCBpc0RlZmF1bHQpCgkJfQoJfQoJcmV0dXJuIHZhbCwgZXJyCn0KCi8vIHNwbGl0IHRoZSBlbnYgdGFnJ3Mga2V5IGludG8gdGhlIGV4cGVjdGVkIGtleSBhbmQgZGVzaXJlZCBvcHRpb24sIGlmIGFueS4KZnVuYyBwYXJzZUtleUZvck9wdGlvbihrZXkgc3RyaW5nKSAoc3RyaW5nLCBbXXN0cmluZykgewoJb3B0cyA6PSBzdHJpbmdzLlNwbGl0KGtleSwgIiwiKQoJcmV0dXJuIG9wdHNbMF0sIG9wdHNbMTpdCn0KCmZ1bmMgZ2V0RnJvbUZpbGUoZmlsZW5hbWUgc3RyaW5nKSAodmFsdWUgc3RyaW5nLCBlcnIgZXJyb3IpIHsKCWIsIGVyciA6PSBvcy5SZWFkRmlsZShmaWxlbmFtZSkKCXJldHVybiBzdHJpbmcoYiksIGVycgp9CgpmdW5jIGdldE9yKGtleSwgZGVmYXVsdFZhbHVlIHN0cmluZywgZGVmRXhpc3RzIGJvb2wsIGVudnMgbWFwW3N0cmluZ11zdHJpbmcpICh2YWwgc3RyaW5nLCBleGlzdHMsIGlzRGVmYXVsdCBib29sKSB7Cgl2YWx1ZSwgZXhpc3RzIDo9IGVudnNba2V5XQoJc3dpdGNoIHsKCWNhc2UgKCFleGlzdHMgfHwga2V5ID09ICIiKSAmJiBkZWZFeGlzdHM6CgkJcmV0dXJuIGRlZmF1bHRWYWx1ZSwgdHJ1ZSwgdHJ1ZQoJY2FzZSBleGlzdHMgJiYgdmFsdWUgPT0gIiIgJiYgZGVmRXhpc3RzOgoJCXJldHVybiBkZWZhdWx0VmFsdWUsIHRydWUsIHRydWUKCWNhc2UgIWV4aXN0czoKCQlyZXR1cm4gIiIsIGZhbHNlLCBmYWxzZQoJfQoKCXJldHVybiB2YWx1ZSwgdHJ1ZSwgZmFsc2UKfQoKZnVuYyBzZXQoZmllbGQgcmVmbGVjdC5WYWx1ZSwgc2YgcmVmbGVjdC5TdHJ1Y3RGaWVsZCwgdmFsdWUgc3RyaW5nLCBmdW5jTWFwIG1hcFtyZWZsZWN0LlR5cGVdUGFyc2VyRnVuYykgZXJyb3IgewoJaWYgdG0gOj0gYXNUZXh0VW5tYXJzaGFsZXIoZmllbGQpOyB0bSAhPSBuaWwgewoJCWlmIGVyciA6PSB0bS5Vbm1hcnNoYWxUZXh0KFtdYnl0ZSh2YWx1ZSkpOyBlcnIgIT0gbmlsIHsKCQkJcmV0dXJuIG5ld1BhcnNlRXJyb3Ioc2YsIGVycikKCQl9CgkJcmV0dXJuIG5pbAoJfQoKCXR5cGVlIDo9IHNmLlR5cGUKCWZpZWxkZWUgOj0gZmllbGQKCWlmIHR5cGVlLktpbmQoKSA9PSByZWZsZWN0LlB0ciB7CgkJdHlwZWUgPSB0eXBlZS5FbGVtKCkKCQlmaWVsZGVlID0gZmllbGQuRWxlbSgpCgl9CgoJcGFyc2VyRnVuYywgb2sgOj0gZnVuY01hcFt0eXBlZV0KCWlmIG9rIHsKCQl2YWwsIGVyciA6PSBwYXJzZXJGdW5jKHZhbHVlKQoJCWlmIGVyciAhPSBuaWwgewoJCQlyZXR1cm4gbmV3UGFyc2VFcnJvcihzZiwgZXJyKQoJCX0KCgkJZmllbGRlZS5TZXQocmVmbGVjdC5WYWx1ZU9mKHZhbCkpCgkJcmV0dXJuIG5pbAoJfQoKCXBhcnNlckZ1bmMsIG9rID0gZGVmYXVsdEJ1aWx0SW5QYXJzZXJzW3R5cGVlLktpbmQoKV0KCWlmIG9rIHsKCQl2YWwsIGVyciA6PSBwYXJzZXJGdW5jKHZhbHVlKQoJCWlmIGVyciAhPSBuaWwgewoJCQlyZXR1cm4gbmV3UGFyc2VFcnJvcihzZiwgZXJyKQoJCX0KCgkJZmllbGRlZS5TZXQocmVmbGVjdC5WYWx1ZU9mKHZhbCkuQ29udmVydCh0eXBlZSkpCgkJcmV0dXJuIG5pbAoJfQoKCXN3aXRjaCBmaWVsZC5LaW5kKCkgewoJY2FzZSByZWZsZWN0LlNsaWNlOgoJCXJldHVybiBoYW5kbGVTbGljZShmaWVsZCwgdmFsdWUsIHNmLCBmdW5jTWFwKQoJY2FzZSByZWZsZWN0Lk1hcDoKCQlyZXR1cm4gaGFuZGxlTWFwKGZpZWxkLCB2YWx1ZSwgc2YsIGZ1bmNNYXApCgl9CgoJcmV0dXJuIG5ld05vUGFyc2VyRXJyb3Ioc2YpCn0KCmZ1bmMgaGFuZGxlU2xpY2UoZmllbGQgcmVmbGVjdC5WYWx1ZSwgdmFsdWUgc3RyaW5nLCBzZiByZWZsZWN0LlN0cnVjdEZpZWxkLCBmdW5jTWFwIG1hcFtyZWZsZWN0LlR5cGVdUGFyc2VyRnVuYykgZXJyb3IgewoJc2VwYXJhdG9yIDo9IHNmLlRhZy5HZXQoImVudlNlcGFyYXRvciIpCglpZiBzZXBhcmF0b3IgPT0gIiIgewoJCXNlcGFyYXRvciA9ICIsIgoJfQoJcGFydHMgOj0gc3RyaW5ncy5TcGxpdCh2YWx1ZSwgc2VwYXJhdG9yKQoKCXR5cGVlIDo9IHNmLlR5cGUuRWxlbSgpCglpZiB0eXBlZS5LaW5kKCkgPT0gcmVmbGVjdC5QdHIgewoJCXR5cGVlID0gdHlwZWUuRWxlbSgpCgl9CgoJaWYgXywgb2sgOj0gcmVmbGVjdC5OZXcodHlwZWUpLkludGVyZmFjZSgpLihlbmNvZGluZy5UZXh0VW5tYXJzaGFsZXIpOyBvayB7CgkJcmV0dXJuIHBhcnNlVGV4dFVubWFyc2hhbGVycyhmaWVsZCwgcGFydHMsIHNmKQoJfQoKCXBhcnNlckZ1bmMsIG9rIDo9IGZ1bmNNYXBbdHlwZWVdCglpZiAhb2sgewoJCXBhcnNlckZ1bmMsIG9rID0gZGVmYXVsdEJ1aWx0SW5QYXJzZXJzW3R5cGVlLktpbmQoKV0KCQlpZiAhb2sgewoJCQlyZXR1cm4gbmV3Tm9QYXJzZXJFcnJvcihzZikKCQl9Cgl9CgoJcmVzdWx0IDo9IHJlZmxlY3QuTWFrZVNsaWNlKHNmLlR5cGUsIDAsIGxlbihwYXJ0cykpCglmb3IgXywgcGFydCA6PSByYW5nZSBwYXJ0cyB7CgkJciwgZXJyIDo9IHBhcnNlckZ1bmMocGFydCkKCQlpZiBlcnIgIT0gbmlsIHsKCQkJcmV0dXJuIG5ld1BhcnNlRXJyb3Ioc2YsIGVycikKCQl9CgkJdiA6PSByZWZsZWN0LlZhbHVlT2YocikuQ29udmVydCh0eXBlZSkKCQlpZiBzZi5UeXBlLkVsZW0oKS5LaW5kKCkgPT0gcmVmbGVjdC5QdHIgewoJCQl2ID0gcmVmbGVjdC5OZXcodHlwZWUpCgkJCXYuRWxlbSgpLlNldChyZWZsZWN0LlZhbHVlT2YocikuQ29udmVydCh0eXBlZSkpCgkJfQoJCXJlc3VsdCA9IHJlZmxlY3QuQXBwZW5kKHJlc3VsdCwgdikKCX0KCWZpZWxkLlNldChyZXN1bHQpCglyZXR1cm4gbmlsCn0KCmZ1bmMgaGFuZGxlTWFwKGZpZWxkIHJlZmxlY3QuVmFsdWUsIHZhbHVlIHN0cmluZywgc2YgcmVmbGVjdC5TdHJ1Y3RGaWVsZCwgZnVuY01hcCBtYXBbcmVmbGVjdC5UeXBlXVBhcnNlckZ1bmMpIGVycm9yIHsKCWtleVR5cGUgOj0gc2YuVHlwZS5LZXkoKQoJa2V5UGFyc2VyRnVuYywgb2sgOj0gZnVuY01hcFtrZXlUeXBlXQoJaWYgIW9rIHsKCQlrZXlQYXJzZXJGdW5jLCBvayA9IGRlZmF1bHRCdWlsdEluUGFyc2Vyc1trZXlUeXBlLktpbmQoKV0KCQlpZiAhb2sgewoJCQlyZXR1cm4gbmV3Tm9QYXJzZXJFcnJvcihzZikKCQl9Cgl9CgoJZWxlbVR5cGUgOj0gc2YuVHlwZS5FbGVtKCkKCWVsZW1QYXJzZXJGdW5jLCBvayA6PSBmdW5jTWFwW2VsZW1UeXBlXQoJaWYgIW9rIHsKCQllbGVtUGFyc2VyRnVuYywgb2sgPSBkZWZhdWx0QnVpbHRJblBhcnNlcnNbZWxlbVR5cGUuS2luZCgpXQoJCWlmICFvayB7CgkJCXJldHVybiBuZXdOb1BhcnNlckVycm9yKHNmKQoJCX0KCX0KCglzZXBhcmF0b3IgOj0gc2YuVGFnLkdldCgiZW52U2VwYXJhdG9yIikKCWlmIHNlcGFyYXRvciA9PSAiIiB7CgkJc2VwYXJhdG9yID0gIiwiCgl9CgoJa2V5VmFsU2VwYXJhdG9yIDo9IHNmLlRhZy5HZXQoImVudktleVZhbFNlcGFyYXRvciIpCglpZiBrZXlWYWxTZXBhcmF0b3IgPT0gIiIgewoJCWtleVZhbFNlcGFyYXRvciA9ICI6IgoJfQoKCXJlc3VsdCA6PSByZWZsZWN0Lk1ha2VNYXAoc2YuVHlwZSkKCWZvciBfLCBwYXJ0IDo9IHJhbmdlIHN0cmluZ3MuU3BsaXQodmFsdWUsIHNlcGFyYXRvcikgewoJCXBhaXJzIDo9IHN0cmluZ3MuU3BsaXROKHBhcnQsIGtleVZhbFNlcGFyYXRvciwgMikKCQlpZiBsZW4ocGFpcnMpICE9IDIgewoJCQlyZXR1cm4gbmV3UGFyc2VFcnJvcihzZiwgZm10LkVycm9yZihgJXEgc2hvdWxkIGJlIGluICJrZXklc3ZhbHVlIiBmb3JtYXRgLCBwYXJ0LCBrZXlWYWxTZXBhcmF0b3IpKQoJCX0KCgkJa2V5LCBlcnIgOj0ga2V5UGFyc2VyRnVuYyhwYWlyc1swXSkKCQlpZiBlcnIgIT0gbmlsIHsKCQkJcmV0dXJuIG5ld1BhcnNlRXJyb3Ioc2YsIGVycikKCQl9CgoJCWVsZW0sIGVyciA6PSBlbGVtUGFyc2VyRnVuYyhwYWlyc1sxXSkKCQlpZiBlcnIgIT0gbmlsIHsKCQkJcmV0dXJuIG5ld1BhcnNlRXJyb3Ioc2YsIGVycikKCQl9CgoJCXJlc3VsdC5TZXRNYXBJbmRleChyZWZsZWN0LlZhbHVlT2Yoa2V5KS5Db252ZXJ0KGtleVR5cGUpLCByZWZsZWN0LlZhbHVlT2YoZWxlbSkuQ29udmVydChlbGVtVHlwZSkpCgl9CgoJZmllbGQuU2V0KHJlc3VsdCkKCXJldHVybiBuaWwKfQoKZnVuYyBhc1RleHRVbm1hcnNoYWxlcihmaWVsZCByZWZsZWN0LlZhbHVlKSBlbmNvZGluZy5UZXh0VW5tYXJzaGFsZXIgewoJaWYgZmllbGQuS2luZCgpID09IHJlZmxlY3QuUHRyIHsKCQlpZiBmaWVsZC5Jc05pbCgpIHsKCQkJZmllbGQuU2V0KHJlZmxlY3QuTmV3KGZpZWxkLlR5cGUoKS5FbGVtKCkpKQoJCX0KCX0gZWxzZSBpZiBmaWVsZC5DYW5BZGRyKCkgewoJCWZpZWxkID0gZmllbGQuQWRkcigpCgl9CgoJdG0sIG9rIDo9IGZpZWxkLkludGVyZmFjZSgpLihlbmNvZGluZy5UZXh0VW5tYXJzaGFsZXIpCglpZiAhb2sgewoJCXJldHVybiBuaWwKCX0KCXJldHVybiB0bQp9CgpmdW5jIHBhcnNlVGV4dFVubWFyc2hhbGVycyhmaWVsZCByZWZsZWN0LlZhbHVlLCBkYXRhIFtdc3RyaW5nLCBzZiByZWZsZWN0LlN0cnVjdEZpZWxkKSBlcnJvciB7CglzIDo9IGxlbihkYXRhKQoJZWxlbVR5cGUgOj0gZmllbGQuVHlwZSgpLkVsZW0oKQoJc2xpY2UgOj0gcmVmbGVjdC5NYWtlU2xpY2UocmVmbGVjdC5TbGljZU9mKGVsZW1UeXBlKSwgcywgcykKCWZvciBpLCB2IDo9IHJhbmdlIGRhdGEgewoJCXN2IDo9IHNsaWNlLkluZGV4KGkpCgkJa2luZCA6PSBzdi5LaW5kKCkKCQlpZiBraW5kID09IHJlZmxlY3QuUHRyIHsKCQkJc3YgPSByZWZsZWN0Lk5ldyhlbGVtVHlwZS5FbGVtKCkpCgkJfSBlbHNlIHsKCQkJc3YgPSBzdi5BZGRyKCkKCQl9CgkJdG0gOj0gc3YuSW50ZXJmYWNlKCkuKGVuY29kaW5nLlRleHRVbm1hcnNoYWxlcikKCQlpZiBlcnIgOj0gdG0uVW5tYXJzaGFsVGV4dChbXWJ5dGUodikpOyBlcnIgIT0gbmlsIHsKCQkJcmV0dXJuIG5ld1BhcnNlRXJyb3Ioc2YsIGVycikKCQl9CgkJaWYga2luZCA9PSByZWZsZWN0LlB0ciB7CgkJCXNsaWNlLkluZGV4KGkpLlNldChzdikKCQl9Cgl9CgoJZmllbGQuU2V0KHNsaWNlKQoKCXJldHVybiBuaWwKfQoKLy8gVG9NYXAgQ29udmVydHMgbGlzdCBvZiBlbnYgdmFycyBhcyBwcm92aWRlZCBieSBvcy5FbnZpcm9uKCkgdG8gbWFwIHlvdQovLyBjYW4gdXNlIGFzIE9wdGlvbnMuRW52aXJvbm1lbnQgZmllbGQKZnVuYyBUb01hcChlbnYgW11zdHJpbmcpIG1hcFtzdHJpbmddc3RyaW5nIHsKCXJldHVybiB0b01hcChlbnYpCn0KCmZ1bmMgaXNJbnZhbGlkUHRyKHYgcmVmbGVjdC5WYWx1ZSkgYm9vbCB7CglyZXR1cm4gcmVmbGVjdC5QdHIgPT0gdi5LaW5kKCkgJiYgdi5FbGVtKCkuS2luZCgpID09IHJlZmxlY3QuSW52YWxpZAp9Cg==", "mode": 420}}')
+for name,item in files.items():
+ p=Path('/testbed')/name
+ p.parent.mkdir(parents=True,exist_ok=True)
+ p.write_bytes(base64.b64decode(item['data']))
+ p.chmod(item['mode'])
+OPENENV_REFERENCE