From c477d83f2493871b215aa2f8b2668b9b84fd6295 Mon Sep 17 00:00:00 2001 From: Robin Jarry Date: Wed, 8 Mar 2023 00:33:41 +0100 Subject: templates: add switch/case functions This allows much shorter templates. Signed-off-by: Robin Jarry Acked-by: Tim Culverhouse --- doc/aerc-templates.7.scd | 9 +++++++++ lib/templates/functions.go | 31 +++++++++++++++++++++++++++++++ models/templates.go | 5 +++++ 3 files changed, 45 insertions(+) diff --git a/doc/aerc-templates.7.scd b/doc/aerc-templates.7.scd index 401c04e7..7f3d6410 100644 --- a/doc/aerc-templates.7.scd +++ b/doc/aerc-templates.7.scd @@ -392,6 +392,15 @@ aerc provides the following additional functions: {{if match .Subject `^(\[[\w-]+\]\s*)?\[(RFC )?PATCH`}}{{.Style .Subject "cyan"}}{{else}}{{.Subject}}{{end}} ``` +*switch* + Do swich/case/default control flows. The switch value is compared with + regular expressions. If none of the case/default arms match, an empty + string is returned. + + ``` + {{switch .Folder (case `^INBOX$` "📥") (case `^Archive/.*` "🗃") (default "📁")}} + ``` + *Function chaining* All of the template functions can be chained together if needed. diff --git a/lib/templates/functions.go b/lib/templates/functions.go index 8bd8f37b..b331dc85 100644 --- a/lib/templates/functions.go +++ b/lib/templates/functions.go @@ -12,6 +12,7 @@ import ( "git.sr.ht/~rjarry/aerc/lib/format" "git.sr.ht/~rjarry/aerc/lib/parse" + "git.sr.ht/~rjarry/aerc/models" "github.com/emersion/go-message/mail" ) @@ -251,6 +252,33 @@ func compactDir(path string) string { return format.CompactPath(path, os.PathSeparator) } +type ( + Case struct{ expr, value string } + Default struct{ value string } +) + +func (c *Case) Matches(s string) bool { return parse.MatchCache(s, c.expr) } +func (c *Case) Value() string { return c.value } +func (d *Default) Matches(s string) bool { return true } +func (d *Default) Value() string { return d.value } + +func switch_(value string, cases ...models.Case) string { + for _, c := range cases { + if c.Matches(value) { + return c.Value() + } + } + return "" +} + +func case_(expr, value string) models.Case { + return &Case{expr: expr, value: value} +} + +func default_(value string) models.Case { + return &Default{value: value} +} + var templateFuncs = template.FuncMap{ "quote": quote, "wrapText": wrapText, @@ -273,4 +301,7 @@ var templateFuncs = template.FuncMap{ "trimSignature": trimSignature, "compactDir": compactDir, "match": parse.MatchCache, + "switch": switch_, + "case": case_, + "default": default_, } diff --git a/models/templates.go b/models/templates.go index 54537a31..dc984fc4 100644 --- a/models/templates.go +++ b/models/templates.go @@ -44,3 +44,8 @@ type TemplateData interface { PendingKeys() string Style(string, string) string } + +type Case interface { + Matches(string) bool + Value() string +} -- cgit v1.2.3-54-g00ecf