api.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package style
  3. import (
  4. "fmt"
  5. "strings"
  6. )
  7. type Context struct {
  8. AllowEscapeCodes bool
  9. }
  10. func (self *Context) SprintFunc(spec string) func(args ...any) string {
  11. p := prefix_for_spec(spec)
  12. s := suffix_for_spec(spec)
  13. return func(args ...any) string {
  14. body := fmt.Sprint(args...)
  15. if !self.AllowEscapeCodes {
  16. return body
  17. }
  18. b := strings.Builder{}
  19. b.Grow(len(p) + len(body) + len(s))
  20. b.WriteString(p)
  21. b.WriteString(body)
  22. b.WriteString(s)
  23. return b.String()
  24. }
  25. }
  26. func (self *Context) UrlFunc(spec string) func(string, string) string {
  27. p := prefix_for_spec(spec)
  28. s := suffix_for_spec(spec)
  29. return func(url, text string) string {
  30. if !self.AllowEscapeCodes {
  31. return text
  32. }
  33. uc := url_code{url: url}
  34. up, us := uc.prefix(), uc.suffix()
  35. b := strings.Builder{}
  36. b.Grow(len(p) + len(up) + len(text) + len(s) + len(us))
  37. b.WriteString(p)
  38. b.WriteString(up)
  39. b.WriteString(text)
  40. b.WriteString(us)
  41. b.WriteString(s)
  42. return b.String()
  43. }
  44. }