Skip to content

Add support for ANSI color codes in titles & subtitles#133

Open
Euheimr wants to merge 3 commits into
awesome-gocui:masterfrom
Euheimr:feature/ansi-color-titles
Open

Add support for ANSI color codes in titles & subtitles#133
Euheimr wants to merge 3 commits into
awesome-gocui:masterfrom
Euheimr:feature/ansi-color-titles

Conversation

@Euheimr

@Euheimr Euheimr commented Mar 12, 2025

Copy link
Copy Markdown

Setting view.TitleColor overrides ANSI color codes contained in the titles. If TitleColor is not set (ColorDefault) and the title/subtitle contains ANSI colors - render them!

Here's an example using the following code:

package main

import (
	"errors"
	"github.com/awesome-gocui/gocui"
	"github.com/gdamore/tcell/v2"
	"log"
)

const (
	ESC   string = "\033"
	RESET string = ESC + "[0m"
	RED   string = ESC + "[31m"
	GREEN string = ESC + "[0;32m"
	BLUE  string = ESC + "[0;34m"
)

func layout(g *gocui.Gui) error {
	maxX, maxY := g.Size()

	// View1 => Using ANSI colors but with Title Color set
	view1, err := g.SetView("view1", 0, 0, maxX/3, maxY-1, 0)
	if err != nil && !errors.Is(err, gocui.ErrUnknownView) {
		return err
	}
	view1.Title = "View1: " + RED + "Test Title"
	view1.Subtitle = "Subtitle test"

	// Setting TitleColor overrides any ANSI colors within Title or Subtitle
	view1.TitleColor = gocui.Attribute(tcell.ColorAzure)

	// View2 => Using ANSI colors without setting TitleColor
	view2, err := g.SetView("view2", maxX/3+1, 0, maxX-1, maxY-1, 0)
	if err != nil && !errors.Is(err, gocui.ErrUnknownView) {
		return err
	}
	view2.Title = "View2: " + BLUE + "Title is blue " + RESET + "(" + GREEN + "this is green" + RESET + ")"
	view2.Subtitle = BLUE + "Subtitle is blue" + RESET

	return nil
}

func quit(g *gocui.Gui, v *gocui.View) error {
	return gocui.ErrQuit
}

func main() {
	app, err := gocui.NewGui(gocui.OutputTrue, true)
	if err != nil {
		log.Panicln(err)
	}
	defer app.Close()

	app.SetManagerFunc(layout)

	if err = app.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit); err != nil {
		log.Panicln(err)
	}

	if err = app.MainLoop(); err != nil && !errors.Is(err, gocui.ErrQuit) {
		log.Panicln(err)
	}
}

Result:

image

Euheimr added 3 commits March 12, 2025 12:20
Setting view.TitleColor overrides ANSI color codes contained in the titles. If TitleColor is not set (ColorDefault) and the title/subtitle contains ANSI colors, render them
The starting location of subtitle was erroneously including the length of ANSI color codes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant