Skip to content

Commit 2f5412d

Browse files
committed
markup: add --citeproc to pandoc converter
Adds the citeproc filter to the pandoc converter. There are several PRs for it this feature already. However, I think simply adding `--citeproc` is the cleanest way to enable this feature, with the option to flesh it out later, e.g., in gohugoio#7529. Some PRs and issues attempt adding more config options to Hugo which indirectly configure pandoc, but I think simply configuring Pandoc via Pandoc itself is simpler, as it is already possible with two YAML blocks -- one for Hugo, and one for Pandoc: --- title: This is the Hugo YAML block --- --- bibliography: assets/pandoc-yaml-block-bibliography.bib ... Document content with @citation! There are other useful options, e.g., gohugoio#4800 attempts to use `nocite`, which works out of the box with this PR: --- title: This is the Hugo YAML block --- --- bibliography: assets/pandoc-yaml-block-bibliography.bib nocite: | @* ... Document content with no citations but a full bibliography: ## Bibliography Other useful options are `csl: ...` and `link-citations: true`, which set the path to a custom CSL file and create HTML links between the references and the bibliography. The following issues and PRs are related: - Add support for parsing citations and Jupyter notebooks via Pandoc and/or Goldmark extension gohugoio#6101 Bundles multiple requests, this PR tackles citation parsing. - WIP: Bibliography with Pandoc gohugoio#4800 Passes the frontmatter to Pandoc and still uses `--filter pandoc-citeproc` instead of `--citeproc`. - Allow configuring Pandoc gohugoio#7529 That PR is much more extensive and might eventually supersede this PR, but I think --bibliography and --citeproc should be independent options (--bibliography should be optional and citeproc can always be specified). - Pandoc - allow citeproc extension to be invoked, with bibliography. gohugoio#8610 Similar to gohugoio#7529, gohugoio#8610 adds a new config option to Hugo. I think passing --citeproc and letting the users decide on the metadata they want to pass to pandoc is better, albeit uglier.
1 parent 8e2fd55 commit 2f5412d

File tree

4 files changed

+228
-11
lines changed

4 files changed

+228
-11
lines changed

docs/content/en/content-management/formats.md

+57-5
Original file line numberDiff line numberDiff line change
@@ -48,21 +48,21 @@ Hugo passes reasonable default arguments to these external helpers by default:
4848

4949
- `asciidoctor`: `--no-header-footer -`
5050
- `rst2html`: `--leave-comments --initial-header-level=2`
51-
- `pandoc`: `--mathjax`
51+
- `pandoc`: `--mathjax` and, for pandoc >= 2.11, `--citeproc`
5252

5353
{{% warning "Performance of External Helpers" %}}
5454
Because additional formats are external commands, generation performance will rely heavily on the performance of the external tool you are using. As this feature is still in its infancy, feedback is welcome.
5555
{{% /warning %}}
5656

5757
### External Helper AsciiDoc
5858

59-
[AsciiDoc](https://github.com/asciidoc/asciidoc) implementation EOLs in Jan 2020 and is no longer supported.
60-
AsciiDoc development is being continued under [Asciidoctor](https://github.com/asciidoctor). The format AsciiDoc
59+
[AsciiDoc](https://github.com/asciidoc/asciidoc) implementation EOLs in Jan 2020 and is no longer supported.
60+
AsciiDoc development is being continued under [Asciidoctor](https://github.com/asciidoctor). The format AsciiDoc
6161
remains of course. Please continue with the implementation Asciidoctor.
6262

6363
### External Helper Asciidoctor
6464

65-
The Asciidoctor community offers a wide set of tools for the AsciiDoc format that can be installed additionally to Hugo.
65+
The Asciidoctor community offers a wide set of tools for the AsciiDoc format that can be installed additionally to Hugo.
6666
[See the Asciidoctor docs for installation instructions](https://asciidoctor.org/docs/install-toolchain/). Make sure that also all
6767
optional extensions like `asciidoctor-diagram` or `asciidoctor-html5s` are installed if required.
6868

@@ -110,13 +110,65 @@ Example of how to set extensions and attributes:
110110
my-attribute-name = "my value"
111111
```
112112

113-
In a complex Asciidoctor environment it is sometimes helpful to debug the exact call to your external helper with all
113+
In a complex Asciidoctor environment it is sometimes helpful to debug the exact call to your external helper with all
114114
parameters. Run Hugo with `-v`. You will get an output like
115115

116116
```
117117
INFO 2019/12/22 09:08:48 Rendering book-as-pdf.adoc with C:\Ruby26-x64\bin\asciidoctor.bat using asciidoc args [--no-header-footer -r asciidoctor-html5s -b html5s -r asciidoctor-diagram --base-dir D:\prototypes\hugo_asciidoc_ddd\docs -a outdir=D:\prototypes\hugo_asciidoc_ddd\build -] ...
118118
```
119119

120+
### External Helper Pandoc
121+
122+
[Pandoc](https://pandoc.org) is a universal document converter and can be used to convert markdown files.
123+
In Hugo, Pandoc can be used for LaTeX-style math (the `--mathjax` command line option is provided):
124+
125+
```
126+
---
127+
title: Math document
128+
---
129+
130+
Some inline math: $a^2 + b^2 = c^2$.
131+
```
132+
133+
This will render in your HTML as:
134+
135+
```
136+
<p>Some inline math: <span class="math inline">\(a^2 + b^2 = c^2\)</span></p>
137+
```
138+
You will have to [add MathJax](https://www.mathjax.org/#gettingstarted) to your template to properly render the math.
139+
140+
For **Pandoc >= 2.11**, you can use [citations](https://pandoc.org/MANUAL.html#extension-citations).
141+
One way is to employ [BibTeX files](https://en.wikibooks.org/wiki/LaTeX/Bibliography_Management#BibTeX) to cite:
142+
143+
```
144+
---
145+
title: Citation document
146+
---
147+
---
148+
bibliography: assets/bibliography.bib
149+
...
150+
This is a citation: @Doe2022
151+
```
152+
153+
Note that Hugo will **not** pass its metadata YAML block to Pandoc; however, it will pass the **second** meta data block, denoted with `---` and `...` to Pandoc.
154+
Thus, all Pandoc settings should go there.
155+
156+
You can also add all elements from a bibliography file (without citing them explicitly) using:
157+
158+
```
159+
---
160+
title: My Publications
161+
---
162+
---
163+
bibliography: assets/bibliography.bib
164+
nocite: |
165+
@*
166+
...
167+
```
168+
169+
It is also possible to provide a custom [CSL style](https://citationstyles.org/authors/) by passing `csl: path-to-style.csl` as a Pandoc option.
170+
171+
120172
## Learn Markdown
121173

122174
Markdown syntax is simple enough to learn in a single sitting. The following are excellent resources to get you up and running:

markup/pandoc/convert.go

+55-2
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,17 @@
1515
package pandoc
1616

1717
import (
18+
"bytes"
19+
"fmt"
20+
"strings"
21+
"sync"
22+
23+
"github.com/gohugoio/hugo/common/collections"
1824
"github.com/gohugoio/hugo/common/hexec"
1925
"github.com/gohugoio/hugo/htesting"
2026
"github.com/gohugoio/hugo/identity"
21-
"github.com/gohugoio/hugo/markup/internal"
22-
2327
"github.com/gohugoio/hugo/markup/converter"
28+
"github.com/gohugoio/hugo/markup/internal"
2429
)
2530

2631
// Provider is the package entry point.
@@ -65,6 +70,9 @@ func (c *pandocConverter) getPandocContent(src []byte, ctx converter.DocumentCon
6570
return src, nil
6671
}
6772
args := []string{"--mathjax"}
73+
if supportsCitations(c.cfg) {
74+
args = append(args[:], "--citeproc")
75+
}
6876
return internal.ExternallyRenderContent(c.cfg, ctx, src, binaryName, args)
6977
}
7078

@@ -77,6 +85,51 @@ func getPandocBinaryName() string {
7785
return ""
7886
}
7987

88+
var versionOnce sync.Once
89+
var pandocVersion string
90+
91+
// getPandocVersion parses the pandoc version output
92+
func getPandocVersion(cfg converter.ProviderConfig) (string, error) {
93+
var err error
94+
95+
versionOnce.Do(func() {
96+
argsv := collections.StringSliceToInterfaceSlice([]string{"--version"})
97+
98+
var out bytes.Buffer
99+
argsv = append(argsv, hexec.WithStdout(&out))
100+
101+
cmd, err := cfg.Exec.New(pandocBinary, argsv...)
102+
if err != nil {
103+
pandocVersion = ""
104+
return
105+
}
106+
107+
err = cmd.Run()
108+
if err != nil {
109+
cfg.Logger.Errorf("%s --version: %v", pandocBinary, err)
110+
}
111+
112+
outbytes := bytes.Replace(out.Bytes(), []byte("\r"), []byte(""), -1)
113+
output := strings.Split(string(outbytes), "\n")[0]
114+
pandocVersion = strings.Split(output, " ")[1]
115+
})
116+
117+
return pandocVersion, err
118+
}
119+
120+
// SupportsCitations returns true for pandoc versions >= 2.11, which include citeproc
121+
func supportsCitations(cfg converter.ProviderConfig) bool {
122+
pandocVersion, err := getPandocVersion(cfg)
123+
supportsCitations := pandocVersion >= "2.11" && err == nil
124+
if htesting.SupportsAll() {
125+
if !supportsCitations {
126+
panic(fmt.Sprintf("pandoc %s does not support citations", pandocVersion))
127+
}
128+
return true
129+
}
130+
return supportsCitations
131+
}
132+
80133
// Supports returns whether Pandoc is installed on this computer.
81134
func Supports() bool {
82135
hasBin := getPandocBinaryName() != ""

markup/pandoc/convert_test.go

+110-4
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,124 @@ import (
2525
qt "github.com/frankban/quicktest"
2626
)
2727

28-
func TestConvert(t *testing.T) {
28+
func setupTestConverter(t *testing.T) (*qt.C, converter.Converter, converter.ProviderConfig) {
2929
if !Supports() {
3030
t.Skip("pandoc not installed")
3131
}
3232
c := qt.New(t)
3333
sc := security.DefaultConfig
3434
sc.Exec.Allow = security.NewWhitelist("pandoc")
35-
p, err := Provider.New(converter.ProviderConfig{Exec: hexec.New(sc), Logger: loggers.NewErrorLogger()})
35+
cfg := converter.ProviderConfig{Exec: hexec.New(sc), Logger: loggers.NewErrorLogger()}
36+
p, err := Provider.New(cfg)
3637
c.Assert(err, qt.IsNil)
3738
conv, err := p.New(converter.DocumentContext{})
3839
c.Assert(err, qt.IsNil)
39-
b, err := conv.Convert(converter.RenderContext{Src: []byte("testContent")})
40+
return c, conv, cfg
41+
}
42+
43+
func TestConvert(t *testing.T) {
44+
c, conv, _ := setupTestConverter(t)
45+
output, err := conv.Convert(converter.RenderContext{Src: []byte("testContent")})
4046
c.Assert(err, qt.IsNil)
41-
c.Assert(string(b.Bytes()), qt.Equals, "<p>testContent</p>\n")
47+
c.Assert(string(output.Bytes()), qt.Equals, "<p>testContent</p>\n")
48+
}
49+
50+
func runCiteprocTest(t *testing.T, content string, expected string) {
51+
c, conv, cfg := setupTestConverter(t)
52+
if !supportsCitations(cfg) {
53+
t.Skip("pandoc does not support citations")
54+
}
55+
output, err := conv.Convert(converter.RenderContext{Src: []byte(content)})
56+
c.Assert(err, qt.IsNil)
57+
c.Assert(string(output.Bytes()), qt.Equals, expected)
58+
}
59+
60+
func TestGetPandocVersionCallTwice(t *testing.T) {
61+
c, _, cfg := setupTestConverter(t)
62+
63+
version1, err1 := getPandocVersion(cfg)
64+
version2, err2 := getPandocVersion(cfg)
65+
c.Assert(version1, qt.Equals, version2)
66+
c.Assert(err1, qt.IsNil)
67+
c.Assert(err2, qt.IsNil)
68+
}
69+
70+
func TestCiteprocWithHugoMeta(t *testing.T) {
71+
content := `
72+
---
73+
title: Test
74+
published: 2022-05-30
75+
---
76+
testContent
77+
`
78+
expected := "<p>testContent</p>\n"
79+
runCiteprocTest(t, content, expected)
80+
}
81+
82+
func TestCiteprocWithPandocMeta(t *testing.T) {
83+
content := `
84+
---
85+
---
86+
---
87+
...
88+
testContent
89+
`
90+
expected := "<p>testContent</p>\n"
91+
runCiteprocTest(t, content, expected)
92+
}
93+
94+
func TestCiteprocWithBibliography(t *testing.T) {
95+
content := `
96+
---
97+
---
98+
---
99+
bibliography: testdata/bibliography.bib
100+
...
101+
testContent
102+
`
103+
expected := "<p>testContent</p>\n"
104+
runCiteprocTest(t, content, expected)
105+
}
106+
107+
func TestCiteprocWithExplicitCitation(t *testing.T) {
108+
content := `
109+
---
110+
---
111+
---
112+
bibliography: testdata/bibliography.bib
113+
...
114+
@Doe2022
115+
`
116+
expected := `<p><span class="citation" data-cites="Doe2022">Doe and Mustermann
117+
(2022)</span></p>
118+
<div id="refs" class="references csl-bib-body hanging-indent"
119+
role="doc-bibliography">
120+
<div id="ref-Doe2022" class="csl-entry" role="doc-biblioentry">
121+
Doe, Jane, and Max Mustermann. 2022. <span>“A Treatise on Hugo
122+
Tests.”</span> <em>Hugo Websites</em>.
123+
</div>
124+
</div>
125+
`
126+
runCiteprocTest(t, content, expected)
127+
}
128+
129+
func TestCiteprocWithNocite(t *testing.T) {
130+
content := `
131+
---
132+
---
133+
---
134+
bibliography: testdata/bibliography.bib
135+
nocite: |
136+
@*
137+
...
138+
`
139+
expected := `<div id="refs" class="references csl-bib-body hanging-indent"
140+
role="doc-bibliography">
141+
<div id="ref-Doe2022" class="csl-entry" role="doc-biblioentry">
142+
Doe, Jane, and Max Mustermann. 2022. <span>“A Treatise on Hugo
143+
Tests.”</span> <em>Hugo Websites</em>.
144+
</div>
145+
</div>
146+
`
147+
runCiteprocTest(t, content, expected)
42148
}
+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
@article{Doe2022,
2+
author = "Jane Doe and Max Mustermann",
3+
title = "A Treatise on Hugo Tests",
4+
journal = "Hugo Websites",
5+
year = "2022",
6+
}

0 commit comments

Comments
 (0)