Skip to content

Instantly share code, notes, and snippets.

@jtpaasch
Created May 18, 2018 20:29
Show Gist options
  • Select an option

  • Save jtpaasch/dd01ee9e13b4e7845e787a5f442e19dc to your computer and use it in GitHub Desktop.

Select an option

Save jtpaasch/dd01ee9e13b4e7845e787a5f442e19dc to your computer and use it in GitHub Desktop.
Another colorizer/formatter for TTYs (OCaml)
module Tty_str = struct
type ttyfmt =
| Plain
| Red
| Green
| Yellow
| Bold
| Dim
| Italic
| Underline
type t = { fmt : ttyfmt; data: string }
let start_of fmt =
match fmt with
| Plain -> ""
| Red -> "\x1b[31m"
| Green -> "\x1b[32m"
| Yellow -> "\x1b[33m"
| Bold -> "\x1b[1m"
| Dim -> "\x1b[2m"
| Italic -> "\x1b[3m"
| Underline -> "\x1b[4m"
let end_of fmt =
match fmt with
| Plain -> ""
| _ -> "\x1b[0m"
let create ?(fmt = Plain) data = { fmt; data }
let string_of ?(for_tty = false) t =
let start_tag =
match for_tty with
| false -> ""
| true -> start_of t.fmt
in
let end_tag =
match for_tty with
| false -> ""
| true -> end_of t.fmt
in
Printf.sprintf "%s%s%s" start_tag t.data end_tag
end
let () =
let line_1 = Tty_str.create "Some plain text" in
let line_2 = Tty_str.create ~fmt:Red "Some red text" in
let line_3 = Tty_str.create ~fmt:Green "Some green text" in
let line_4 = Tty_str.create ~fmt:Yellow "Some yellow text" in
let line_5 = Tty_str.create ~fmt:Bold "Some bold text" in
let line_6 = Tty_str.create ~fmt:Italic "Some italic text" in
let line_7 = Tty_str.create ~fmt:Dim "Some dim text" in
let line_8 = Tty_str.create ~fmt:Underline "Some underlined text" in
let lines =
[line_1; line_2; line_3; line_4; line_5; line_6; line_7; line_8] in
Printf.printf "Print with colors, for a TTY:\n----------------\n";
List.iter
(fun s -> Printf.printf "%s\n" (Tty_str.string_of ~for_tty:true s)) lines;
Printf.printf "\nPrint without colors, for no TTY.\n----------------\n";
List.iter
(fun s -> Printf.printf "%s\n" (Tty_str.string_of s)) lines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment