Debian Codegraph @

markup/highlight/config.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 provides code highlighting.
15 package highlight
16
17 import (
18 "fmt"
19 gohtml "html"
20 "strconv"
21 "strings"
22
23 "github.com/alecthomas/chroma/v2/formatters/html"
24 "github.com/spf13/cast"
25
26 "github.com/gohugoio/hugo/config"
27 "github.com/gohugoio/hugo/markup/converter/hooks"
28
29 "github.com/mitchellh/mapstructure"
30 )
31
32 const (
33 lineanchorsKey = "lineanchors"
34 lineNosKey = "linenos"
35 hlLinesKey = "hl_lines"
36 linosStartKey = "linenostart"
37 )
38
39 var DefaultConfig = Config{
40 // The highlighter style to use.
41 // See https://xyproto.github.io/splash/docs/all.html
42 Style: "monokai",
43 LineNoStart: 1,
44 CodeFences: true,
45 NoClasses: true,
46 LineNumbersInTable: true,
47 TabWidth: 4,
48 WrapperClass: "highlight",
49 }
50
51 type Config struct {
52 Style string
53
54 // Enable syntax highlighting of fenced code blocks.
55 CodeFences bool
56
57 // The class or classes to use for the outermost element of the highlighted code.
58 WrapperClass string
59
60 // Use inline CSS styles.
61 NoClasses bool
62
63 // When set, line numbers will be printed.
64 LineNos any
65 LineNumbersInTable bool
66
67 // When set, add links to line numbers
68 AnchorLineNos bool
69 LineAnchors string
70
71 // Start the line numbers from this value (default is 1).
72 LineNoStart int
73
74 // A space separated list of line numbers, e.g. “3-8 10-20”.
75 Hl_Lines string
76
77 // If set, the markup will not be wrapped in any container.
78 Hl_inline bool
79
80 // A parsed and ready to use list of line ranges.
81 HL_lines_parsed [][2]int `json:"-"`
82
83 // TabWidth sets the number of characters for a tab. Defaults to 4.
84 TabWidth int
85
86 GuessSyntax bool
87 }
88
89 const errLineNosMsg = `lineNos must be one of true, false, "inline", or "table"; got %[1]v (%[1]T)`
90
91 func (cfg Config) toHTMLOptions() ([]html.Option, error) {
92 var (
93 lineAnchors string
94 lineNos bool
95 inTable = cfg.LineNumbersInTable
96 )
97
98 if cfg.LineAnchors != "" {
99 // Chroma writes this verbatim into id and href attributes.
100 lineAnchors = gohtml.EscapeString(cfg.LineAnchors) + "-"
101 }
102
103 switch v := cfg.LineNos.(type) {
104 case string:
105 switch v {
106 case "inline":
107 lineNos = true
108 inTable = false
109 case "table":
110 lineNos = true
111 inTable = true
112 default:
113 return nil, fmt.Errorf(errLineNosMsg, v)
114 }
115 case bool:
116 lineNos = v
117 case nil:
118 lineNos = false
119 default:
120 return nil, fmt.Errorf(errLineNosMsg, v)
121 }
122
123 options := []html.Option{
124 html.TabWidth(cfg.TabWidth),
125 html.WithLineNumbers(lineNos),
126 html.BaseLineNumber(cfg.LineNoStart),
127 html.LineNumbersInTable(inTable),
128 html.WithClasses(!cfg.NoClasses),
129 html.WithLinkableLineNumbers(cfg.AnchorLineNos, lineAnchors),
130 html.InlineCode(cfg.Hl_inline),
131 }
132
133 if cfg.Hl_Lines != "" || cfg.HL_lines_parsed != nil {
134 var ranges [][2]int
135 if cfg.HL_lines_parsed != nil {
136 ranges = cfg.HL_lines_parsed
137 } else {
138 var err error
139 ranges, err = hlLinesToRanges(cfg.LineNoStart, cfg.Hl_Lines)
140 if err != nil {
141 ranges = nil
142 }
143 }
144
145 if ranges != nil {
146 options = append(options, html.HighlightLines(ranges))
147 }
148 }
149
150 return options, nil
151 }
152
153 func applyOptionsFromString(opts string, cfg *Config) error {
154 optsm, err := parseHighlightOptions(opts)
155 if err != nil {
156 return err
157 }
158 return mapstructure.WeakDecode(optsm, cfg)
159 }
160
161 func applyOptionsFromMap(optsm map[string]any, cfg *Config) error {
162 normalizeHighlightOptions(optsm)
163 return mapstructure.WeakDecode(optsm, cfg)
164 }
165
166 // applyOptions applies opts (a string or a map) to cfg. The type and code
167 // options, if set, are not part of Config and instead override lang and code
168 // respectively. Shared by Highlight and HighlightCodeBlock. See issue 11872.
169 func applyOptions(opts any, cfg *Config, lang, code *string) error {
170 if opts == nil {
171 return nil
172 }
173
174 var optsm map[string]any
175 switch vv := opts.(type) {
176 case map[string]any:
177 optsm = make(map[string]any, len(vv))
178 for k, v := range vv {
179 optsm[strings.ToLower(k)] = v
180 }
181 default:
182 s, err := cast.ToStringE(opts)
183 if err != nil {
184 return err
185 }
186 if optsm, err = parseHighlightOptions(s); err != nil {
187 return err
188 }
189 }
190
191 if v, found := optsm["type"]; found {
192 *lang = cast.ToString(v)
193 delete(optsm, "type")
194 }
195 if v, found := optsm["code"]; found {
196 *code = cast.ToString(v)
197 delete(optsm, "code")
198 }
199
200 return applyOptionsFromMap(optsm, cfg)
201 }
202
203 func applyOptionsFromCodeBlockContext(ctx hooks.CodeblockContext, cfg *Config) error {
204 if cfg.LineAnchors == "" {
205 const lineAnchorPrefix = "hl-"
206 // Set it to the ordinal with a prefix.
207 cfg.LineAnchors = fmt.Sprintf("%s%d", lineAnchorPrefix, ctx.Ordinal())
208 }
209
210 return nil
211 }
212
213 // ApplyLegacyConfig applies legacy config from back when we had
214 // Pygments.
215 func ApplyLegacyConfig(cfg config.Provider, conf *Config) error {
216 if conf.Style == DefaultConfig.Style {
217 if s := cfg.GetString("pygmentsStyle"); s != "" {
218 conf.Style = s
219 }
220 }
221
222 if conf.NoClasses == DefaultConfig.NoClasses && cfg.IsSet("pygmentsUseClasses") {
223 conf.NoClasses = !cfg.GetBool("pygmentsUseClasses")
224 }
225
226 if conf.CodeFences == DefaultConfig.CodeFences && cfg.IsSet("pygmentsCodeFences") {
227 conf.CodeFences = cfg.GetBool("pygmentsCodeFences")
228 }
229
230 if conf.GuessSyntax == DefaultConfig.GuessSyntax && cfg.IsSet("pygmentsCodefencesGuessSyntax") {
231 conf.GuessSyntax = cfg.GetBool("pygmentsCodefencesGuessSyntax")
232 }
233
234 if cfg.IsSet("pygmentsOptions") {
235 if err := applyOptionsFromString(cfg.GetString("pygmentsOptions"), conf); err != nil {
236 return err
237 }
238 }
239
240 return nil
241 }
242
243 func parseHighlightOptions(in string) (map[string]any, error) {
244 in = strings.Trim(in, " ")
245 opts := make(map[string]any)
246
247 if in == "" {
248 return opts, nil
249 }
250
251 for v := range strings.SplitSeq(in, ",") {
252 keyVal := strings.Split(v, "=")
253 key := strings.Trim(keyVal[0], " ")
254 if len(keyVal) != 2 {
255 return opts, fmt.Errorf("invalid Highlight option: %s", key)
256 }
257 opts[key] = keyVal[1]
258
259 }
260
261 normalizeHighlightOptions(opts)
262
263 return opts, nil
264 }
265
266 func normalizeHighlightOptions(m map[string]any) {
267 if m == nil {
268 return
269 }
270
271 // lowercase all keys
272 for k, v := range m {
273 delete(m, k)
274 m[strings.ToLower(k)] = v
275 }
276
277 baseLineNumber := 1
278 if v, ok := m[linosStartKey]; ok {
279 baseLineNumber = cast.ToInt(v)
280 }
281
282 for k, v := range m {
283 switch k {
284 case lineNosKey:
285 if v == "table" || v == "inline" {
286 m["lineNumbersInTable"] = v == "table"
287 }
288 if vs, ok := v.(string); ok {
289 m[k] = vs != "false"
290 }
291 case hlLinesKey:
292 if hlRanges, ok := v.([][2]int); ok {
293 for i := range hlRanges {
294 hlRanges[i][0] += baseLineNumber
295 hlRanges[i][1] += baseLineNumber
296 }
297 delete(m, k)
298 m[k+"_parsed"] = hlRanges
299 }
300 }
301 }
302 }
303
304 // startLine compensates for https://github.com/alecthomas/chroma/issues/30
305 func hlLinesToRanges(startLine int, s string) ([][2]int, error) {
306 var ranges [][2]int
307 s = strings.TrimSpace(s)
308
309 if s == "" {
310 return ranges, nil
311 }
312
313 // Variants:
314 // 1 2 3 4
315 // 1-2 3-4
316 // 1-2 3
317 // 1 3-4
318 // 1 3-4
319 fields := strings.SplitSeq(s, " ")
320 for field := range fields {
321 field = strings.TrimSpace(field)
322 if field == "" {
323 continue
324 }
325 numbers := strings.Split(field, "-")
326 var r [2]int
327 first, err := strconv.Atoi(numbers[0])
328 if err != nil {
329 return ranges, err
330 }
331 first = first + startLine - 1
332 r[0] = first
333 if len(numbers) > 1 {
334 second, err := strconv.Atoi(numbers[1])
335 if err != nil {
336 return ranges, err
337 }
338 second = second + startLine - 1
339 r[1] = second
340 } else {
341 r[1] = first
342 }
343
344 ranges = append(ranges, r)
345 }
346 return ranges, nil
347 }