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 package lipgloss
// enableANSIColors is only needed on Windows. // enableLegacyWindowsANSI is only needed on Windows.
func enableANSIColors() {} func enableLegacyWindowsANSI() {}

View File

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

View File

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

View File

@ -190,6 +190,10 @@ func (s Style) Render(str string) string {
useSpaceStyler = underlineSpaces || strikethroughSpaces 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 { if bold {
te = te.Bold() te = te.Bold()
} }