Printing Color in Terminal with Clojure

1 minute read

In Clojure, printing colored text to the terminal can be achieved by using ANSI escape codes, which are sequences of characters that modify text attributes like color, boldness, or background color. These codes are recognized by most modern terminal emulators.

Here’s how you can print colored text in Clojure using ANSI escape codes.

Example with ANSI Escape Codes:

1
2
3
4
5
6
7
8
9
10
(def red "\u001b[31m")
(def green "\u001b[32m")
(def yellow "\u001b[33m")
(def blue "\u001b[34m")
(def reset "\u001b[0m")

(println (str red "This is red!" reset))
(println (str green "This is green!" reset))
(println (str yellow "This is yellow!" reset))
(println (str blue "This is blue!" reset))

Explanation:

\u001b: This is the escape character (ESC), which starts an ANSI code.

[31m, [32m, etc.: These are the color codes for foreground colors:

    31m is red.
    32m is green.
    33m is yellow.
    34m is blue.
    0m resets all formatting (returning the text to the default terminal style).

List of Common ANSI Color Codes:

Foreground colors:
    30m: Black
    31m: Red
    32m: Green
    33m: Yellow
    34m: Blue
    35m: Magenta
    36m: Cyan
    37m: White
Background colors:
    40m: Black
    41m: Red
    42m: Green
    43m: Yellow
    44m: Blue
    45m: Magenta
    46m: Cyan
    47m: White
Text attributes:
    1m: Bold
    4m: Underlined
    0m: Reset to normal

Using a Clojure Library:

If you’d like a more feature-rich or convenient way to manage colored text, you can use libraries like clojure.tools.logging or a simpler one like clojure-term-color that simplifies this process. Example using the clojure-term-color library:

Add the dependency to your project.clj (if using Leiningen):

[clojure-term-color "0.1.0"]

Use it like so:

(require '[term-color.core :as t])

(println (t/color :red "This is red!"))
(println (t/color :green "This is green!"))
(println (t/color :blue "This is blue!"))

This library will internally handle the ANSI escape codes, making your code cleaner and more maintainable. Conclusion:

You can print colored text in Clojure using ANSI escape codes directly or use a library for better convenience and additional features.

Source Code

Find the project source code here https://gitlab.com/clojure-diary/code/color-print

Updated: