Backtestshugorun-20261009-153657#15112
Add css.ChromaStyles
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches move the Chroma CSS generation into a shared `markup/highlight` helper and call it from both the gen command and the new template function, which satisfies the issue's code-sharing ask. Both preserve the existing CLI behavior. The main difference is how each creates the Resource. The issue says this should be delegated to `create.Client.FromString`. - **Patch A** does exactly that. FromString gives it the standard resource caching and target-path handling. It also normalizes leading slashes via `paths.ToSlashTrimLeading` and tests that case (`/css/chroma_light.css`). - **Patch B** bypasses the create client. It builds the resource itself with `ResourceSpec.NewResource` and adds its own `hmaps.Cache` of size 10 keyed on a hash of the options map. This duplicates infrastructure the issue told it to reuse and adds risk: a small ad-hoc cache, an anonymous group identity, and no target-path normalization. On usability: - **Patch A** makes `targetPath` optional, deriving it from style and mode. Its `modeSelector` accepts either a bool or "light"/"dark", matching the issue's example where `modeSelector` is "dark". It also returns a clear error when that value conflicts with `mode`. - **Patch B** requires `targetPath`. It accepts `modeSelector` only as a bool (via weak decoding), so the issue's own example, with `modeSelector` set to "dark", would likely fail to decode or behave unexpectedly. - **Patch B**'s one nice touch is defaulting the style to `markup.highlight.style`. On tests and docs: - **Patch A**'s tests cover more: default path naming, case-insensitive style names, the string forms of `modeSelector`, mismatch errors, and argument-count errors. - **Patch B** adds a benchmark plus basic tests. - **Patch A** also adds documentation. Overall, Patch A follows the issue's guidance more closely and handles the described scenario more robustly.
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
40m 18s
Wall-clock time in the container
Full test suite
No new failures
236 passed · 3 skipped · 239 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
542vs 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..fb89ffd68 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,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)+ if err := highlight.WriteChromaCSS(&buf, highlight.ChromaStylesOptions{+ Style: style,+ Mode: mode,+ ModeSelector: modeSelector,+ HighlightStyle: highlightStyle,+ LineNumbersInlineStyle: lineNumbersInlineStyle,+ LineNumbersTableStyle: lineNumbersTableStyle,+ OmitClassComments: omitClassComments,+ }); err != nil {+ return err } - fmt.Print(css)+ fmt.Print(buf.String()) 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", highlight.DefaultChromaStyle, "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..7f1a26c5c@@ -0,0 +1,49 @@+---+title: css.ChromaStyles+description: Returns a CSS stylesheet resource for the Chroma syntax highlighter.+categories: []+keywords: [highlight, chroma, syntax highlighting]+params:+ functions_and_methods:+ aliases: []+ returnType: resource.Resource+ signatures: ['css.ChromaStyles [OPTIONS]']+---++Use this function to generate the CSS stylesheet needed when `markup.highlight.noClasses` is `false`. It accepts the same options as the [`hugo gen chromastyles`][] command, plus a target path.++```go-html-template+{{ $light := css.ChromaStyles (dict "style" "github" "mode" "light" "modeSelector" true) }}+{{ $dark := css.ChromaStyles (dict "style" "github" "mode" "dark" "modeSelector" true) }}+<link rel="stylesheet" href="{{ $light.RelPermalink }}">+<link rel="stylesheet" href="{{ $dark.RelPermalink }}">+```++## Options++targetPath+: (`string`) The path to the generated stylesheet, relative to the `publishDir`. Default is `css/chroma_STYLE.css`, or `css/chroma_STYLE_MODE.css` when `mode` is set.++style+: (`string`) The highlighter 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`. If omitted, the style's default mode is used.++modeSelector+: (`bool` or `string`) 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 between them with a class on a parent element. You may also set this to `light` or `dark`, which enables the mode selector and sets `mode` if not already set. 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`.++[`hugo gen chromastyles`]: /commands/hugo_gen_chromastyles/+[syntax highlighting styles]: /quick-reference/syntax-highlighting-styles/markup/highlight/chromastyles.gonew file mode 100644index 000000000..c4bae3220@@ -0,0 +1,169 @@+// 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"+ "io"+ "slices"+ "strings"++ "github.com/alecthomas/chroma/v2"+ "github.com/alecthomas/chroma/v2/formatters/html"+ "github.com/alecthomas/chroma/v2/styles"+)++// DefaultChromaStyle is the default style used when generating Chroma stylesheets.+const DefaultChromaStyle = "friendly"++// ChromaStylesOptions configures the generation of a CSS stylesheet for the Chroma code highlighter.+// This is shared by the "hugo gen chromastyles" command and the css.ChromaStyles template function.+type ChromaStylesOptions struct {+ // The Chroma style name, e.g. "monokai".+ Style string++ // The style mode, "light" or "dark". If empty, the style's default mode is used.+ 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, e.g. "#fff000 bg:#000fff".+ LineNumbersInlineStyle string++ // Foreground and background colors for table line numbers, e.g. "#fff000 bg:#000fff".+ LineNumbersTableStyle string++ // Omit CSS class comment prefixes in the generated CSS.+ OmitClassComments bool+}++// WriteChromaCSS writes a Chroma CSS stylesheet configured by opts to w.+func WriteChromaCSS(w io.Writer, opts ChromaStylesOptions) 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(chromaCSSOverrides(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)+ }++ _, err = io.WriteString(w, css)+ return err+}++// 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..43a63a824@@ -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 = ["taxonomy", "term", "section", "rss", "sitemap"]+-- layouts/home.html --+{{ $dark := css.ChromaStyles (dict "targetPath" "css/chroma_dark.css" "style" "github" "mode" "dark" "modeSelector" true) }}+{{ $light := css.ChromaStyles (dict "targetPath" "/css/chroma_light.css" "style" "github" "mode" "light" "modeSelector" "light") }}+{{ $plain := css.ChromaStyles (dict "targetPath" "css/plain.css" "style" "Monokai" "omitClassComments" true "highlightStyle" "bg:#123456") }}+{{ $default := css.ChromaStyles }}+{{ $defaultMode := css.ChromaStyles (dict "style" "github" "modeSelector" "dark") }}+dark: {{ $dark.RelPermalink }}|{{ $dark.MediaType }}|+light: {{ $light.RelPermalink }}|+plain: {{ $plain.RelPermalink }}|+default: {{ $default.RelPermalink }}|+defaultMode: {{ $defaultMode.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/plain.css|",+ "default: /css/chroma_friendly.css|",+ "defaultMode: /css/chroma_github_dark.css|",+ )++ b.AssertFileContent("public/css/chroma_dark.css", "/* Background */ .dark .bg {", ".dark .chroma ", "! .light ")+ b.AssertFileContent("public/css/chroma_light.css", "/* Background */ .light .bg {", ".light .chroma ", "! .dark ")+ b.AssertFileContent("public/css/plain.css", ".chroma .hl", "#123456", "! /* Background */", "! .dark ", "! .light ")+ b.AssertFileContent("public/css/chroma_friendly.css", "/* Background */ .bg {", ".chroma ")+ b.AssertFileContent("public/css/chroma_github_dark.css", ".dark .chroma ")+}++func TestChromaStylesErrors(t *testing.T) {+ t.Parallel()++ for _, test := range []struct {+ name string+ args string+ wantErr string+ }{+ {"invalid style", `(dict "style" "nosuchstyle")`, "invalid style: nosuchstyle"},+ {"invalid mode", `(dict "style" "github" "mode" "dim")`, "invalid mode: dim"},+ {"style without mode", `(dict "style" "friendly" "mode" "dark")`, `style "friendly" does not have a "dark" mode`},+ {"invalid modeSelector", `(dict "style" "github" "modeSelector" "dim")`, `invalid modeSelector "dim"`},+ {"mismatched modeSelector", `(dict "style" "github" "mode" "light" "modeSelector" "dark")`, `modeSelector "dark" does not match mode "light"`},+ {"too many args", `(dict) (dict)`, "must not provide more than one argument"},+ } {+ t.Run(test.name, func(t *testing.T) {+ t.Parallel()+ files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "section", "rss", "sitemap"]+-- layouts/home.html --+{{ $css := css.ChromaStyles ` + test.args + ` }}{{ $css.RelPermalink }}+`+ b, err := hugolib.TestE(t, files)+ b.Assert(err, qt.IsNotNil)+ b.Assert(err.Error(), qt.Contains, test.wantErr)+ })+ }+}tpl/css/css.goindex 64fc45ea6..e48a00eaa 100644@@ -1,9 +1,12 @@ package css import (+ "bytes" "context" "errors" "fmt"+ "strconv"+ "strings" "sync" "github.com/gohugoio/hugo/common/hmaps"@@ -11,8 +14,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" "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"@@ -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,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 +183,109 @@ func (ns *Namespace) Build(args ...any) (resource.Resource, error) { return ns.jsTransformClient.Process(r, m) } +// ChromaStyles creates a CSS stylesheet Resource for the Chroma code highlighter.+// The options map accepts targetPath and the options of 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 not provide more than one argument (options map)")+ }+ 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 convert options: %w", err)+ }+ }++ targetPath, opts, err := decodeChromaStylesOptions(m)+ if err != nil {+ return nil, fmt.Errorf("css.ChromaStyles: %w", err)+ }++ var buf bytes.Buffer+ if err := highlight.WriteChromaCSS(&buf, opts); err != nil {+ return nil, fmt.Errorf("css.ChromaStyles: %w", err)+ }++ return ns.createClient.FromString(targetPath, buf.String())+}++// chromaStylesOptions is the options map accepted by css.ChromaStyles.+type chromaStylesOptions struct {+ // The target path of the generated stylesheet.+ // Defaults to css/chroma_<style>.css, or css/chroma_<style>_<mode>.css when mode is set.+ TargetPath string++ Style string+ Mode string+ HighlightStyle string+ LineNumbersInlineStyle string+ LineNumbersTableStyle string+ OmitClassComments bool++ // Either a boolean or the name of the mode class ("light" or "dark").+ ModeSelector any+}++func decodeChromaStylesOptions(m map[string]any) (string, highlight.ChromaStylesOptions, error) {+ var (+ decoded chromaStylesOptions+ opts highlight.ChromaStylesOptions+ )+ if err := mapstructure.WeakDecode(m, &decoded); err != nil {+ return "", opts, err+ }++ opts = highlight.ChromaStylesOptions{+ Style: strings.ToLower(decoded.Style),+ Mode: decoded.Mode,+ HighlightStyle: decoded.HighlightStyle,+ LineNumbersInlineStyle: decoded.LineNumbersInlineStyle,+ LineNumbersTableStyle: decoded.LineNumbersTableStyle,+ OmitClassComments: decoded.OmitClassComments,+ }+ if opts.Style == "" {+ opts.Style = highlight.DefaultChromaStyle+ }++ switch v := decoded.ModeSelector.(type) {+ case nil:+ case bool:+ opts.ModeSelector = v+ case string:+ switch v {+ case "light", "dark":+ if opts.Mode == "" {+ opts.Mode = v+ } else if opts.Mode != v {+ return "", opts, fmt.Errorf("modeSelector %q does not match mode %q", v, opts.Mode)+ }+ opts.ModeSelector = true+ default:+ b, err := strconv.ParseBool(v)+ if err != nil {+ return "", opts, fmt.Errorf("invalid modeSelector %q: must be a boolean, \"light\" or \"dark\"", v)+ }+ opts.ModeSelector = b+ }+ default:+ return "", opts, fmt.Errorf("invalid modeSelector %v (%T): must be a boolean, \"light\" or \"dark\"", v, v)+ }++ targetPath := decoded.TargetPath+ if targetPath == "" {+ name := "chroma_" + opts.Style+ if opts.Mode != "" {+ name += "_" + opts.Mode+ }+ targetPath = "css/" + name + ".css"+ }++ return paths.ToSlashTrimLeading(targetPath), opts, nil+}+ func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { scssClient, err := scss.New(d.BaseFs.Assets, d.ResourceSpec)@@ -189,6 +299,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{@@ -211,6 +322,11 @@ func init() { [][2]string{}, ) + ns.AddMethodMapping(ctx.ChromaStyles,+ nil,+ [][2]string{},+ )+ ns.AddMethodMapping(ctx.Build, nil, [][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{},