Backtestshugorun-20261007-020926#15112
Add css.ChromaStyles
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 chromastyles generation logic out of commands/gen.go into a shared markup/highlight package, so the CLI and the new template function use the same code. Both add a css.ChromaStyles template function that returns a Resource. Patch B follows the issue's explicit guidance that creating the Resource "should be delegated to `create.Client.FromString`". Patch A instead calls ResourceSpec.NewResource directly with a hand-rolled LazyPublish/Anonymous descriptor and its own small LRU cache. This duplicates what create.Client already does and adds risk around identity and dependency tracking and publishing semantics. Patch B also handles the edges better: - It copies the input map rather than decoding it in place, so site params used as options are not mutated, and a test asserts this. - It normalizes targetPath with paths.ToSlashTrimLeading. - It rejects unknown option keys, such as the typo `styel`, with a clear error. - It prefixes errors with `css.ChromaStyles:`. Patch A has one nice touch: it defaults the style to the markup.highlight.style config value, which arguably fits the "configured in hugo.toml" wish. Patch B defaults to `friendly`, but its documentation shows config-driven options via site.Params, which also meets that wish. On tests, Patch B adds both unit tests for the shared package (decoding, mode selector, highlight style, error cases) and integration tests (params-sourced options, map immutability, error cases including a non-map argument). Patch A has integration and error tests plus a benchmark but no unit coverage of the shared code. Patch B also adds documentation. Overall, Patch B is more faithful to the issue's design direction, 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
26m 9s
Wall-clock time in the container
Full test suite
No new failures
3,693 passed · 97 skipped · 3,799 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
607vs 437 merged
Changed lines, ours vs merged
The issue
View on GitHubWe 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 options would be
targetPath+ the options in https://gohugo.io/commands/hugo_gen_chromastyles/#hugo-gen-chromastyles - Some sharing of code between the gen command in the commands package would be sensible.
- Creating the
Resourceshould be delegated tocreate.Client.FromString.
The two patches
commands/gen.goindex 8d9224a08..4e45dda05 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,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 := chromastyles.String(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 },@@ -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 docs/content/en/functions/css/ChromaStyles.mdnew file mode 100644index 000000000..e8c7a6955@@ -0,0 +1,51 @@+---+title: css.ChromaStyles+description: Returns a CSS resource with the syntax highlighting styles for the Chroma code highlighter.+categories: []+keywords: []+params:+ functions_and_methods:+ aliases: []+ returnType: resource.Resource+ signatures: ['css.ChromaStyles OPTIONS']+---++The `css.ChromaStyles` function generates a CSS stylesheet for the [Chroma](https://github.com/alecthomas/chroma) code highlighter, the same as the [`hugo gen chromastyles`](/commands/hugo_gen_chromastyles/) command. The stylesheet is needed if `markup.highlight.noClasses` is disabled in your project configuration.++```go-html-template+{{ $dark := css.ChromaStyles (dict+ "targetPath" "css/chroma_dark.css"+ "style" "github"+ "mode" "dark"+ "modeSelector" true+) }}+<link rel="stylesheet" href="{{ $dark.RelPermalink }}">+```++The options map can also come from your project configuration, e.g. `{{ css.ChromaStyles site.Params.chroma.dark }}`.++## Options++targetPath+: (`string`) The publish path of the stylesheet, relative to the root of the published site. Required.++style+: (`string`) The Chroma style name. See the [syntax highlighting styles](/quick-reference/syntax-highlighting-styles/) for a preview of the available styles. Default is `friendly`.++mode+: (`string`) The style mode, either `light` or `dark`. Default is the style's own mode.++modeSelector+: (`bool`) Whether to scope every selector under a top level mode class, e.g. `.dark .chroma`. This allows you to include both a light and a dark stylesheet and toggle them with a class on a parent element. Default is `false`.++highlightStyle+: (`string`) The foreground and background colors for highlighted lines, e.g. `#fff000 bg:#000fff`.++lineNumbersInlineStyle+: (`string`) The foreground and background colors for inline line numbers, e.g. `#fff000 bg:#000fff`.++lineNumbersTableStyle+: (`string`) The foreground and background colors for table line numbers, e.g. `#fff000 bg:#000fff`.++omitClassComments+: (`bool`) Whether to omit the CSS class comment prefixes in the generated CSS. Default is `false`.markup/highlight/chromastyles/chromastyles.gonew file mode 100644index 000000000..3229d46f9@@ -0,0 +1,201 @@+// 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"+ "io"+ "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 style used when none is set.+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". Empty means the style's default.+ Mode string++ // Whether to 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, e.g. "#fff000 bg:#000fff".+ LineNumbersInlineStyle string++ // Foreground and background colors for table line numbers, e.g. "#fff000 bg:#000fff".+ LineNumbersTableStyle string++ // Whether to omit the CSS class comment prefixes.+ OmitClassComments bool+}++// DecodeOptions decodes m into Options, applying defaults.+func DecodeOptions(m map[string]any) (Options, error) {+ opts := Options{Style: DefaultStyle}+ if m == nil {+ return opts, nil+ }+ var md mapstructure.Metadata+ if err := mapstructure.WeakDecodeMetadata(m, &opts, &md); err != nil {+ return opts, fmt.Errorf("failed to decode chroma styles options: %w", err)+ }+ if len(md.Unused) > 0 {+ slices.Sort(md.Unused)+ return opts, fmt.Errorf("unknown chroma styles option(s): %s", strings.Join(md.Unused, ", "))+ }+ return opts, nil+}++// Write writes the CSS stylesheet for the given options to w.+func Write(w io.Writer, opts Options) error {+ styleName := strings.ToLower(opts.Style)+ if styleName == "" {+ styleName = DefaultStyle+ }+ 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+ }++ htmlOptions := []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.+ htmlOptions = append(htmlOptions, html.WithCustomCSS(cssOverrides(style)))+ }++ formatter := html.New(htmlOptions...)++ if !opts.ModeSelector {+ return formatter.WriteCSS(w, style)+ }++ // 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)+ }++ var buf bytes.Buffer+ if err := formatter.WriteCSS(&buf, style); err != nil {+ return err+ }+ replacer := strings.NewReplacer(+ ".bg {", prefix+".bg {",+ ".chroma ", prefix+".chroma ",+ )+ _, err = replacer.WriteString(w, buf.String())+ return err+}++// String returns the CSS stylesheet for the given options.+func String(opts Options) (string, error) {+ var buf bytes.Buffer+ if err := Write(&buf, opts); err != nil {+ return "", err+ }+ return buf.String(), nil+}++// cssOverrides re-emits leaf token colors that Chroma's minifier drops+// because they equal the style's default foreground (the .chroma color). Without+// mode selector 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..13a7032cf@@ -0,0 +1,96 @@+// 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.Equals, Options{Style: DefaultStyle})++ opts, err = DecodeOptions(map[string]any{+ "style": "monokai",+ "mode": "dark",+ "modeselector": "true",+ "highlightStyle": "#fff000 bg:#000fff",+ "lineNumbersInlineStyle": "#aaa",+ "lineNumbersTableStyle": "#bbb",+ "omitClassComments": true,+ })+ c.Assert(err, qt.IsNil)+ c.Assert(opts, qt.Equals, Options{+ Style: "monokai",+ Mode: "dark",+ ModeSelector: true,+ HighlightStyle: "#fff000 bg:#000fff",+ LineNumbersInlineStyle: "#aaa",+ LineNumbersTableStyle: "#bbb",+ OmitClassComments: true,+ })++ _, err = DecodeOptions(map[string]any{"styel": "monokai"})+ c.Assert(err, qt.ErrorMatches, `unknown chroma styles option\(s\): styel`)+}++func TestString(t *testing.T) {+ c := qt.New(t)++ css, err := String(Options{Style: "monokai"})+ c.Assert(err, qt.IsNil)+ c.Assert(css, qt.Contains, "/* GenericSubheading */")+ c.Assert(css, qt.Contains, ".chroma ")+ c.Assert(css, qt.Not(qt.Contains), ".dark ")++ css, err = String(Options{Style: "monokai", OmitClassComments: true})+ c.Assert(err, qt.IsNil)+ c.Assert(css, qt.Not(qt.Contains), "GenericSubheading")++ // Same-colour leaf token classes are kept without mode selector.+ css, err = String(Options{Style: "github-dark"})+ c.Assert(err, qt.IsNil)+ c.Assert(css, qt.Matches, `(?s).*\.chroma \.nx \{ color:#e6edf3 \}.*`)++ css, err = String(Options{Style: "github", Mode: "dark", ModeSelector: true})+ c.Assert(err, qt.IsNil)+ c.Assert(css, qt.Contains, ".dark .chroma ")+ c.Assert(css, qt.Contains, ".dark .bg {")++ css, err = String(Options{Style: "github", Mode: "light", ModeSelector: true})+ c.Assert(err, qt.IsNil)+ c.Assert(css, qt.Contains, ".light .chroma ")++ css, err = String(Options{Style: "ashen", ModeSelector: true})+ c.Assert(err, qt.IsNil)+ c.Assert(css, qt.Contains, ".dark .chroma ")++ css, err = String(Options{Style: "monokai", HighlightStyle: "#fff000 bg:#000fff"})+ c.Assert(err, qt.IsNil)+ c.Assert(css, qt.Matches, `(?s).*\.chroma \.hl \{[^}]*#000fff.*`)++ _, err = String(Options{Style: "__invalid_style__"})+ c.Assert(err, qt.ErrorMatches, `invalid style: __invalid_style__`)++ _, err = String(Options{Style: "github", Mode: "dim"})+ c.Assert(err, qt.ErrorMatches, `invalid mode: dim`)++ _, err = String(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..a2c17a13a@@ -0,0 +1,86 @@+// 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 = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+[params.chroma.dark]+targetPath = "css/chroma_dark.css"+style = "github"+mode = "dark"+modeSelector = true+-- layouts/home.html --+{{ $light := css.ChromaStyles (dict "targetPath" "css/chroma_light.css" "style" "github" "mode" "light" "modeSelector" true "omitClassComments" true) }}+{{ $dark := css.ChromaStyles site.Params.chroma.dark }}+{{ $plain := css.ChromaStyles (dict "targetPath" "/css/chroma.css" "style" "monokai" "highlightStyle" "bg:#000fff") }}+Light: {{ $light.RelPermalink }}|{{ $light.MediaType }}|+Dark: {{ $dark.RelPermalink }}|+Plain: {{ $plain.RelPermalink }}|+DarkParams: {{ site.Params.chroma.dark.targetpath }}|+`++ b := hugolib.Test(t, files)++ b.AssertFileContent("public/index.html",+ "Light: /css/chroma_light.css|text/css|",+ "Dark: /css/chroma_dark.css|",+ "Plain: /css/chroma.css|",+ // The options map must not be modified.+ "DarkParams: css/chroma_dark.css|",+ )+ b.AssertFileContent("public/css/chroma_light.css", ".light .chroma ", "! .dark ", "! /* ")+ b.AssertFileContent("public/css/chroma_dark.css", ".dark .chroma ", ".dark .bg {", "! .light ", "/* Background */")+ b.AssertFileContent("public/css/chroma.css", "/* LineHighlight */ .chroma .hl { background-color:#000fff }", "! .dark ")+}++func TestChromaStylesErrors(t *testing.T) {+ t.Parallel()++ for _, test := range []struct {+ name string+ args string+ wantErr string+ }{+ {"no targetPath", `(dict "style" "monokai")`, "targetPath must be set"},+ {"invalid style", `(dict "targetPath" "a.css" "style" "__invalid_style__")`, "invalid style: __invalid_style__"},+ {"invalid mode", `(dict "targetPath" "a.css" "style" "github" "mode" "dim")`, "invalid mode: dim"},+ {"style without mode", `(dict "targetPath" "a.css" "style" "friendly" "mode" "dark")`, `style "friendly" does not have a "dark" mode`},+ {"unknown option", `(dict "targetPath" "a.css" "styel" "monokai")`, `unknown chroma styles option\(s\): styel`},+ {"not a map", `"monokai"`, "invalid options"},+ } {+ t.Run(test.name, func(t *testing.T) {+ t.Parallel()+ files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- layouts/home.html --+{{ $r := css.ChromaStyles ` + test.args + ` }}{{ $r.RelPermalink }}+`+ b, err := hugolib.TestE(t, files)+ b.Assert(err, qt.IsNotNil)+ b.Assert(err.Error(), qt.Matches, `(?s).*css\.ChromaStyles: .*`+test.wantErr+`.*`)+ })+ }+}tpl/css/css.goindex 64fc45ea6..b79ee4d9c 100644@@ -4,6 +4,7 @@ import ( "context" "errors" "fmt"+ "strings" "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.@@ -176,6 +180,47 @@ func (ns *Namespace) Build(args ...any) (resource.Resource, error) { return ns.jsTransformClient.Process(r, m) } +// ChromaStyles creates a CSS Resource with the Chroma code highlighter+// styles for the given options. The options are "targetPath" (required) and+// the same options as the "hugo gen chromastyles" command: "style", "mode",+// "modeSelector", "highlightStyle", "lineNumbersInlineStyle",+// "lineNumbersTableStyle" and "omitClassComments".+func (ns *Namespace) ChromaStyles(args ...any) (resource.Resource, error) {+ if len(args) != 1 {+ return nil, errors.New("must provide exactly one argument, an options map")+ }+ in, err := hmaps.ToStringMapE(args[0])+ if err != nil {+ return nil, fmt.Errorf("css.ChromaStyles: invalid options: %w", err)+ }++ // Copy the options, the input map may be e.g. site params.+ var targetPath string+ m := make(map[string]any, len(in))+ for k, v := range in {+ if strings.EqualFold(k, "targetPath") {+ targetPath = cast.ToString(v)+ continue+ }+ m[k] = v+ }+ targetPath = paths.ToSlashTrimLeading(targetPath)+ 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.String(opts)+ if err != nil {+ return nil, fmt.Errorf("css.ChromaStyles: %w", err)+ }++ return ns.createClient.FromString(targetPath, s)+}+ func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { scssClient, err := scss.New(d.BaseFs.Assets, d.ResourceSpec)@@ -189,6 +234,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 +242,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{},
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{},