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{
122 // LoadSyntaxFiles loads the syntax files from the default directory (configDir)
123 func LoadSyntaxFiles() {
124 // Load the user's custom syntax files, if there are any
125 LoadSyntaxFilesFromDir(configDir + "/syntax")
127 // Load the pre-installed syntax files from inside the binary
128 for _, filetype := range preInstalledSynFiles {
129 data, err := Asset("runtime/syntax/" + filetype + ".micro")
131 TermMessage("Unable to load pre-installed syntax file " + filetype)
135 LoadSyntaxFile(string(data), filetype+".micro")
139 // LoadSyntaxFilesFromDir loads the syntax files from a specified directory
140 // To load the syntax files, we must fill the `syntaxFiles` map
141 // This involves finding the regex for syntax and if it exists, the regex
142 // for the header. Then we must get the text for the file and the filetype.
143 func LoadSyntaxFilesFromDir(dir string) {
144 colorscheme = make(Colorscheme)
148 defStyle = tcell.StyleDefault.
149 Foreground(tcell.ColorDefault).
150 Background(tcell.ColorDefault)
152 // There may be another default style defined in the colorscheme
153 // In that case we should use that one
154 if style, ok := colorscheme["default"]; ok {
158 screen.SetStyle(defStyle)
161 syntaxFiles = make(map[[2]*regexp.Regexp]FileTypeRules)
162 files, _ := ioutil.ReadDir(dir)
163 for _, f := range files {
164 if filepath.Ext(f.Name()) == ".micro" {
165 filename := dir + "/" + f.Name()
166 text, err := ioutil.ReadFile(filename)
169 TermMessage("Error loading syntax file " + filename + ": " + err.Error())
172 LoadSyntaxFile(string(text), filename)
177 // JoinRule takes a syntax rule (which can be multiple regular expressions)
178 // and joins it into one regular expression by ORing everything together
179 func JoinRule(rule string) string {
180 split := strings.Split(rule, `" "`)
181 joined := strings.Join(split, ")|(")
182 joined = "(" + joined + ")"
186 // LoadSyntaxFile simply gets the filetype of a the syntax file and the source for the
187 // file and creates FileTypeRules out of it. If this filetype is the one opened by the user
188 // the rules will be loaded and compiled later
189 // In this function we are only concerned with loading the syntax and header regexes
190 func LoadSyntaxFile(text, filename string) {
192 lines := strings.Split(string(text), "\n")
194 // Regex for parsing syntax statements
195 syntaxParser := regexp.MustCompile(`syntax "(.*?)"\s+"(.*)"+`)
196 // Regex for parsing header statements
197 headerParser := regexp.MustCompile(`header "(.*)"`)
199 // Is there a syntax definition in this file?
200 hasSyntax := syntaxParser.MatchString(text)
201 // Is there a header definition in this file?
202 hasHeader := headerParser.MatchString(text)
204 var syntaxRegex *regexp.Regexp
205 var headerRegex *regexp.Regexp
207 for lineNum, line := range lines {
208 if (hasSyntax == (syntaxRegex != nil)) && (hasHeader == (headerRegex != nil)) {
209 // We found what we we're supposed to find
213 if strings.TrimSpace(line) == "" ||
214 strings.TrimSpace(line)[0] == '#' {
219 if strings.HasPrefix(line, "syntax") {
221 syntaxMatches := syntaxParser.FindSubmatch([]byte(line))
222 if len(syntaxMatches) == 3 {
223 if syntaxRegex != nil {
224 TermError(filename, lineNum, "Syntax statement redeclaration")
227 filetype = string(syntaxMatches[1])
228 extensions := JoinRule(string(syntaxMatches[2]))
230 syntaxRegex, err = regexp.Compile(extensions)
232 TermError(filename, lineNum, err.Error())
236 TermError(filename, lineNum, "Syntax statement is not valid: "+line)
239 } else if strings.HasPrefix(line, "header") {
241 headerMatches := headerParser.FindSubmatch([]byte(line))
242 if len(headerMatches) == 2 {
243 header := JoinRule(string(headerMatches[1]))
245 headerRegex, err = regexp.Compile(header)
247 TermError(filename, lineNum, "Regex error: "+err.Error())
251 TermError(filename, lineNum, "Header statement is not valid: "+line)
256 if syntaxRegex != nil {
257 // Add the current rules to the syntaxFiles variable
258 regexes := [2]*regexp.Regexp{syntaxRegex, headerRegex}
259 syntaxFiles[regexes] = FileTypeRules{filetype, filename, text}
263 // LoadRulesFromFile loads just the syntax rules from a given file
264 // Only the necessary rules are loaded when the buffer is opened.
265 // If we load all the rules for every filetype when micro starts, there's a bit of lag
266 // A rule just explains how to color certain regular expressions
267 // Example: color comment "//.*"
268 // This would color all strings that match the regex "//.*" in the comment color defined
269 // by the colorscheme
270 func LoadRulesFromFile(text, filename string) []SyntaxRule {
271 lines := strings.Split(string(text), "\n")
273 // Regex for parsing standard syntax rules
274 ruleParser := regexp.MustCompile(`color (.*?)\s+(?:\((.*?)\)\s+)?"(.*)"`)
275 // Regex for parsing syntax rules with start="..." end="..."
276 ruleStartEndParser := regexp.MustCompile(`color (.*?)\s+(?:\((.*?)\)\s+)?start="(.*)"\s+end="(.*)"`)
278 var rules []SyntaxRule
279 for lineNum, line := range lines {
280 if strings.TrimSpace(line) == "" ||
281 strings.TrimSpace(line)[0] == '#' ||
282 strings.HasPrefix(line, "syntax") ||
283 strings.HasPrefix(line, "header") {
288 // Syntax rule, but it could be standard or start-end
289 if ruleParser.MatchString(line) {
290 // Standard syntax rule
292 submatch := ruleParser.FindSubmatch([]byte(line))
296 if len(submatch) == 4 {
297 // If len is 4 then the user specified some additional flags to use
298 color = string(submatch[1])
299 flags = string(submatch[2])
300 regexStr = "(?" + flags + ")" + JoinRule(string(submatch[3]))
301 } else if len(submatch) == 3 {
302 // If len is 3, no additional flags were given
303 color = string(submatch[1])
304 regexStr = JoinRule(string(submatch[2]))
306 // If len is not 3 or 4 there is a problem
307 TermError(filename, lineNum, "Invalid statement: "+line)
311 regex, err := regexp.Compile(regexStr)
313 TermError(filename, lineNum, err.Error())
318 // The user could give us a "color" that is really a part of the colorscheme
319 // in which case we should look that up in the colorscheme
320 // They can also just give us a straight up color
322 groups := strings.Split(color, ".")
325 for i, g := range groups {
330 if style, ok := colorscheme[curGroup]; ok {
334 } else if style, ok := colorscheme[color]; ok {
337 st = StringToStyle(color)
339 // Add the regex, flags, and style
340 // False because this is not start-end
341 rules = append(rules, SyntaxRule{regex, flags, false, st})
342 } else if ruleStartEndParser.MatchString(line) {
343 // Start-end syntax rule
344 submatch := ruleStartEndParser.FindSubmatch([]byte(line))
348 // Use m and s flags by default
350 if len(submatch) == 5 {
351 // If len is 5 the user provided some additional flags
352 color = string(submatch[1])
353 flags += string(submatch[2])
354 start = string(submatch[3])
355 end = string(submatch[4])
356 } else if len(submatch) == 4 {
357 // If len is 4 the user did not provide additional flags
358 color = string(submatch[1])
359 start = string(submatch[2])
360 end = string(submatch[3])
362 // If len is not 4 or 5 there is a problem
363 TermError(filename, lineNum, "Invalid statement: "+line)
368 regex, err := regexp.Compile("(?" + flags + ")" + "(" + start + ").*?(" + end + ")")
370 TermError(filename, lineNum, err.Error())
375 // The user could give us a "color" that is really a part of the colorscheme
376 // in which case we should look that up in the colorscheme
377 // They can also just give us a straight up color
379 if _, ok := colorscheme[color]; ok {
380 st = colorscheme[color]
382 st = StringToStyle(color)
384 // Add the regex, flags, and style
385 // True because this is start-end
386 rules = append(rules, SyntaxRule{regex, flags, true, st})
392 // GetRules finds the syntax rules that should be used for the buffer
393 // and returns them. It also returns the filetype of the file
394 func GetRules(buf *Buffer) ([]SyntaxRule, string) {
395 for r := range syntaxFiles {
396 if r[0] != nil && r[0].MatchString(buf.Path) {
397 // Check if the syntax statement matches the extension
398 return LoadRulesFromFile(syntaxFiles[r].text, syntaxFiles[r].filename), syntaxFiles[r].filetype
399 } else if r[1] != nil && r[1].MatchString(buf.Line(0)) {
400 // Check if the header statement matches the first line
401 return LoadRulesFromFile(syntaxFiles[r].text, syntaxFiles[r].filename), syntaxFiles[r].filetype
404 return nil, "Unknown"
407 // SyntaxMatches is an alias to a map from character numbers to styles,
408 // so map[3] represents the style of the third character
409 type SyntaxMatches [][]tcell.Style
411 // Match takes a buffer and returns the syntax matches: a 2d array specifying how it should be syntax highlighted
412 // We match the rules from up `synLinesUp` lines and down `synLinesDown` lines
413 func Match(v *View) SyntaxMatches {
417 viewStart := v.Topline
418 viewEnd := v.Topline + v.height
419 if viewEnd > buf.NumLines {
420 viewEnd = buf.NumLines
423 lines := buf.Lines(viewStart, viewEnd)
424 matches := make(SyntaxMatches, len(lines))
426 for i, line := range lines {
427 matches[i] = make([]tcell.Style, len(line)+1)
428 for j, _ := range matches[i] {
429 matches[i][j] = defStyle
433 // We don't actually check the entire buffer, just from synLinesUp to synLinesDown
434 totalStart := v.Topline - synLinesUp
435 totalEnd := v.Topline + v.height + synLinesDown
439 if totalEnd > buf.NumLines {
440 totalEnd = buf.NumLines
443 str := strings.Join(buf.Lines(totalStart, totalEnd), "\n")
444 startNum := ToCharPos(Loc{0, totalStart}, v.Buf)
446 for _, rule := range rules {
448 if indicies := rule.regex.FindAllStringIndex(str, -1); indicies != nil {
449 for _, value := range indicies {
450 value[0] = runePos(value[0], str) + startNum
451 value[1] = runePos(value[1], str) + startNum
452 startLoc := FromCharPos(value[0], buf)
453 endLoc := FromCharPos(value[1], buf)
454 for curLoc := startLoc; curLoc.LessThan(endLoc); curLoc = curLoc.Move(1, buf) {
455 if curLoc.Y < v.Topline {
458 colNum, lineNum := curLoc.X, curLoc.Y
459 if lineNum == -1 || colNum == -1 {
463 if lineNum >= 0 && lineNum < v.height {
464 matches[lineNum][colNum] = rule.style
470 for lineN, line := range lines {
471 if indicies := rule.regex.FindAllStringIndex(line, -1); indicies != nil {
472 for _, value := range indicies {
473 start := runePos(value[0], line)
474 end := runePos(value[1], line)
475 // messenger.Message(start, " ", end)
476 for i := start; i < end; i++ {
477 matches[lineN][i] = rule.style