Backtestshugorun-20261013-011256#15112

Issue #15112 Merged fix PR #15149 Run 13 Oct 2026 · run-20261013-011256 gohugoio/hugo

Add css.ChromaStyles

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches move the CLI generation logic into a shared markup/highlight function, refactor `hugo gen chromastyles` to use it, and add a `css.ChromaStyles` template function. Both produce essentially identical CSS. They differ mainly in how the Resource is created and how options are handled.

Correctness and fit to the issue:
- The issue says resource creation should be delegated to `create.Client.FromString`. Patch B does exactly that, so it inherits create's caching, publishing and dependency tracking.
- Patch A builds the resource directly with `ResourceSpec.NewResource` and `GroupIdentity: identity.Anonymous`, plus its own 10-entry hash cache. This bypasses the requested path. The anonymous identity can weaken change tracking and rebuild behavior.
- Patch A does have one nice touch: the style defaults to `markup.highlight.style`. That goes beyond the ask.
- Patch A decodes with `WeakDecode`, which silently ignores misspelled options.
- Patch B rejects unknown keys with a clear error, normalizes `targetPath` (it trims the leading slash and treats "/" as empty), and wraps errors with a `css.ChromaStyles:` prefix.

Tests:
- Patch B adds unit tests for `DecodeOptions` and `Generate`.
- Its integration tests cover merging options from `site.Params`, the media type, highlightStyle, omitClassComments, the default style, and a broader error table (unknown option, slash-only targetPath, empty style).
- Patch A's integration tests and benchmark are thinner.

Scope and craft:
- Patch B adds documentation and exposes a `DefaultStyle` constant that the CLI flag shares.
- Patch B's separate `chromastyles` package is clean.

Overall, Patch B follows the issue's explicit design guidance and is more robust and better tested.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

57m 48s

Wall-clock time in the container

Full test suite

No new failures

225 passed · 3 skipped · 242 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

594vs 437 merged

Changed lines, ours vs merged

We have a CLI command for this, with Chroma's recent addition of dark/light modes, it would be convenient to generate these on-the-fly. This would allow this to be configured in hugo.toml and also allow the user an easier way to find the correct settings.

E.g.

{{ $dark := css.ChromaStyles dict 
  "targetPath" "css/croma_dark.css"
   "style" "monokai"
   "modeSelector" "dark"
    "mode" "dark"
}}
<link rel="stylesheet" href="{{ $dark.RelPermalink }}">

This would be even more useful if we fix #15103.

The two patches

Our patch+485 −109
commands/gen.goindex 8d9224a08..42b04f284 100644@@ -21,12 +21,8 @@ import ( 	"os" 	"path" 	"path/filepath"-	"slices" 	"strings" -	"github.com/alecthomas/chroma/v2"-	"github.com/alecthomas/chroma/v2/formatters/html"-	"github.com/alecthomas/chroma/v2/styles" 	"github.com/bep/simplecobra" 	"github.com/goccy/go-yaml" 	"github.com/gohugoio/hugo/common/hugo"@@ -34,6 +30,7 @@ import ( 	"github.com/gohugoio/hugo/helpers" 	"github.com/gohugoio/hugo/hugofs" 	"github.com/gohugoio/hugo/hugolib"+	"github.com/gohugoio/hugo/markup/highlight/chromastyles" 	"github.com/gohugoio/hugo/parser" 	"github.com/spf13/cobra" 	"github.com/spf13/cobra/doc"@@ -65,91 +62,31 @@ func newGenCommand() *genCommand { See https://gohugo.io/quick-reference/syntax-highlighting-styles/ for a preview of the available styles.`,  			run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {-				style = strings.ToLower(style)-				if !slices.Contains(styles.Names(), style) {-					return fmt.Errorf("invalid style: %s", style)-				}-				var chromaStyle *chroma.Style-				if mode != "" {-					var chromaMode chroma.Mode-					switch mode {-					case "light":-						chromaMode = chroma.Light-					case "dark":-						chromaMode = chroma.Dark-					default:-						return fmt.Errorf("invalid mode: %s", mode)-					}--					chromaStyle = styles.GetForMode(style, chromaMode)-					if chromaStyle.Mode() != chromaMode {-						return fmt.Errorf("style %q does not have a %q mode", style, mode)-					}-				} else {-					chromaStyle = styles.Get(style)-				}-				builder := chromaStyle.Builder()-				if highlightStyle != "" {-					builder.Add(chroma.LineHighlight, highlightStyle)-				}-				if lineNumbersInlineStyle != "" {-					builder.Add(chroma.LineNumbers, lineNumbersInlineStyle)-				}-				if lineNumbersTableStyle != "" {-					builder.Add(chroma.LineNumbersTable, lineNumbersTableStyle)-				}-				style, err := builder.Build()-				if err != nil {-					return err-				}- 				if omitEmpty { 					// See https://github.com/alecthomas/chroma/commit/5b2a4c5a26c503c79bc86ba3c4ae5b330028bd3d 					hugo.Deprecate("--omitEmpty", "Flag is no longer needed, empty classes are now always omitted.", "v0.149.0") 				}-				options := []html.Option{-					html.WithCSSComments(!omitClassComments),-				}-				if !modeSelector {-					// Only needed for the shared-scope overlay; --modeSelector-					// gives each mode its own scope and makes this redundant.-					options = append(options, html.WithCustomCSS(chromaCSSOverrides(style)))-				}--				formatter := html.New(options...) -				var buf bytes.Buffer-				fmt.Fprintf(&buf, "/* Generated using: hugo %s */\n\n", strings.Join(os.Args[1:], " "))-				formatter.WriteCSS(&buf, style)-				css := buf.String()-				if modeSelector {-					// Scope every selector under a top level mode class, e.g. ".dark .chroma".-					// This allows generating both light and dark stylesheets and toggling-					// them with a parent class on the page.-					// There's no upstream option for this (I think), so do string replacements for now.-					// TODO(bep) upstream option for this.-					var prefix string-					switch style.Mode() {-					case chroma.Light:-						prefix = ".light "-					case chroma.Dark:-						prefix = ".dark "-					default:-						return fmt.Errorf("style %q does not have a %q mode", style.Name, mode)-					}-					replacer := strings.NewReplacer(-						".bg {", prefix+".bg {",-						".chroma ", prefix+".chroma ",-					)-					css = replacer.Replace(css)+				css, err := chromastyles.Generate(chromastyles.Options{+					Style:                  style,+					Mode:                   mode,+					ModeSelector:           modeSelector,+					HighlightStyle:         highlightStyle,+					LineNumbersInlineStyle: lineNumbersInlineStyle,+					LineNumbersTableStyle:  lineNumbersTableStyle,+					OmitClassComments:      omitClassComments,+				})+				if err != nil {+					return err 				} +				fmt.Printf("/* Generated using: hugo %s */\n\n", strings.Join(os.Args[1:], " ")) 				fmt.Print(css) 				return nil 			}, 			withc: func(cmd *cobra.Command, r *rootCommand) { 				cmd.ValidArgsFunction = cobra.NoFileCompletions-				cmd.PersistentFlags().StringVar(&style, "style", "friendly", "highlighter style")+				cmd.PersistentFlags().StringVar(&style, "style", chromastyles.DefaultStyle, "highlighter style") 				_ = cmd.RegisterFlagCompletionFunc("style", cobra.NoFileCompletions) 				cmd.PersistentFlags().StringVar(&mode, "mode", "", `style mode ("light", "dark")`) 				_ = cmd.RegisterFlagCompletionFunc("mode", cobra.FixedCompletions([]string{"light", "dark"}, cobra.ShellCompDirectiveNoFileComp))@@ -330,38 +267,6 @@ url: %s 	} } -// chromaCSSOverrides re-emits leaf token colors that Chroma's minifier drops-// because they equal the style's default foreground (the .chroma color). Without-// modeSelector scoping, a paired light/dark stylesheet shares the same .chroma-// scope, and the light sheet's explicit rule (e.g. .chroma .nx) would otherwise-// leak into dark mode, since an explicit declaration beats inheritance.-func chromaCSSOverrides(style *chroma.Style) map[chroma.TokenType]string {-	bg := style.Get(chroma.Background)-	m := make(map[chroma.TokenType]string)-	for tt := range chroma.StandardTypes {-		if tt == chroma.Background || !style.Has(tt) || !chromaLeafToken(tt) {-			continue-		}-		entry := style.Get(tt)-		if !entry.Sub(bg).IsZero() || !entry.Colour.IsSet() {-			continue-		}-		if css := html.StyleEntryToCSS(chroma.StyleEntry{Colour: entry.Colour}); css != "" {-			m[tt] = css-		}-	}-	return m-}--func chromaLeafToken(tt chroma.TokenType) bool {-	for other := range chroma.StandardTypes {-		if other != tt && (other.Category() == tt || other.SubCategory() == tt) {-			return false-		}-	}-	return true-}- type genCommand struct { 	rootCmd *rootCommand docs/content/en/functions/css/ChromaStyles.mdnew file mode 100644index 000000000..6c234a8a1@@ -0,0 +1,56 @@+---+title: css.ChromaStyles+description: Returns a CSS resource containing a stylesheet for the Chroma syntax highlighter.+categories: []+keywords: []+params:+  functions_and_methods:+    aliases: []+    returnType: resource.Resource+    signatures: [css.ChromaStyles OPTIONS]+---++{{< new-in 0.165.0 />}}++Use the `css.ChromaStyles` function to generate a syntax highlighting stylesheet when `markup.highlight.noClasses` is disabled in your project configuration. It is the template equivalent of the [`hugo gen chromastyles`][] command.++```go-html-template+{{ $opts := dict+  "targetPath" "css/chroma_dark.css"+  "style" "github"+  "mode" "dark"+  "modeSelector" true+}}+{{ with css.ChromaStyles $opts }}+  <link rel="stylesheet" href="{{ .RelPermalink }}">+{{ end }}+```++## Options++targetPath+: (`string`) The publish path of the stylesheet, relative to the `publishDir`. Required.++style+: (`string`) The name of the Chroma style. See the [syntax highlighting styles][] for a preview of the available styles. Default is `friendly`.++mode+: (`string`) The style mode, either `light` or `dark`. Returns an error if the style does not have the given mode.++modeSelector+: (`bool`) Whether to scope every selector under a top level mode class, e.g. `.dark .chroma`, allowing you to toggle light and dark stylesheets with a class on a parent element. Default is `false`.++highlightStyle+: (`string`) Foreground and background colors for highlighted lines, e.g. `#fff000 bg:#000fff`.++lineNumbersInlineStyle+: (`string`) Foreground and background colors for inline line numbers, e.g. `#fff000 bg:#000fff`.++lineNumbersTableStyle+: (`string`) Foreground and background colors for table line numbers, e.g. `#fff000 bg:#000fff`.++omitClassComments+: (`bool`) Whether to omit CSS class comment prefixes in the generated CSS. Default is `false`.++[`hugo gen chromastyles`]: /commands/hugo_gen_chromastyles/+[syntax highlighting styles]: /quick-reference/syntax-highlighting-styles/docs/data/docs.yamlindex 19b950dd5..ada47f519 100644@@ -2859,6 +2859,14 @@ tpl:           Build processes the given CSS Resource with ESBuild.           Note that this method is identical to the one in the js Namespace.         Examples: []+      ChromaStyles:+        Aliases: null+        Args:+        - args+        Description: |-+          ChromaStyles creates a CSS Resource with a stylesheet for the Chroma code highlighter.+          The options are the same as for the hugo gen chromastyles command, plus a required targetPath.+        Examples: []       PostCSS:         Aliases:         - postCSSmarkup/highlight/chromastyles/chromastyles.gonew file mode 100644index 000000000..0465059f0@@ -0,0 +1,195 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++// Package chromastyles generates CSS stylesheets for the Chroma code highlighter.+// It is shared by the hugo gen chromastyles command and the css.ChromaStyles template function.+package chromastyles++import (+	"bytes"+	"fmt"+	"slices"+	"strings"++	"github.com/alecthomas/chroma/v2"+	"github.com/alecthomas/chroma/v2/formatters/html"+	"github.com/alecthomas/chroma/v2/styles"+	"github.com/mitchellh/mapstructure"+)++// DefaultStyle is the default Chroma style.+const DefaultStyle = "friendly"++// Options configures the generated stylesheet.+type Options struct {+	// The Chroma style name, e.g. "monokai".+	Style string++	// The style mode, "light" or "dark". Optional.+	Mode string++	// Scope every selector under a top level mode class, e.g. ".dark .chroma".+	ModeSelector bool++	// Foreground and background colors for highlighted lines, e.g. "#fff000 bg:#000fff".+	HighlightStyle string++	// Foreground and background colors for inline line numbers.+	LineNumbersInlineStyle string++	// Foreground and background colors for table line numbers.+	LineNumbersTableStyle string++	// Omit CSS class comment prefixes in the generated CSS.+	OmitClassComments bool+}++// DecodeOptions decodes m into Options, applying defaults.+// Keys are matched case-insensitively.+func DecodeOptions(m map[string]any) (Options, error) {+	opts := Options{Style: DefaultStyle}+	if m == nil {+		return opts, nil+	}+	var md mapstructure.Metadata+	decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{+		WeaklyTypedInput: true,+		Metadata:         &md,+		Result:           &opts,+	})+	if err != nil {+		return opts, err+	}+	if err := decoder.Decode(m); err != nil {+		return opts, err+	}+	if len(md.Unused) > 0 {+		slices.Sort(md.Unused)+		return opts, fmt.Errorf("unknown option(s): %s", strings.Join(md.Unused, ", "))+	}+	return opts, nil+}++// Generate generates a CSS stylesheet for the given options.+func Generate(opts Options) (string, error) {+	styleName := strings.ToLower(opts.Style)+	if !slices.Contains(styles.Names(), styleName) {+		return "", fmt.Errorf("invalid style: %s", styleName)+	}++	var chromaStyle *chroma.Style+	if opts.Mode != "" {+		var chromaMode chroma.Mode+		switch opts.Mode {+		case "light":+			chromaMode = chroma.Light+		case "dark":+			chromaMode = chroma.Dark+		default:+			return "", fmt.Errorf("invalid mode: %s", opts.Mode)+		}++		chromaStyle = styles.GetForMode(styleName, chromaMode)+		if chromaStyle.Mode() != chromaMode {+			return "", fmt.Errorf("style %q does not have a %q mode", styleName, opts.Mode)+		}+	} else {+		chromaStyle = styles.Get(styleName)+	}+	builder := chromaStyle.Builder()+	if opts.HighlightStyle != "" {+		builder.Add(chroma.LineHighlight, opts.HighlightStyle)+	}+	if opts.LineNumbersInlineStyle != "" {+		builder.Add(chroma.LineNumbers, opts.LineNumbersInlineStyle)+	}+	if opts.LineNumbersTableStyle != "" {+		builder.Add(chroma.LineNumbersTable, opts.LineNumbersTableStyle)+	}+	style, err := builder.Build()+	if err != nil {+		return "", err+	}++	options := []html.Option{+		html.WithCSSComments(!opts.OmitClassComments),+	}+	if !opts.ModeSelector {+		// Only needed for the shared-scope overlay; ModeSelector+		// gives each mode its own scope and makes this redundant.+		options = append(options, html.WithCustomCSS(cssOverrides(style)))+	}++	formatter := html.New(options...)++	var buf bytes.Buffer+	if err := formatter.WriteCSS(&buf, style); err != nil {+		return "", err+	}+	css := buf.String()+	if opts.ModeSelector {+		// Scope every selector under a top level mode class, e.g. ".dark .chroma".+		// This allows generating both light and dark stylesheets and toggling+		// them with a parent class on the page.+		// There's no upstream option for this (I think), so do string replacements for now.+		// TODO(bep) upstream option for this.+		var prefix string+		switch style.Mode() {+		case chroma.Light:+			prefix = ".light "+		case chroma.Dark:+			prefix = ".dark "+		default:+			return "", fmt.Errorf("style %q does not have a %q mode", style.Name, opts.Mode)+		}+		replacer := strings.NewReplacer(+			".bg {", prefix+".bg {",+			".chroma ", prefix+".chroma ",+		)+		css = replacer.Replace(css)+	}++	return css, nil+}++// cssOverrides re-emits leaf token colors that Chroma's minifier drops+// because they equal the style's default foreground (the .chroma color). Without+// modeSelector scoping, a paired light/dark stylesheet shares the same .chroma+// scope, and the light sheet's explicit rule (e.g. .chroma .nx) would otherwise+// leak into dark mode, since an explicit declaration beats inheritance.+func cssOverrides(style *chroma.Style) map[chroma.TokenType]string {+	bg := style.Get(chroma.Background)+	m := make(map[chroma.TokenType]string)+	for tt := range chroma.StandardTypes {+		if tt == chroma.Background || !style.Has(tt) || !leafToken(tt) {+			continue+		}+		entry := style.Get(tt)+		if !entry.Sub(bg).IsZero() || !entry.Colour.IsSet() {+			continue+		}+		if css := html.StyleEntryToCSS(chroma.StyleEntry{Colour: entry.Colour}); css != "" {+			m[tt] = css+		}+	}+	return m+}++func leafToken(tt chroma.TokenType) bool {+	for other := range chroma.StandardTypes {+		if other != tt && (other.Category() == tt || other.SubCategory() == tt) {+			return false+		}+	}+	return true+}markup/highlight/chromastyles/chromastyles_test.gonew file mode 100644index 000000000..260aeb7f3@@ -0,0 +1,75 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package chromastyles++import (+	"testing"++	qt "github.com/frankban/quicktest"+)++func TestDecodeOptions(t *testing.T) {+	c := qt.New(t)++	opts, err := DecodeOptions(nil)+	c.Assert(err, qt.IsNil)+	c.Assert(opts, qt.DeepEquals, Options{Style: DefaultStyle})++	opts, err = DecodeOptions(map[string]any{+		"style":                  "monokai",+		"MODE":                   "dark",+		"modeSelector":           "true",+		"highlightStyle":         "#fff",+		"lineNumbersInlineStyle": "#aaa",+		"lineNumbersTableStyle":  "#bbb",+		"omitClassComments":      true,+	})+	c.Assert(err, qt.IsNil)+	c.Assert(opts, qt.DeepEquals, Options{+		Style:                  "monokai",+		Mode:                   "dark",+		ModeSelector:           true,+		HighlightStyle:         "#fff",+		LineNumbersInlineStyle: "#aaa",+		LineNumbersTableStyle:  "#bbb",+		OmitClassComments:      true,+	})++	_, err = DecodeOptions(map[string]any{"foo": "bar"})+	c.Assert(err, qt.ErrorMatches, "unknown option\\(s\\): foo")+}++func TestGenerate(t *testing.T) {+	c := qt.New(t)++	css, err := Generate(Options{Style: "github-dark"})+	c.Assert(err, qt.IsNil)+	// Same-colour token classes are kept when not scoped by mode selector.+	c.Assert(css, qt.Matches, `(?s).*NameOther.*\.chroma \.nx \{ color:#e6edf3 \}.*`)++	css, err = Generate(Options{Style: "ashen", ModeSelector: true})+	c.Assert(err, qt.IsNil)+	c.Assert(css, qt.Contains, ".dark .chroma ")++	css, err = Generate(Options{Style: "monokai", OmitClassComments: true})+	c.Assert(err, qt.IsNil)+	c.Assert(css, qt.Not(qt.Contains), "GenericSubheading")++	_, err = Generate(Options{Style: "__invalid_style__"})+	c.Assert(err, qt.ErrorMatches, "invalid style: __invalid_style__")+	_, err = Generate(Options{Style: ""})+	c.Assert(err, qt.ErrorMatches, "invalid style: ")+	_, err = Generate(Options{Style: "friendly", Mode: "dark"})+	c.Assert(err, qt.ErrorMatches, `style "friendly" does not have a "dark" mode`)+}tpl/css/chromastyles_integration_test.gonew file mode 100644index 000000000..91126aa0b@@ -0,0 +1,87 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package css_test++import (+	"testing"++	qt "github.com/frankban/quicktest"+	"github.com/gohugoio/hugo/hugolib"+)++func TestChromaStyles(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["page", "section", "taxonomy", "term", "sitemap", "rss"]+[params.chroma]+style = "github"+mode = "dark"+modeSelector = true+-- layouts/home.html --+{{ $dark := css.ChromaStyles (merge site.Params.chroma (dict "targetPath" "css/chroma_dark.css")) }}+{{ $light := css.ChromaStyles (dict "targetPath" "/css/chroma_light.css" "style" "github" "mode" "light" "modeSelector" true) }}+{{ $plain := css.ChromaStyles (dict "targetPath" "css/chroma_plain.css" "style" "Monokai" "omitClassComments" true "highlightStyle" "#fff000 bg:#000fff") }}+{{ $default := css.ChromaStyles (dict "targetPath" "css/chroma_default.css") }}+Dark: {{ $dark.RelPermalink }}|{{ $dark.MediaType }}|+Light: {{ $light.RelPermalink }}|+Plain: {{ $plain.RelPermalink }}|+Default: {{ $default.RelPermalink }}|+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html",+		"Dark: /css/chroma_dark.css|text/css|",+		"Light: /css/chroma_light.css|",+		"Plain: /css/chroma_plain.css|",+		"Default: /css/chroma_default.css|",+	)+	b.AssertFileContent("public/css/chroma_dark.css", "/* Background */ .dark .bg {", ".dark .chroma ", "! Generated using")+	b.AssertFileContent("public/css/chroma_light.css", ".light .chroma ", "! .dark ")+	b.AssertFileContent("public/css/chroma_plain.css", ".chroma .hl { color:#fff000;background-color:#000fff }", "! /* LineHighlight */", "! .dark ", "! .light ")+	// friendly is the default style.+	b.AssertFileContent("public/css/chroma_default.css", "/* Background */ .bg { background-color:#f0f0f0; }")+}++func TestChromaStylesErrors(t *testing.T) {+	t.Parallel()++	for _, test := range []struct {+		name     string+		template string+		expected string+	}{+		{"no targetPath", `{{ css.ChromaStyles (dict "style" "monokai") }}`, "targetPath must be set"},+		{"slash-only targetPath", `{{ css.ChromaStyles (dict "targetPath" "/") }}`, "targetPath must be set"},+		{"empty style", `{{ css.ChromaStyles (dict "targetPath" "a.css" "style" "") }}`, "invalid style: "},+		{"invalid style", `{{ css.ChromaStyles (dict "targetPath" "a.css" "style" "__invalid_style__") }}`, "invalid style: __invalid_style__"},+		{"invalid mode", `{{ css.ChromaStyles (dict "targetPath" "a.css" "style" "github" "mode" "dim") }}`, "invalid mode: dim"},+		{"missing mode", `{{ css.ChromaStyles (dict "targetPath" "a.css" "style" "friendly" "mode" "dark") }}`, `style "friendly" does not have a "dark" mode`},+		{"unknown option", `{{ css.ChromaStyles (dict "targetPath" "a.css" "styel" "monokai") }}`, "unknown option(s): styel"},+	} {+		t.Run(test.name, func(t *testing.T) {+			t.Parallel()+			files := `+-- hugo.toml --+disableKinds = ["page", "section", "taxonomy", "term", "sitemap", "rss"]+-- layouts/home.html --+` + test.template + "\n"+			b, err := hugolib.TestE(t, files)+			b.Assert(err, qt.IsNotNil)+			b.Assert(err.Error(), qt.Contains, test.expected)+		})+	}+}tpl/css/css.goindex 64fc45ea6..1bcfdb951 100644@@ -4,6 +4,7 @@ import ( 	"context" 	"errors" 	"fmt"+	"maps" 	"sync"  	"github.com/gohugoio/hugo/common/hmaps"@@ -11,8 +12,10 @@ import ( 	"github.com/gohugoio/hugo/common/paths" 	"github.com/gohugoio/hugo/common/types/css" 	"github.com/gohugoio/hugo/deps"+	"github.com/gohugoio/hugo/markup/highlight/chromastyles" 	"github.com/gohugoio/hugo/resources" 	"github.com/gohugoio/hugo/resources/resource"+	"github.com/gohugoio/hugo/resources/resource_factories/create" 	"github.com/gohugoio/hugo/resources/resource_transformers/babel" 	"github.com/gohugoio/hugo/resources/resource_transformers/cssjs" 	jstransform "github.com/gohugoio/hugo/resources/resource_transformers/js"@@ -34,6 +37,7 @@ type Namespace struct { 	tailwindcssClient *cssjs.TailwindCSSClient 	babelClient       *babel.Client 	jsTransformClient *jstransform.Client+	createClient      *create.Client  	// The Dart Client requires a os/exec process, so  only 	// create it if we really need it.@@ -54,6 +58,46 @@ func (ns *Namespace) Unquoted(v any) css.UnquotedString { 	return css.UnquotedString(s) } +// ChromaStyles creates a CSS Resource with a stylesheet for the Chroma code highlighter.+// The options are the same as for the hugo gen chromastyles command, plus a required targetPath.+func (ns *Namespace) ChromaStyles(args ...any) (resource.Resource, error) {+	if len(args) > 1 {+		return nil, errors.New("must not provide more arguments than options")+	}++	var m map[string]any+	if len(args) == 1 && args[0] != nil {+		var err error+		m, err = hmaps.ToStringMapE(args[0])+		if err != nil {+			return nil, fmt.Errorf("css.ChromaStyles: failed to decode options: %w", err)+		}+		// Copy so we can safely remove the targetPath below.+		m = maps.Clone(m)+	}++	var targetPath string+	if v, k, found := hmaps.LookupEqualFold(m, "targetPath"); found {+		targetPath = paths.ToSlashTrimLeading(cast.ToString(v))+		delete(m, k)+	}+	if targetPath == "" {+		return nil, errors.New("css.ChromaStyles: targetPath must be set")+	}++	opts, err := chromastyles.DecodeOptions(m)+	if err != nil {+		return nil, fmt.Errorf("css.ChromaStyles: %w", err)+	}++	s, err := chromastyles.Generate(opts)+	if err != nil {+		return nil, fmt.Errorf("css.ChromaStyles: %w", err)+	}++	return ns.createClient.FromString(targetPath, s)+}+ // PostCSS processes the given Resource with PostCSS. func (ns *Namespace) PostCSS(args ...any) (resource.Resource, error) { 	if len(args) > 2 {@@ -189,6 +233,7 @@ func init() { 			tailwindcssClient: cssjs.NewTailwindCSSClient(d.ResourceSpec), 			babelClient:       babel.New(d.ResourceSpec), 			jsTransformClient: jstransform.New(d.BaseFs.Assets, d.ResourceSpec, true),+			createClient:      create.New(d.ResourceSpec), 		}  		ns := &internal.TemplateFuncsNamespace{@@ -196,6 +241,11 @@ func init() { 			Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, 		} +		ns.AddMethodMapping(ctx.ChromaStyles,+			nil,+			[][2]string{},+		)+ 		ns.AddMethodMapping(ctx.PostCSS, 			[]string{"postCSS"}, 			[][2]string{}, 
Merged fix · PR #15149+328 −109
commands/gen.goindex 8d9224a08..f3747722c 100644@@ -21,12 +21,8 @@ import ( 	"os" 	"path" 	"path/filepath"-	"slices" 	"strings" -	"github.com/alecthomas/chroma/v2"-	"github.com/alecthomas/chroma/v2/formatters/html"-	"github.com/alecthomas/chroma/v2/styles" 	"github.com/bep/simplecobra" 	"github.com/goccy/go-yaml" 	"github.com/gohugoio/hugo/common/hugo"@@ -34,6 +30,7 @@ import ( 	"github.com/gohugoio/hugo/helpers" 	"github.com/gohugoio/hugo/hugofs" 	"github.com/gohugoio/hugo/hugolib"+	"github.com/gohugoio/hugo/markup/highlight" 	"github.com/gohugoio/hugo/parser" 	"github.com/spf13/cobra" 	"github.com/spf13/cobra/doc"@@ -65,85 +62,24 @@ func newGenCommand() *genCommand { See https://gohugo.io/quick-reference/syntax-highlighting-styles/ for a preview of the available styles.`,  			run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {-				style = strings.ToLower(style)-				if !slices.Contains(styles.Names(), style) {-					return fmt.Errorf("invalid style: %s", style)-				}-				var chromaStyle *chroma.Style-				if mode != "" {-					var chromaMode chroma.Mode-					switch mode {-					case "light":-						chromaMode = chroma.Light-					case "dark":-						chromaMode = chroma.Dark-					default:-						return fmt.Errorf("invalid mode: %s", mode)-					}--					chromaStyle = styles.GetForMode(style, chromaMode)-					if chromaStyle.Mode() != chromaMode {-						return fmt.Errorf("style %q does not have a %q mode", style, mode)-					}-				} else {-					chromaStyle = styles.Get(style)-				}-				builder := chromaStyle.Builder()-				if highlightStyle != "" {-					builder.Add(chroma.LineHighlight, highlightStyle)-				}-				if lineNumbersInlineStyle != "" {-					builder.Add(chroma.LineNumbers, lineNumbersInlineStyle)-				}-				if lineNumbersTableStyle != "" {-					builder.Add(chroma.LineNumbersTable, lineNumbersTableStyle)-				}-				style, err := builder.Build()-				if err != nil {-					return err-				}- 				if omitEmpty { 					// See https://github.com/alecthomas/chroma/commit/5b2a4c5a26c503c79bc86ba3c4ae5b330028bd3d 					hugo.Deprecate("--omitEmpty", "Flag is no longer needed, empty classes are now always omitted.", "v0.149.0") 				}-				options := []html.Option{-					html.WithCSSComments(!omitClassComments),-				}-				if !modeSelector {-					// Only needed for the shared-scope overlay; --modeSelector-					// gives each mode its own scope and makes this redundant.-					options = append(options, html.WithCustomCSS(chromaCSSOverrides(style)))-				}--				formatter := html.New(options...)--				var buf bytes.Buffer-				fmt.Fprintf(&buf, "/* Generated using: hugo %s */\n\n", strings.Join(os.Args[1:], " "))-				formatter.WriteCSS(&buf, style)-				css := buf.String()-				if modeSelector {-					// Scope every selector under a top level mode class, e.g. ".dark .chroma".-					// This allows generating both light and dark stylesheets and toggling-					// them with a parent class on the page.-					// There's no upstream option for this (I think), so do string replacements for now.-					// TODO(bep) upstream option for this.-					var prefix string-					switch style.Mode() {-					case chroma.Light:-						prefix = ".light "-					case chroma.Dark:-						prefix = ".dark "-					default:-						return fmt.Errorf("style %q does not have a %q mode", style.Name, mode)-					}-					replacer := strings.NewReplacer(-						".bg {", prefix+".bg {",-						".chroma ", prefix+".chroma ",-					)-					css = replacer.Replace(css)+				css, err := highlight.ChromaStylesCSS(highlight.ChromaStylesOptions{+					Style:                  style,+					Mode:                   mode,+					ModeSelector:           modeSelector,+					HighlightStyle:         highlightStyle,+					LineNumbersInlineStyle: lineNumbersInlineStyle,+					LineNumbersTableStyle:  lineNumbersTableStyle,+					OmitClassComments:      omitClassComments,+				})+				if err != nil {+					return err 				} +				fmt.Printf("/* Generated using: hugo %s */\n\n", strings.Join(os.Args[1:], " ")) 				fmt.Print(css) 				return nil 			},@@ -330,38 +266,6 @@ url: %s 	} } -// chromaCSSOverrides re-emits leaf token colors that Chroma's minifier drops-// because they equal the style's default foreground (the .chroma color). Without-// modeSelector scoping, a paired light/dark stylesheet shares the same .chroma-// scope, and the light sheet's explicit rule (e.g. .chroma .nx) would otherwise-// leak into dark mode, since an explicit declaration beats inheritance.-func chromaCSSOverrides(style *chroma.Style) map[chroma.TokenType]string {-	bg := style.Get(chroma.Background)-	m := make(map[chroma.TokenType]string)-	for tt := range chroma.StandardTypes {-		if tt == chroma.Background || !style.Has(tt) || !chromaLeafToken(tt) {-			continue-		}-		entry := style.Get(tt)-		if !entry.Sub(bg).IsZero() || !entry.Colour.IsSet() {-			continue-		}-		if css := html.StyleEntryToCSS(chroma.StyleEntry{Colour: entry.Colour}); css != "" {-			m[tt] = css-		}-	}-	return m-}--func chromaLeafToken(tt chroma.TokenType) bool {-	for other := range chroma.StandardTypes {-		if other != tt && (other.Category() == tt || other.SubCategory() == tt) {-			return false-		}-	}-	return true-}- type genCommand struct { 	rootCmd *rootCommand markup/highlight/chromastyles.gonew file mode 100644index 000000000..f76f37b29@@ -0,0 +1,161 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package highlight++import (+	"bytes"+	"fmt"+	"slices"+	"strings"++	"github.com/alecthomas/chroma/v2"+	"github.com/alecthomas/chroma/v2/formatters/html"+	"github.com/alecthomas/chroma/v2/styles"+)++// ChromaStylesOptions holds options for ChromaStylesCSS.+type ChromaStylesOptions struct {+	// Highlighter style, e.g. "monokai".+	Style string++	// Style mode, "light" or "dark".+	Mode string++	// Scope selectors under a top level mode class, e.g. ".dark .chroma".+	ModeSelector bool++	// Foreground and background colors for highlighted lines, e.g. "#fff000 bg:#000fff".+	HighlightStyle string++	// Foreground and background colors for inline line numbers.+	LineNumbersInlineStyle string++	// Foreground and background colors for table line numbers.+	LineNumbersTableStyle string++	// Omit CSS class comment prefixes in the generated CSS.+	OmitClassComments bool+}++// ChromaStylesCSS generates a CSS stylesheet for the Chroma code highlighter.+// This stylesheet is needed if markup.highlight.noClasses is disabled in config.+func ChromaStylesCSS(opts ChromaStylesOptions) (string, error) {+	name := strings.ToLower(opts.Style)+	if !slices.Contains(styles.Names(), name) {+		return "", fmt.Errorf("invalid style: %s", name)+	}+	var chromaStyle *chroma.Style+	if opts.Mode != "" {+		var mode chroma.Mode+		switch opts.Mode {+		case "light":+			mode = chroma.Light+		case "dark":+			mode = chroma.Dark+		default:+			return "", fmt.Errorf("invalid mode: %s", opts.Mode)+		}++		chromaStyle = styles.GetForMode(name, mode)+		if chromaStyle.Mode() != mode {+			return "", fmt.Errorf("style %q does not have a %q mode", name, opts.Mode)+		}+	} else {+		chromaStyle = styles.Get(name)+	}+	builder := chromaStyle.Builder()+	if opts.HighlightStyle != "" {+		builder.Add(chroma.LineHighlight, opts.HighlightStyle)+	}+	if opts.LineNumbersInlineStyle != "" {+		builder.Add(chroma.LineNumbers, opts.LineNumbersInlineStyle)+	}+	if opts.LineNumbersTableStyle != "" {+		builder.Add(chroma.LineNumbersTable, opts.LineNumbersTableStyle)+	}+	style, err := builder.Build()+	if err != nil {+		return "", err+	}++	options := []html.Option{+		html.WithCSSComments(!opts.OmitClassComments),+	}+	if !opts.ModeSelector {+		// Only needed for the shared-scope overlay; modeSelector+		// gives each mode its own scope and makes this redundant.+		options = append(options, html.WithCustomCSS(chromaCSSOverrides(style)))+	}++	var buf bytes.Buffer+	if err := html.New(options...).WriteCSS(&buf, style); err != nil {+		return "", err+	}+	css := buf.String()+	if opts.ModeSelector {+		// Scope every selector under a top level mode class, e.g. ".dark .chroma".+		// This allows generating both light and dark stylesheets and toggling+		// them with a parent class on the page.+		// There's no upstream option for this (I think), so do string replacements for now.+		// TODO(bep) upstream option for this.+		var prefix string+		switch style.Mode() {+		case chroma.Light:+			prefix = ".light "+		case chroma.Dark:+			prefix = ".dark "+		default:+			return "", fmt.Errorf("style %q does not have a light or dark mode", style.Name)+		}+		replacer := strings.NewReplacer(+			".bg {", prefix+".bg {",+			".chroma ", prefix+".chroma ",+		)+		css = replacer.Replace(css)+	}++	return css, nil+}++// chromaCSSOverrides re-emits leaf token colors that Chroma's minifier drops+// because they equal the style's default foreground (the .chroma color). Without+// modeSelector scoping, a paired light/dark stylesheet shares the same .chroma+// scope, and the light sheet's explicit rule (e.g. .chroma .nx) would otherwise+// leak into dark mode, since an explicit declaration beats inheritance.+func chromaCSSOverrides(style *chroma.Style) map[chroma.TokenType]string {+	bg := style.Get(chroma.Background)+	m := make(map[chroma.TokenType]string)+	for tt := range chroma.StandardTypes {+		if tt == chroma.Background || !style.Has(tt) || !chromaLeafToken(tt) {+			continue+		}+		entry := style.Get(tt)+		if !entry.Sub(bg).IsZero() || !entry.Colour.IsSet() {+			continue+		}+		if css := html.StyleEntryToCSS(chroma.StyleEntry{Colour: entry.Colour}); css != "" {+			m[tt] = css+		}+	}+	return m+}++func chromaLeafToken(tt chroma.TokenType) bool {+	for other := range chroma.StandardTypes {+		if other != tt && (other.Category() == tt || other.SubCategory() == tt) {+			return false+		}+	}+	return true+}tpl/css/chromastyles_integration_test.gonew file mode 100644index 000000000..f4e366c3f@@ -0,0 +1,97 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package css_test++import (+	"strings"+	"testing"++	qt "github.com/frankban/quicktest"+	"github.com/gohugoio/hugo/hugolib"+	"github.com/gohugoio/hugo/tpl/css"+)++// See issue 15112.+func TestChromaStyles(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "rss", "sitemap", "section", "page"]+[markup.highlight]+style = "monokai"+-- layouts/home.html --+{{ $light := css.ChromaStyles (dict "targetPath" "css/chroma-light.css" "style" "github" "mode" "light" "modeSelector" true) }}+{{ $dark := css.ChromaStyles (dict "targetPath" "css/chroma-dark.css" "style" "github" "mode" "dark" "modeSelector" true) }}+{{ $default := css.ChromaStyles (dict "targetPath" "css/chroma.css") }}+Light: {{ $light.RelPermalink }}|Dark: {{ $dark.RelPermalink }}|Default: {{ $default.RelPermalink }}|+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html", "Light: /css/chroma-light.css|Dark: /css/chroma-dark.css|Default: /css/chroma.css|")+	b.AssertFileContent("public/css/chroma-light.css", ".light .chroma ", ".light .bg {")+	b.AssertFileContent("public/css/chroma-dark.css", ".dark .chroma ", ".dark .bg {")+	// Style defaults to markup.highlight.style, monokai background.+	b.AssertFileContent("public/css/chroma.css", "/* Background */ .bg {", "background-color:#272822")+}++func TestChromaStylesErrors(t *testing.T) {+	t.Parallel()++	filesTemplate := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "rss", "sitemap", "section", "page"]+-- layouts/home.html --+{{ css.ChromaStyles OPTS }}+`++	for _, test := range []struct {+		opts  string+		match string+	}{+		{`(dict "style" "monokai")`, `.*targetPath cannot be empty.*`},+		{`(dict "targetPath" "css/chroma.css" "style" "doesnotexist")`, `.*invalid style: doesnotexist.*`},+		{`(dict "targetPath" "css/chroma.css" "mode" "blue")`, `.*invalid mode: blue.*`},+		{`(dict "targetPath" "css/chroma.css" "style" "friendly" "mode" "dark")`, `.*style "friendly" does not have a "dark" mode.*`},+	} {+		files := strings.ReplaceAll(filesTemplate, "OPTS", test.opts)+		b, err := hugolib.TestE(t, files)+		b.Assert(err, qt.ErrorMatches, test.match)+	}+}++func BenchmarkChromaStyles(b *testing.B) {+	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "rss", "sitemap", "section", "page"]+-- layouts/all.html --+All.+`++	bb := hugolib.Test(b, files)++	bb.Assert(true, qt.IsTrue)+	s := bb.H.Sites[0]+	ns := s.TemplateStore.GetTemplateFuncsNamespace("css").(*css.Namespace)++	opts := map[string]any{"targetPath": "css/chroma.css", "style": "monokai", "mode": "light", "modeSelector": true}++	b.ResetTimer()++	for b.Loop() {+		_, err := ns.ChromaStyles(opts)+		bb.Assert(err, qt.IsNil)+	}+}tpl/css/css.goindex 64fc45ea6..71cc605be 100644@@ -6,11 +6,16 @@ import ( 	"fmt" 	"sync" +	"github.com/gohugoio/hugo/common/hashing" 	"github.com/gohugoio/hugo/common/hmaps"+	"github.com/gohugoio/hugo/common/hugio" 	"github.com/gohugoio/hugo/common/hugo" 	"github.com/gohugoio/hugo/common/paths" 	"github.com/gohugoio/hugo/common/types/css" 	"github.com/gohugoio/hugo/deps"+	"github.com/gohugoio/hugo/identity"+	"github.com/gohugoio/hugo/markup/highlight"+	"github.com/gohugoio/hugo/markup/markup_config" 	"github.com/gohugoio/hugo/resources" 	"github.com/gohugoio/hugo/resources/resource" 	"github.com/gohugoio/hugo/resources/resource_transformers/babel"@@ -21,6 +26,7 @@ import ( 	"github.com/gohugoio/hugo/resources/resource_transformers/tocss/scss" 	"github.com/gohugoio/hugo/tpl/internal" 	"github.com/gohugoio/hugo/tpl/internal/resourcehelpers"+	"github.com/mitchellh/mapstructure" 	"github.com/spf13/cast" ) @@ -34,6 +40,8 @@ type Namespace struct { 	tailwindcssClient *cssjs.TailwindCSSClient 	babelClient       *babel.Client 	jsTransformClient *jstransform.Client+	chromaStylesCache *hmaps.Cache[uint64, resource.Resource]+	highlightConfig   highlight.Config  	// The Dart Client requires a os/exec process, so  only 	// create it if we really need it.@@ -42,6 +50,48 @@ type Namespace struct { 	scssClientDartSass     *dartsass.Client } +// ChromaStyles generates a CSS stylesheet for the Chroma code highlighter+// and returns it as a Resource. This stylesheet is needed if+// markup.highlight.noClasses is disabled in config.+// The style defaults to the markup.highlight.style config setting.+func (ns *Namespace) ChromaStyles(opts any) (resource.Resource, error) {+	key := hashing.HashUint64(opts)+	return ns.chromaStylesCache.GetOrCreate(key, func() (resource.Resource, error) {+		m, err := hmaps.ToStringMapE(opts)+		if err != nil {+			return nil, err+		}+		var o struct {+			TargetPath                    string+			highlight.ChromaStylesOptions `mapstructure:",squash"`+		}++		if err := mapstructure.WeakDecode(m, &o); err != nil {+			return nil, err+		}+		if o.TargetPath == "" {+			return nil, errors.New("targetPath cannot be empty")+		}+		if o.Style == "" {+			o.Style = ns.highlightConfig.Style+		}+		css, err := highlight.ChromaStylesCSS(o.ChromaStylesOptions)+		if err != nil {+			return nil, err+		}++		return ns.d.ResourceSpec.NewResource(+			resources.ResourceSourceDescriptor{+				LazyPublish:   true,+				GroupIdentity: identity.Anonymous,+				OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) {+					return hugio.NewReadSeekerNoOpCloserFromString(css), nil+				},+				TargetPath: o.TargetPath,+			})+	})+}+ // Quoted returns a string that needs to be quoted in CSS. func (ns *Namespace) Quoted(v any) css.QuotedString { 	s := cast.ToString(v)@@ -189,6 +239,8 @@ func init() { 			tailwindcssClient: cssjs.NewTailwindCSSClient(d.ResourceSpec), 			babelClient:       babel.New(d.ResourceSpec), 			jsTransformClient: jstransform.New(d.BaseFs.Assets, d.ResourceSpec, true),+			chromaStylesCache: hmaps.NewCacheWithOptions[uint64, resource.Resource](hmaps.CacheOptions{Size: 10}),+			highlightConfig:   d.Conf.GetConfigSection("markup").(markup_config.Config).Highlight, 		}  		ns := &internal.TemplateFuncsNamespace{@@ -196,6 +248,11 @@ func init() { 			Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, 		} +		ns.AddMethodMapping(ctx.ChromaStyles,+			nil,+			[][2]string{},+		)+ 		ns.AddMethodMapping(ctx.PostCSS, 			[]string{"postCSS"}, 			[][2]string{},