Skip to content

Instantly share code, notes, and snippets.

@dekimsey
Created November 1, 2022 19:56
Show Gist options
  • Save dekimsey/e0c668d2a543015f9aa3528ceeb4b064 to your computer and use it in GitHub Desktop.
Save dekimsey/e0c668d2a543015f9aa3528ceeb4b064 to your computer and use it in GitHub Desktop.
museli/termenv#71 work-around
package main
import (
"fmt"
"strings"
"github.com/mattn/go-runewidth"
"github.com/muesli/termenv"
)
const URLAnchorSeq = "8;;%s\007%s"
const URLNameSeq = "%s8;;%s\007%s"
// Style is a string that various rendering styles can be applied to.
type Style struct {
string
url string
styles []string
}
// String returns a new Style.
func String(s ...string) Style {
return Style{
string: strings.Join(s, " "),
}
}
func (t Style) String() string {
return t.Styled(t.string)
}
// Styled renders s with all applied styles.
func (t Style) Styled(s string) string {
if len(t.styles) == 0 {
return s
}
seq := strings.Join(t.styles, ";")
if seq == "" {
return s
}
if t.url != "" {
s = fmt.Sprintf("%s8;;%s\007%s%s8;;\007", termenv.OSC, t.url, s, termenv.OSC)
}
return fmt.Sprintf("%s%sm%s%sm", termenv.CSI, seq, s, termenv.CSI+termenv.ResetSeq)
}
// Foreground sets a foreground color.
func (t Style) Foreground(c termenv.Color) Style {
if c != nil {
t.styles = append(t.styles, c.Sequence(false))
}
return t
}
// Background sets a background color.
func (t Style) Background(c termenv.Color) Style {
if c != nil {
t.styles = append(t.styles, c.Sequence(true))
}
return t
}
// Bold enables bold rendering.
func (t Style) Bold() Style {
t.styles = append(t.styles, termenv.BoldSeq)
return t
}
// Faint enables faint rendering.
func (t Style) Faint() Style {
t.styles = append(t.styles, termenv.FaintSeq)
return t
}
// Italic enables italic rendering.
func (t Style) Italic() Style {
t.styles = append(t.styles, termenv.ItalicSeq)
return t
}
// Underline enables underline rendering.
func (t Style) Underline() Style {
t.styles = append(t.styles, termenv.UnderlineSeq)
return t
}
// Overline enables overline rendering.
func (t Style) Overline() Style {
t.styles = append(t.styles, termenv.OverlineSeq)
return t
}
// Blink enables blink mode.
func (t Style) Blink() Style {
t.styles = append(t.styles, termenv.BlinkSeq)
return t
}
// Reverse enables reverse color mode.
func (t Style) Reverse() Style {
t.styles = append(t.styles, termenv.ReverseSeq)
return t
}
// CrossOut enables crossed-out rendering.
func (t Style) CrossOut() Style {
t.styles = append(t.styles, termenv.CrossOutSeq)
return t
}
func (t Style) Anchor(url string) Style {
t.url = url
return t
}
// Width returns the width required to print all runes in Style.
func (t Style) Width() int {
return runewidth.StringWidth(t.string)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment