hugo/helpers/pygments.go

238 lines
5.5 KiB
Go
Raw Normal View History

// Copyright 2016 The Hugo Authors. All rights reserved.
2013-12-05 09:42:29 -05:00
//
2015-11-23 22:16:36 -05:00
// Licensed under the Apache License, Version 2.0 (the "License");
2013-12-05 09:42:29 -05:00
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2015-11-23 22:16:36 -05:00
// http://www.apache.org/licenses/LICENSE-2.0
2013-12-05 09:42:29 -05:00
//
// 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 helpers
import (
2014-01-29 17:50:31 -05:00
"bytes"
"crypto/sha1"
"fmt"
"io"
"io/ioutil"
2014-01-29 17:50:31 -05:00
"os/exec"
"path/filepath"
"sort"
2014-01-29 17:50:31 -05:00
"strings"
"github.com/spf13/hugo/hugofs"
jww "github.com/spf13/jwalterweatherman"
"github.com/spf13/viper"
2013-12-05 09:42:29 -05:00
)
Shortcode rewrite, take 2 This commit contains a restructuring and partial rewrite of the shortcode handling. Prior to this commit rendering of the page content was mingled with handling of the shortcodes. This led to several oddities. The new flow is: 1. Shortcodes are extracted from page and replaced with placeholders. 2. Shortcodes are processed and rendered 3. Page is processed 4. The placeholders are replaced with the rendered shortcodes The handling of summaries is also made simpler by this. This commit also introduces some other chenges: 1. distinction between shortcodes that need further processing and those who do not: * `{{< >}}`: Typically raw HTML. Will not be processed. * `{{% %}}`: Will be processed by the page's markup engine (Markdown or (infuture) Asciidoctor) The above also involves a new shortcode-parser, with lexical scanning inspired by Rob Pike's talk called "Lexical Scanning in Go", which should be easier to understand, give better error messages and perform better. 2. If you want to exclude a shortcode from being processed (for documentation etc.), the inner part of the shorcode must be commented out, i.e. `{{%/* movie 47238zzb */%}}`. See the updated shortcode section in the documentation for further examples. The new parser supports nested shortcodes. This isn't new, but has two related design choices worth mentioning: * The shortcodes will be rendered individually, so If both `{{< >}}` and `{{% %}}` are used in the nested hierarchy, one will be passed through the page's markdown processor, the other not. * To avoid potential costly overhead of always looking far ahead for a possible closing tag, this implementation looks at the template itself, and is branded as a container with inner content if it contains a reference to `.Inner` Fixes #565 Fixes #480 Fixes #461 And probably some others.
2014-10-27 16:48:30 -04:00
const pygmentsBin = "pygmentize"
2013-12-05 09:42:29 -05:00
// HasPygments checks to see if Pygments is installed and available
// on the system.
Shortcode rewrite, take 2 This commit contains a restructuring and partial rewrite of the shortcode handling. Prior to this commit rendering of the page content was mingled with handling of the shortcodes. This led to several oddities. The new flow is: 1. Shortcodes are extracted from page and replaced with placeholders. 2. Shortcodes are processed and rendered 3. Page is processed 4. The placeholders are replaced with the rendered shortcodes The handling of summaries is also made simpler by this. This commit also introduces some other chenges: 1. distinction between shortcodes that need further processing and those who do not: * `{{< >}}`: Typically raw HTML. Will not be processed. * `{{% %}}`: Will be processed by the page's markup engine (Markdown or (infuture) Asciidoctor) The above also involves a new shortcode-parser, with lexical scanning inspired by Rob Pike's talk called "Lexical Scanning in Go", which should be easier to understand, give better error messages and perform better. 2. If you want to exclude a shortcode from being processed (for documentation etc.), the inner part of the shorcode must be commented out, i.e. `{{%/* movie 47238zzb */%}}`. See the updated shortcode section in the documentation for further examples. The new parser supports nested shortcodes. This isn't new, but has two related design choices worth mentioning: * The shortcodes will be rendered individually, so If both `{{< >}}` and `{{% %}}` are used in the nested hierarchy, one will be passed through the page's markdown processor, the other not. * To avoid potential costly overhead of always looking far ahead for a possible closing tag, this implementation looks at the template itself, and is branded as a container with inner content if it contains a reference to `.Inner` Fixes #565 Fixes #480 Fixes #461 And probably some others.
2014-10-27 16:48:30 -04:00
func HasPygments() bool {
2014-01-29 17:50:31 -05:00
if _, err := exec.LookPath(pygmentsBin); err != nil {
Shortcode rewrite, take 2 This commit contains a restructuring and partial rewrite of the shortcode handling. Prior to this commit rendering of the page content was mingled with handling of the shortcodes. This led to several oddities. The new flow is: 1. Shortcodes are extracted from page and replaced with placeholders. 2. Shortcodes are processed and rendered 3. Page is processed 4. The placeholders are replaced with the rendered shortcodes The handling of summaries is also made simpler by this. This commit also introduces some other chenges: 1. distinction between shortcodes that need further processing and those who do not: * `{{< >}}`: Typically raw HTML. Will not be processed. * `{{% %}}`: Will be processed by the page's markup engine (Markdown or (infuture) Asciidoctor) The above also involves a new shortcode-parser, with lexical scanning inspired by Rob Pike's talk called "Lexical Scanning in Go", which should be easier to understand, give better error messages and perform better. 2. If you want to exclude a shortcode from being processed (for documentation etc.), the inner part of the shorcode must be commented out, i.e. `{{%/* movie 47238zzb */%}}`. See the updated shortcode section in the documentation for further examples. The new parser supports nested shortcodes. This isn't new, but has two related design choices worth mentioning: * The shortcodes will be rendered individually, so If both `{{< >}}` and `{{% %}}` are used in the nested hierarchy, one will be passed through the page's markdown processor, the other not. * To avoid potential costly overhead of always looking far ahead for a possible closing tag, this implementation looks at the template itself, and is branded as a container with inner content if it contains a reference to `.Inner` Fixes #565 Fixes #480 Fixes #461 And probably some others.
2014-10-27 16:48:30 -04:00
return false
}
return true
}
// Highlight takes some code and returns highlighted code.
func Highlight(code, lang, optsStr string) string {
Shortcode rewrite, take 2 This commit contains a restructuring and partial rewrite of the shortcode handling. Prior to this commit rendering of the page content was mingled with handling of the shortcodes. This led to several oddities. The new flow is: 1. Shortcodes are extracted from page and replaced with placeholders. 2. Shortcodes are processed and rendered 3. Page is processed 4. The placeholders are replaced with the rendered shortcodes The handling of summaries is also made simpler by this. This commit also introduces some other chenges: 1. distinction between shortcodes that need further processing and those who do not: * `{{< >}}`: Typically raw HTML. Will not be processed. * `{{% %}}`: Will be processed by the page's markup engine (Markdown or (infuture) Asciidoctor) The above also involves a new shortcode-parser, with lexical scanning inspired by Rob Pike's talk called "Lexical Scanning in Go", which should be easier to understand, give better error messages and perform better. 2. If you want to exclude a shortcode from being processed (for documentation etc.), the inner part of the shorcode must be commented out, i.e. `{{%/* movie 47238zzb */%}}`. See the updated shortcode section in the documentation for further examples. The new parser supports nested shortcodes. This isn't new, but has two related design choices worth mentioning: * The shortcodes will be rendered individually, so If both `{{< >}}` and `{{% %}}` are used in the nested hierarchy, one will be passed through the page's markdown processor, the other not. * To avoid potential costly overhead of always looking far ahead for a possible closing tag, this implementation looks at the template itself, and is branded as a container with inner content if it contains a reference to `.Inner` Fixes #565 Fixes #480 Fixes #461 And probably some others.
2014-10-27 16:48:30 -04:00
if !HasPygments() {
2014-04-09 15:08:47 -04:00
jww.WARN.Println("Highlighting requires Pygments to be installed and in the path")
2014-01-29 17:50:31 -05:00
return code
}
2013-12-05 09:42:29 -05:00
options, err := parsePygmentsOpts(optsStr)
if err != nil {
jww.ERROR.Print(err.Error())
return code
}
// Try to read from cache first
hash := sha1.New()
io.WriteString(hash, code)
io.WriteString(hash, lang)
io.WriteString(hash, options)
fs := hugofs.Os
ignoreCache := viper.GetBool("ignoreCache")
cacheDir := viper.GetString("cacheDir")
var cachefile string
if !ignoreCache && cacheDir != "" {
cachefile = filepath.Join(cacheDir, fmt.Sprintf("pygments-%x", hash.Sum(nil)))
exists, err := Exists(cachefile, fs)
if err != nil {
jww.ERROR.Print(err.Error())
return code
}
if exists {
f, err := fs.Open(cachefile)
if err != nil {
jww.ERROR.Print(err.Error())
return code
}
s, err := ioutil.ReadAll(f)
if err != nil {
jww.ERROR.Print(err.Error())
return code
}
return string(s)
}
}
// No cache file, render and cache it
2014-01-29 17:50:31 -05:00
var out bytes.Buffer
var stderr bytes.Buffer
var langOpt string
if lang == "" {
langOpt = "-g" // Try guessing the language
} else {
2015-10-12 14:47:06 -04:00
langOpt = "-l" + lang
}
cmd := exec.Command(pygmentsBin, langOpt, "-fhtml", "-O", options)
2014-01-29 17:50:31 -05:00
cmd.Stdin = strings.NewReader(code)
cmd.Stdout = &out
cmd.Stderr = &stderr
2013-12-05 09:42:29 -05:00
2014-01-29 17:50:31 -05:00
if err := cmd.Run(); err != nil {
jww.ERROR.Print(stderr.String())
2014-01-29 17:50:31 -05:00
return code
}
2013-12-05 09:42:29 -05:00
str := string(normalizeExternalHelperLineFeeds([]byte(out.String())))
// inject code tag into Pygments output
if lang != "" && strings.Contains(str, "<pre>") {
codeTag := fmt.Sprintf(`<pre><code class="language-%s" data-lang="%s">`, lang, lang)
str = strings.Replace(str, "<pre>", codeTag, 1)
str = strings.Replace(str, "</pre>", "</code></pre>", 1)
}
if !ignoreCache && cachefile != "" {
// Write cache file
if err := WriteToDisk(cachefile, strings.NewReader(str), fs); err != nil {
jww.ERROR.Print(stderr.String())
}
}
return str
2013-12-05 09:42:29 -05:00
}
var pygmentsKeywords = make(map[string]bool)
func init() {
pygmentsKeywords["encoding"] = true
2015-12-07 12:00:28 -05:00
pygmentsKeywords["outencoding"] = true
pygmentsKeywords["nowrap"] = true
pygmentsKeywords["full"] = true
pygmentsKeywords["title"] = true
pygmentsKeywords["style"] = true
pygmentsKeywords["noclasses"] = true
2015-05-06 20:55:28 -04:00
pygmentsKeywords["classprefix"] = true
2015-12-07 12:00:28 -05:00
pygmentsKeywords["cssclass"] = true
pygmentsKeywords["cssstyles"] = true
pygmentsKeywords["prestyles"] = true
pygmentsKeywords["linenos"] = true
pygmentsKeywords["hl_lines"] = true
pygmentsKeywords["linenostart"] = true
pygmentsKeywords["linenostep"] = true
pygmentsKeywords["linenospecial"] = true
pygmentsKeywords["nobackground"] = true
pygmentsKeywords["lineseparator"] = true
2015-12-03 19:17:48 -05:00
pygmentsKeywords["lineanchors"] = true
pygmentsKeywords["linespans"] = true
2015-12-07 12:00:28 -05:00
pygmentsKeywords["anchorlinenos"] = true
2016-10-06 08:59:49 -04:00
pygmentsKeywords["startinline"] = true
}
func parseOptions(options map[string]string, in string) error {
in = strings.Trim(in, " ")
2016-03-19 12:12:10 -04:00
if in == "" {
return nil
}
for _, v := range strings.Split(in, ",") {
keyVal := strings.Split(v, "=")
key := strings.ToLower(strings.Trim(keyVal[0], " "))
if len(keyVal) != 2 || !pygmentsKeywords[key] {
return fmt.Errorf("invalid Pygments option: %s", key)
}
2016-03-19 12:12:10 -04:00
options[key] = keyVal[1]
}
return nil
}
func createOptionsString(options map[string]string) string {
var keys []string
for k := range options {
keys = append(keys, k)
}
sort.Strings(keys)
var optionsStr string
for i, k := range keys {
optionsStr += fmt.Sprintf("%s=%s", k, options[k])
if i < len(options)-1 {
optionsStr += ","
}
}
return optionsStr
}
func parseDefaultPygmentsOpts() (map[string]string, error) {
options := make(map[string]string)
err := parseOptions(options, viper.GetString("pygmentsOptions"))
if err != nil {
return nil, err
}
if viper.IsSet("pygmentsStyle") {
options["style"] = viper.GetString("pygmentsStyle")
}
if viper.IsSet("pygmentsUseClasses") {
if viper.GetBool("pygmentsUseClasses") {
options["noclasses"] = "false"
} else {
options["noclasses"] = "true"
}
}
if _, ok := options["encoding"]; !ok {
options["encoding"] = "utf8"
}
return options, nil
}
func parsePygmentsOpts(in string) (string, error) {
options, err := parseDefaultPygmentsOpts()
if err != nil {
return "", err
}
err = parseOptions(options, in)
if err != nil {
return "", err
}
return createOptionsString(options), nil
}