Coloured terminal output from Fortran

Viewed 8698

My program outputs state of computations to the terminal and includes quite a bit of information. I would like to, if possible, color code parts of the text.

I have seen how it can be done in Bash and C++ by referring to threads on this site. However, I have not been able to use any of that to achieve the same result in Fortran (modern). For example, I tried this sample code, which I thought should work:

PROGRAM test
    PRINT*, 'A great color is \033[95m pink \033[0m.'
END PROGRAM test

I would have expected the output to be "A great color is pink" where pink is colored pink. Instead I get "A great color is \033[95m pink \033[0m." I don't understand what I am missing.

If I replace the print line in the code with: CALL EXECUTE_COMMAND_LINE("echo 'A great color is \033[95m pink \033[0m.'") then I get the output as desired. However I wouldn't want to keep calling on echo from my code. Is there any way I can get colored output?

Thanks!

4 Answers

This is kind of an old question, but I figured I'd throw in my answer in case anyone comes along later (as I did) looking for an answer to this.

I had a similar problem as you did, trying to get escape sequences to work. I ended up going to the man page for gfortran. searching for 'escape' lead me to the compiler option '-fbackslash'. From the man page:

Change the interpretation of backslashes in string literals from a single backslash character to "C-style" escape characters. The following combinations are expanded "\a", "\b", "\f", "\n", "\r", "\t", "\v", "\", and "\0" to the ASCII characters alert, backspace, form feed, newline, carriage return, horizontal tab, vertical tab, backslash, and NUL , respectively. Additionally, "\x"nn, "\u"nnnn and "\U"nnnnnnnn (where each n is a hexadecimal digit) are translated into the Unicode characters corresponding to the specified code points. All other combinations of a character preceded by \ are unexpanded.

So, to get escape sequences to work in Fortran, all we need to do is compile with this option. The one thing that's different is that we have to use hexadecimal numbers along with x instead of octal numbers. In this specific case, instead of \033 we use \x1B. For example, PRINT *, "\x1B[31mThis text is red.\x1B[0m will print some text in red.

I think this method is definitely preferable to concatenating a bunch of individually defined characters each time we want to use color.

Related