package syntax_test import ( "fmt" "rickub.com/turbo-editors/turbo-core/syntax" ) // Colouring a line of Markdown. func ExampleHighlight() { spans := syntax.Highlight(syntax.LanguageMarkdown, "# Title") for _, s := range spans[0] { fmt.Printf("%d-%d %v\n", s.Start, s.End, s.Class) } // Output: // 0-7 heading } // The cache is what the editor draws from: it re-scans only when the buffer's // revision has moved. func ExampleCache() { cache := syntax.NewCache(syntax.LanguageOf("settings.toml", "[editor]")) cache.Update("theme = \"turbo-dark\"", 1) cache.Update("theme = \"turbo-dark\"", 1) // no work: same revision for _, s := range cache.Line(0) { fmt.Println(s.Class) } // Output: // identifier // operator // string } // TOML is coloured with the classes every language here shares, so a theme // needs no keys of its own for it: a table header reads as a type, a key as an // identifier. func ExampleHighlight_toml() { spans := syntax.Highlight(syntax.LanguageTOML, "[editor]\ntheme = \"turbo-dark\" # ours\n") for _, s := range spans[1] { fmt.Printf("%d-%d %v\n", s.Start, s.End, s.Class) } // Output: // 0-5 identifier // 6-7 operator // 8-20 string // 21-27 comment } // A file is named by its extension, and only failing that by its first line. // Go is absent from this list on purpose: this library colours the languages // every editor built on it shares, and each editor registers the one it is for. func ExampleLanguageOf() { fmt.Println(syntax.LanguageOf(".turbo-go/settings.toml", "[editor]")) fmt.Println(syntax.LanguageOf("README.md", "# Title")) fmt.Println(syntax.LanguageOf("configure", "#!/bin/sh")) // no extension, so the shebang decides fmt.Println(syntax.LanguageOf("photo.png", "")) // Output: // toml // markdown // bash // none } // Teaching the package a language of your own. This is what Turbo Rust does at // start-up, with a scanner written against syntax.LineScanner. func ExampleRegister() { syntax.Register(syntax.Definition{ Language: "rust", Extensions: []string{".rs"}, Highlight: func(src string) [][]syntax.Span { return syntax.ScanLines(src, func(line []rune, carry struct{}) ([]syntax.Span, struct{}) { s := syntax.NewLineScanner(line) s.TakeRest(syntax.ClassComment) // a scanner worth the name does more return s.Spans(), carry }) }, }) fmt.Println(syntax.LanguageOf("main.rs", "")) fmt.Println(syntax.Highlight("rust", "fn main() {}")[0][0].Class) // Output: // rust // comment }