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