From a427b4a907f2d8f5797a9b1b8c4df6ff9584120a Mon Sep 17 00:00:00 2001 From: Randall Winkhart Date: Sat, 14 Jun 2025 09:37:24 -0400 Subject: [PATCH] Only include syntax layers specified by build tags; lazy-load syntax layers --- README.md | 13 +++++-------- syntax/1entry.go | 25 +++++++++++++++++++++++++ syntax/{go.go => stxGo.go} | 8 ++++++-- 3 files changed, 36 insertions(+), 10 deletions(-) create mode 100644 syntax/1entry.go rename syntax/{go.go => stxGo.go} (94%) diff --git a/README.md b/README.md index 441db54..8837a1d 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,8 @@ Be sure to point your code to the correct path of `syntax_files`. Below is a simple example for highlighting a string (a Go snippet in this case). It uses `github.com/fatih/color` to actually colorize the output to the console. +It must be built with `-tags=stxGo` to include the Go syntax layer. + ```go package main @@ -46,12 +48,8 @@ func helloWorld() { fmt.Println("Hello world") }` - // Load the go syntax file - // Make sure that the syntax_files directory is in the current directory - syntaxFile := syntax.GetGo() - - // Parse it into a `*highlight.Def` - syntaxDef, err := highlight.ParseDef(syntaxFile) + // Load and parse the go syntax layer into a `*highlight.Def` + syntaxDef, err := highlight.ParseDef(syntax.Get("go")) if err != nil { fmt.Println(err) return @@ -59,6 +57,7 @@ func helloWorld() { // Make a new highlighter from the definition h := highlight.NewHighlighter(syntaxDef) + // Highlight the string // Matches is an array of maps which point to groups // matches[lineNum][colNum] will give you the change in group at that line and column number @@ -84,8 +83,6 @@ func helloWorld() { color.Set(color.FgHiBlue) case highlight.Groups["preproc"]: - //fallthrough - //case highlight.Groups["high.red"]: color.Set(color.FgHiRed) case highlight.Groups["special"]: diff --git a/syntax/1entry.go b/syntax/1entry.go new file mode 100644 index 0000000..899b8ba --- /dev/null +++ b/syntax/1entry.go @@ -0,0 +1,25 @@ +package syntax + +import "sync" + +var syntaxMap = make(map[string]*lazySyntax) + +type lazySyntax struct { + once sync.Once + syntaxLayer []byte + init func() []byte +} + +func (ls *lazySyntax) get() []byte { + ls.once.Do(func() { + ls.syntaxLayer = ls.init() + }) + return ls.syntaxLayer +} + +func Get(id string) []byte { + if syntax, exists := syntaxMap[id]; exists { + return syntax.get() + } + return nil +} diff --git a/syntax/go.go b/syntax/stxGo.go similarity index 94% rename from syntax/go.go rename to syntax/stxGo.go index 817ec09..a481eea 100644 --- a/syntax/go.go +++ b/syntax/stxGo.go @@ -1,7 +1,10 @@ +//go:build stxGo + package syntax -func GetGo() []byte { - return []byte(`filetype: go +func init() { + syntaxMap["go"] = &lazySyntax{init: func() []byte { + return []byte(`filetype: go detect: filename: "\\.go$" @@ -67,4 +70,5 @@ rules: rules: - todo: "(TODO|XXX|FIXME):?" `) + }} }