Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

To clarify: .NET being cross platform, I write console apps that I run on both Windows and MacOS, and in both cases if I redirect the color output to a .txt file and open it in an editor, there are no ANSI escape sequences in the file. So I was wondering if there is some other standard for sending control codes to a terminal that is independent of the output stream.

Or is there some voodoo by which the ANSI sequences get stripped from the output when redirected to a file?



> Or is there some voodoo by which the ANSI sequences get stripped from the output when redirected to a file?

Not quite, but programs in general use some voodoo to detect when they are being redirected and won't output ANSI codes when they detect that.

Often there will be a flag to enable/disable color, or let it detect when color is desired. On Linux ls accepts the --color=WHEN parameter, where WHEN can be always (`ls --color=always > ls-with-ansi-codes.txt` will output color codes), it can be never (just don't output ANSI codes, no matter whether you detect output redirection) or it can be auto (will show colors when you execute `ls --color=auto` but not when you do `ls --color=auto > ls-without-ansi-codes.txt`).


On windows, there are APIs for setting color that could be ignored if STDOUT isn't a terminal.

On posix platforms, there's an API to check if a given file handle is a tty or not. https://github.com/corasaurus-hex/isatty/blob/main/isatty.c is an example of using the API, in a Janet context.

I assume that .NET's support for Linux/macOS is using that API decide if it should strip color codes or not.


Well yes like I said on Windows you can access the terminal and set its properties without encoding terminal escape sequences in the output stream. On Linux afaik escape sequences are the only way. On MacOS i have no idea. Generally speaking the escape sequences aren't "standard" but different terminals (and these days terminal emulators) all have their own codes. Hence ncurses which tries to encapsulate this and provide a uniform API so that the application doesn't have to deal with these murky details.

Have you double checked with s hex editor what is in the txt file? Suppose it could also be your text editor that doesn't want to render those codes.


Are you manually inserting the ANSI sequences into the stream? Or are you using a library that does this for you?

Often times libraries that let you specify output color will helpfully query the capabilities of the output device, and avoid writing the control codes if it’s (for example) a plain text file.


They are sometimes stripped when redirecting. Maybe try executing it headless and reading the output?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: