rdstdin.nim 2.4 KB

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