Hello everyone,
I'm having a problem with printing colored output in Nim. I tried this:
import terminal
styledEcho(fgYellow, "This text is yellow")
styledEcho(fgBlue, "This text is blue")
styledEcho(fgRed, "This text is red")
styledEcho(fgGreen, "This text is green")
and it works fine. The only problems is that I don't want to be limited just to a few built-in colors.
Does anyone know how to print custom colored text in Nim? Thanks.
The Nim stdlib styledEcho uses ANSI escape sequences which are sorta-kinda portable across many terminals. On most the color set is quite limited to 8 or 16 foreground and 8 or 16 background.
Some terminals have added quite a bit more flexibility. xterm256 added 6*6*6 color cube (and grey scale) sometime in the 1990s. More recently xterm, st, alacritty, and I think kitty added "true color" where you can specify 2 hex digit (1 byte) RGB for 24 bit color. Assuming these terminal features will sadly make your code much less terminal portable
Since only end users really know how much terminal diversity needs supporting, if you want to use beyond the basics, it is much friendlier to have run-time rather than compile-time configuration. There is some example code in cligen/humanUt and some example use cases & user-configurations in lc, procs, and hldiff
Hmm I didn't knew about styledEcho and used my own colors :)
You can define any color you want yourself
proc green*(s: string): string = "\e[32m" & s & "\e[0m"
proc grey*(s: string): string = "\e[90m" & s & "\e[0m"
proc yellow*(s: string): string = "\e[33m" & s & "\e[0m"
proc red*(s: string): string = "\e[31m" & s & "\e[0m"
echo "The grass is " & "green".green & " and the sun is " & "yellow".yellow
Thank you for your help, I use this code:
var ocean = "\t\e[38;5;38;23m"
echo ocean, "hello!"
It works perfectly, the only thing I had to do was to download Windows Terminal from Microsoft Store (it's much better in my opinion, both functionality and design).I got some basic colors if you want
let
red = "\e[31m"
yellow = "\e[33m"
cyan = "\e[36m"
green = "\e[32m"
blue = "\e[34m"
def = "\e[0m"
def is defaultYou might find some more terminal color inspiration here if you are on linux
https://github.com/qqtop/NimCx
for lots off raw color constants to try see
https://github.com/qqtop/NimCx/blob/master/nimcx/cxconsts.nim