aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--doc/aerc-templates.7.scd14
-rw-r--r--lib/templates/functions.go20
-rw-r--r--lib/templates/functions_test.go34
3 files changed, 68 insertions, 0 deletions
diff --git a/doc/aerc-templates.7.scd b/doc/aerc-templates.7.scd
index b5681030..2c773bef 100644
--- a/doc/aerc-templates.7.scd
+++ b/doc/aerc-templates.7.scd
@@ -490,6 +490,20 @@ aerc provides the following additional functions:
{{replace `(.+) - .+ at .+\..+` `$1` ((index .OriginalFrom 0).Name)}}
```
+*head*
+ Return first n characters from string.
+
+ ```
+ {{"hello" | head 2}}
+ ```
+
+*tail*
+ Return last n characters from string.
+
+ ```
+ {{"hello" | tail 2}}
+ ```
+
*.Style*
Apply a user-defined style (see *aerc-stylesets*(7)) to a string.
diff --git a/lib/templates/functions.go b/lib/templates/functions.go
index 8b7af449..0d204b8f 100644
--- a/lib/templates/functions.go
+++ b/lib/templates/functions.go
@@ -334,6 +334,24 @@ func hasPrefix(prefix, s string) bool {
return strings.HasPrefix(s, prefix)
}
+func head(n uint, s string) string {
+ r := []rune(s)
+ length := uint(len(r))
+ if length >= n {
+ return string(r[:n])
+ }
+ return s
+}
+
+func tail(n uint, s string) string {
+ r := []rune(s)
+ length := uint(len(r))
+ if length >= n {
+ return string(r[length-n:])
+ }
+ return s
+}
+
var templateFuncs = template.FuncMap{
"quote": quote,
"wrapText": wrapText,
@@ -367,4 +385,6 @@ var templateFuncs = template.FuncMap{
"toLower": strings.ToLower,
"toUpper": strings.ToUpper,
"replace": replace,
+ "head": head,
+ "tail": tail,
}
diff --git a/lib/templates/functions_test.go b/lib/templates/functions_test.go
index 492aad01..3dac591e 100644
--- a/lib/templates/functions_test.go
+++ b/lib/templates/functions_test.go
@@ -121,3 +121,37 @@ func TestTemplates_DifferentInitialsFormats(t *testing.T) {
assert.Equal(t, c.initials, intls[0])
}
}
+
+func TestTemplates_Head(t *testing.T) {
+ type testCase struct {
+ head uint
+ input string
+ output string
+ }
+ cases := []testCase{
+ {head: 3, input: "abcde", output: "abc"},
+ {head: 10, input: "abcde", output: "abcde"},
+ }
+
+ for _, c := range cases {
+ out := head(c.head, c.input)
+ assert.Equal(t, c.output, out)
+ }
+}
+
+func TestTemplates_Tail(t *testing.T) {
+ type testCase struct {
+ tail uint
+ input string
+ output string
+ }
+ cases := []testCase{
+ {tail: 2, input: "abcde", output: "de"},
+ {tail: 8, input: "abcde", output: "abcde"},
+ }
+
+ for _, c := range cases {
+ out := tail(c.tail, c.input)
+ assert.Equal(t, c.output, out)
+ }
+}