Debian Codegraph @

highlight.go

raw symbols SCIP
1 // Package syntaxhighlight provides syntax highlighting for code. It currently
2 // uses a language-independent lexer and performs decently on JavaScript, Java,
3 // Ruby, Python, Go, and C.
4 package syntaxhighlight
5
6 import (
7 "bytes"
8 "io"
9 "strings"
10 "text/scanner"
11 "text/template"
12 "unicode"
13 "unicode/utf8"
14
15 "github.com/sourcegraph/annotate"
16 )
17
18 // Kind represents a syntax highlighting kind (class) which will be assigned to tokens.
19 // A syntax highlighting scheme (style) maps text style properties to each token kind.
20 type Kind uint8
21
22 // A set of supported highlighting kinds
23 const (
24 Whitespace Kind = iota
25 String
26 Keyword
27 Comment
28 Type
29 Literal
30 Punctuation
31 Plaintext
32 Tag
33 HTMLTag
34 HTMLAttrName
35 HTMLAttrValue
36 Decimal
37 )
38
39 //go:generate gostringer -type=Kind
40
41 // Printer implements an interface to render highlighted output
42 // (see HTMLPrinter for the implementation of this interface)
43 type Printer interface {
44 Print(w io.Writer, kind Kind, tokText string) error
45 }
46
47 // HTMLConfig holds the HTML class configuration to be used by annotators when
48 // highlighting code.
49 type HTMLConfig struct {
50 String string
51 Keyword string
52 Comment string
53 Type string
54 Literal string
55 Punctuation string
56 Plaintext string
57 Tag string
58 HTMLTag string
59 HTMLAttrName string
60 HTMLAttrValue string
61 Decimal string
62 Whitespace string
63
64 AsOrderedList bool
65 }
66
67 // HTMLPrinter implements Printer interface and is used to produce
68 // HTML-based highligher
69 type HTMLPrinter HTMLConfig
70
71 // Class returns the set class for a given token Kind.
72 func (c HTMLConfig) Class(kind Kind) string {
73 switch kind {
74 case String:
75 return c.String
76 case Keyword:
77 return c.Keyword
78 case Comment:
79 return c.Comment
80 case Type:
81 return c.Type
82 case Literal:
83 return c.Literal
84 case Punctuation:
85 return c.Punctuation
86 case Plaintext:
87 return c.Plaintext
88 case Tag:
89 return c.Tag
90 case HTMLTag:
91 return c.HTMLTag
92 case HTMLAttrName:
93 return c.HTMLAttrName
94 case HTMLAttrValue:
95 return c.HTMLAttrValue
96 case Decimal:
97 return c.Decimal
98 }
99 return ""
100 }
101
102 // Print is the function that emits highlighted source code using
103 // <span class="...">...</span> wrapper tags
104 func (p HTMLPrinter) Print(w io.Writer, kind Kind, tokText string) error {
105 if p.AsOrderedList {
106 if i := strings.Index(tokText, "\n"); i > -1 {
107 if err := p.Print(w, kind, tokText[:i]); err != nil {
108 return err
109 }
110 w.Write([]byte("</li>\n<li>"))
111 if err := p.Print(w, kind, tokText[i+1:]); err != nil {
112 return err
113 }
114 return nil
115 }
116 }
117
118 class := ((HTMLConfig)(p)).Class(kind)
119 if class != "" {
120 _, err := w.Write([]byte(`<span class="`))
121 if err != nil {
122 return err
123 }
124 _, err = io.WriteString(w, class)
125 if err != nil {
126 return err
127 }
128 _, err = w.Write([]byte(`">`))
129 if err != nil {
130 return err
131 }
132 }
133 template.HTMLEscape(w, []byte(tokText))
134 if class != "" {
135 _, err := w.Write([]byte(`</span>`))
136 if err != nil {
137 return err
138 }
139 }
140 return nil
141 }
142
143 type Annotator interface {
144 Annotate(start int, kind Kind, tokText string) (*annotate.Annotation, error)
145 }
146
147 type HTMLAnnotator HTMLConfig
148
149 func (a HTMLAnnotator) Annotate(start int, kind Kind, tokText string) (*annotate.Annotation, error) {
150 class := ((HTMLConfig)(a)).Class(kind)
151 if class != "" {
152 left := []byte(`<span class="`)
153 left = append(left, []byte(class)...)
154 left = append(left, []byte(`">`)...)
155 return &annotate.Annotation{
156 Start: start, End: start + len(tokText),
157 Left: left, Right: []byte("</span>"),
158 }, nil
159 }
160 return nil, nil
161 }
162
163 // Option is a type of the function that can modify
164 // one or more of the options in the HTMLConfig structure.
165 type Option func(options *HTMLConfig)
166
167 // OrderedList allows you to format the output as an ordered list
168 // to have line numbers in the output.
169 //
170 // Example:
171 // AsHTML(input, OrderedList())
172 func OrderedList() Option {
173 return func(o *HTMLConfig) {
174 o.AsOrderedList = true
175 }
176 }
177
178 // DefaultHTMLConfig provides class names that match those of google-code-prettify
179 // (https://code.google.com/p/google-code-prettify/).
180 var DefaultHTMLConfig = HTMLConfig{
181 String: "str",
182 Keyword: "kwd",
183 Comment: "com",
184 Type: "typ",
185 Literal: "lit",
186 Punctuation: "pun",
187 Plaintext: "pln",
188 Tag: "tag",
189 HTMLTag: "htm",
190 HTMLAttrName: "atn",
191 HTMLAttrValue: "atv",
192 Decimal: "dec",
193 Whitespace: "",
194 }
195
196 func Print(s *scanner.Scanner, w io.Writer, p Printer) error {
197 tok := s.Scan()
198 for tok != scanner.EOF {
199 tokText := s.TokenText()
200 err := p.Print(w, tokenKind(tok, tokText), tokText)
201 if err != nil {
202 return err
203 }
204
205 tok = s.Scan()
206 }
207
208 return nil
209 }
210
211 func Annotate(src []byte, a Annotator) (annotate.Annotations, error) {
212 s := NewScanner(src)
213
214 var anns annotate.Annotations
215 read := 0
216
217 tok := s.Scan()
218 for tok != scanner.EOF {
219 tokText := s.TokenText()
220
221 ann, err := a.Annotate(read, tokenKind(tok, tokText), tokText)
222 if err != nil {
223 return nil, err
224 }
225 read += len(tokText)
226 if ann != nil {
227 anns = append(anns, ann)
228 }
229
230 tok = s.Scan()
231 }
232
233 return anns, nil
234 }
235
236 // AsHTML converts source code into an HTML-highlighted version;
237 // It accepts optional configuration parameters to control rendering
238 // (see OrderedList as one example)
239 func AsHTML(src []byte, options ...Option) ([]byte, error) {
240 opt := DefaultHTMLConfig
241 for _, f := range options {
242 f(&opt)
243 }
244
245 var buf bytes.Buffer
246 if opt.AsOrderedList {
247 buf.Write([]byte("<ol>\n<li>"))
248 }
249 err := Print(NewScanner(src), &buf, HTMLPrinter(opt))
250 if opt.AsOrderedList {
251 buf.Write([]byte("</li>\n</ol>"))
252 }
253 if err != nil {
254 return nil, err
255 }
256 return buf.Bytes(), nil
257 }
258
259 // NewScanner is a helper that takes a []byte src, wraps it in a reader and creates a Scanner.
260 func NewScanner(src []byte) *scanner.Scanner {
261 return NewScannerReader(bytes.NewReader(src))
262 }
263
264 // NewScannerReader takes a reader src and creates a Scanner.
265 func NewScannerReader(src io.Reader) *scanner.Scanner {
266 var s scanner.Scanner
267 s.Init(src)
268 s.Error = func(_ *scanner.Scanner, _ string) {}
269 s.Whitespace = 0
270 s.Mode = s.Mode ^ scanner.SkipComments
271 return &s
272 }
273
274 func tokenKind(tok rune, tokText string) Kind {
275 switch tok {
276 case scanner.Ident:
277 if _, isKW := keywords[tokText]; isKW {
278 return Keyword
279 }
280 if r, _ := utf8.DecodeRuneInString(tokText); unicode.IsUpper(r) {
281 return Type
282 }
283 return Plaintext
284 case scanner.Float, scanner.Int:
285 return Decimal
286 case scanner.Char, scanner.String, scanner.RawString:
287 return String
288 case scanner.Comment:
289 return Comment
290 }
291 if unicode.IsSpace(tok) {
292 return Whitespace
293 }
294 return Punctuation
295 }