// Copyright (C) 2018 Marius Schellenberger package render import ( "git.giftfish.de/ston1th/gowiki/pkg/core" "github.com/blevesearch/bleve/analysis" "github.com/blevesearch/bleve/analysis/char/html" "github.com/russross/blackfriday" "html/template" "regexp" "strconv" "strings" ) var filter = makeFilter() func makeFilter() analysis.CharFilter { f, _ := html.CharFilterConstructor(nil, nil) return f } var ( reHeader = regexp.MustCompile("()(.+)()") reLink = regexp.MustCompile(`id="(.+?)"`) whiteSpace = regexp.MustCompile(`\s+`) reIndex = regexp.MustCompile("(.+)") titleRe = regexp.MustCompile("[^a-zA-Z0-9 -]+") ) func Render(p *core.Page) string { rend := blackfriday.MarkdownCommon([]byte(p.Markdown)) toc, html := buildTOC(string(rend)) html = strings.Replace(html, "", `
`, -1) html = strings.Replace(html, "", `
`, -1) html = strings.Replace(html, "${1}${2}${3}`) html = reLink.ReplaceAllStringFunc(html, func(s string) string { if len(s) >= 3 { return `id="` + Title(s[2:]) + `"` } return s }) for k, v := range hn { link := Title(v[2]) i := m[link] m[link] = i + 1 newLink := link + strconv.Itoa(i) html = strings.Replace(html, link+`"`, newLink+`"`, 1) toc += before(hn, k) toc += `
  • ` + v[2] + "" toc += after(hn, k) } return toc, html } func before(arr [][]string, i int) string { c, _ := strconv.Atoi(arr[i][1]) if c == 1 { return `
      ` } return "" } func after(arr [][]string, i int) string { c, _ := strconv.Atoi(arr[i][1]) if len(arr) <= i+1 { return closeTag(c-1) + "
    " } n, _ := strconv.Atoi(arr[i+1][1]) switch { case n == 1: return closeTag(c-n) + "" case n < c: return closeTag(c - n) case n > c: return openTag(n - c) case n == c: return "
  • " } return "" } func openTag(j int) (ret string) { for i := 0; i < j; i++ { ret += `" } if j > 1 { ret = strings.Replace(ret, "", "", -1) } return }