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