linenoise.nim 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. type
  10. Completions* = object
  11. len*: csize_t
  12. cvec*: cstringArray
  13. CompletionCallback* = proc (a2: cstring; a3: ptr Completions) {.cdecl.}
  14. {.compile: "linenoise.c".}
  15. proc setCompletionCallback*(a2: CompletionCallback) {.
  16. importc: "linenoiseSetCompletionCallback".}
  17. proc addCompletion*(a2: ptr Completions; a3: cstring) {.
  18. importc: "linenoiseAddCompletion".}
  19. proc readLine*(prompt: cstring): cstring {.importc: "linenoise".}
  20. proc historyAdd*(line: cstring): cint {.importc: "linenoiseHistoryAdd",
  21. discardable.}
  22. proc historySetMaxLen*(len: cint): cint {.importc: "linenoiseHistorySetMaxLen".}
  23. proc historySave*(filename: cstring): cint {.importc: "linenoiseHistorySave".}
  24. proc historyLoad*(filename: cstring): cint {.importc: "linenoiseHistoryLoad".}
  25. proc clearScreen*() {.importc: "linenoiseClearScreen".}
  26. proc setMultiLine*(ml: cint) {.importc: "linenoiseSetMultiLine".}
  27. proc printKeyCodes*() {.importc: "linenoisePrintKeyCodes".}
  28. proc free*(s: cstring) {.importc: "free", header: "<stdlib.h>".}
  29. when not defined(windows):
  30. # C interface
  31. type LinenoiseStatus = enum
  32. linenoiseStatus_ctrl_unknown
  33. linenoiseStatus_ctrl_C
  34. linenoiseStatus_ctrl_D
  35. type LinenoiseData* = object
  36. status: LinenoiseStatus
  37. proc linenoiseExtra(prompt: cstring, data: ptr LinenoiseData): cstring {.importc.}
  38. # stable nim interface
  39. type Status* = enum
  40. lnCtrlUnkown
  41. lnCtrlC
  42. lnCtrlD
  43. type ReadLineResult* = object
  44. line*: string
  45. status*: Status
  46. proc readLineStatus*(prompt: string, result: var ReadLineResult) =
  47. ## line editing API that allows returning the line entered and an indicator
  48. ## of which control key was entered, allowing user to distinguish between
  49. ## for example ctrl-C vs ctrl-D.
  50. runnableExamples("-r:off"):
  51. var ret: ReadLineResult
  52. while true:
  53. readLineStatus("name: ", ret) # ctrl-D will exit, ctrl-C will go to next prompt
  54. if ret.line.len > 0: echo ret.line
  55. if ret.status == lnCtrlD: break
  56. echo "exiting"
  57. var data: LinenoiseData
  58. let buf = linenoiseExtra(prompt, data.addr)
  59. result.line = $buf
  60. free(buf)
  61. result.status = data.status.ord.Status