How to make win32 console recognize ANSI/VT100 escape sequences in `c`?
Asked Answered
C

14

95

I'm building a lightweight version of the ncurses library. So far, it works pretty well with VT100-compatible terminals, but win32 console fails to recognise the \033 code as the beginning of an escape sequence:

# include <stdio.h>
# include "term.h"

int main(void) {
  puts(BOLD COLOR(FG, RED) "Bold text" NOT_BOLD " is cool!" CLEAR);
  return 0;
}

Screenshot

What needs to be done on the C code level, in order that the ANSI.SYS driver is loaded and the ANSI/VT100 escape sequences recognized?

Cutlery answered 26/5, 2013 at 0:25 Comment(13)
there is colorama module for Python: "On Windows, Colorama strips these ANSI characters from stdout and converts them into equivalent win32 calls for colored text. On other platforms, Colorama does nothing."Kirst
Please notice that the rules of the game have changed drastically as of recent versions of Windows 10.Immix
FYI, in latest Windows 10, you can enable ANSI in conhost via the following reghack -- in HKCU\Console create a DWORD named VirtualTerminalLevel and set it to 0x1; then restart cmd.exe. -- You can test it with the following powershell "?[1;31mele ?[32mct ?[33mroni ?[35mX ?[36mtar ?[m".Replace('?', [char]27);.Evetteevey
upd learn.microsoft.com/en-us/windows/console/… here how it could be enabled without editing registry, and possibly breaking other applicationsShivers
ANSI.SYS is a thing I don't see since the WIN98 days.Satan
@Evetteevey Your suggestion doesn't appear to work with Windows 10 V22H2 (OS Build 19045.2604). Ugh! MS!Lipolysis
Maybe same question as batch file - How to echo with different colors in the Windows command line - Stack Overflow.Gregorio
Plz always specify the language you are trying to attempt since without it there can be multiple answers in multiple languages. And different languages have different ways to handle 1Ansi escape sequence`Basic
@VinodSrivastav No, ISO / DEC VT-100 terminal escape sequences is a protocol, it's the "language" itself.Arnitaarno
@JohanBoulé Are you telling us en.wikipedia.org/wiki/ANSI_escape_code is a language ? Kindly enlighten how you classified it as language and not encoding. BTW the comment was there as the Q was not tagged with a language even when the code is from c and i see answers from python and other languages.Basic
@VinodSrivastav Yes, this is what I said and meant, it defines display instructions formatted/encoded in a certain way as to be interpreted by the video terminal hardware or software emulating it. That's a display language, just like Postscript or HTML. The OP posted some C code but it's important to understand that C is irrelevant to be problem. On Windows, terminal duty isn't handled by ANSI.SYS anymore but by the conhost.exe process, which is initialized with the standard sequence interpreter turned off by default, because MS is fearful of corner cases breaking legacy (cr)apps.Arnitaarno
@JohanBoulé I am failing to understand why they embeded an interpreter in the terminal hardware which works even with my TV. But it's all about ANSI escape code \033 , \x1b or as unicode \u001b[38 all that matters is the way your program passes the message. For the OP it should work as learn.microsoft.com/en-us/windows/console/… as cmd.exe disables VT mode before starting other programs which is different then python code here https://mcmap.net/q/25739/-how-do-i-print-colored-text-to-the-terminal . That's why C is relevent to OP.Basic
@VinodSrivastav Hmmm, unlike a TV, a hardware terminal doesn't receive video signal, it receives display instructions. I think a good analogy is a Postscript printer.Arnitaarno
G
86

[UPDATE] For latest Windows 10 please read useful contribution by @brainslugs83, just below in the comments to this answer.

While for versions before Windows 10 Anniversary Update:

ANSI.SYS has a restriction that it can run only in the context of the MS-DOS sub-system under Windows 95-Vista.

Microsoft KB101875 explains how to enable ANSI.SYS in a command window, but it does not apply to Windows NT. According to the article: we all love colors, modern versions of Windows do not have this nice ANSI support.

Instead, Microsoft created a lot of functions, but this is far from your need to operate ANSI/VT100 escape sequence.

For a more detailed explanation, see the Wikipedia article:

ANSI.SYS also works in NT-derived systems for 16-bit legacy programs executing under the NTVDM.

The Win32 console does not natively support ANSI escape sequences at all. Software such as Ansicon can however act as a wrapper around the standard Win32 console and add support for ANSI escape sequences.

So I think ANSICON by Jason Hood is your solution. It is written in C, supports 32-bit and 64-bit versions of Windows, and the source is available.

Also I found some other similar question or post which ultimately have been answered to use ANSICON:

Gentlemanly answered 28/5, 2013 at 18:43 Comment(6)
I once did a hack to make ANSI work in Windows XP without any thirdparty tools groups.google.com/forum/#!topic/alt.msdos.batch.nt/YZnoq80McdsDiptych
How times change ;) In Windows 10 Anniversary Update and beyond, Windows Console was updated with pretty solid support for ANSI/VT sequences, and in Creators Update, was updated to support 24-bit RGB colors too: blogs.msdn.microsoft.com/commandline/2016/09/22/…Veach
Answer updated according to Rich Turner contributionGentlemanly
@Simon thanks, I removed the link because it doesn't work btw there is an archived version of kb/101875 hereGentlemanly
FYI, in latest Windows 10, you can enable ANSI in conhost via the following reghack -- in HKCU\Console create a DWORD named VirtualTerminalLevel and set it to 0x1; then restart cmd.exe. -- You can test it with the following powershell "?[1;31mele ?[32mct ?[33mroni ?[35mX ?[36mtar ?[m".Replace('?', [char]27);.Evetteevey
Thanks @brainslugs83 - Answer updated to cite your commentGentlemanly
T
41

Starting from Windows 10 TH2 (v1511), conhost.exe and cmd.exe support ANSI and VT100 Escape Sequences out of the box (although they have to be enabled).

See my answer over at superuser for more details.

Thunderhead answered 8/3, 2016 at 10:33 Comment(2)
The 105xx builds was the only builds having VT100 sequences enabled by default. In previous and later builds it's disabled by default cause it was enabled by mistake. See here for the explanation wpdev.uservoice.com/forums/…Deeplaid
FYI, in latest Windows 10, you can enable ANSI in conhost via the following reghack -- in HKCU\Console create a DWORD named VirtualTerminalLevel and set it to 0x1; then restart cmd.exe. -- You can test it with the following powershell "?[1;31mele ?[32mct ?[33mroni ?[35mX ?[36mtar ?[m".Replace('?', [char]27);.Evetteevey
D
29

Base on @BrainSlugs83 you can activate on the current Windows 10 version via register, with this command line:

REG ADD HKCU\CONSOLE /f /v VirtualTerminalLevel /t REG_DWORD /d 1
Devanagari answered 15/5, 2019 at 13:24 Comment(4)
Is this supported in all Windows 10 versions ? Or available from a specific update ?Churchly
in the firsts version of Windows 10 is not supported, but in the currents one work fine.Phile
I want to know the specific version that supported this.Churchly
@Churchly According to superuser.com/a/1300251/702169, first supporting version is build 16257.Monochromat
C
20

For Python 2.7 the following script works for me fine with Windows 10 (v1607)

import os

print '\033[35m'+'color-test'+'\033[39m'+" test end"
os.system('') #enable VT100 Escape Sequence for WINDOWS 10 Ver. 1607
print '\033[35m'+'color-test'+'\033[39m'+" test end"

Result should be:

[35mcolor-test[39m test end

color-test test end
Cercus answered 24/9, 2016 at 9:59 Comment(5)
That starts to look like black magic and no mention of how to turn off the console setting afterwards? curiously, it works for me, but unclear why from the magical empty string.Headdress
If you wrap the printed material in parentheses (...) this works in Python 3 on Windows 10 (v1703). (i.e. print('\033[35m'+'color-test'+'\033[39m'+" test end"))Kalidasa
Does someone have a source or know what os.system('') changes to the console ?Ami
os.system('') works apparently because of a bug in cmd.exe (cmd.exe enables VT mode, but doesn't disable it on exit). For more info, and better code to enable VT mode, see discussion on issue 30075 on python.orgEnamor
You end console codes that end with m by doing \033[0m. Or, if you want to reset the whole terminal, and clear the screen, do \033c.Dunston
P
18

Starting from Windows 10, you can use ENABLE_VIRTUAL_TERMINAL_PROCESSING to enable ANSI escape sequences:

https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx

Perceivable answered 13/6, 2016 at 7:4 Comment(0)
K
13

If ANSICON is not acceptable since it requires you to install something on the system, a more lightweight solution that parses and translates the ANSI codes into the relevant Win32 API console functions such as SetConsoleTextAttribute.

https://github.com/mattn/ansicolor-w32.c

Kobarid answered 3/3, 2015 at 16:21 Comment(1)
Just for instance, you can recompile the app by using the ParseAndPrintString function directly.Gavrah
L
8

For coloring the cmd you need Windows.h and use SetConsoleTextAttribute() more details can be found in http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047%28v=vs.85%29.aspx

Ludwog answered 26/5, 2013 at 1:40 Comment(1)
That's quite an unwieldy solution, not to mention the fact that this only allows for the coloring of a text - not the rest of ANSI.SYS codes. users.cybercity.dk/~bse26236/batutil/help/ANSI~S_S.HTMCutlery
M
7

In lastest win10, it can be done by SetConsoleMode(originMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING). See https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#example

Merth answered 10/8, 2018 at 1:35 Comment(0)
B
5

Maybe ANSICON can help u

Just download and extract files, depending on your windows os: 32bit or 64bit

Install it with: ansicon -i

Biblio answered 14/12, 2016 at 14:40 Comment(0)
R
2

I personally like clink. It not only processes ANSI codes, it also adds many other features so Windows Console behaves like bash (history, reverse history search, keyboard shortcuts, etc.):

  • The same line editing as Bash (from GNU's Readline library).
  • History persistence between sessions.
  • Context sensitive completion;
    • Executables (and aliases).
    • Directory commands.
    • Environment variables
    • Thirdparty tools; Git, Mercurial, SVN, Go, and P4.
  • New keyboard shortcuts;
    • Paste from clipboard (Ctrl-V).
    • Incremental history search (Ctrl-R/Ctrl-S).
    • Powerful completion (TAB).
    • Undo (Ctrl-Z).
    • Automatic "cd .." (Ctrl-PgUp).
    • Environment variable expansion (Ctrl-Alt-E).
    • (press Alt-H for many more...)
  • Scriptable completion with Lua.
  • Coloured and scriptable prompt.
  • Auto-answering of the "Terminate batch job?" prompt.
Rhinehart answered 20/2, 2018 at 13:31 Comment(0)
N
2

Ansi.sys (in the system32 folder) is an "MSDOS driver" provided as part of Windows XP, 2000, and earlier versions of NT. In 2000 and XP, it is located in the system32 folder (I don't remember the structure of earlier versions of NT). Programs that run in the DOS subsystem and use standard output can use ANSI.SYS just as they could running over MSDOS.

To load ansi.sys, you must use the device= or devicehigh= command in config, just as you would in MSDOS. On Windows NT 5 (2K & XP), each copy of the DOS subsystem can be given a separate config file in the pif/shortcut (use the "advanced" button), and there is a default file called CONFIG.NT (also in the system32 folder), which is used if the pif/shortcut does not specify a special config file.

When ansi.sys is loaded correctly, mem /d will report that it is loaded. On earlier versions of NT, you can and must load a proper DOS environment to load ansi.sys, and ansi art will work at the prompt. On Win 2K and XP, loading ansi.sys will have no effect on your "CMD prompt" because CMD is not a DOS program: it is a 32 bit Windows console program. For some reason that I do not understand, on WinXP, even if you load a fixed copy of command.com using "command.com /p", the command prompt will not be ansi enabled: perhaps when you do it that way it only emulates loading command.com?

In any case, when you use an actual DOS version of command.com, ansi is enabled after being loaded: you can demonstrate it's use with a bit of ansi art like this:

command /c type ansiart.ans

(here is an example: http://artscene.textfiles.com/ansi/artwork/beastie.ans)

CONFIG.NT (in the system32 folder) contains an example of the syntax for loading device drivers. You will need to be an Administrator to edit that default file, or you can make a copy of it.

On Win 2K and XP, the default "shortcut" for MSDOS is a .PIF file, not a .LNK file. If you create a .lnk file to CMD, you won't be able to set special config and autoexec files, it will use the default CONFIG.NT. If you want to use a special config file for just one DOS application, you can make a copy of the "MSDOS shortcut", or you can make a copy of "_default.pif", found in your Windows folder.

Nadya answered 22/3, 2018 at 2:52 Comment(0)
P
2

I found this tool to be working for my end. Microsoft Color Tool from GitHub

Unzip the compressed file then open CMD with Administration permission.

Go to the folder where you unzip the file in CMD.

Then execute this command "colortool -b scheme-name"

The scheme-name needs to be replaced with any of these options below:

  • campbell.ini
  • campbell-legacy.ini
  • cmd-legacy.ini
  • deuternopia.itermcolors
  • OneHalfDark.itermcolors
  • OneHalfLight.itermcolors
  • solarized_dark.itermcolors
  • solarized_light.itermcolors

In my case, the command would be like this "colortool -b solarized_dark.itermcolors"

Click right on the console window and select Properties.

You don't need to change any value just click "OK" to save the setting. (You will notice that your font already contains colors).

Console Property

Then restart your cmd or powerShell.

The ANSI color should be enabled and working with the color scheme you chose before.

Picket answered 26/7, 2018 at 13:33 Comment(2)
I tried this and then docker-machine refused to connect.Desmond
I'm sorry for so long but the method above was never tested for docker.Picket
B
2

Had the same issue. I installed ConEmu and that one solved my problem.

Barolet answered 26/1, 2019 at 16:30 Comment(0)
S
0

Somehow in Windows you just need to call any shell command first, rather call the system function. Just in start of your main method put system("");, and don't forget to include stdlib.h.

I noticed this when I looked at some of my old programs that also used ANSI codes to understand why they work, but my new code is not

Shame answered 3/11, 2022 at 19:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.