Debian Codegraph @

hugolib/page__content.go

raw
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hugolib
15
16 import (
17 "context"
18 "errors"
19 "fmt"
20 "html/template"
21 "sort"
22 "strings"
23 "sync/atomic"
24 "unicode/utf8"
25
26 maps0 "maps"
27
28 "github.com/bep/helpers/contexthelpers"
29 "github.com/bep/logg"
30
31 "github.com/gohugoio/hugo/common/herrors"
32 "github.com/gohugoio/hugo/common/hmaps"
33 "github.com/gohugoio/hugo/common/hugio"
34 "github.com/gohugoio/hugo/common/hugo"
35 "github.com/gohugoio/hugo/common/predicate"
36 "github.com/gohugoio/hugo/common/types/hstring"
37 "github.com/gohugoio/hugo/helpers"
38 "github.com/gohugoio/hugo/markup"
39 "github.com/gohugoio/hugo/markup/converter"
40 "github.com/gohugoio/hugo/markup/goldmark/hugocontext"
41 "github.com/gohugoio/hugo/markup/tableofcontents"
42 "github.com/gohugoio/hugo/parser/metadecoders"
43 "github.com/gohugoio/hugo/parser/pageparser"
44 "github.com/gohugoio/hugo/resources"
45 "github.com/gohugoio/hugo/resources/page"
46 "github.com/gohugoio/hugo/resources/resource"
47 "github.com/gohugoio/hugo/tpl"
48 "github.com/mitchellh/mapstructure"
49 "github.com/spf13/cast"
50 )
51
52 const (
53 internalSummaryDividerBase = "HUGOMORE42"
54 )
55
56 var (
57 internalSummaryDividerPreString = "\n\n" + internalSummaryDividerBase + "\n\n"
58 internalSummaryDividerPre = []byte(internalSummaryDividerPreString)
59 )
60
61 type pageContentReplacement struct {
62 val []byte
63
64 source pageparser.Item
65 }
66
67 func (m *pageMetaSource) parseFrontMatter(
68 h *HugoSites,
69 sid uint64,
70 ) error {
71 var filename string
72 if m.f != nil {
73 filename = m.f.Filename()
74 }
75
76 m.pi = &contentParseInfo{
77 h: h,
78 sid: sid,
79 openSource: m.openSource,
80 shortcodeParseInfo: newShortcodeHandler(filename, h.Deps),
81 }
82
83 source, err := m.pi.contentSource(m)
84 if err != nil {
85 return err
86 }
87
88 items, err := pageparser.ParseBytes(
89 source,
90 pageparser.Config{
91 NoFrontMatter: m.noFrontMatter,
92 },
93 )
94 if err != nil {
95 return err
96 }
97
98 m.pi.itemsStep1 = items
99
100 if err := m.pi.parseSource(source, m.noFrontMatter); err != nil {
101 return err
102 }
103
104 return nil
105 }
106
107 func (m *pageMeta) newCachedContent(s *Site) (*cachedContent, error) {
108 if m.pageMetaSource.pi == nil {
109 panic("pageMeta.pageMetaSource.pi must be set before creating cachedContent")
110 }
111
112 c := &cachedContent{
113 pm: s.pageMap,
114 StaleInfo: m,
115 pi: m.pi,
116 enableEmoji: s.conf.EnableEmoji,
117 scopes: hmaps.NewCache[string, *cachedContentScope](),
118 }
119 var hasName predicate.P[string] = m.pi.shortcodeParseInfo.hasName
120 c.hasShortcode.Store(&hasName)
121
122 return c, nil
123 }
124
125 // Content cached for a page instance.
126 type cachedContent struct {
127 pm *pageMap
128
129 resource.StaleInfo
130
131 // Parsed content.
132 pi *contentParseInfo
133
134 enableEmoji bool
135
136 // Whether the content has a given shortcode name.
137 hasShortcode atomic.Pointer[predicate.P[string]]
138
139 scopes *hmaps.Cache[string, *cachedContentScope]
140 }
141
142 func (c *cachedContent) getOrCreateScope(scope string, pco *pageContentOutput) *cachedContentScope {
143 key := scope + pco.po.f.Name
144 cs, _ := c.scopes.GetOrCreate(key, func() (*cachedContentScope, error) {
145 return &cachedContentScope{
146 cachedContent: c,
147 pco: pco,
148 scope: scope,
149 }, nil
150 })
151 return cs
152 }
153
154 // contentParseInfo is shared between all Page instances created from the same source.
155 type contentParseInfo struct {
156 h *HugoSites
157
158 sid uint64
159
160 // The source bytes.
161 openSource hugio.OpenReadSeekCloser
162
163 frontMatter map[string]any
164
165 // Whether the parsed content contains a summary separator.
166 hasSummaryDivider bool
167
168 // Returns the position in bytes after any front matter.
169 posMainContent int
170
171 // Indicates whether we must do placeholder replacements.
172 hasNonMarkdownShortcode bool
173
174 // Items from the page parser.
175 // These maps directly to the source
176 itemsStep1 pageparser.Items
177
178 // *shortcode, pageContentReplacement or pageparser.Item
179 itemsStep2 []any
180
181 // The shortcode handler.
182 shortcodeParseInfo *shortcodeParseInfo
183 }
184
185 func (pi *contentParseInfo) AddBytes(item pageparser.Item) {
186 pi.itemsStep2 = append(pi.itemsStep2, item)
187 }
188
189 func (pi *contentParseInfo) AddReplacement(val []byte, source pageparser.Item) {
190 pi.itemsStep2 = append(pi.itemsStep2, pageContentReplacement{val: val, source: source})
191 }
192
193 func (pi *contentParseInfo) AddShortcode(s *shortcode) {
194 pi.itemsStep2 = append(pi.itemsStep2, s)
195 if s.insertPlaceholder() {
196 pi.hasNonMarkdownShortcode = true
197 }
198 }
199
200 // sourceMapEntry maps a range in rendered content back to a position in the original source.
201 type sourceMapEntry struct {
202 renderOffset int // start offset in content sent to Goldmark
203 sourceOffset int // corresponding offset in original source file
204 isShortcode bool // if true, any pos in this segment maps to sourceOffset
205 }
206
207 // resolveSourceOffset maps a position in rendered content to an offset in the original source.
208 func resolveSourceOffset(sm []sourceMapEntry, pos int) int {
209 i := sort.Search(len(sm), func(i int) bool {
210 return sm[i].renderOffset > pos
211 }) - 1
212 if i < 0 {
213 return pos
214 }
215 e := sm[i]
216 if e.isShortcode {
217 return e.sourceOffset
218 }
219 return e.sourceOffset + (pos - e.renderOffset)
220 }
221
222 // contentToRenderForItems returns the content to be processed by Goldmark or similar.
223 func (pi *contentParseInfo) contentToRender(ctx context.Context, source []byte, renderedShortcodes map[string]shortcodeRenderer) ([]byte, []sourceMapEntry, bool, error) {
224 var hasVariants bool
225 c := make([]byte, 0, len(source)+(len(source)/10))
226 var sm []sourceMapEntry
227
228 for _, it := range pi.itemsStep2 {
229 switch v := it.(type) {
230 case pageparser.Item:
231 sm = append(sm, sourceMapEntry{renderOffset: len(c), sourceOffset: v.Pos()})
232 c = append(c, source[v.Pos():v.Pos()+len(v.Val(source))]...)
233 case pageContentReplacement:
234 sm = append(sm, sourceMapEntry{renderOffset: len(c), sourceOffset: v.source.Pos()})
235 c = append(c, v.val...)
236 case *shortcode:
237 sm = append(sm, sourceMapEntry{renderOffset: len(c), sourceOffset: v.pos, isShortcode: true})
238 if !v.insertPlaceholder() {
239 // Insert the rendered shortcode.
240 renderedShortcode, found := renderedShortcodes[v.placeholder]
241 if !found {
242 // This should never happen.
243 panic(fmt.Sprintf("rendered shortcode %q not found", v.placeholder))
244 }
245
246 b, more, err := renderedShortcode.renderShortcode(ctx)
247 if err != nil {
248 return nil, nil, false, fmt.Errorf("failed to render shortcode: %w", err)
249 }
250 hasVariants = hasVariants || more
251 c = append(c, []byte(b)...)
252
253 } else {
254 // Insert the placeholder so we can insert the content after
255 // markdown processing.
256 c = append(c, []byte(v.placeholder)...)
257 }
258 default:
259 panic(fmt.Sprintf("unknown item type %T", it))
260 }
261 }
262
263 return c, sm, hasVariants, nil
264 }
265
266 func (c *cachedContent) IsZero() bool {
267 return len(c.pi.itemsStep2) == 0
268 }
269
270 func (pi *contentParseInfo) parseSource(source []byte, skipFrontMatter bool) error {
271 if len(pi.itemsStep1) == 0 {
272 return nil
273 }
274
275 s := pi.shortcodeParseInfo
276
277 fail := func(err error, i pageparser.Item) error {
278 if fe, ok := err.(herrors.FileError); ok {
279 return fe
280 }
281
282 pos := posFromInput("", source, i.Pos())
283
284 return herrors.NewFileErrorFromPos(err, pos)
285 }
286
287 iter := pageparser.NewIterator(pi.itemsStep1)
288
289 // the parser is guaranteed to return items in proper order or fail, so …
290 // … it's safe to keep some "global" state
291 var ordinal int
292
293 Loop:
294 for {
295 it := iter.Next()
296
297 switch {
298 case it.Type == pageparser.TypeIgnore:
299 case it.IsFrontMatter():
300 if !skipFrontMatter {
301 if err := pi.parseFrontMatter(it, iter, source); err != nil {
302 return err
303 }
304 }
305 next := iter.Peek()
306 if !next.IsDone() {
307 pi.posMainContent = next.Pos()
308 }
309 case it.Type == pageparser.TypeLeadSummaryDivider:
310 posBody := -1
311 f := func(item pageparser.Item) bool {
312 if posBody == -1 && !item.IsDone() {
313 posBody = item.Pos()
314 }
315
316 if item.IsNonWhitespace(source) {
317 // Done
318 return false
319 }
320 return true
321 }
322 iter.PeekWalk(f)
323
324 pi.hasSummaryDivider = true
325
326 // The content may be rendered by Goldmark or similar,
327 // and we need to track the summary.
328 pi.AddReplacement(internalSummaryDividerPre, it)
329
330 // Handle shortcode
331 case it.IsLeftShortcodeDelim():
332 // let extractShortcode handle left delim (will do so recursively)
333 iter.Backup()
334
335 currShortcode, err := s.extractShortcode(ordinal, 0, source, iter)
336 if err != nil {
337 return fail(err, it)
338 }
339
340 currShortcode.pos = it.Pos()
341 currShortcode.length = iter.Current().Pos() - it.Pos()
342 if currShortcode.placeholder == "" {
343 currShortcode.placeholder = createShortcodePlaceholder("s", pi.sid, uint64(currShortcode.ordinal))
344 }
345
346 if currShortcode.name != "" {
347 s.addName(currShortcode.name)
348 }
349
350 if currShortcode.params == nil {
351 var s []string
352 currShortcode.params = s
353 }
354
355 currShortcode.placeholder = createShortcodePlaceholder("s", pi.sid, uint64(ordinal))
356 ordinal++
357 s.shortcodes = append(s.shortcodes, currShortcode)
358
359 pi.AddShortcode(currShortcode)
360
361 case it.IsEOF():
362 break Loop
363 case it.IsError():
364 return fail(it.Err, it)
365 default:
366 pi.AddBytes(it)
367 }
368 }
369
370 return nil
371 }
372
373 func (pi *contentParseInfo) parseFrontMatter(it pageparser.Item, iter *pageparser.Iterator, source []byte) error {
374 if pi.frontMatter != nil {
375 return nil
376 }
377
378 f := pageparser.FormatFromFrontMatterType(it.Type)
379 var err error
380 pi.frontMatter, err = metadecoders.Default.UnmarshalToMap(it.Val(source), f)
381 if err != nil {
382 fe := herrors.UnwrapFileError(err)
383 if fe == nil {
384 fe = herrors.NewFileError(err)
385 }
386 pos := fe.Position()
387
388 // Offset the starting position of front matter.
389 offset := iter.LineNumber(source) - 1
390
391 pos.LineNumber += offset
392
393 fe.UpdatePosition(pos)
394 fe.SetFilename("") // It will be set later.
395 return fe
396 }
397
398 return nil
399 }
400
401 func (c *cachedContent) mustSource() []byte {
402 source, err := c.pi.contentSource(c)
403 if err != nil {
404 panic(err)
405 }
406 return source
407 }
408
409 func (pi *contentParseInfo) contentSource(s resource.StaleInfo) ([]byte, error) {
410 key := pi.sid
411 versionv := s.StaleVersion()
412
413 v, err := pi.h.cacheContentSource.GetOrCreate(key, func(uint64) (*resources.StaleValue[[]byte], error) {
414 b, err := pi.readSourceAll()
415 if err != nil {
416 return nil, err
417 }
418
419 return &resources.StaleValue[[]byte]{
420 Value: b,
421 StaleVersionFunc: func() uint32 {
422 return s.StaleVersion() - versionv
423 },
424 }, nil
425 })
426 if err != nil {
427 return nil, err
428 }
429
430 return v.Value, nil
431 }
432
433 func (pi *contentParseInfo) readSourceAll() ([]byte, error) {
434 if pi.openSource == nil {
435 return []byte{}, nil
436 }
437 r, err := pi.openSource()
438 if err != nil {
439 return nil, err
440 }
441 defer r.Close()
442
443 return hugio.ReadAll(r)
444 }
445
446 type contentTableOfContents struct {
447 // For Goldmark we split Parse and Render.
448 astDoc any
449
450 tableOfContents *tableofcontents.Fragments
451 tableOfContentsHTML template.HTML
452
453 // Temporary storage of placeholders mapped to their content.
454 // These are shortcodes etc. Some of these will need to be replaced
455 // after any markup is rendered, so they share a common prefix.
456 contentPlaceholders map[string]shortcodeRenderer
457
458 contentToRender []byte
459
460 sourceInfo
461 }
462
463 type sourceInfo struct {
464 // Optional override for the filename used in position reporting.
465 filename string
466 // The original source bytes.
467 source []byte
468 // Maps positions in the content sent to Goldmark back to the original source.
469 sourceMap []sourceMapEntry
470 }
471
472 type contentSummary struct {
473 content template.HTML
474 contentWithoutSummary template.HTML
475 summary page.Summary
476 }
477
478 type contentPlainPlainWords struct {
479 plain string
480 plainWords []string
481
482 wordCount int
483 fuzzyWordCount int
484 readingTime int
485 }
486
487 func (c *cachedContentScope) keyScope(ctx context.Context) string {
488 return hugo.GetMarkupScope(ctx) + c.pco.po.f.Name + fmt.Sprintf("_%d", c.pi.sid)
489 }
490
491 func (c *cachedContentScope) contentRendered(ctx context.Context) (contentSummary, error) {
492 cp := c.pco
493 ctx = tpl.Context.DependencyScope.Set(ctx, pageDependencyScopeGlobal)
494 key := c.keyScope(ctx)
495
496 versionv := c.version(cp)
497
498 v, err := c.pm.cacheContentRendered.GetOrCreate(key, func(string) (*resources.StaleValue[contentSummary], error) {
499 cp.po.p.s.Log.Trace(logg.StringFunc(func() string {
500 return fmt.Sprintln("contentRendered", key)
501 }))
502
503 cp.po.p.s.h.contentRenderCounter.Add(1)
504 cp.contentRendered.Store(true)
505 po := cp.po
506
507 ct, err := c.contentToC(ctx)
508 if err != nil {
509 return nil, err
510 }
511
512 rs, err := func() (*resources.StaleValue[contentSummary], error) {
513 rs := &resources.StaleValue[contentSummary]{
514 StaleVersionFunc: func() uint32 {
515 return c.version(cp) - versionv
516 },
517 }
518
519 if len(c.pi.itemsStep2) == 0 {
520 // Nothing to do.
521 return rs, nil
522 }
523
524 var b []byte
525
526 if ct.astDoc != nil {
527 // The content is parsed, but not rendered.
528 r, ok, err := po.contentRenderer.RenderContent(ctx, ct.contentToRender, ct.sourceInfo, ct.astDoc)
529 if err != nil {
530 return nil, err
531 }
532
533 if !ok {
534 return nil, errors.New("invalid state: astDoc is set but RenderContent returned false")
535 }
536
537 b = r.Bytes()
538
539 } else {
540 // Copy the content to be rendered.
541 b = make([]byte, len(ct.contentToRender))
542 copy(b, ct.contentToRender)
543 }
544
545 // There are one or more replacement tokens to be replaced.
546 var hasShortcodeVariants bool
547 tokenHandler := func(ctx context.Context, token string) ([]byte, error) {
548 if token == tocShortcodePlaceholder {
549 return []byte(ct.tableOfContentsHTML), nil
550 }
551 renderer, found := ct.contentPlaceholders[token]
552 if found {
553 repl, more, err := renderer.renderShortcode(ctx)
554 if err != nil {
555 return nil, err
556 }
557 hasShortcodeVariants = hasShortcodeVariants || more
558 return repl, nil
559 }
560 // This should never happen.
561 panic(fmt.Errorf("unknown shortcode token %q (number of tokens: %d)", token, len(ct.contentPlaceholders)))
562 }
563
564 b, err = expandShortcodeTokens(ctx, b, tokenHandler)
565 if err != nil {
566 return nil, err
567 }
568 if hasShortcodeVariants {
569 cp.po.p.incrPageOutputTemplateVariation()
570 }
571
572 var result contentSummary
573 if c.pi.hasSummaryDivider {
574 s := string(b)
575 summarized := page.ExtractSummaryFromHTMLWithDivider(cp.po.p.m.pageConfigSource.ContentMediaType, s, internalSummaryDividerBase)
576 result.summary = page.Summary{
577 Text: template.HTML(summarized.Summary()),
578 Type: page.SummaryTypeManual,
579 Truncated: summarized.Truncated(),
580 }
581 result.contentWithoutSummary = template.HTML(summarized.ContentWithoutSummary())
582 result.content = template.HTML(summarized.Content())
583 } else {
584 result.content = template.HTML(string(b))
585 }
586
587 if !c.pi.hasSummaryDivider && cp.po.p.m.pageConfig.Summary == "" {
588 numWords := cp.po.p.s.conf.SummaryLength
589 isCJKLanguage := cp.po.p.m.pageConfig.IsCJKLanguage
590 summary := page.ExtractSummaryFromHTML(cp.po.p.m.pageConfigSource.ContentMediaType, string(result.content), numWords, isCJKLanguage)
591 result.summary = page.Summary{
592 Text: template.HTML(summary.Summary()),
593 Type: page.SummaryTypeAuto,
594 Truncated: summary.Truncated(),
595 }
596 result.contentWithoutSummary = template.HTML(summary.ContentWithoutSummary())
597 }
598 rs.Value = result
599
600 return rs, nil
601 }()
602 if err != nil {
603 return rs, cp.po.p.wrapError(err)
604 }
605
606 if rs.Value.summary.IsZero() {
607 b, err := cp.po.contentRenderer.ParseAndRenderContent(ctx, []byte(cp.po.p.m.pageConfig.Summary), false)
608 if err != nil {
609 return nil, err
610 }
611 html := cp.po.p.s.ContentSpec.TrimShortHTML(b.Bytes(), cp.po.p.m.pageConfigSource.Content.Markup)
612 rs.Value.summary = page.Summary{
613 Text: helpers.BytesToHTML(html),
614 Type: page.SummaryTypeFrontMatter,
615 Truncated: rs.Value.summary.Truncated,
616 }
617 rs.Value.contentWithoutSummary = rs.Value.content
618 }
619
620 return rs, err
621 })
622 if err != nil {
623 return contentSummary{}, cp.po.p.wrapError(err)
624 }
625
626 return v.Value, nil
627 }
628
629 func (c *cachedContentScope) mustContentToC(ctx context.Context) contentTableOfContents {
630 ct, err := c.contentToC(ctx)
631 if err != nil {
632 panic(err)
633 }
634 return ct
635 }
636
637 type contextKey uint8
638
639 const (
640 contextKeyContentCallback contextKey = iota
641 )
642
643 var setGetContentCallbackInContext = contexthelpers.NewContextDispatcher[func(*pageContentOutput, contentTableOfContents)](contextKeyContentCallback)
644
645 func (c *cachedContentScope) contentToC(ctx context.Context) (contentTableOfContents, error) {
646 cp := c.pco
647 key := c.keyScope(ctx)
648 versionv := c.version(cp)
649
650 v, err := c.pm.contentTableOfContents.GetOrCreate(key, func(string) (*resources.StaleValue[contentTableOfContents], error) {
651 var err error
652 var ct contentTableOfContents
653 ct.source, err = c.pi.contentSource(c)
654 if err != nil {
655 return nil, err
656 }
657
658 if err := cp.initRenderHooks(); err != nil {
659 return nil, err
660 }
661 po := cp.po
662 p := po.p
663 ct.contentPlaceholders, err = c.pi.shortcodeParseInfo.prepareShortcodesForPage(po, false)
664 if err != nil {
665 return nil, err
666 }
667
668 // Callback called from below (e.g. in .RenderString)
669 ctxCallback := func(cp2 *pageContentOutput, ct2 contentTableOfContents) {
670 cp.otherOutputs.Set(cp2.po.p.pid, cp2)
671
672 // Merge content placeholders
673 maps0.Copy(ct.contentPlaceholders, ct2.contentPlaceholders)
674
675 if p.s.conf.Internal.Watch {
676 for _, s := range cp2.po.p.m.content.pi.shortcodeParseInfo.shortcodes {
677 cp.trackDependency(s.templ)
678 }
679 }
680
681 // Transfer shortcode names so HasShortcode works for shortcodes from included pages.
682 combined := cp.po.p.m.content.hasShortcode.Load().Or(*cp2.po.p.m.content.hasShortcode.Load())
683 cp.po.p.m.content.hasShortcode.Store(&combined)
684 if cp2.po.p.pageOutputTemplateVariationsState.Load() > 0 {
685 cp.po.p.incrPageOutputTemplateVariation()
686 }
687 }
688
689 ctx = setGetContentCallbackInContext.Set(ctx, ctxCallback)
690
691 var hasVariants bool
692 ct.contentToRender, ct.sourceMap, hasVariants, err = c.pi.contentToRender(ctx, ct.source, ct.contentPlaceholders)
693 if err != nil {
694 return nil, err
695 }
696
697 ct.contentToRender = hugocontext.DedentMarkers(ct.contentToRender)
698
699 if hasVariants {
700 p.incrPageOutputTemplateVariation()
701 }
702
703 isHTML := cp.po.p.m.pageConfigSource.ContentMediaType.IsHTML()
704
705 if !isHTML {
706 createAndSetToC := func(tocProvider converter.TableOfContentsProvider) error {
707 cfg := p.s.ContentSpec.Converters.GetMarkupConfig()
708 ct.tableOfContents = tocProvider.TableOfContents()
709 ct.tableOfContentsHTML, err = ct.tableOfContents.ToHTML(
710 cfg.TableOfContents.StartLevel,
711 cfg.TableOfContents.EndLevel,
712 cfg.TableOfContents.Ordered,
713 )
714 return err
715 }
716
717 // If the converter supports doing the parsing separately, we do that.
718 parseResult, ok, err := po.contentRenderer.ParseContent(ctx, ct.contentToRender)
719 if err != nil {
720 return nil, err
721 }
722 if ok {
723 // This is Goldmark.
724 // Store away the parse result for later use.
725 createAndSetToC(parseResult)
726
727 ct.astDoc = parseResult.Doc()
728
729 } else {
730
731 // This is Asciidoctor etc.
732 r, err := po.contentRenderer.ParseAndRenderContent(ctx, ct.contentToRender, true)
733 if err != nil {
734 return nil, err
735 }
736
737 ct.contentToRender = r.Bytes()
738
739 if tocProvider, ok := r.(converter.TableOfContentsProvider); ok {
740 createAndSetToC(tocProvider)
741 } else {
742 tmpContent, tmpTableOfContents := helpers.ExtractTOC(ct.contentToRender)
743 ct.tableOfContentsHTML = helpers.BytesToHTML(tmpTableOfContents)
744 ct.tableOfContents = tableofcontents.Empty
745 ct.contentToRender = tmpContent
746 }
747 }
748 }
749
750 return &resources.StaleValue[contentTableOfContents]{
751 Value: ct,
752 StaleVersionFunc: func() uint32 {
753 return c.version(cp) - versionv
754 },
755 }, nil
756 })
757 if err != nil {
758 return contentTableOfContents{}, err
759 }
760
761 return v.Value, nil
762 }
763
764 func (c *cachedContent) version(cp *pageContentOutput) uint32 {
765 // Both of these gets incremented on change.
766 return c.StaleVersion() + cp.contentRenderedVersion
767 }
768
769 func (c *cachedContentScope) contentPlain(ctx context.Context) (contentPlainPlainWords, error) {
770 cp := c.pco
771 key := c.keyScope(ctx)
772
773 versionv := c.version(cp)
774
775 v, err := c.pm.cacheContentPlain.GetOrCreateWitTimeout(key, cp.po.p.s.Conf.Timeout(), func(string) (*resources.StaleValue[contentPlainPlainWords], error) {
776 var result contentPlainPlainWords
777 rs := &resources.StaleValue[contentPlainPlainWords]{
778 StaleVersionFunc: func() uint32 {
779 return c.version(cp) - versionv
780 },
781 }
782
783 rendered, err := c.contentRendered(ctx)
784 if err != nil {
785 return nil, err
786 }
787
788 result.plain = tpl.StripHTML(string(rendered.content))
789 result.plainWords = strings.Fields(result.plain)
790
791 isCJKLanguage := cp.po.p.m.pageConfig.IsCJKLanguage
792
793 if isCJKLanguage {
794 result.wordCount = 0
795 for _, word := range result.plainWords {
796 runeCount := utf8.RuneCountInString(word)
797 if len(word) == runeCount {
798 result.wordCount++
799 } else {
800 result.wordCount += runeCount
801 }
802 }
803 } else {
804 result.wordCount = helpers.TotalWords(result.plain)
805 }
806
807 // TODO(bep) is set in a test. Fix that.
808 if result.fuzzyWordCount == 0 {
809 result.fuzzyWordCount = (result.wordCount + 99) / 100 * 100
810 }
811
812 if isCJKLanguage {
813 result.readingTime = (result.wordCount + 499) / 500
814 } else {
815 result.readingTime = (result.wordCount + 211) / 212
816 }
817
818 rs.Value = result
819
820 return rs, nil
821 })
822 if err != nil {
823 if herrors.IsTimeoutError(err) {
824 err = fmt.Errorf("timed out rendering the page content. Extend the `timeout` limit in your Hugo config file: %w", err)
825 }
826 return contentPlainPlainWords{}, err
827 }
828 return v.Value, nil
829 }
830
831 type cachedContentScope struct {
832 *cachedContent
833 pco *pageContentOutput
834 scope string
835 }
836
837 func (c *cachedContentScope) prepareContext(ctx context.Context) context.Context {
838 // A regular page's shortcode etc. may be rendered by e.g. the home page,
839 // so we need to track any changes to this content's page.
840 ctx = tpl.Context.DependencyManagerScopedProvider.Set(ctx, c.pco.po.p)
841
842 // The markup scope is recursive, so if already set to a non zero value, preserve that value.
843 if s := hugo.GetMarkupScope(ctx); s != "" || s == c.scope {
844 return ctx
845 }
846 return hugo.SetMarkupScope(ctx, c.scope)
847 }
848
849 func (c *cachedContentScope) Render(ctx context.Context) (page.Content, error) {
850 return c, nil
851 }
852
853 func (c *cachedContentScope) Content(ctx context.Context) (template.HTML, error) {
854 ctx = c.prepareContext(ctx)
855 cr, err := c.contentRendered(ctx)
856 if err != nil {
857 return "", err
858 }
859 return cr.content, nil
860 }
861
862 func (c *cachedContentScope) ContentWithoutSummary(ctx context.Context) (template.HTML, error) {
863 ctx = c.prepareContext(ctx)
864 cr, err := c.contentRendered(ctx)
865 if err != nil {
866 return "", err
867 }
868 return cr.contentWithoutSummary, nil
869 }
870
871 func (c *cachedContentScope) Summary(ctx context.Context) (page.Summary, error) {
872 ctx = c.prepareContext(ctx)
873 rendered, err := c.contentRendered(ctx)
874 return rendered.summary, err
875 }
876
877 func (c *cachedContentScope) RenderString(ctx context.Context, args ...any) (template.HTML, error) {
878 ctx = c.prepareContext(ctx)
879
880 if len(args) < 1 || len(args) > 2 {
881 return "", errors.New("want 1 or 2 arguments")
882 }
883
884 pco := c.pco
885
886 var contentToRender string
887 opts := defaultRenderStringOpts
888 sidx := 1
889
890 if len(args) == 1 {
891 sidx = 0
892 } else {
893 m, ok := args[0].(map[string]any)
894 if !ok {
895 return "", errors.New("first argument must be a map")
896 }
897
898 if err := mapstructure.WeakDecode(m, &opts); err != nil {
899 return "", fmt.Errorf("failed to decode options: %w", err)
900 }
901 if opts.Markup != "" {
902 opts.Markup = markup.ResolveMarkup(opts.Markup)
903 }
904 }
905
906 contentToRenderv := args[sidx]
907
908 if _, ok := contentToRenderv.(hstring.HTML); ok {
909 // This content is already rendered, this is potentially
910 // a infinite recursion.
911 return "", errors.New("text is already rendered, repeating it may cause infinite recursion")
912 }
913
914 var err error
915 contentToRender, err = cast.ToStringE(contentToRenderv)
916 if err != nil {
917 return "", err
918 }
919
920 if err = pco.initRenderHooks(); err != nil {
921 return "", err
922 }
923
924 conv := pco.po.p.getContentConverter()
925
926 if opts.Markup != "" && opts.Markup != pco.po.p.m.pageConfigSource.ContentMediaType.SubType {
927 var err error
928 conv, err = pco.po.p.m.newContentConverter(pco.po.p, opts.Markup)
929 if err != nil {
930 return "", pco.po.p.wrapError(err)
931 }
932 }
933
934 var rendered []byte
935
936 parseInfo := &contentParseInfo{
937 h: pco.po.p.s.h,
938 sid: pco.po.p.pid,
939 }
940
941 if pageparser.HasShortcode(contentToRender) {
942 ct := contentTableOfContents{
943 filename: pco.po.p.pathOrTitle() + " (rendered from string)",
944 source: []byte(contentToRender),
945 }
946 ct.contentToRender = ct.source
947 // String contains a shortcode.
948 parseInfo.itemsStep1, err = pageparser.ParseBytes(ct.source, pageparser.Config{
949 NoFrontMatter: true,
950 NoSummaryDivider: true,
951 })
952 if err != nil {
953 return "", err
954 }
955
956 parseInfo.shortcodeParseInfo = newShortcodeHandler(pco.po.p.pathOrTitle(), pco.po.p.s.h.Deps)
957 if err := parseInfo.parseSource(ct.source, true); err != nil {
958 return "", err
959 }
960
961 placeholders, err := parseInfo.shortcodeParseInfo.prepareShortcodesForPage(pco.po, true)
962 if err != nil {
963 return "", err
964 }
965
966 var hasVariants bool
967 ct.contentToRender, ct.sourceMap, hasVariants, err = parseInfo.contentToRender(ctx, ct.source, placeholders)
968 if err != nil {
969 return "", err
970 }
971 if hasVariants {
972 pco.po.p.incrPageOutputTemplateVariation()
973 }
974 b, err := pco.renderContentWithConverter(ctx, conv, ct.contentToRender, ct.sourceInfo, false)
975 if err != nil {
976 return "", pco.po.p.wrapError(err)
977 }
978 rendered = b.Bytes()
979
980 if parseInfo.hasNonMarkdownShortcode {
981 var hasShortcodeVariants bool
982
983 tokenHandler := func(ctx context.Context, token string) ([]byte, error) {
984 if token == tocShortcodePlaceholder {
985 toc, err := c.contentToC(ctx)
986 if err != nil {
987 return nil, err
988 }
989 // The Page's TableOfContents was accessed in a shortcode.
990 return []byte(toc.tableOfContentsHTML), nil
991 }
992 renderer, found := placeholders[token]
993 if found {
994 repl, more, err := renderer.renderShortcode(ctx)
995 if err != nil {
996 return nil, err
997 }
998 hasShortcodeVariants = hasShortcodeVariants || more
999 return repl, nil
1000 }
1001 // This should not happen.
1002 return nil, fmt.Errorf("RenderString: unknown shortcode token %q", token)
1003 }
1004
1005 rendered, err = expandShortcodeTokens(ctx, rendered, tokenHandler)
1006 if err != nil {
1007 return "", err
1008 }
1009 if hasShortcodeVariants {
1010 pco.po.p.incrPageOutputTemplateVariation()
1011 }
1012 }
1013
1014 // We need a consolidated view in $page.HasShortcode
1015 combined := pco.po.p.m.content.hasShortcode.Load().Or(parseInfo.shortcodeParseInfo.hasName)
1016 pco.po.p.m.content.hasShortcode.Store(&combined)
1017
1018 } else {
1019 si := sourceInfo{
1020 filename: pco.po.p.pathOrTitle() + " (rendered from string)",
1021 source: []byte(contentToRender),
1022 }
1023 c, err := pco.renderContentWithConverter(ctx, conv, si.source, si, false)
1024 if err != nil {
1025 return "", pco.po.p.wrapError(err)
1026 }
1027
1028 rendered = c.Bytes()
1029 }
1030
1031 if opts.Display == "inline" {
1032 markup := pco.po.p.m.pageConfigSource.Content.Markup
1033 if opts.Markup != "" {
1034 markup = pco.po.p.s.ContentSpec.ResolveMarkup(opts.Markup)
1035 }
1036 rendered = pco.po.p.s.ContentSpec.TrimShortHTML(rendered, markup)
1037 }
1038
1039 return template.HTML(string(rendered)), nil
1040 }
1041
1042 func (c *cachedContentScope) RenderShortcodes(ctx context.Context) (template.HTML, error) {
1043 ctx = c.prepareContext(ctx)
1044
1045 pco := c.pco
1046 content := pco.po.p.m.content
1047
1048 source, err := content.pi.contentSource(content)
1049 if err != nil {
1050 return "", err
1051 }
1052 ct, err := c.contentToC(ctx)
1053 if err != nil {
1054 return "", err
1055 }
1056
1057 var insertPlaceholders bool
1058 var hasVariants bool
1059 cb := setGetContentCallbackInContext.Get(ctx)
1060 if cb != nil {
1061 insertPlaceholders = true
1062 }
1063 cc := make([]byte, 0, len(source)+(len(source)/10))
1064 for _, it := range content.pi.itemsStep2 {
1065 switch v := it.(type) {
1066 case pageparser.Item:
1067 cc = append(cc, source[v.Pos():v.Pos()+len(v.Val(source))]...)
1068 case pageContentReplacement:
1069 // Ignore.
1070 case *shortcode:
1071 if !insertPlaceholders || !v.insertPlaceholder() {
1072 // Insert the rendered shortcode.
1073 renderedShortcode, found := ct.contentPlaceholders[v.placeholder]
1074 if !found {
1075 // This should never happen.
1076 panic(fmt.Sprintf("rendered shortcode %q not found", v.placeholder))
1077 }
1078
1079 b, more, err := renderedShortcode.renderShortcode(ctx)
1080 if err != nil {
1081 return "", fmt.Errorf("failed to render shortcode: %w", err)
1082 }
1083 hasVariants = hasVariants || more
1084 cc = append(cc, []byte(b)...)
1085
1086 } else {
1087 // Insert the placeholder so we can insert the content after
1088 // markdown processing.
1089 cc = append(cc, []byte(v.placeholder)...)
1090 }
1091 default:
1092 panic(fmt.Sprintf("unknown item type %T", it))
1093 }
1094 }
1095
1096 if hasVariants {
1097 pco.po.p.incrPageOutputTemplateVariation()
1098 }
1099
1100 if cb != nil {
1101 cb(pco, ct)
1102 }
1103
1104 if tpl.Context.IsInGoldmark.Get(ctx) {
1105 // This content will be parsed and rendered by Goldmark.
1106 // Wrap it in a special Hugo markup to assign the correct Page from
1107 // the stack.
1108 return template.HTML(hugocontext.Wrap(cc, pco.po.p.pid)), nil
1109 }
1110
1111 // Strip any Hugo context markers from nested RenderShortcodes calls
1112 // that won't be processed by Goldmark.
1113 cc = hugocontext.Strip(cc)
1114
1115 return helpers.BytesToHTML(cc), nil
1116 }
1117
1118 func (c *cachedContentScope) Plain(ctx context.Context) string {
1119 ctx = c.prepareContext(ctx)
1120 return c.mustContentPlain(ctx).plain
1121 }
1122
1123 func (c *cachedContentScope) PlainWords(ctx context.Context) []string {
1124 ctx = c.prepareContext(ctx)
1125 return c.mustContentPlain(ctx).plainWords
1126 }
1127
1128 func (c *cachedContentScope) WordCount(ctx context.Context) int {
1129 ctx = c.prepareContext(ctx)
1130 return c.mustContentPlain(ctx).wordCount
1131 }
1132
1133 func (c *cachedContentScope) FuzzyWordCount(ctx context.Context) int {
1134 ctx = c.prepareContext(ctx)
1135 return c.mustContentPlain(ctx).fuzzyWordCount
1136 }
1137
1138 func (c *cachedContentScope) ReadingTime(ctx context.Context) int {
1139 ctx = c.prepareContext(ctx)
1140 return c.mustContentPlain(ctx).readingTime
1141 }
1142
1143 func (c *cachedContentScope) Len(ctx context.Context) int {
1144 ctx = c.prepareContext(ctx)
1145 return len(c.mustContentRendered(ctx).content)
1146 }
1147
1148 func (c *cachedContentScope) Fragments(ctx context.Context) *tableofcontents.Fragments {
1149 ctx = c.prepareContext(ctx)
1150 toc := c.mustContentToC(ctx).tableOfContents
1151 if toc == nil {
1152 return nil
1153 }
1154 return toc
1155 }
1156
1157 func (c *cachedContentScope) fragmentsHTML(ctx context.Context) template.HTML {
1158 ctx = c.prepareContext(ctx)
1159 return c.mustContentToC(ctx).tableOfContentsHTML
1160 }
1161
1162 func (c *cachedContentScope) mustContentPlain(ctx context.Context) contentPlainPlainWords {
1163 r, err := c.contentPlain(ctx)
1164 if err != nil {
1165 c.pco.fail(err)
1166 }
1167 return r
1168 }
1169
1170 func (c *cachedContentScope) mustContentRendered(ctx context.Context) contentSummary {
1171 r, err := c.contentRendered(ctx)
1172 if err != nil {
1173 c.pco.fail(err)
1174 }
1175 return r
1176 }