Guest User

Untitled

a guest
May 24th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. module Tty_str = struct
  2.  
  3. type ttyfmt =
  4. | Plain
  5. | Red
  6. | Green
  7. | Yellow
  8. | Bold
  9. | Dim
  10. | Italic
  11. | Underline
  12.  
  13. type t = { fmt : ttyfmt; data: string }
  14.  
  15. let start_of fmt =
  16. match fmt with
  17. | Plain -> ""
  18. | Red -> "\x1b[31m"
  19. | Green -> "\x1b[32m"
  20. | Yellow -> "\x1b[33m"
  21. | Bold -> "\x1b[1m"
  22. | Dim -> "\x1b[2m"
  23. | Italic -> "\x1b[3m"
  24. | Underline -> "\x1b[4m"
  25.  
  26. let end_of fmt =
  27. match fmt with
  28. | Plain -> ""
  29. | _ -> "\x1b[0m"
  30.  
  31. let create ?(fmt = Plain) data = { fmt; data }
  32.  
  33. let string_of ?(for_tty = false) t =
  34. let start_tag =
  35. match for_tty with
  36. | false -> ""
  37. | true -> start_of t.fmt
  38. in
  39. let end_tag =
  40. match for_tty with
  41. | false -> ""
  42. | true -> end_of t.fmt
  43. in
  44. Printf.sprintf "%s%s%s" start_tag t.data end_tag
  45.  
  46. end
  47.  
  48. let () =
  49. let line_1 = Tty_str.create "Some plain text" in
  50. let line_2 = Tty_str.create ~fmt:Red "Some red text" in
  51. let line_3 = Tty_str.create ~fmt:Green "Some green text" in
  52. let line_4 = Tty_str.create ~fmt:Yellow "Some yellow text" in
  53. let line_5 = Tty_str.create ~fmt:Bold "Some bold text" in
  54. let line_6 = Tty_str.create ~fmt:Italic "Some italic text" in
  55. let line_7 = Tty_str.create ~fmt:Dim "Some dim text" in
  56. let line_8 = Tty_str.create ~fmt:Underline "Some underlined text" in
  57.  
  58. let lines =
  59. [line_1; line_2; line_3; line_4; line_5; line_6; line_7; line_8] in
  60.  
  61. Printf.printf "Print with colors, for a TTY:\n----------------\n";
  62. List.iter
  63. (fun s -> Printf.printf "%s\n" (Tty_str.string_of ~for_tty:true s)) lines;
  64.  
  65. Printf.printf "\nPrint without colors, for no TTY.\n----------------\n";
  66. List.iter
  67. (fun s -> Printf.printf "%s\n" (Tty_str.string_of s)) lines
Add Comment
Please, Sign In to add comment