From ffb3b073d702472d4b2dfe432b6b341b67748005 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Mon, 13 Mar 2023 09:39:35 +0530 Subject: [PATCH] Convenient loop API to print styled strings --- tools/tui/loop/api.go | 20 ++++++++++++++++++-- tools/tui/loop/run.go | 2 ++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/tools/tui/loop/api.go b/tools/tui/loop/api.go index 7f66cb7f7..280bee7a1 100644 --- a/tools/tui/loop/api.go +++ b/tools/tui/loop/api.go @@ -5,13 +5,14 @@ package loop import ( "encoding/base64" "fmt" - "kitty/tools/tty" - "kitty/tools/utils" "strings" "time" "golang.org/x/sys/unix" + "kitty/tools/tty" + "kitty/tools/utils" + "kitty/tools/utils/style" "kitty/tools/wcswidth" ) @@ -59,6 +60,8 @@ type Loop struct { pending_writes []*write_msg pending_mouse_events *utils.RingBuffer[MouseEvent] on_SIGTSTP func() error + style_cache map[string]func(...any) string + style_ctx style.Context // Suspend the loop restoring terminal state. Call the return resume function to restore the loop Suspend func() (func() error, error) @@ -201,6 +204,19 @@ func (self *Loop) Println(args ...any) { self.QueueWriteString("\r\n") } +func (self *Loop) SprintStyled(style string, args ...any) string { + f := self.style_cache[style] + if f == nil { + f = self.style_ctx.SprintFunc(style) + self.style_cache[style] = f + } + return f(args...) +} + +func (self *Loop) PrintStyled(style string, args ...any) { + self.QueueWriteString(self.SprintStyled(style, args...)) +} + func (self *Loop) SaveCursorPosition() { self.QueueWriteString("\x1b7") } diff --git a/tools/tui/loop/run.go b/tools/tui/loop/run.go index a0f2e535b..68831e42a 100644 --- a/tools/tui/loop/run.go +++ b/tools/tui/loop/run.go @@ -33,6 +33,8 @@ func new_loop() *Loop { l.escape_code_parser.HandlePM = l.handle_pm l.escape_code_parser.HandleRune = l.handle_rune l.escape_code_parser.HandleEndOfBracketedPaste = l.handle_end_of_bracketed_paste + l.style_cache = make(map[string]func(...any) string) + l.style_ctx.AllowEscapeCodes = true return &l }