Only include syntax layers specified by build tags; lazy-load syntax layers

This commit is contained in:
2025-06-14 09:37:24 -04:00
parent 4966337b1f
commit a427b4a907
3 changed files with 36 additions and 10 deletions
+5 -8
View File
@@ -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). 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 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 ```go
package main package main
@@ -46,12 +48,8 @@ func helloWorld() {
fmt.Println("Hello world") fmt.Println("Hello world")
}` }`
// Load the go syntax file // Load and parse the go syntax layer into a `*highlight.Def`
// Make sure that the syntax_files directory is in the current directory syntaxDef, err := highlight.ParseDef(syntax.Get("go"))
syntaxFile := syntax.GetGo()
// Parse it into a `*highlight.Def`
syntaxDef, err := highlight.ParseDef(syntaxFile)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
return return
@@ -59,6 +57,7 @@ func helloWorld() {
// Make a new highlighter from the definition // Make a new highlighter from the definition
h := highlight.NewHighlighter(syntaxDef) h := highlight.NewHighlighter(syntaxDef)
// Highlight the string // Highlight the string
// Matches is an array of maps which point to groups // 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 // 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) color.Set(color.FgHiBlue)
case highlight.Groups["preproc"]: case highlight.Groups["preproc"]:
//fallthrough
//case highlight.Groups["high.red"]:
color.Set(color.FgHiRed) color.Set(color.FgHiRed)
case highlight.Groups["special"]: case highlight.Groups["special"]:
+25
View File
@@ -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
}
+6 -2
View File
@@ -1,7 +1,10 @@
//go:build stxGo
package syntax package syntax
func GetGo() []byte { func init() {
return []byte(`filetype: go syntaxMap["go"] = &lazySyntax{init: func() []byte {
return []byte(`filetype: go
detect: detect:
filename: "\\.go$" filename: "\\.go$"
@@ -67,4 +70,5 @@ rules:
rules: rules:
- todo: "(TODO|XXX|FIXME):?" - todo: "(TODO|XXX|FIXME):?"
`) `)
}}
} }