Using ANSI in a Windows console (terminal)

By | 2021/11/19

To use ANSI-Escape sequences in a Windows10 console, it must be enabled in the registry:

  • Press “WIN+r” hotkey
  • Enter “cmd.exe” ⏎
  • Enter “REG ADD HKCU\CONSOLE /f /v VirtualTerminalLevel /t REG_DWORD /d 1” ⏎

Using it with scala (13.6), example:

File “ansi.scala”:

import io.AnsiColor._
println(s"${RED}${BOLD}Hello world!${RESET}")
println(s"${YELLOW}${BOLD}Hello world!${RESET}")
println(s"${GREEN}${BOLD}Hello world!${RESET}")

File “ansiRunAsScalaScript.bat”:

@call scala ansi.scala
@pause

File “ansi_linux.scala:

(Code is Scala 3 syntax)

import io.AnsiColor._

@main def hello =
  println(s"${RED}${BOLD}Hello world!${RESET}")
  println(s"${YELLOW}${BOLD}Hello world!${RESET}")
  println(s"${GREEN}${BOLD}Hello world!${RESET}")
end hello

File “ansiRunAsScalaScript.sh” (LF):

!/bin/bash
scala ansi_linux.scala
read -p "Press [Enter] key …"

Result:

Windows (german)
Linux (WSL/Debian)

Or simplified uses only one file (Linux only) “ansi.sc” (Scala 3 syntax):

#!/bin/sh
exec scala "$0" "$@"
!#

import io.AnsiColor._

@main def hello =
  println(s"${RED}${BOLD}Hello world!${RESET}")
  println(s"${YELLOW}${BOLD}Hello world!${RESET}")
  println(s"${GREEN}${BOLD}Hello world!${RESET}")
end hello

Run with:
./ansi.sc

API: scala.io.AnsiColor