Debian Codegraph @

markup/highlight/highlight.go

raw
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package highlight
15
16 import (
17 "context"
18 "fmt"
19 gohtml "html"
20 "html/template"
21 "io"
22 "strings"
23
24 "github.com/alecthomas/chroma/v2"
25 "github.com/alecthomas/chroma/v2/formatters/html"
26 "github.com/alecthomas/chroma/v2/lexers"
27 "github.com/alecthomas/chroma/v2/styles"
28 "github.com/gohugoio/hugo/common/hugio"
29 "github.com/gohugoio/hugo/common/text"
30 "github.com/gohugoio/hugo/markup/converter/hooks"
31 "github.com/gohugoio/hugo/markup/highlight/chromalexers"
32 "github.com/gohugoio/hugo/markup/internal/attributes"
33 )
34
35 // Markdown attributes used by the Chroma highlighter.
36 var chromaHighlightProcessingAttributes = map[string]bool{
37 "anchorLineNos": true,
38 "guessSyntax": true,
39 "hl_Lines": true,
40 "lineAnchors": true,
41 "lineNos": true,
42 "lineNoStart": true,
43 "lineNumbersInTable": true,
44 "noClasses": true,
45 "style": true,
46 "tabWidth": true,
47 }
48
49 func init() {
50 for k, v := range chromaHighlightProcessingAttributes {
51 chromaHighlightProcessingAttributes[strings.ToLower(k)] = v
52 }
53 }
54
55 func New(cfg Config) Highlighter {
56 return chromaHighlighter{
57 cfg: cfg,
58 }
59 }
60
61 type Highlighter interface {
62 Highlight(code, lang string, opts any) (string, error)
63 HighlightCodeBlock(ctx hooks.CodeblockContext, opts any) (HighlightResult, error)
64 hooks.CodeBlockRenderer
65 hooks.IsDefaultCodeBlockRendererProvider
66 }
67
68 type chromaHighlighter struct {
69 cfg Config
70 }
71
72 func (h chromaHighlighter) Highlight(code, lang string, opts any) (string, error) {
73 cfg := h.cfg
74 if err := applyOptions(opts, &cfg, &lang, &code); err != nil {
75 return "", err
76 }
77 var b strings.Builder
78
79 if _, _, err := highlight(&b, code, lang, nil, cfg); err != nil {
80 return "", err
81 }
82
83 return b.String(), nil
84 }
85
86 func (h chromaHighlighter) HighlightCodeBlock(ctx hooks.CodeblockContext, opts any) (HighlightResult, error) {
87 cfg := h.cfg
88
89 var b strings.Builder
90
91 attributes := ctx.(hooks.AttributesOptionsSliceProvider).AttributesSlice()
92
93 if err := applyOptionsFromMap(ctx.Options(), &cfg); err != nil {
94 return HighlightResult{}, err
95 }
96
97 lang, code := ctx.Type(), ctx.Inner()
98
99 // Apply these last so the user can override them, including the type and code.
100 if err := applyOptions(opts, &cfg, &lang, &code); err != nil {
101 return HighlightResult{}, err
102 }
103
104 if err := applyOptionsFromCodeBlockContext(ctx, &cfg); err != nil {
105 return HighlightResult{}, err
106 }
107
108 low, high, err := highlight(&b, code, lang, attributes, cfg)
109 if err != nil {
110 return HighlightResult{}, err
111 }
112
113 highlighted := b.String()
114 if high == 0 {
115 high = len(highlighted)
116 }
117
118 return HighlightResult{
119 highlighted: template.HTML(highlighted),
120 innerLow: low,
121 innerHigh: high,
122 }, nil
123 }
124
125 func (h chromaHighlighter) RenderCodeblock(cctx context.Context, w hugio.FlexiWriter, ctx hooks.CodeblockContext) error {
126 cfg := h.cfg
127
128 attributes := ctx.(hooks.AttributesOptionsSliceProvider).AttributesSlice()
129
130 if err := applyOptionsFromMap(ctx.Options(), &cfg); err != nil {
131 return err
132 }
133
134 if err := applyOptionsFromCodeBlockContext(ctx, &cfg); err != nil {
135 return err
136 }
137
138 code := text.Puts(ctx.Inner())
139
140 _, _, err := highlight(w, code, ctx.Type(), attributes, cfg)
141 return err
142 }
143
144 func (h chromaHighlighter) IsDefaultCodeBlockRenderer() bool {
145 return true
146 }
147
148 // HighlightResult holds the result of an highlighting operation.
149 type HighlightResult struct {
150 innerLow int
151 innerHigh int
152 highlighted template.HTML
153 }
154
155 // Wrapped returns the highlighted code wrapped in a <div>, <pre> and <code> tag.
156 func (h HighlightResult) Wrapped() template.HTML {
157 return h.highlighted
158 }
159
160 // Inner returns the highlighted code without the wrapping <div>, <pre> and <code> tag, suitable for inline use.
161 func (h HighlightResult) Inner() template.HTML {
162 return h.highlighted[h.innerLow:h.innerHigh]
163 }
164
165 func highlight(fw hugio.FlexiWriter, code, lang string, attributes []attributes.Attribute, cfg Config) (int, int, error) {
166 var lexer chroma.Lexer
167 if lang != "" {
168 lexer = chromalexers.Get(lang)
169 }
170
171 if lexer == nil && cfg.GuessSyntax {
172 lexer = lexers.Analyse(code)
173 if lexer == nil {
174 lexer = lexers.Fallback
175 }
176 lang = strings.ToLower(lexer.Config().Name)
177 }
178
179 w := &byteCountFlexiWriter{delegate: fw}
180
181 if lexer == nil {
182 if cfg.Hl_inline {
183 fmt.Fprintf(w, "<code%s>%s</code>", inlineCodeAttrs(lang), gohtml.EscapeString(code))
184 return 0, 0, nil
185 }
186
187 preWrapper := getPreWrapper(lang, w)
188 fmt.Fprint(w, preWrapper.Start(true, ""))
189 fmt.Fprint(w, gohtml.EscapeString(code))
190 fmt.Fprint(w, preWrapper.End(true))
191 return preWrapper.low, preWrapper.high, nil
192 }
193
194 style := styles.Get(cfg.Style)
195 if style == nil {
196 style = styles.Fallback
197 }
198 lexer = chroma.Coalesce(lexer)
199
200 iterator, err := lexer.Tokenise(nil, code)
201 if err != nil {
202 return 0, 0, err
203 }
204
205 if !cfg.Hl_inline {
206 writeDivStart(w, attributes, cfg.WrapperClass)
207 }
208
209 options, err := cfg.toHTMLOptions()
210 if err != nil {
211 return 0, 0, err
212 }
213
214 var wrapper html.PreWrapper
215
216 if cfg.Hl_inline {
217 wrapper = startEnd{
218 start: func(code bool, styleAttr string) string {
219 if code {
220 return fmt.Sprintf(`<code%s>`, inlineCodeAttrs(lang))
221 }
222 return ``
223 },
224 end: func(code bool) string {
225 if code {
226 return `</code>`
227 }
228
229 return ``
230 },
231 }
232 } else {
233 wrapper = getPreWrapper(lang, w)
234 }
235
236 options = append(options, html.WithPreWrapper(wrapper))
237
238 formatter := html.New(options...)
239
240 if err := formatter.Format(w, style, iterator); err != nil {
241 return 0, 0, err
242 }
243
244 if !cfg.Hl_inline {
245 writeDivEnd(w)
246 }
247
248 if p, ok := wrapper.(*preWrapper); ok {
249 return p.low, p.high, nil
250 }
251
252 return 0, 0, nil
253 }
254
255 func getPreWrapper(language string, writeCounter *byteCountFlexiWriter) *preWrapper {
256 return &preWrapper{language: language, writeCounter: writeCounter}
257 }
258
259 type preWrapper struct {
260 low int
261 high int
262 writeCounter *byteCountFlexiWriter
263 language string
264 }
265
266 func (p *preWrapper) Start(code bool, styleAttr string) string {
267 var language string
268 if code {
269 language = p.language
270 }
271 w := &strings.Builder{}
272 WritePreStart(w, language, styleAttr)
273 p.low = p.writeCounter.counter + w.Len()
274 return w.String()
275 }
276
277 func inlineCodeAttrs(lang string) string {
278 lang = gohtml.EscapeString(lang)
279 return fmt.Sprintf(` class="code-inline language-%s"`, lang)
280 }
281
282 func WritePreStart(w io.Writer, language, styleAttr string) {
283 fmt.Fprintf(w, `<pre tabindex="0"%s>`, styleAttr)
284 fmt.Fprint(w, "<code")
285 if language != "" {
286 language = gohtml.EscapeString(language)
287 fmt.Fprint(w, ` class="language-`+language+`"`)
288 fmt.Fprint(w, ` data-lang="`+language+`"`)
289 }
290 fmt.Fprint(w, ">")
291 }
292
293 const preEnd = "</code></pre>"
294
295 func (p *preWrapper) End(code bool) string {
296 p.high = p.writeCounter.counter
297 return preEnd
298 }
299
300 type startEnd struct {
301 start func(code bool, styleAttr string) string
302 end func(code bool) string
303 }
304
305 func (s startEnd) Start(code bool, styleAttr string) string {
306 return s.start(code, styleAttr)
307 }
308
309 func (s startEnd) End(code bool) string {
310 return s.end(code)
311 }
312
313 func writeDivStart(w hugio.FlexiWriter, attrs []attributes.Attribute, wrapperClass string) {
314 w.WriteString(`<div class="`)
315 w.WriteString(wrapperClass)
316 if attrs != nil {
317 for _, attr := range attrs {
318 if attr.Name == "class" {
319 w.WriteString(" " + gohtml.EscapeString(attr.ValueString()))
320 break
321 }
322 }
323 _, _ = w.WriteString("\"")
324 attributes.RenderAttributes(w, true, attrs...)
325 } else {
326 _, _ = w.WriteString("\"")
327 }
328
329 w.WriteString(">")
330 }
331
332 func writeDivEnd(w hugio.FlexiWriter) {
333 w.WriteString("</div>")
334 }
335
336 type byteCountFlexiWriter struct {
337 delegate hugio.FlexiWriter
338 counter int
339 }
340
341 func (w *byteCountFlexiWriter) Write(p []byte) (int, error) {
342 n, err := w.delegate.Write(p)
343 w.counter += n
344 return n, err
345 }
346
347 func (w *byteCountFlexiWriter) WriteByte(c byte) error {
348 w.counter++
349 return w.delegate.WriteByte(c)
350 }
351
352 func (w *byteCountFlexiWriter) WriteString(s string) (int, error) {
353 n, err := w.delegate.WriteString(s)
354 w.counter += n
355 return n, err
356 }
357
358 func (w *byteCountFlexiWriter) WriteRune(r rune) (int, error) {
359 n, err := w.delegate.WriteRune(r)
360 w.counter += n
361 return n, err
362 }