xonecas.io
62159
Sy

symb / files

symb / internal / tui / atexpand.go

892 bytes
1package tui
2
3import (
4	"fmt"
5	"os"
6	"regexp"
7	"strings"
8
9	"github.com/xonecas/symb/internal/hashline"
10)
11
12// atMentionRe matches @path tokens, where path is any non-whitespace sequence.
13var atMentionRe = regexp.MustCompile(`@(\S+)`)
14
15// expandAtMentions replaces @path tokens in the input string with the
16// hashline-tagged contents of the referenced file. If the file cannot be
17// read, the token is left as-is.
18func expandAtMentions(input string) string {
19	return atMentionRe.ReplaceAllStringFunc(input, func(match string) string {
20		path := match[1:] // strip leading @
21		data, err := os.ReadFile(path)
22		if err != nil {
23			return match // leave token intact
24		}
25		content := strings.TrimRight(string(data), "\n")
26		tagged := hashline.TagLines(content, 1)
27		var sb strings.Builder
28		fmt.Fprintf(&sb, "@%s\n", path)
29		sb.WriteString(hashline.FormatTagged(tagged))
30		return sb.String()
31	})
32}