message-builder.scm 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. (library (message-builder)
  2. (export choices->message
  3. build-prompt-string)
  4. (import
  5. (except (rnrs base) let-values map error)
  6. (only (guile)
  7. ;; lambda forms
  8. lambda* λ
  9. display
  10. ;; control flow
  11. when
  12. ;; string
  13. string-join
  14. ;; display
  15. simple-format
  16. ;; ports
  17. call-with-output-string)
  18. ;; lists
  19. (srfi srfi-1)))
  20. (define rest
  21. (λ (lst)
  22. "alias for cdr"
  23. (cdr lst)))
  24. (define build-prompt-string
  25. (lambda* (prompt-text
  26. #:key
  27. (choices #f)
  28. (choices-opener "[")
  29. (choices-separator "/")
  30. (choices-closer "]")
  31. (input-separator ": "))
  32. "Construct the string, which is displayed before the
  33. cursor of an input."
  34. (call-with-output-string
  35. (λ (string-port)
  36. (when prompt-text
  37. (display prompt-text string-port))
  38. (when (and prompt-text choices)
  39. (display " " string-port))
  40. (when choices
  41. (display choices-opener string-port)
  42. (display (string-join choices choices-separator) string-port)
  43. (display choices-closer string-port))
  44. (display input-separator string-port)))))
  45. (define choices->message
  46. (lambda* (choices
  47. choice-texts
  48. #:key (separator ":") (spacer " ") (choice-end "\n") (end ""))
  49. "Transform choices into a string message, ready to be
  50. shown to a user supposed to make a choice."
  51. (call-with-output-string
  52. (λ (string-port)
  53. (let next-choice ([rest-choices choices] [rest-choice-texts choice-texts])
  54. (cond
  55. [(null? rest-choices)
  56. (display end string-port)]
  57. [else
  58. (simple-format string-port
  59. "~a~a~a~a~a"
  60. (first rest-choices)
  61. separator
  62. spacer
  63. (first rest-choice-texts)
  64. choice-end)
  65. (next-choice (cdr rest-choices)
  66. (cdr rest-choice-texts))]))))))