return remain line if interrupt.

This commit is contained in:
chzyer 2016-03-25 17:08:13 +08:00
parent bb5b4af6e7
commit 1e409caaf3
2 changed files with 26 additions and 9 deletions

View File

@ -47,7 +47,7 @@ func main() {
Prompt: "\033[31m»\033[0m ", Prompt: "\033[31m»\033[0m ",
HistoryFile: "/tmp/readline.tmp", HistoryFile: "/tmp/readline.tmp",
AutoComplete: completer, AutoComplete: completer,
InterruptPrompt: "\nInterrupt, Press Ctrl+D to exit", InterruptPrompt: "^C",
EOFPrompt: "exit", EOFPrompt: "exit",
}) })
if err != nil { if err != nil {
@ -65,9 +65,16 @@ func main() {
log.SetOutput(l.Stderr()) log.SetOutput(l.Stderr())
for { for {
line, err := l.Readline() line, err := l.Readline()
if err == io.EOF { if err == readline.ErrInterrupt {
if len(line) == 0 {
break
} else {
continue
}
} else if err == io.EOF {
break break
} }
line = strings.TrimSpace(line) line = strings.TrimSpace(line)
switch { switch {
case strings.HasPrefix(line, "mode "): case strings.HasPrefix(line, "mode "):

View File

@ -9,6 +9,14 @@ var (
ErrInterrupt = errors.New("Interrupt") ErrInterrupt = errors.New("Interrupt")
) )
type InterruptError struct {
Line []rune
}
func (*InterruptError) Error() string {
return "Interrupted"
}
type Operation struct { type Operation struct {
cfg *Config cfg *Config
t *Terminal t *Terminal
@ -248,11 +256,13 @@ func (o *Operation) ioloop() {
} }
o.buf.MoveToLineEnd() o.buf.MoveToLineEnd()
o.buf.Refresh(nil) o.buf.Refresh(nil)
o.buf.WriteString(o.cfg.InterruptPrompt + "\n") hint := o.cfg.InterruptPrompt + "\n"
o.buf.Reset() o.buf.WriteString(hint)
remain := o.buf.Reset()
remain = remain[:len(remain)-len([]rune(hint))]
isUpdateHistory = false isUpdateHistory = false
o.history.Revert() o.history.Revert()
o.errchan <- ErrInterrupt o.errchan <- &InterruptError{remain}
default: default:
if o.IsSearchMode() { if o.IsSearchMode() {
o.SearchChar(r) o.SearchChar(r)
@ -302,10 +312,7 @@ func (o *Operation) Stdout() io.Writer {
func (o *Operation) String() (string, error) { func (o *Operation) String() (string, error) {
r, err := o.Runes() r, err := o.Runes()
if err != nil { return string(r), err
return "", err
}
return string(r), nil
} }
func (o *Operation) Runes() ([]rune, error) { func (o *Operation) Runes() ([]rune, error) {
@ -321,6 +328,9 @@ func (o *Operation) Runes() ([]rune, error) {
case r := <-o.outchan: case r := <-o.outchan:
return r, nil return r, nil
case err := <-o.errchan: case err := <-o.errchan:
if e, ok := err.(*InterruptError); ok {
return e.Line, ErrInterrupt
}
return nil, err return nil, err
} }
} }