diff --git a/example/main.go b/example/main.go index e550e95..69fef4b 100644 --- a/example/main.go +++ b/example/main.go @@ -37,6 +37,7 @@ var completer = readline.NewPrefixCompleter( readline.PcItem("install"), readline.PcItem("test"), ), + readline.PcItem("sleep"), ) func main() { @@ -101,6 +102,9 @@ func main() { }() case line == "bye": goto exit + case line == "sleep": + log.Println("sleep 4 second") + time.Sleep(4 * time.Second) case line == "": default: log.Println("you said:", strconv.Quote(line)) diff --git a/operation.go b/operation.go index b3a5c5d..fde6341 100644 --- a/operation.go +++ b/operation.go @@ -254,6 +254,9 @@ func (o *Operation) String() (string, error) { } func (o *Operation) Runes() ([]rune, error) { + o.t.EnterRawMode() + defer o.t.ExitRawMode() + o.buf.Refresh(nil) // print prompt o.t.KickRead() r := <-o.outchan @@ -268,6 +271,9 @@ func (o *Operation) Password(prompt string) ([]byte, error) { if prompt != "" { fmt.Fprintf(w, prompt) } + o.t.EnterRawMode() + defer o.t.ExitRawMode() + b, err := terminal.ReadPassword(int(os.Stdin.Fd())) fmt.Fprint(w, "\r\n") return b, err diff --git a/terminal.go b/terminal.go index 381f01d..32ca3ae 100644 --- a/terminal.go +++ b/terminal.go @@ -24,13 +24,8 @@ func NewTerminal(cfg *Config) (*Terminal, error) { if err := cfg.Init(); err != nil { return nil, err } - state, err := MakeRaw(StdinFd) - if err != nil { - return nil, err - } t := &Terminal{ cfg: cfg, - state: state, kickChan: make(chan struct{}, 1), outchan: make(chan rune), stopChan: make(chan struct{}, 1), @@ -40,6 +35,22 @@ func NewTerminal(cfg *Config) (*Terminal, error) { return t, nil } +func (t *Terminal) EnterRawMode() (err error) { + t.state, err = MakeRaw(StdinFd) + return err +} + +func (t *Terminal) ExitRawMode() (err error) { + if t.state == nil { + return + } + err = Restore(StdinFd, t.state) + if err == nil { + t.state = nil + } + return err +} + func (t *Terminal) Write(b []byte) (int, error) { return t.cfg.Stdout.Write(b) } @@ -137,5 +148,5 @@ func (t *Terminal) Close() error { } t.stopChan <- struct{}{} t.wg.Wait() - return Restore(StdinFd, t.state) + return t.ExitRawMode() }