4 "github.com/zyedidia/tcell"
11 // FileTypeRules represents a complete set of syntax rules for a filetype
12 type FileTypeRules struct {
18 // SyntaxRule represents a regex to highlight in a certain style
19 type SyntaxRule struct {
24 // Whether this regex is a start=... end=... regex
26 // How to highlight it
30 var syntaxFiles map[[2]*regexp.Regexp]FileTypeRules
32 // These syntax files are pre installed and embedded in the resulting binary by go-bindata
33 var preInstalledSynFiles = []string{
120 // LoadSyntaxFiles loads the syntax files from the default directory (configDir)
121 func LoadSyntaxFiles() {
122 // Load the user's custom syntax files, if there are any
123 LoadSyntaxFilesFromDir(configDir + "/syntax")
125 // Load the pre-installed syntax files from inside the binary
126 for _, filetype := range preInstalledSynFiles {
127 data, err := Asset("runtime/syntax/" + filetype + ".micro")
129 TermMessage("Unable to load pre-installed syntax file " + filetype)
133 LoadSyntaxFile(string(data), filetype+".micro")
137 // LoadSyntaxFilesFromDir loads the syntax files from a specified directory
138 // To load the syntax files, we must fill the `syntaxFiles` map
139 // This involves finding the regex for syntax and if it exists, the regex
140 // for the header. Then we must get the text for the file and the filetype.
141 func LoadSyntaxFilesFromDir(dir string) {
142 colorscheme = make(Colorscheme)
146 defStyle = tcell.StyleDefault.
147 Foreground(tcell.ColorDefault).
148 Background(tcell.ColorDefault)
150 // There may be another default style defined in the colorscheme
151 // In that case we should use that one
152 if style, ok := colorscheme["default"]; ok {
156 syntaxFiles = make(map[[2]*regexp.Regexp]FileTypeRules)
157 files, _ := ioutil.ReadDir(dir)
158 for _, f := range files {
159 if filepath.Ext(f.Name()) == ".micro" {
160 filename := dir + "/" + f.Name()
161 text, err := ioutil.ReadFile(filename)
164 TermMessage("Error loading syntax file " + filename + ": " + err.Error())
167 LoadSyntaxFile(string(text), filename)
172 // JoinRule takes a syntax rule (which can be multiple regular expressions)
173 // and joins it into one regular expression by ORing everything together
174 func JoinRule(rule string) string {
175 split := strings.Split(rule, `" "`)
176 joined := strings.Join(split, ")|(")
177 joined = "(" + joined + ")"
181 // LoadSyntaxFile simply gets the filetype of a the syntax file and the source for the
182 // file and creates FileTypeRules out of it. If this filetype is the one opened by the user
183 // the rules will be loaded and compiled later
184 // In this function we are only concerned with loading the syntax and header regexes
185 func LoadSyntaxFile(text, filename string) {
187 lines := strings.Split(string(text), "\n")
189 // Regex for parsing syntax statements
190 syntaxParser := regexp.MustCompile(`syntax "(.*?)"\s+"(.*)"+`)
191 // Regex for parsing header statements
192 headerParser := regexp.MustCompile(`header "(.*)"`)
194 // Is there a syntax definition in this file?
195 hasSyntax := syntaxParser.MatchString(text)
196 // Is there a header definition in this file?
197 hasHeader := headerParser.MatchString(text)
199 var syntaxRegex *regexp.Regexp
200 var headerRegex *regexp.Regexp
202 for lineNum, line := range lines {
203 if (hasSyntax == (syntaxRegex != nil)) && (hasHeader == (headerRegex != nil)) {
204 // We found what we we're supposed to find
208 if strings.TrimSpace(line) == "" ||
209 strings.TrimSpace(line)[0] == '#' {
214 if strings.HasPrefix(line, "syntax") {
216 syntaxMatches := syntaxParser.FindSubmatch([]byte(line))
217 if len(syntaxMatches) == 3 {
218 if syntaxRegex != nil {
219 TermError(filename, lineNum, "Syntax statement redeclaration")
222 filetype = string(syntaxMatches[1])
223 extensions := JoinRule(string(syntaxMatches[2]))
225 syntaxRegex, err = regexp.Compile(extensions)
227 TermError(filename, lineNum, err.Error())
231 TermError(filename, lineNum, "Syntax statement is not valid: "+line)
234 } else if strings.HasPrefix(line, "header") {
236 headerMatches := headerParser.FindSubmatch([]byte(line))
237 if len(headerMatches) == 2 {
238 header := JoinRule(string(headerMatches[1]))
240 headerRegex, err = regexp.Compile(header)
242 TermError(filename, lineNum, "Regex error: "+err.Error())
246 TermError(filename, lineNum, "Header statement is not valid: "+line)
251 if syntaxRegex != nil {
252 // Add the current rules to the syntaxFiles variable
253 regexes := [2]*regexp.Regexp{syntaxRegex, headerRegex}
254 syntaxFiles[regexes] = FileTypeRules{filetype, filename, text}
258 // LoadRulesFromFile loads just the syntax rules from a given file
259 // Only the necessary rules are loaded when the buffer is opened.
260 // If we load all the rules for every filetype when micro starts, there's a bit of lag
261 // A rule just explains how to color certain regular expressions
262 // Example: color comment "//.*"
263 // This would color all strings that match the regex "//.*" in the comment color defined
264 // by the colorscheme
265 func LoadRulesFromFile(text, filename string) []SyntaxRule {
266 lines := strings.Split(string(text), "\n")
268 // Regex for parsing standard syntax rules
269 ruleParser := regexp.MustCompile(`color (.*?)\s+(?:\((.*?)\)\s+)?"(.*)"`)
270 // Regex for parsing syntax rules with start="..." end="..."
271 ruleStartEndParser := regexp.MustCompile(`color (.*?)\s+(?:\((.*?)\)\s+)?start="(.*)"\s+end="(.*)"`)
273 var rules []SyntaxRule
274 for lineNum, line := range lines {
275 if strings.TrimSpace(line) == "" ||
276 strings.TrimSpace(line)[0] == '#' ||
277 strings.HasPrefix(line, "syntax") ||
278 strings.HasPrefix(line, "header") {
283 // Syntax rule, but it could be standard or start-end
284 if ruleParser.MatchString(line) {
285 // Standard syntax rule
287 submatch := ruleParser.FindSubmatch([]byte(line))
291 if len(submatch) == 4 {
292 // If len is 4 then the user specified some additional flags to use
293 color = string(submatch[1])
294 flags = string(submatch[2])
295 regexStr = "(?" + flags + ")" + JoinRule(string(submatch[3]))
296 } else if len(submatch) == 3 {
297 // If len is 3, no additional flags were given
298 color = string(submatch[1])
299 regexStr = JoinRule(string(submatch[2]))
301 // If len is not 3 or 4 there is a problem
302 TermError(filename, lineNum, "Invalid statement: "+line)
306 regex, err := regexp.Compile(regexStr)
308 TermError(filename, lineNum, err.Error())
313 // The user could give us a "color" that is really a part of the colorscheme
314 // in which case we should look that up in the colorscheme
315 // They can also just give us a straight up color
317 groups := strings.Split(color, ".")
320 for i, g := range groups {
325 if style, ok := colorscheme[curGroup]; ok {
329 } else if style, ok := colorscheme[color]; ok {
332 st = StringToStyle(color)
334 // Add the regex, flags, and style
335 // False because this is not start-end
336 rules = append(rules, SyntaxRule{regex, flags, false, st})
337 } else if ruleStartEndParser.MatchString(line) {
338 // Start-end syntax rule
339 submatch := ruleStartEndParser.FindSubmatch([]byte(line))
343 // Use m and s flags by default
345 if len(submatch) == 5 {
346 // If len is 5 the user provided some additional flags
347 color = string(submatch[1])
348 flags += string(submatch[2])
349 start = string(submatch[3])
350 end = string(submatch[4])
351 } else if len(submatch) == 4 {
352 // If len is 4 the user did not provide additional flags
353 color = string(submatch[1])
354 start = string(submatch[2])
355 end = string(submatch[3])
357 // If len is not 4 or 5 there is a problem
358 TermError(filename, lineNum, "Invalid statement: "+line)
363 regex, err := regexp.Compile("(?" + flags + ")" + "(" + start + ").*?(" + end + ")")
365 TermError(filename, lineNum, err.Error())
370 // The user could give us a "color" that is really a part of the colorscheme
371 // in which case we should look that up in the colorscheme
372 // They can also just give us a straight up color
374 if _, ok := colorscheme[color]; ok {
375 st = colorscheme[color]
377 st = StringToStyle(color)
379 // Add the regex, flags, and style
380 // True because this is start-end
381 rules = append(rules, SyntaxRule{regex, flags, true, st})
387 // GetRules finds the syntax rules that should be used for the buffer
388 // and returns them. It also returns the filetype of the file
389 func GetRules(buf *Buffer) ([]SyntaxRule, string) {
390 for r := range syntaxFiles {
391 if r[0] != nil && r[0].MatchString(buf.Path) {
392 // Check if the syntax statement matches the extension
393 return LoadRulesFromFile(syntaxFiles[r].text, syntaxFiles[r].filename), syntaxFiles[r].filetype
394 } else if r[1] != nil && r[1].MatchString(buf.Line(0)) {
395 // Check if the header statement matches the first line
396 return LoadRulesFromFile(syntaxFiles[r].text, syntaxFiles[r].filename), syntaxFiles[r].filetype
399 return nil, "Unknown"
402 // SyntaxMatches is an alias to a map from character numbers to styles,
403 // so map[3] represents the style of the third character
404 type SyntaxMatches [][]tcell.Style
406 // Match takes a buffer and returns the syntax matches: a 2d array specifying how it should be syntax highlighted
407 // We match the rules from up `synLinesUp` lines and down `synLinesDown` lines
408 func Match(v *View) SyntaxMatches {
412 viewStart := v.Topline
413 viewEnd := v.Topline + v.height
414 if viewEnd > buf.NumLines {
415 viewEnd = buf.NumLines
418 lines := buf.Lines(viewStart, viewEnd)
419 matches := make(SyntaxMatches, len(lines))
421 for i, line := range lines {
422 matches[i] = make([]tcell.Style, len(line)+1)
423 for j, _ := range matches[i] {
424 matches[i][j] = defStyle
428 // We don't actually check the entire buffer, just from synLinesUp to synLinesDown
429 totalStart := v.Topline - synLinesUp
430 totalEnd := v.Topline + v.height + synLinesDown
434 if totalEnd > buf.NumLines {
435 totalEnd = buf.NumLines
438 str := strings.Join(buf.Lines(totalStart, totalEnd), "\n")
439 startNum := ToCharPos(Loc{0, totalStart}, v.Buf)
441 toplineNum := ToCharPos(Loc{0, v.Topline}, v.Buf)
443 for _, rule := range rules {
445 if indicies := rule.regex.FindAllStringIndex(str, -1); indicies != nil {
446 for _, value := range indicies {
447 value[0] = runePos(value[0], str) + startNum
448 value[1] = runePos(value[1], str) + startNum
449 for i := value[0]; i < value[1]; i++ {
453 loc := FromCharPos(i, buf)
454 colNum, lineNum := loc.X, loc.Y
455 if lineNum == -1 || colNum == -1 {
459 if lineNum >= 0 && lineNum < v.height {
460 matches[lineNum][colNum] = rule.style
466 for lineN, line := range lines {
467 if indicies := rule.regex.FindAllStringIndex(line, -1); indicies != nil {
468 for _, value := range indicies {
469 start := runePos(value[0], line)
470 end := runePos(value[1], line)
471 for i := start; i < end; i++ {
472 matches[lineN][i] = rule.style