Debian Codegraph @

present/parse.go

raw symbols SCIP
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package present
6
7 import (
8 "bufio"
9 "bytes"
10 "errors"
11 "fmt"
12 "html/template"
13 "io"
14 "log"
15 "net/url"
16 "os"
17 "regexp"
18 "slices"
19 "strings"
20 "time"
21 "unicode"
22 "unicode/utf8"
23
24 "github.com/yuin/goldmark"
25 "github.com/yuin/goldmark/ast"
26 "github.com/yuin/goldmark/renderer/html"
27 "github.com/yuin/goldmark/text"
28 )
29
30 var (
31 parsers = make(map[string]ParseFunc)
32 funcs = template.FuncMap{}
33 )
34
35 // Template returns an empty template with the action functions in its FuncMap.
36 func Template() *template.Template {
37 return template.New("").Funcs(funcs)
38 }
39
40 // Render renders the doc to the given writer using the provided template.
41 func (d *Doc) Render(w io.Writer, t *template.Template) error {
42 data := struct {
43 *Doc
44 Template *template.Template
45 PlayEnabled bool
46 NotesEnabled bool
47 }{d, t, PlayEnabled, NotesEnabled}
48 return t.ExecuteTemplate(w, "root", data)
49 }
50
51 // Render renders the section to the given writer using the provided template.
52 func (s *Section) Render(w io.Writer, t *template.Template) error {
53 data := struct {
54 *Section
55 Template *template.Template
56 PlayEnabled bool
57 }{s, t, PlayEnabled}
58 return t.ExecuteTemplate(w, "section", data)
59 }
60
61 type ParseFunc func(ctx *Context, fileName string, lineNumber int, inputLine string) (Elem, error)
62
63 // Register binds the named action, which does not begin with a period, to the
64 // specified parser to be invoked when the name, with a period, appears in the
65 // present input text.
66 func Register(name string, parser ParseFunc) {
67 if len(name) == 0 || name[0] == ';' {
68 panic("bad name in Register: " + name)
69 }
70 parsers["."+name] = parser
71 }
72
73 // Doc represents an entire document.
74 type Doc struct {
75 Title string
76 Subtitle string
77 Summary string
78 Time time.Time
79 Authors []Author
80 TitleNotes []string
81 Sections []Section
82 Tags []string
83 OldURL []string
84 }
85
86 // Author represents the person who wrote and/or is presenting the document.
87 type Author struct {
88 Elem []Elem
89 }
90
91 // TextElem returns the first text elements of the author details.
92 // This is used to display the author' name, job title, and company
93 // without the contact details.
94 func (p *Author) TextElem() (elems []Elem) {
95 for _, el := range p.Elem {
96 if _, ok := el.(Text); !ok {
97 break
98 }
99 elems = append(elems, el)
100 }
101 return
102 }
103
104 // Section represents a section of a document (such as a presentation slide)
105 // comprising a title and a list of elements.
106 type Section struct {
107 Number []int
108 Title string
109 ID string // HTML anchor ID
110 Elem []Elem
111 Notes []string
112 Classes []string
113 Styles []string
114 }
115
116 // HTMLAttributes for the section
117 func (s Section) HTMLAttributes() template.HTMLAttr {
118 if len(s.Classes) == 0 && len(s.Styles) == 0 {
119 return ""
120 }
121
122 var class string
123 if len(s.Classes) > 0 {
124 class = fmt.Sprintf(`class=%q`, strings.Join(s.Classes, " "))
125 }
126 var style string
127 if len(s.Styles) > 0 {
128 style = fmt.Sprintf(`style=%q`, strings.Join(s.Styles, " "))
129 }
130 return template.HTMLAttr(strings.Join([]string{class, style}, " "))
131 }
132
133 // Sections contained within the section.
134 func (s Section) Sections() (sections []Section) {
135 for _, e := range s.Elem {
136 if section, ok := e.(Section); ok {
137 sections = append(sections, section)
138 }
139 }
140 return
141 }
142
143 // Level returns the level of the given section.
144 // The document title is level 1, main section 2, etc.
145 func (s Section) Level() int {
146 return len(s.Number) + 1
147 }
148
149 // FormattedNumber returns a string containing the concatenation of the
150 // numbers identifying a Section.
151 func (s Section) FormattedNumber() string {
152 b := &bytes.Buffer{}
153 for _, n := range s.Number {
154 fmt.Fprintf(b, "%v.", n)
155 }
156 return b.String()
157 }
158
159 func (s Section) TemplateName() string { return "section" }
160
161 // Elem defines the interface for a present element. That is, something that
162 // can provide the name of the template used to render the element.
163 type Elem interface {
164 TemplateName() string
165 }
166
167 // renderElem implements the elem template function, used to render
168 // sub-templates.
169 func renderElem(t *template.Template, e Elem) (template.HTML, error) {
170 var data any = e
171 if s, ok := e.(Section); ok {
172 data = struct {
173 Section
174 Template *template.Template
175 }{s, t}
176 }
177 return execTemplate(t, e.TemplateName(), data)
178 }
179
180 // pageNum derives a page number from a section.
181 func pageNum(s Section, offset int) int {
182 if len(s.Number) == 0 {
183 return offset
184 }
185 return s.Number[0] + offset
186 }
187
188 func init() {
189 funcs["elem"] = renderElem
190 funcs["pagenum"] = pageNum
191 }
192
193 // execTemplate is a helper to execute a template and return the output as a
194 // template.HTML value.
195 func execTemplate(t *template.Template, name string, data any) (template.HTML, error) {
196 b := new(bytes.Buffer)
197 err := t.ExecuteTemplate(b, name, data)
198 if err != nil {
199 return "", err
200 }
201 return template.HTML(b.String()), nil
202 }
203
204 // Text represents an optionally preformatted paragraph.
205 type Text struct {
206 Lines []string
207 Pre bool
208 Raw string // original text, for Pre==true
209 }
210
211 func (t Text) TemplateName() string { return "text" }
212
213 // List represents a bulleted list.
214 type List struct {
215 Bullet []string
216 }
217
218 func (l List) TemplateName() string { return "list" }
219
220 // Lines is a helper for parsing line-based input.
221 type Lines struct {
222 line int // 0 indexed, so has 1-indexed number of last line returned
223 text []string
224 comment string
225 }
226
227 func readLines(r io.Reader) (*Lines, error) {
228 var lines []string
229 s := bufio.NewScanner(r)
230 for s.Scan() {
231 lines = append(lines, s.Text())
232 }
233 if err := s.Err(); err != nil {
234 return nil, err
235 }
236 return &Lines{0, lines, "#"}, nil
237 }
238
239 func (l *Lines) next() (text string, ok bool) {
240 for {
241 current := l.line
242 l.line++
243 if current >= len(l.text) {
244 return "", false
245 }
246 text = l.text[current]
247 // Lines starting with l.comment are comments.
248 if l.comment == "" || !strings.HasPrefix(text, l.comment) {
249 ok = true
250 break
251 }
252 }
253 return
254 }
255
256 func (l *Lines) back() {
257 l.line--
258 }
259
260 func (l *Lines) nextNonEmpty() (text string, ok bool) {
261 for {
262 text, ok = l.next()
263 if !ok {
264 return
265 }
266 if len(text) > 0 {
267 break
268 }
269 }
270 return
271 }
272
273 // A Context specifies the supporting context for parsing a presentation.
274 type Context struct {
275 // ReadFile reads the file named by filename and returns the contents.
276 ReadFile func(filename string) ([]byte, error)
277 }
278
279 // ParseMode represents flags for the Parse function.
280 type ParseMode int
281
282 const (
283 // If set, parse only the title and subtitle.
284 TitlesOnly ParseMode = 1
285 )
286
287 // Parse parses a document from r.
288 func (ctx *Context) Parse(r io.Reader, name string, mode ParseMode) (*Doc, error) {
289 doc := new(Doc)
290 lines, err := readLines(r)
291 if err != nil {
292 return nil, err
293 }
294
295 // Detect Markdown-enabled vs legacy present file.
296 // Markdown-enabled files have a title line beginning with "# "
297 // (like preprocessed C files of yore).
298 isMarkdown := false
299 for i := lines.line; i < len(lines.text); i++ {
300 line := lines.text[i]
301 if line == "" {
302 continue
303 }
304 isMarkdown = strings.HasPrefix(line, "# ")
305 break
306 }
307
308 sectionPrefix := "*"
309 if isMarkdown {
310 sectionPrefix = "##"
311 lines.comment = "//"
312 }
313
314 for i := lines.line; i < len(lines.text); i++ {
315 if strings.HasPrefix(lines.text[i], sectionPrefix) {
316 break
317 }
318
319 if isSpeakerNote(lines.text[i]) {
320 doc.TitleNotes = append(doc.TitleNotes, trimSpeakerNote(lines.text[i]))
321 }
322 }
323
324 err = parseHeader(doc, isMarkdown, lines)
325 if err != nil {
326 return nil, err
327 }
328 if mode&TitlesOnly != 0 {
329 return doc, nil
330 }
331
332 // Authors
333 if doc.Authors, err = parseAuthors(name, sectionPrefix, lines); err != nil {
334 return nil, err
335 }
336
337 // Sections
338 if doc.Sections, err = parseSections(ctx, name, sectionPrefix, lines, []int{}); err != nil {
339 return nil, err
340 }
341
342 return doc, nil
343 }
344
345 // Parse parses a document from r. Parse reads assets used by the presentation
346 // from the file system using os.ReadFile.
347 func Parse(r io.Reader, name string, mode ParseMode) (*Doc, error) {
348 ctx := Context{ReadFile: os.ReadFile}
349 return ctx.Parse(r, name, mode)
350 }
351
352 // isHeading matches any section heading.
353 var (
354 isHeadingLegacy = regexp.MustCompile(`^\*+( |$)`)
355 isHeadingMarkdown = regexp.MustCompile(`^\#+( |$)`)
356 )
357
358 // lesserHeading returns true if text is a heading of a lesser or equal level
359 // than that denoted by prefix.
360 func lesserHeading(isHeading *regexp.Regexp, text, prefix string) bool {
361 return isHeading.MatchString(text) && !strings.HasPrefix(text, prefix+prefix[:1])
362 }
363
364 // parseSections parses Sections from lines for the section level indicated by
365 // number (a nil number indicates the top level).
366 func parseSections(ctx *Context, name, prefix string, lines *Lines, number []int) ([]Section, error) {
367 isMarkdown := prefix[0] == '#'
368 isHeading := isHeadingLegacy
369 if isMarkdown {
370 isHeading = isHeadingMarkdown
371 }
372 var sections []Section
373 for i := 1; ; i++ {
374 // Next non-empty line is title.
375 text, ok := lines.nextNonEmpty()
376 for ok && text == "" {
377 text, ok = lines.next()
378 }
379 if !ok {
380 break
381 }
382 if text != prefix && !strings.HasPrefix(text, prefix+" ") {
383 lines.back()
384 break
385 }
386 // Markdown sections can end in {#id} to set the HTML anchor for the section.
387 // This is nicer than the default #TOC_1_2-style anchor.
388 title := strings.TrimSpace(text[len(prefix):])
389 id := ""
390 if isMarkdown && strings.HasSuffix(title, "}") {
391 j := strings.LastIndex(title, "{#")
392 if j >= 0 {
393 id = title[j+2 : len(title)-1]
394 title = strings.TrimSpace(title[:j])
395 }
396 }
397 section := Section{
398 Number: append(slices.Clone(number), i),
399 Title: title,
400 ID: id,
401 }
402 text, ok = lines.nextNonEmpty()
403 for ok && !lesserHeading(isHeading, text, prefix) {
404 var e Elem
405 r, _ := utf8.DecodeRuneInString(text)
406 switch {
407 case !isMarkdown && unicode.IsSpace(r):
408 i := strings.IndexFunc(text, func(r rune) bool {
409 return !unicode.IsSpace(r)
410 })
411 if i < 0 {
412 break
413 }
414 indent := text[:i]
415 var s []string
416 for ok && (strings.HasPrefix(text, indent) || text == "") {
417 if text != "" {
418 text = text[i:]
419 }
420 s = append(s, text)
421 text, ok = lines.next()
422 }
423 lines.back()
424 pre := strings.Join(s, "\n")
425 raw := pre
426 pre = strings.Replace(pre, "\t", " ", -1) // browsers treat tabs badly
427 pre = strings.TrimRightFunc(pre, unicode.IsSpace)
428 e = Text{Lines: []string{pre}, Pre: true, Raw: raw}
429 case !isMarkdown && strings.HasPrefix(text, "- "):
430 var b []string
431 for {
432 if strings.HasPrefix(text, "- ") {
433 b = append(b, text[2:])
434 } else if len(b) > 0 && strings.HasPrefix(text, " ") {
435 b[len(b)-1] += "\n" + strings.TrimSpace(text)
436 } else {
437 break
438 }
439 if text, ok = lines.next(); !ok {
440 break
441 }
442 }
443 lines.back()
444 e = List{Bullet: b}
445 case isSpeakerNote(text):
446 section.Notes = append(section.Notes, trimSpeakerNote(text))
447 case strings.HasPrefix(text, prefix+prefix[:1]+" ") || text == prefix+prefix[:1]:
448 lines.back()
449 subsecs, err := parseSections(ctx, name, prefix+prefix[:1], lines, section.Number)
450 if err != nil {
451 return nil, err
452 }
453 for _, ss := range subsecs {
454 section.Elem = append(section.Elem, ss)
455 }
456 case strings.HasPrefix(text, prefix+prefix[:1]):
457 return nil, fmt.Errorf("%s:%d: badly nested section inside %s: %s", name, lines.line, prefix, text)
458 case strings.HasPrefix(text, "."):
459 args := strings.Fields(text)
460 if args[0] == ".background" {
461 section.Classes = append(section.Classes, "background")
462 section.Styles = append(section.Styles, "background-image: url('"+args[1]+"')")
463 break
464 }
465 parser := parsers[args[0]]
466 if parser == nil {
467 return nil, fmt.Errorf("%s:%d: unknown command %q", name, lines.line, text)
468 }
469 t, err := parser(ctx, name, lines.line, text)
470 if err != nil {
471 return nil, err
472 }
473 e = t
474
475 case isMarkdown:
476 // Collect Markdown lines, including blank lines and indented text.
477 var block []string
478 endLine, endBlock := lines.line-1, -1 // end is last non-empty line
479 for ok {
480 trim := strings.TrimSpace(text)
481 if trim != "" {
482 // Command breaks text block.
483 // Section heading breaks text block in markdown.
484 if text[0] == '.' || text[0] == '#' || isSpeakerNote(text) {
485 break
486 }
487 if strings.HasPrefix(text, `\.`) { // Backslash escapes initial period.
488 text = text[1:]
489 }
490 endLine, endBlock = lines.line, len(block)
491 }
492 block = append(block, text)
493 text, ok = lines.next()
494 }
495 block = block[:endBlock+1]
496 lines.line = endLine + 1
497 if len(block) == 0 {
498 break
499 }
500
501 // Replace all leading tabs with 4 spaces,
502 // which render better in code blocks.
503 // CommonMark defines that for parsing the structure of the file
504 // a tab is equivalent to 4 spaces, so this change won't
505 // affect the later parsing at all.
506 // An alternative would be to apply this to code blocks after parsing,
507 // at the same time that we update <a> targets, but that turns out
508 // to be quite difficult to modify in the AST.
509 for i, line := range block {
510 if len(line) > 0 && line[0] == '\t' {
511 short := strings.TrimLeft(line, "\t")
512 line = strings.Repeat(" ", len(line)-len(short)) + short
513 block[i] = line
514 }
515 }
516 html, err := renderMarkdown([]byte(strings.Join(block, "\n")))
517 if err != nil {
518 return nil, err
519 }
520 e = HTML{HTML: html}
521
522 default:
523 // Collect text lines.
524 var block []string
525 for ok && strings.TrimSpace(text) != "" {
526 // Command breaks text block.
527 // Section heading breaks text block in markdown.
528 if text[0] == '.' || isSpeakerNote(text) {
529 lines.back()
530 break
531 }
532 if strings.HasPrefix(text, `\.`) { // Backslash escapes initial period.
533 text = text[1:]
534 }
535 block = append(block, text)
536 text, ok = lines.next()
537 }
538 if len(block) == 0 {
539 break
540 }
541 e = Text{Lines: block}
542 }
543 if e != nil {
544 section.Elem = append(section.Elem, e)
545 }
546 text, ok = lines.nextNonEmpty()
547 }
548 if isHeading.MatchString(text) {
549 lines.back()
550 }
551 sections = append(sections, section)
552 }
553
554 if len(sections) == 0 {
555 return nil, fmt.Errorf("%s:%d: unexpected line: %s", name, lines.line+1, lines.text[lines.line])
556 }
557 return sections, nil
558 }
559
560 func parseHeader(doc *Doc, isMarkdown bool, lines *Lines) error {
561 var ok bool
562 // First non-empty line starts header.
563 doc.Title, ok = lines.nextNonEmpty()
564 if !ok {
565 return errors.New("unexpected EOF; expected title")
566 }
567 if isMarkdown {
568 doc.Title = strings.TrimSpace(strings.TrimPrefix(doc.Title, "#"))
569 }
570
571 for {
572 text, ok := lines.next()
573 if !ok {
574 return errors.New("unexpected EOF")
575 }
576 if text == "" {
577 break
578 }
579 if isSpeakerNote(text) {
580 continue
581 }
582 if strings.HasPrefix(text, "Tags:") {
583 tags := strings.Split(text[len("Tags:"):], ",")
584 for i := range tags {
585 tags[i] = strings.TrimSpace(tags[i])
586 }
587 doc.Tags = append(doc.Tags, tags...)
588 } else if strings.HasPrefix(text, "Summary:") {
589 doc.Summary = strings.TrimSpace(text[len("Summary:"):])
590 } else if strings.HasPrefix(text, "OldURL:") {
591 doc.OldURL = append(doc.OldURL, strings.TrimSpace(text[len("OldURL:"):]))
592 } else if t, ok := parseTime(text); ok {
593 doc.Time = t
594 } else if doc.Subtitle == "" {
595 doc.Subtitle = text
596 } else {
597 return fmt.Errorf("unexpected header line: %q", text)
598 }
599 }
600 return nil
601 }
602
603 func parseAuthors(name, sectionPrefix string, lines *Lines) (authors []Author, err error) {
604 // This grammar demarcates authors with blanks.
605
606 // Skip blank lines.
607 if _, ok := lines.nextNonEmpty(); !ok {
608 return nil, errors.New("unexpected EOF")
609 }
610 lines.back()
611
612 var a *Author
613 for {
614 text, ok := lines.next()
615 if !ok {
616 return nil, errors.New("unexpected EOF")
617 }
618
619 // If we find a section heading, we're done.
620 if strings.HasPrefix(text, sectionPrefix) {
621 lines.back()
622 break
623 }
624
625 if isSpeakerNote(text) {
626 continue
627 }
628
629 // If we encounter a blank we're done with this author.
630 if a != nil && len(text) == 0 {
631 authors = append(authors, *a)
632 a = nil
633 continue
634 }
635 if a == nil {
636 a = new(Author)
637 }
638
639 // Parse the line. Those that
640 // - begin with @ are twitter names,
641 // - contain slashes are links, or
642 // - contain an @ symbol are an email address.
643 // The rest is just text.
644 var el Elem
645 switch {
646 case strings.HasPrefix(text, "@"):
647 el = parseAuthorURL(name, "http://twitter.com/"+text[1:])
648 case strings.Contains(text, ":"):
649 el = parseAuthorURL(name, text)
650 case strings.Contains(text, "@"):
651 el = parseAuthorURL(name, "mailto:"+text)
652 }
653 if l, ok := el.(Link); ok {
654 l.Label = text
655 el = l
656 }
657 if el == nil {
658 el = Text{Lines: []string{text}}
659 }
660 a.Elem = append(a.Elem, el)
661 }
662 if a != nil {
663 authors = append(authors, *a)
664 }
665 return authors, nil
666 }
667
668 func parseAuthorURL(name, text string) Elem {
669 u, err := url.Parse(text)
670 if err != nil {
671 log.Printf("parsing %s author block: invalid URL %q: %v", name, text, err)
672 return nil
673 }
674 return Link{URL: u}
675 }
676
677 func parseTime(text string) (t time.Time, ok bool) {
678 t, err := time.Parse("15:04 2 Jan 2006", text)
679 if err == nil {
680 return t, true
681 }
682 t, err = time.Parse("2 Jan 2006", text)
683 if err == nil {
684 // at 11am UTC it is the same date everywhere
685 t = t.Add(time.Hour * 11)
686 return t, true
687 }
688 return time.Time{}, false
689 }
690
691 func isSpeakerNote(s string) bool {
692 return strings.HasPrefix(s, ": ") || s == ":"
693 }
694
695 func trimSpeakerNote(s string) string {
696 if s == ":" {
697 return ""
698 }
699 return strings.TrimPrefix(s, ": ")
700 }
701
702 func renderMarkdown(input []byte) (template.HTML, error) {
703 md := goldmark.New(goldmark.WithRendererOptions(html.WithUnsafe()))
704 reader := text.NewReader(input)
705 doc := md.Parser().Parse(reader)
706 fixupMarkdown(doc)
707 var b strings.Builder
708 if err := md.Renderer().Render(&b, input, doc); err != nil {
709 return "", err
710 }
711 return template.HTML(b.String()), nil
712 }
713
714 func fixupMarkdown(n ast.Node) {
715 ast.Walk(n, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
716 if entering {
717 switch n := n.(type) {
718 case *ast.Link:
719 n.SetAttributeString("target", []byte("_blank"))
720 // https://developers.google.com/web/tools/lighthouse/audits/noopener
721 n.SetAttributeString("rel", []byte("noopener"))
722 }
723 }
724 return ast.WalkContinue, nil
725 })
726 }