rdstdin.nim 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. ##
  15. ## **Examples:**
  16. ##
  17. ## .. code-block:: nim
  18. ## echo readLineFromStdin("Is Nim awesome? (Y/n):")
  19. ## var userResponse: string
  20. ## doAssert readLineFromStdin("How are you?:", line = userResponse)
  21. ## echo userResponse
  22. when defined(Windows):
  23. proc readLineFromStdin*(prompt: string): TaintedString {.
  24. tags: [ReadIOEffect, WriteIOEffect].} =
  25. ## Reads a line from stdin.
  26. stdout.write(prompt)
  27. result = readLine(stdin)
  28. proc readLineFromStdin*(prompt: string, line: var TaintedString): bool {.
  29. tags: [ReadIOEffect, WriteIOEffect].} =
  30. ## Reads a `line` from stdin. `line` must not be
  31. ## ``nil``! May throw an IO exception.
  32. ## A line of text may be delimited by ``CR``, ``LF`` or
  33. ## ``CRLF``. The newline character(s) are not part of the returned string.
  34. ## Returns ``false`` if the end of the file has been reached, ``true``
  35. ## otherwise. If ``false`` is returned `line` contains no new data.
  36. stdout.write(prompt)
  37. result = readLine(stdin, line)
  38. elif defined(genode):
  39. proc readLineFromStdin*(prompt: string): TaintedString {.
  40. tags: [ReadIOEffect, WriteIOEffect].} =
  41. stdin.readLine()
  42. proc readLineFromStdin*(prompt: string, line: var TaintedString): bool {.
  43. tags: [ReadIOEffect, WriteIOEffect].} =
  44. stdin.readLine(line)
  45. else:
  46. import linenoise
  47. proc readLineFromStdin*(prompt: string): TaintedString {.
  48. tags: [ReadIOEffect, WriteIOEffect].} =
  49. var buffer = linenoise.readLine(prompt)
  50. if isNil(buffer):
  51. raise newException(IOError, "Linenoise returned nil")
  52. result = TaintedString($buffer)
  53. if result.string.len > 0:
  54. historyAdd(buffer)
  55. linenoise.free(buffer)
  56. proc readLineFromStdin*(prompt: string, line: var TaintedString): bool {.
  57. tags: [ReadIOEffect, WriteIOEffect].} =
  58. var buffer = linenoise.readLine(prompt)
  59. if isNil(buffer):
  60. line.string.setLen(0)
  61. return false
  62. line = TaintedString($buffer)
  63. if line.string.len > 0:
  64. historyAdd(buffer)
  65. linenoise.free(buffer)
  66. result = true