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{
124 // LoadSyntaxFiles loads the syntax files from the default directory (configDir)
125 func LoadSyntaxFiles() {
126 // Load the user's custom syntax files, if there are any
127 LoadSyntaxFilesFromDir(configDir + "/syntax")
129 // Load the pre-installed syntax files from inside the binary
130 for _, filetype := range preInstalledSynFiles {
131 data, err := Asset("runtime/syntax/" + filetype + ".micro")
133 TermMessage("Unable to load pre-installed syntax file " + filetype)
137 LoadSyntaxFile(string(data), filetype+".micro")
141 // LoadSyntaxFilesFromDir loads the syntax files from a specified directory
142 // To load the syntax files, we must fill the `syntaxFiles` map
143 // This involves finding the regex for syntax and if it exists, the regex
144 // for the header. Then we must get the text for the file and the filetype.
145 func LoadSyntaxFilesFromDir(dir string) {
146 colorscheme = make(Colorscheme)
150 defStyle = tcell.StyleDefault.
151 Foreground(tcell.ColorDefault).
152 Background(tcell.ColorDefault)
154 // There may be another default style defined in the colorscheme
155 // In that case we should use that one
156 if style, ok := colorscheme["default"]; ok {
160 screen.SetStyle(defStyle)
163 syntaxFiles = make(map[[2]*regexp.Regexp]FileTypeRules)
164 files, _ := ioutil.ReadDir(dir)
165 for _, f := range files {
166 if filepath.Ext(f.Name()) == ".micro" {
167 filename := dir + "/" + f.Name()
168 text, err := ioutil.ReadFile(filename)
171 TermMessage("Error loading syntax file " + filename + ": " + err.Error())
174 LoadSyntaxFile(string(text), filename)
179 // JoinRule takes a syntax rule (which can be multiple regular expressions)
180 // and joins it into one regular expression by ORing everything together
181 func JoinRule(rule string) string {
182 split := strings.Split(rule, `" "`)
183 joined := strings.Join(split, ")|(")
184 joined = "(" + joined + ")"
188 // LoadSyntaxFile simply gets the filetype of a the syntax file and the source for the
189 // file and creates FileTypeRules out of it. If this filetype is the one opened by the user
190 // the rules will be loaded and compiled later
191 // In this function we are only concerned with loading the syntax and header regexes
192 func LoadSyntaxFile(text, filename string) {
194 lines := strings.Split(string(text), "\n")
196 // Regex for parsing syntax statements
197 syntaxParser := regexp.MustCompile(`syntax "(.*?)"\s+"(.*)"+`)
198 // Regex for parsing header statements
199 headerParser := regexp.MustCompile(`header "(.*)"`)
201 // Is there a syntax definition in this file?
202 hasSyntax := syntaxParser.MatchString(text)
203 // Is there a header definition in this file?
204 hasHeader := headerParser.MatchString(text)
206 var syntaxRegex *regexp.Regexp
207 var headerRegex *regexp.Regexp
209 for lineNum, line := range lines {
210 if (hasSyntax == (syntaxRegex != nil)) && (hasHeader == (headerRegex != nil)) {
211 // We found what we we're supposed to find
215 if strings.TrimSpace(line) == "" ||
216 strings.TrimSpace(line)[0] == '#' {
221 if strings.HasPrefix(line, "syntax") {
223 syntaxMatches := syntaxParser.FindSubmatch([]byte(line))
224 if len(syntaxMatches) == 3 {
225 if syntaxRegex != nil {
226 TermError(filename, lineNum, "Syntax statement redeclaration")
229 filetype = string(syntaxMatches[1])
230 extensions := JoinRule(string(syntaxMatches[2]))
232 syntaxRegex, err = regexp.Compile(extensions)
234 TermError(filename, lineNum, err.Error())
238 TermError(filename, lineNum, "Syntax statement is not valid: "+line)
241 } else if strings.HasPrefix(line, "header") {
243 headerMatches := headerParser.FindSubmatch([]byte(line))
244 if len(headerMatches) == 2 {
245 header := JoinRule(string(headerMatches[1]))
247 headerRegex, err = regexp.Compile(header)
249 TermError(filename, lineNum, "Regex error: "+err.Error())
253 TermError(filename, lineNum, "Header statement is not valid: "+line)
258 if syntaxRegex != nil {
259 // Add the current rules to the syntaxFiles variable
260 regexes := [2]*regexp.Regexp{syntaxRegex, headerRegex}
261 syntaxFiles[regexes] = FileTypeRules{filetype, filename, text}
265 // LoadRulesFromFile loads just the syntax rules from a given file
266 // Only the necessary rules are loaded when the buffer is opened.
267 // If we load all the rules for every filetype when micro starts, there's a bit of lag
268 // A rule just explains how to color certain regular expressions
269 // Example: color comment "//.*"
270 // This would color all strings that match the regex "//.*" in the comment color defined
271 // by the colorscheme
272 func LoadRulesFromFile(text, filename string) []SyntaxRule {
273 lines := strings.Split(string(text), "\n")
275 // Regex for parsing standard syntax rules
276 ruleParser := regexp.MustCompile(`color (.*?)\s+(?:\((.*?)\)\s+)?"(.*)"`)
277 // Regex for parsing syntax rules with start="..." end="..."
278 ruleStartEndParser := regexp.MustCompile(`color (.*?)\s+(?:\((.*?)\)\s+)?start="(.*)"\s+end="(.*)"`)
280 var rules []SyntaxRule
281 for lineNum, line := range lines {
282 if strings.TrimSpace(line) == "" ||
283 strings.TrimSpace(line)[0] == '#' ||
284 strings.HasPrefix(line, "syntax") ||
285 strings.HasPrefix(line, "header") {
290 // Syntax rule, but it could be standard or start-end
291 if ruleParser.MatchString(line) {
292 // Standard syntax rule
294 submatch := ruleParser.FindSubmatch([]byte(line))
298 if len(submatch) == 4 {
299 // If len is 4 then the user specified some additional flags to use
300 color = string(submatch[1])
301 flags = string(submatch[2])
302 regexStr = "(?" + flags + ")" + JoinRule(string(submatch[3]))
303 } else if len(submatch) == 3 {
304 // If len is 3, no additional flags were given
305 color = string(submatch[1])
306 regexStr = JoinRule(string(submatch[2]))
308 // If len is not 3 or 4 there is a problem
309 TermError(filename, lineNum, "Invalid statement: "+line)
313 regex, err := regexp.Compile(regexStr)
315 TermError(filename, lineNum, err.Error())
320 // The user could give us a "color" that is really a part of the colorscheme
321 // in which case we should look that up in the colorscheme
322 // They can also just give us a straight up color
324 groups := strings.Split(color, ".")
327 for i, g := range groups {
332 if style, ok := colorscheme[curGroup]; ok {
336 } else if style, ok := colorscheme[color]; ok {
339 st = StringToStyle(color)
341 // Add the regex, flags, and style
342 // False because this is not start-end
343 rules = append(rules, SyntaxRule{regex, flags, false, st})
344 } else if ruleStartEndParser.MatchString(line) {
345 // Start-end syntax rule
346 submatch := ruleStartEndParser.FindSubmatch([]byte(line))
350 // Use m and s flags by default
352 if len(submatch) == 5 {
353 // If len is 5 the user provided some additional flags
354 color = string(submatch[1])
355 flags += string(submatch[2])
356 start = string(submatch[3])
357 end = string(submatch[4])
358 } else if len(submatch) == 4 {
359 // If len is 4 the user did not provide additional flags
360 color = string(submatch[1])
361 start = string(submatch[2])
362 end = string(submatch[3])
364 // If len is not 4 or 5 there is a problem
365 TermError(filename, lineNum, "Invalid statement: "+line)
370 regex, err := regexp.Compile("(?" + flags + ")" + "(" + start + ").*?(" + end + ")")
372 TermError(filename, lineNum, err.Error())
377 // The user could give us a "color" that is really a part of the colorscheme
378 // in which case we should look that up in the colorscheme
379 // They can also just give us a straight up color
381 if _, ok := colorscheme[color]; ok {
382 st = colorscheme[color]
384 st = StringToStyle(color)
386 // Add the regex, flags, and style
387 // True because this is start-end
388 rules = append(rules, SyntaxRule{regex, flags, true, st})
394 // FindFileType finds the filetype for the given buffer
395 func FindFileType(buf *Buffer) string {
396 for r := range syntaxFiles {
397 if r[0] != nil && r[0].MatchString(buf.Path) {
398 // The syntax statement matches the extension
399 return syntaxFiles[r].filetype
400 } else if r[1] != nil && r[1].MatchString(buf.Line(0)) {
401 // The header statement matches the first line
402 return syntaxFiles[r].filetype
408 // GetRules finds the syntax rules that should be used for the buffer
409 // and returns them. It also returns the filetype of the file
410 func GetRules(buf *Buffer) []SyntaxRule {
411 for r := range syntaxFiles {
412 if syntaxFiles[r].filetype == buf.FileType() {
413 return LoadRulesFromFile(syntaxFiles[r].text, syntaxFiles[r].filename)
419 // SyntaxMatches is an alias to a map from character numbers to styles,
420 // so map[3] represents the style of the third character
421 type SyntaxMatches [][]tcell.Style
423 // Match takes a buffer and returns the syntax matches: a 2d array specifying how it should be syntax highlighted
424 // We match the rules from up `synLinesUp` lines and down `synLinesDown` lines
425 func Match(v *View) SyntaxMatches {
429 viewStart := v.Topline
430 viewEnd := v.Topline + v.height
431 if viewEnd > buf.NumLines {
432 viewEnd = buf.NumLines
435 lines := buf.Lines(viewStart, viewEnd)
436 matches := make(SyntaxMatches, len(lines))
438 for i, line := range lines {
439 matches[i] = make([]tcell.Style, len(line)+1)
440 for j := range matches[i] {
441 matches[i][j] = defStyle
445 // We don't actually check the entire buffer, just from synLinesUp to synLinesDown
446 totalStart := v.Topline - synLinesUp
447 totalEnd := v.Topline + v.height + synLinesDown
451 if totalEnd > buf.NumLines {
452 totalEnd = buf.NumLines
455 str := strings.Join(buf.Lines(totalStart, totalEnd), "\n")
456 startNum := ToCharPos(Loc{0, totalStart}, v.Buf)
458 for _, rule := range rules {
460 if indicies := rule.regex.FindAllStringIndex(str, -1); indicies != nil {
461 for _, value := range indicies {
462 value[0] = runePos(value[0], str) + startNum
463 value[1] = runePos(value[1], str) + startNum
464 startLoc := FromCharPos(value[0], buf)
465 endLoc := FromCharPos(value[1], buf)
466 for curLoc := startLoc; curLoc.LessThan(endLoc); curLoc = curLoc.Move(1, buf) {
467 if curLoc.Y < v.Topline {
470 colNum, lineNum := curLoc.X, curLoc.Y
471 if lineNum == -1 || colNum == -1 {
475 if lineNum >= 0 && lineNum < v.height {
476 matches[lineNum][colNum] = rule.style
482 for lineN, line := range lines {
483 if indicies := rule.regex.FindAllStringIndex(line, -1); indicies != nil {
484 for _, value := range indicies {
485 start := runePos(value[0], line)
486 end := runePos(value[1], line)
487 for i := start; i < end; i++ {
488 matches[lineN][i] = rule.style