From 4a4500d56bde6a4384d8f311c5d85085ff15f21f Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Sun, 28 Aug 2022 10:12:35 +0530 Subject: [PATCH] Dont make urls part of styling, instead have a dedicated UrlFunc API Since urls can potentially change a lot, caching them makes no sense --- tools/utils/style/api.go | 21 +++++++++++++++++++++ tools/utils/style/wrapper.go | 6 ------ tools/utils/style/wrapper_test.go | 6 +++++- 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/tools/utils/style/api.go b/tools/utils/style/api.go index 42892bf22..c3aeaf1e7 100644 --- a/tools/utils/style/api.go +++ b/tools/utils/style/api.go @@ -28,3 +28,24 @@ func (self *Context) SprintFunc(spec string) func(args ...interface{}) string { return b.String() } } + +func (self *Context) UrlFunc(spec string) func(string, string) string { + p := prefix_for_spec(spec) + s := suffix_for_spec(spec) + + return func(url string, text string) string { + if !self.AllowEscapeCodes { + return text + } + uc := url_code{url: url} + up, us := uc.prefix(), uc.suffix() + b := strings.Builder{} + b.Grow(len(p) + len(up) + len(text) + len(s) + len(us)) + b.WriteString(p) + b.WriteString(up) + b.WriteString(text) + b.WriteString(us) + b.WriteString(s) + return b.String() + } +} diff --git a/tools/utils/style/wrapper.go b/tools/utils/style/wrapper.go index f8db44659..31c665901 100644 --- a/tools/utils/style/wrapper.go +++ b/tools/utils/style/wrapper.go @@ -298,7 +298,6 @@ func (self *sgr_code) update() { func parse_spec(spec string) []escape_code { ans := make([]escape_code, 0, 1) sgr := sgr_code{} - url := url_code{} sparts, _ := shlex.Split(spec) for _, p := range sparts { parts := strings.SplitN(p, "=", 2) @@ -326,17 +325,12 @@ func parse_spec(spec string) []escape_code { sgr.underline.from_string(val) case "ucol", "underline_color", "uc": sgr.uc.from_string(val) - case "url": - url.url = val } } sgr.update() if !sgr.is_empty() { ans = append(ans, &sgr) } - if !url.is_empty() { - ans = append(ans, &url) - } return ans } diff --git a/tools/utils/style/wrapper_test.go b/tools/utils/style/wrapper_test.go index 0b69b0b2b..c7d85fc4e 100644 --- a/tools/utils/style/wrapper_test.go +++ b/tools/utils/style/wrapper_test.go @@ -44,5 +44,9 @@ func TestANSIStyleSprint(t *testing.T) { test("uc=123", "\x1b[58:5:123m", "\x1b[59m") test("uc=1", "\x1b[58:5:1m", "\x1b[59m") - test("url=123", "\x1b]8;;123\x1b\\", "\x1b]8;;\x1b\\") + actual := ctx.UrlFunc("u=curly uc=cyan")("http://moo.com", "___") + expected := "\x1b[4:3;58:5:6m\x1b]8;;http://moo.com\x1b\\___\x1b]8;;\x1b\\\x1b[4:0;59m" + if actual != expected { + t.Fatalf("Formatting URL failed expected != actual: %#v != %#v", expected, actual) + } }