rdstdin.nim 2.5 KB

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