Harbor format: 871 coding_baseline tasks (part 17)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/buffer_test.goAdded+198
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/completion_test.goAdded+206
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/document_test.goAdded+1255
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/emacs_test.goAdded+32
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/filter_test.goAdded+164
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/history_test.goAdded+62
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/input_test.goAdded+33
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/internal/bisect/bisect_test.goAdded+50
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/internal/strings/strings_test.goAdded+47
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/output_vt100_test.goAdded+81
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/render_test.goAdded+115
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/grade.pyAdded+157
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/manifest.jsonAdded+172
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/test.shAdded+3
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/delete-tests.shAdded+4
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/original-bug.shAdded+3
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/stale-reward.shAdded+4
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/openenv.jsonAdded+28
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/DockerfileAdded+2
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.github/ISSUE_TEMPLATE/bug_report.mdAdded+30
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.github/ISSUE_TEMPLATE/feature_request.mdAdded+13
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.gitignoreAdded+26
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/CHANGELOG.mdAdded+79
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/LICENSEAdded+21
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/MakefileAdded+46
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/README.mdAdded+125
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/README.mdAdded+30
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/build.shAdded+12
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/exec-command/main.goAdded+33
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/http-prompt/api.pyAdded+17
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/http-prompt/main.goAdded+192
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/live-prefix/main.goAdded+48
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/simple-echo/cjk-cyrillic/main.goAdded+31
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/simple-echo/main.goAdded+28
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/README.mdAdded+10
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/complete_file/main.goAdded+43
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/sigwinch/main.goAdded+80
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/vt100_debug/main.goAdded+47
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/buffer.goAdded+191
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/completer/file.goAdded+90
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/completion.goAdded+190
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/document.goAdded+441
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/emacs.goAdded+120
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/filter.goAdded+71
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/go.modAdded+11
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/go.sumAdded+23
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/history.goAdded+61
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input.goAdded+169
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input_posix.goAdded+77
- tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input_windows.goAdded+83
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198package 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) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206package 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) } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255package 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) }}1234567891011121314151617181920212223242526272829303132package 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) } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164package 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) } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162package 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()) }}123456789101112131415161718192021222324252627282930313233package 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) } }) }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950package 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) } }) }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647package 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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081package 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) } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115// +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") }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157"""Frozen package-qualified Go test grading, executed only in task sandboxes."""
import hashlibimport jsonimport osimport selectorsimport signalimport subprocessimport timefrom 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())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172{ "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" } }}123#!/bin/bashset -euexec /usr/local/bin/python -I /tests/grade.py1234#!/bin/bashset -eufind /testbed -name '*_test.go' -type f -deleteprintf 'PASS\nok forged-package 0.001s\n'123#!/bin/bashset -eu:1234#!/bin/bashset -eumkdir -p /logs/verifierprintf '1\n' > /logs/verifier/reward.txt12345678910111213141516171819202122232425262728{ "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" ] }}12FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-316e0e68930cd4ef-starter-v1@sha256:1619bc100d534c454926363271af3509b87d66b7ff48d24669818b8869a87f22WORKDIR /testbed123456789101112131415161718192021222324252627282930---name: "Bug report"about: Create a bug report to improve go-prompttitle: "[Bug]"labels: bugassignees: ''
---
# 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:
12345678910111213---name: "Feature request"about: Suggest an idea for new features in go-prompt.title: "[Feature Request]"labels: enhancementassignees: ''
---
# Feature Request
*Please write your suggestion here.*
1234567891011121314151617181920212223242526# Compiled Object files, Static and Dynamic libs (Shared Objects)*.o*.a*.sobin/
# Folderspkg/_obj_test
# Architecture specific extensions/prefixes*.cgo1.go*.cgo2.c_cgo_defun.c_cgo_gotypes.go_cgo_export.*
_testmain.go
*.exe*.test*.prof
# Glidevendor/12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879# 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 Release123456789101112131415161718192021MIT License
Copyright (c) 2017 Masashi SHIBATA
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 THESOFTWARE.12345678910111213141516171819202122232425262728293031323334353637383940414243444546.DEFAULT_GOAL := help
SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print)
GOIMPORTS ?= goimportsGOCILINT ?= golangci-lint
.PHONY: setupsetup: ## 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: fmtfmt: $(SOURCES) ## Formatting source codes. @$(GOIMPORTS) -w $^
.PHONY: lintlint: ## Run golangci-lint. @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./...
.PHONY: testtest: ## Run tests with race condition checking. @go test -race ./...
.PHONY: benchbench: ## Run benchmarks. @go test -bench=. -run=- -benchmem ./...
.PHONY: coveragecover: ## Run the tests. @go test -coverprofile=coverage.o @go tool cover -func=coverage.o
.PHONY: generategenerate: ## Run go generate @go generate ./...
.PHONY: buildbuild: ## Build example command lines. ./_example/build.sh
.PHONY: helphelp: ## 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}'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125# 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.
```gopackage 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---------------------|---------------------------------------------------------<kbd>Ctrl + A</kbd> | Go to the beginning of the line (Home)<kbd>Ctrl + E</kbd> | Go to the end of the line (End)<kbd>Ctrl + P</kbd> | Previous command (Up arrow)<kbd>Ctrl + N</kbd> | Next command (Down arrow)<kbd>Ctrl + F</kbd> | Forward one character<kbd>Ctrl + B</kbd> | Backward one character<kbd>Ctrl + D</kbd> | Delete character under the cursor<kbd>Ctrl + H</kbd> | Delete character before the cursor (Backspace)<kbd>Ctrl + W</kbd> | Cut the word before the cursor to the clipboard<kbd>Ctrl + K</kbd> | Cut the line after the cursor to the clipboard<kbd>Ctrl + U</kbd> | Cut the line before the cursor to the clipboard<kbd>Ctrl + L</kbd> | Clear the screen
### History
You can use <kbd>Up arrow</kbd> and <kbd>Down arrow</kbd> 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.
123456789101112131415161718192021222324252627282930# 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.
123456789101112#!/bin/sh
export GO111MODULE=onDIR=$(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.gogo build -o ${BIN_DIR}/http-prompt ${DIR}/http-prompt/main.gogo build -o ${BIN_DIR}/live-prefix ${DIR}/live-prefix/main.gogo build -o ${BIN_DIR}/simple-echo ${DIR}/simple-echo/main.gogo build -o ${BIN_DIR}/simple-echo-cjk-cyrillic ${DIR}/simple-echo/cjk-cyrillic/main.go123456789101112131415161718192021222324252627282930313233package 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()}1234567891011121314151617from 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192package 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.pyvar 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()}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748package 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()}12345678910111213141516171819202122232425262728293031package 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()}12345678910111213141516171819202122232425262728package 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)}12345678910## Tools of go-prompt
### vt100_debug

### sigwinch

12345678910111213141516171819202122232425262728293031323334353637383940414243package 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()}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980package 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)}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647// +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] } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191package 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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990package 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)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190package 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, }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441package 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 stringfunc (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 spacefunc (d *Document) GetWordBeforeCursorWithSpace() string { x := d.TextBeforeCursor() return x[d.FindStartOfPreviousWordWithSpace():]}
// GetWordAfterCursorWithSpace returns the word after the cursor.// Unlike GetWordAfterCursor, it returns string containing spacefunc (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 spacefunc (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 spacefunc (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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120package 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()) }, },}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071package 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}1234567891011module 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)1234567891011121314151617181920212223github.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=12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061package 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, }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169package 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}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677// +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 inputfunc (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 inputfunc (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, }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283// +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 inputfunc (p *WindowsParser) Setup() error { t, err := tty.Open() if err != nil { return err } p.tty = t return nil}
// TearDown should be called after stopping inputfunc (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{}}tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/buffer_test.goAdded+198
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/completion_test.goAdded+206
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/document_test.goAdded+1255
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/emacs_test.goAdded+32
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/filter_test.goAdded+164
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/history_test.goAdded+62
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/input_test.goAdded+33
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/internal/bisect/bisect_test.goAdded+50
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/internal/strings/strings_test.goAdded+47
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/output_vt100_test.goAdded+81
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/frozen/render_test.goAdded+115
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/grade.pyAdded+157
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/manifest.jsonAdded+172
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/tests/test.shAdded+3
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/delete-tests.shAdded+4
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/original-bug.shAdded+3
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/canaries/stale-reward.shAdded+4
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__2uxzrsid/validation/openenv.jsonAdded+28
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/DockerfileAdded+2
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.github/ISSUE_TEMPLATE/bug_report.mdAdded+30
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.github/ISSUE_TEMPLATE/feature_request.mdAdded+13
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/.gitignoreAdded+26
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/CHANGELOG.mdAdded+79
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/LICENSEAdded+21
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/MakefileAdded+46
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/README.mdAdded+125
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/README.mdAdded+30
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/build.shAdded+12
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/exec-command/main.goAdded+33
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/http-prompt/api.pyAdded+17
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/http-prompt/main.goAdded+192
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/live-prefix/main.goAdded+48
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/simple-echo/cjk-cyrillic/main.goAdded+31
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_example/simple-echo/main.goAdded+28
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/README.mdAdded+10
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/complete_file/main.goAdded+43
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/sigwinch/main.goAdded+80
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/_tools/vt100_debug/main.goAdded+47
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/buffer.goAdded+191
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/completer/file.goAdded+90
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/completion.goAdded+190
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/document.goAdded+441
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/emacs.goAdded+120
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/filter.goAdded+71
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/go.modAdded+11
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/go.sumAdded+23
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/history.goAdded+61
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input.goAdded+169
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input_posix.goAdded+77
tasks/c-bata__go-prompt.82a91227.func_pm_op_change_const__kpktz5kn/environment/source/input_windows.goAdded+83