Don't enable ANSI in cmd.exe until absolutely necessary

This commit is contained in:
Christian Rocha 2021-04-06 15:12:44 -04:00
parent fedd7a49aa
commit 874349bbec
4 changed files with 16 additions and 8 deletions

View File

@ -2,5 +2,5 @@
package lipgloss
// enableANSIColors is only needed on Windows.
func enableANSIColors() {}
// enableLegacyWindowsANSI is only needed on Windows.
func enableLegacyWindowsANSI() {}

View File

@ -4,18 +4,23 @@ package lipgloss
import (
"os"
"sync"
"golang.org/x/sys/windows"
)
var enableANSI sync.Once
// enableANSIColors enables support for ANSI color sequences in the Windows
// default console (cmd.exe and the PowerShell application). Note that this
// only works with Windows 10. Also note that Windows Terminal supports colors
// by default.
func enableANSIColors() {
stdout := windows.Handle(os.Stdout.Fd())
var originalMode uint32
func enableLegacyWindowsANSI() {
enableANSI.Do(func() {
stdout := windows.Handle(os.Stdout.Fd())
var originalMode uint32
windows.GetConsoleMode(stdout, &originalMode)
windows.SetConsoleMode(stdout, originalMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING)
windows.GetConsoleMode(stdout, &originalMode)
windows.SetConsoleMode(stdout, originalMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING)
})
}

View File

@ -18,7 +18,6 @@ var (
// actual check only once.
func ColorProfile() termenv.Profile {
getColorProfile.Do(func() {
enableANSIColors()
colorProfile = termenv.ColorProfile()
})
return colorProfile

View File

@ -190,6 +190,10 @@ func (s Style) Render(str string) string {
useSpaceStyler = underlineSpaces || strikethroughSpaces
)
// Enable support for ANSI on the legacy Windows cmd.exe console. This is a
// no-op on non-Windows systems and on Windows runs only once.
enableLegacyWindowsANSI()
if bold {
te = te.Bold()
}