rdstdin.nim 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module contains code for reading from `stdin`:idx:. On UNIX the
  10. ## linenoise library is wrapped and set up to provide default key bindings
  11. ## (e.g. you can navigate with the arrow keys). On Windows ``system.readLine``
  12. ## is used. This suffices because Windows' console already provides the
  13. ## wanted functionality.
  14. {.deadCodeElim: on.} # dce option deprecated
  15. when defined(Windows):
  16. proc readLineFromStdin*(prompt: string): TaintedString {.
  17. tags: [ReadIOEffect, WriteIOEffect].} =
  18. ## Reads a line from stdin.
  19. stdout.write(prompt)
  20. result = readLine(stdin)
  21. proc readLineFromStdin*(prompt: string, line: var TaintedString): bool {.
  22. tags: [ReadIOEffect, WriteIOEffect].} =
  23. ## Reads a `line` from stdin. `line` must not be
  24. ## ``nil``! May throw an IO exception.
  25. ## A line of text may be delimited by ``CR``, ``LF`` or
  26. ## ``CRLF``. The newline character(s) are not part of the returned string.
  27. ## Returns ``false`` if the end of the file has been reached, ``true``
  28. ## otherwise. If ``false`` is returned `line` contains no new data.
  29. stdout.write(prompt)
  30. result = readLine(stdin, line)
  31. elif defined(genode):
  32. proc readLineFromStdin*(prompt: string): TaintedString {.
  33. tags: [ReadIOEffect, WriteIOEffect].} =
  34. stdin.readLine()
  35. proc readLineFromStdin*(prompt: string, line: var TaintedString): bool {.
  36. tags: [ReadIOEffect, WriteIOEffect].} =
  37. stdin.readLine(line)
  38. else:
  39. import linenoise, termios
  40. proc readLineFromStdin*(prompt: string): TaintedString {.
  41. tags: [ReadIOEffect, WriteIOEffect].} =
  42. var buffer = linenoise.readLine(prompt)
  43. if isNil(buffer):
  44. raise newException(IOError, "Linenoise returned nil")
  45. result = TaintedString($buffer)
  46. if result.string.len > 0:
  47. historyAdd(buffer)
  48. linenoise.free(buffer)
  49. proc readLineFromStdin*(prompt: string, line: var TaintedString): bool {.
  50. tags: [ReadIOEffect, WriteIOEffect].} =
  51. var buffer = linenoise.readLine(prompt)
  52. if isNil(buffer):
  53. line.string.setLen(0)
  54. return false
  55. line = TaintedString($buffer)
  56. if line.string.len > 0:
  57. historyAdd(buffer)
  58. linenoise.free(buffer)
  59. result = true