readline.go 982 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. package getch
  10. import (
  11. "bytes"
  12. "io"
  13. )
  14. /*
  15. ReadLine reads a single line from the terminal. Can optionally include
  16. an echo writer. If the mask is not 0 then the echo will be the mask
  17. character.
  18. */
  19. func ReadLine(echo io.Writer, mask rune) (string, error) {
  20. var ret bytes.Buffer
  21. var err error
  22. if err = Start(); err == nil {
  23. var e *KeyEvent
  24. defer Stop()
  25. for err == nil && (e == nil || e.Code != KeyEnter) {
  26. if e, err = Getch(); e != nil {
  27. if e.Rune != 0 {
  28. ebytes := []byte(string(e.Rune))
  29. ret.Write(ebytes)
  30. if echo != nil {
  31. if mask == 0 {
  32. echo.Write(ebytes)
  33. } else {
  34. echo.Write([]byte(string(mask)))
  35. }
  36. }
  37. }
  38. }
  39. }
  40. }
  41. return ret.String(), err
  42. }