Issues with Char and printing ansi color codes to the terminal with Motoko

I’m toying around with printing different colors to the console with Motoko, and am running into issues utilizing the Char type to print out ascii or utf8.

For example, I’d like to do something like:

Debug.print("\033[32mThis is green font.\033[0m");
Debug.print("\033[33mThis is yellow font.\033[0m");
Debug.print("\033[34mThis is blue font.\033[0m");
Debug.print("\033[38mThis is the default font. \033[0m");

Take the first line of the example (green font). I’ve tried assignment like let char = '\033[32m', and the same with the end (close) character, as well as various ascii, utf, and unicode combinations like '\u{\6a}' mentioned in these docs, but keep getting the error, syntax error [M0002], malformed operator

So far, the only chars I’ve been able to to assign are single, individual characters like ‘c’ and ‘京’. While I have been able to use a small set of escaped characters like ‘\33’ or ‘\62’, I can’t follow the 33 up with a ‘[0-90-9m’ as defined in the ansi escape code standard.

The Char definition states that I should be able to do more than that, although I also haven’t seen any examples of this in the charTest.mo file in motoko-base

ascii ::= ['\x00'-'\x7f']
ascii_no_nl ::= ['\x00'-'\x09''\x0b'-'\x7f']
utf8cont ::= ['\x80'-'\xbf']
utf8enc ::=
    ['\xc2'-'\xdf'] utf8cont
  | ['\xe0'] ['\xa0'-'\xbf'] utf8cont
  | ['\xed'] ['\x80'-'\x9f'] utf8cont
  | ['\xe1'-'\xec''\xee'-'\xef'] utf8cont utf8cont
  | ['\xf0'] ['\x90'-'\xbf'] utf8cont utf8cont
  | ['\xf4'] ['\x80'-'\x8f'] utf8cont utf8cont
  | ['\xf1'-'\xf3'] utf8cont utf8cont utf8cont
utf8 ::= ascii | utf8enc
utf8_no_nl ::= ascii_no_nl | utf8enc

escape ::= ['n''r''t''\\''\'''\"']

character ::=
  | [^'"''\\''\x00'-'\x1f''\x7f'-'\xff']
  | utf8enc
  | '\\'escape
  | '\\'hexdigit hexdigit
  | "\\u{" hexnum '}'

char := '\'' character '\''
1 Like

Technically, a “character” is a single Unicode code point. The escape sequence "\033[32m" consists of 5 code points, so it isn’t a single character in the sense of Unicode, even if it is printed as one by ANSI terminals interpreting it specially.

This is not specific to Motoko, no other programming language that has a character type will accept that string as a character value. You can only store it as a text string.

3 Likes