Insert code tag for server-side syntax highlighting
authorNathan Youngman <git@nathany.com>
Wed, 14 Oct 2015 21:10:50 +0000 (15:10 -0600)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Thu, 15 Oct 2015 15:59:28 +0000 (17:59 +0200)
Inserts a code tag into Pygments output with the language-info that is present when using client-side highlighting (useful for CSS hooks)

```html
<code class="language-go" data-lang="go">
```

closes #1490

helpers/content_renderer_test.go
helpers/pygments.go

index 90b4c4939bcecfcdd6469ba60fbf0e797f98b402..1c84818a208903ea1e7a0661e66e908bf215997e 100644 (file)
@@ -38,7 +38,7 @@ func TestCodeFence(t *testing.T) {
                input, expected string
        }
        data := []test{
-               {true, "<html></html>", "<div class=\"highlight\"><pre><span class=\"nt\">&lt;html&gt;&lt;/html&gt;</span>\n</pre></div>\n"},
+               {true, "<html></html>", "<div class=\"highlight\"><pre><code class=\"language-html\" data-lang=\"html\"><span class=\"nt\">&lt;html&gt;&lt;/html&gt;</span>\n</code></pre></div>\n"},
                {false, "<html></html>", "<pre><code class=\"language-html\">&lt;html&gt;&lt;/html&gt;</code></pre>\n"},
        }
 
index 29a5ec54f3a6aa3633d52db034fff6c139151f64..17c30ee0a11bfe82af01438f26dce2d200a8af7c 100644 (file)
@@ -111,14 +111,23 @@ func Highlight(code, lang, optsStr string) string {
                return code
        }
 
+       str := 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 cachefile != "" {
                // Write cache file
-               if err := WriteToDisk(cachefile, bytes.NewReader(out.Bytes()), fs); err != nil {
+               if err := WriteToDisk(cachefile, strings.NewReader(str), fs); err != nil {
                        jww.ERROR.Print(stderr.String())
                }
        }
 
-       return out.String()
+       return str
 }
 
 var pygmentsKeywords = make(map[string]bool)