rdstdin.nim 2.4 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. runnableExamples("-r:off"):
  15. echo readLineFromStdin("Is Nim awesome? (Y/n): ")
  16. var line: string
  17. while true:
  18. let ok = readLineFromStdin("How are you? ", line)
  19. if not ok: break # ctrl-C or ctrl-D will cause a break
  20. if line.len > 0: echo line
  21. echo "exiting"
  22. when defined(windows):
  23. proc readLineFromStdin*(prompt: string): string {.
  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 string): 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): string {.
  40. tags: [ReadIOEffect, WriteIOEffect].} =
  41. stdin.readLine()
  42. proc readLineFromStdin*(prompt: string, line: var string): bool {.
  43. tags: [ReadIOEffect, WriteIOEffect].} =
  44. stdin.readLine(line)
  45. else:
  46. import linenoise
  47. proc readLineFromStdin*(prompt: string, line: var string): bool {.
  48. tags: [ReadIOEffect, WriteIOEffect].} =
  49. var buffer = linenoise.readLine(prompt)
  50. if isNil(buffer):
  51. line.setLen(0)
  52. return false
  53. line = $buffer
  54. if line.len > 0:
  55. historyAdd(buffer)
  56. linenoise.free(buffer)
  57. result = true
  58. proc readLineFromStdin*(prompt: string): string {.inline.} =
  59. if not readLineFromStdin(prompt, result):
  60. raise newException(IOError, "Linenoise returned nil")