]> git.lizzy.rs Git - micro.git/blob - highlighter.go
Really improve syntax file compatibility with nano
[micro.git] / highlighter.go
1 package main
2
3 import (
4         "fmt"
5         "github.com/gdamore/tcell"
6         "io/ioutil"
7         "os/user"
8         "path/filepath"
9         "regexp"
10         "strings"
11 )
12
13 var syntaxFiles map[[2]*regexp.Regexp][2]string
14
15 // LoadSyntaxFiles loads the syntax files from the default directory ~/.micro
16 func LoadSyntaxFiles() {
17         usr, _ := user.Current()
18         dir := usr.HomeDir
19         LoadSyntaxFilesFromDir(dir + "/.micro")
20 }
21
22 // JoinRule takes a syntax rule (which can be multiple regular expressions)
23 // and joins it into one regular expression by ORing everything together
24 func JoinRule(rule string) string {
25         split := strings.Split(rule, `" "`)
26         joined := strings.Join(split, ")|(")
27         joined = "(" + joined + ")"
28         return joined
29 }
30
31 // LoadSyntaxFilesFromDir loads the syntax files from a specified directory
32 // To load the syntax files, we must fill the `syntaxFiles` map
33 // This involves finding the regex for syntax and if it exists, the regex
34 // for the header. Then we must get the text for the file and the filetype.
35 func LoadSyntaxFilesFromDir(dir string) {
36         syntaxFiles = make(map[[2]*regexp.Regexp][2]string)
37         files, _ := ioutil.ReadDir(dir)
38         for _, f := range files {
39                 if filepath.Ext(f.Name()) == ".micro" {
40                         text, err := ioutil.ReadFile(dir + "/" + f.Name())
41
42                         if err != nil {
43                                 fmt.Println("Error loading syntax files:", err)
44                                 continue
45                         }
46                         lines := strings.Split(string(text), "\n")
47
48                         syntaxParser := regexp.MustCompile(`syntax "(.*?)"\s+"(.*)"+`)
49                         headerParser := regexp.MustCompile(`header "(.*)"`)
50
51                         var syntaxRegex *regexp.Regexp
52                         var headerRegex *regexp.Regexp
53                         var filetype string
54                         var rules string
55                         for _, line := range lines {
56                                 if strings.TrimSpace(line) == "" ||
57                                         strings.TrimSpace(line)[0] == '#' {
58                                         // Ignore this line
59                                         continue
60                                 }
61
62                                 if strings.HasPrefix(line, "syntax") {
63                                         syntaxMatches := syntaxParser.FindSubmatch([]byte(line))
64                                         if len(syntaxMatches) == 3 {
65                                                 if syntaxRegex != nil {
66                                                         regexes := [2]*regexp.Regexp{syntaxRegex, headerRegex}
67                                                         syntaxFiles[regexes] = [2]string{rules, filetype}
68                                                 }
69
70                                                 filetype = string(syntaxMatches[1])
71                                                 extensions := JoinRule(string(syntaxMatches[2]))
72
73                                                 syntaxRegex, err = regexp.Compile(extensions)
74                                                 if err != nil {
75                                                         fmt.Println("Regex error:", err)
76                                                         continue
77                                                 }
78                                         } else {
79                                                 fmt.Println("Syntax statement is not valid:", line)
80                                                 continue
81                                         }
82                                 } else if strings.HasPrefix(line, "header") {
83                                         headerMatches := headerParser.FindSubmatch([]byte(line))
84                                         if len(headerMatches) == 2 {
85                                                 header := JoinRule(string(headerMatches[1]))
86
87                                                 headerRegex, err = regexp.Compile(header)
88                                                 if err != nil {
89                                                         fmt.Println("Regex error:", err)
90                                                         continue
91                                                 }
92                                         } else {
93                                                 fmt.Println("Header statement is not valid:", line)
94                                                 continue
95                                         }
96                                 } else {
97                                         rules += line + "\n"
98                                 }
99                         }
100                         if syntaxRegex != nil {
101                                 regexes := [2]*regexp.Regexp{syntaxRegex, headerRegex}
102                                 syntaxFiles[regexes] = [2]string{rules, filetype}
103                         }
104                 }
105         }
106 }
107
108 // GetRules finds the syntax rules that should be used for the buffer
109 // and returns them. It also returns the filetype of the file
110 func GetRules(buf *Buffer) (string, string) {
111         for r := range syntaxFiles {
112                 if r[0] != nil && r[0].MatchString(buf.path) {
113                         return syntaxFiles[r][0], syntaxFiles[r][1]
114                 } else if r[1] != nil && r[1].MatchString(buf.lines[0]) {
115                         return syntaxFiles[r][0], syntaxFiles[r][1]
116                 }
117         }
118         return "", "Unknown"
119 }
120
121 // Match takes a buffer and returns a map specifying how it should be syntax highlighted
122 // The map is from character numbers to styles, so map[3] represents the style change
123 // at the third character in the buffer
124 func Match(rules string, buf *Buffer) map[int]tcell.Style {
125         // rules := strings.TrimSpace(GetRules(buf))
126         str := buf.text
127
128         lines := strings.Split(rules, "\n")
129         m := make(map[int]tcell.Style)
130         parser := regexp.MustCompile(`color (.*?)\s+"(.*)"`)
131         for _, line := range lines {
132                 if strings.TrimSpace(line) == "" ||
133                         strings.TrimSpace(line)[0] == '#' ||
134                         strings.HasPrefix(line, "syntax") ||
135                         strings.HasPrefix(line, "header") {
136                         // Ignore this line
137                         continue
138                 }
139                 submatch := parser.FindSubmatch([]byte(line))
140                 color := string(submatch[1])
141                 regex, err := regexp.Compile(string(submatch[2]))
142                 if err != nil {
143                         // Error with the regex!
144                         continue
145                 }
146                 st := StringToStyle(color)
147
148                 if regex.MatchString(str) {
149                         indicies := regex.FindAllStringIndex(str, -1)
150                         for _, value := range indicies {
151                                 for i := value[0] + 1; i < value[1]; i++ {
152                                         if _, exists := m[i]; exists {
153                                                 delete(m, i)
154                                         }
155                                 }
156                                 m[value[0]] = st
157                                 if _, exists := m[value[1]]; !exists {
158                                         m[value[1]] = tcell.StyleDefault
159                                 }
160                         }
161                 }
162         }
163
164         return m
165 }
166
167 // StringToStyle returns a style from a string
168 func StringToStyle(str string) tcell.Style {
169         var fg string
170         var bg string
171         split := strings.Split(str, ",")
172         if len(split) > 1 {
173                 fg, bg = split[0], split[1]
174         } else {
175                 fg = split[0]
176         }
177
178         return tcell.StyleDefault.Foreground(StringToColor(fg)).Background(StringToColor(bg))
179 }
180
181 // StringToColor returns a tcell color from a string representation of a color
182 func StringToColor(str string) tcell.Color {
183         switch str {
184         case "black":
185                 return tcell.ColorBlack
186         case "red":
187                 return tcell.ColorMaroon
188         case "green":
189                 return tcell.ColorGreen
190         case "yellow":
191                 return tcell.ColorOlive
192         case "blue":
193                 return tcell.ColorNavy
194         case "magenta":
195                 return tcell.ColorPurple
196         case "cyan":
197                 return tcell.ColorTeal
198         case "white":
199                 return tcell.ColorSilver
200         case "brightblack":
201                 return tcell.ColorGray
202         case "brightred":
203                 return tcell.ColorRed
204         case "brightgreen":
205                 return tcell.ColorLime
206         case "brightyellow":
207                 return tcell.ColorYellow
208         case "brightblue":
209                 return tcell.ColorBlue
210         case "brightmagenta":
211                 return tcell.ColorFuchsia
212         case "brightcyan":
213                 return tcell.ColorAqua
214         case "brightwhite":
215                 return tcell.ColorWhite
216         default:
217                 return tcell.ColorDefault
218         }
219 }