From 20747fcf104aa05bdc4d7d2b12a2488940bcae2f Mon Sep 17 00:00:00 2001 From: Koni Marti Date: Wed, 10 May 2023 23:56:24 +0200 Subject: commands: expand and complete template code Expand and complete template code. The exline does understand template code and can evaluate it. With this patch, the completion systems supports writing the templates by showing the available template data fields and template functions. Pressing after }} will show the evaluated template in the completion menu. Complex template code, such as if-else statements work as well. Examples: :filter -f {{ will show the possible template data fields and functions :filter -f {{index (.To|email) 0}} will show the value of the template expression in the completion list Pressing twice after a completed template expression will substitute the expression with its value. :{{if match .Folder "INBOX"}}check-mail{{else}}cf INBOX{{end}} Signed-off-by: Koni Marti Acked-by: Robin Jarry --- commands/commands.go | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) (limited to 'commands') diff --git a/commands/commands.go b/commands/commands.go index f50a1e8a..c6f95aaa 100644 --- a/commands/commands.go +++ b/commands/commands.go @@ -141,6 +141,58 @@ func (cmds *Commands) ExecuteCommand( return NoSuchCommand(args[0]) } +func GetTemplateCompletion( + aerc *widgets.Aerc, cmd string, +) ([]string, string, bool) { + args, err := splitCmd(cmd) + if err != nil || len(args) == 0 { + return nil, "", false + } + + countLeft := strings.Count(cmd, "{{") + if countLeft == 0 { + return nil, "", false + } + countRight := strings.Count(cmd, "}}") + + switch { + case countLeft > countRight: + // complete template terms + var i int + for i = len(cmd) - 1; i >= 0; i-- { + if strings.ContainsRune("{()| ", rune(cmd[i])) { + break + } + } + search, prefix := cmd[i+1:], cmd[:i+1] + padding := strings.Repeat(" ", + len(search)-len(strings.TrimLeft(search, " "))) + options := FilterList( + templates.Terms(), + strings.TrimSpace(search), + "", + aerc.SelectedAccountUiConfig().FuzzyComplete, + ) + return options, prefix + padding, true + case countLeft == countRight: + // expand template + data := templateData(aerc, nil, nil) + t, err := templates.ParseTemplate("", cmd) + if err != nil { + log.Warnf("template parsing failed: %v", err) + return nil, "", false + } + var sb strings.Builder + if err = templates.Render(t, &sb, data); err != nil { + log.Warnf("template rendering failed: %v", err) + return nil, "", false + } + return []string{sb.String()}, "", true + } + + return nil, "", false +} + // GetCompletions returns the completion options and the command prefix func (cmds *Commands) GetCompletions( aerc *widgets.Aerc, cmd string, -- cgit