Sphinx rst2pdf and role directives - python-sphinx

In a reStructuredText on Sphinx 2.x, I want to put a content that changes depending on the output format.
In any source document, say, index.rst, add the following lines:
.. role:: pdf(raw)
:format: pdf
.. role:: latex(raw)
:format: latex
.. role:: html(raw)
:format: html
.. |foo| replace::
:pdf:`PDF!`
:latex:`LaTeX!`
:html:`HTML!`
I am |foo|
I expect it shows "I am HTML!" when the output format is in HTML, "I am LaTeX!" if it's LaTeX (even after converting the product to PDF via pdflatex) and "I am PDF!" if it's PDF.
I make the HTML version using make html and I see only "I am HTML!" in a web browser as I expect:
Install rst2pdf. Put the following lines in conf.py:
extensions = [
'rst2pdf.pdfbuilder'
]
pdf_documents = [(
'index',
u'testRst2Pdf',
u'Test Title',
u'Sarah Author')]
Make the PDF version with
sphinx-build -b pdf ./source/ ./build/
Update. Below is the output. No error. I ran this using WSL 1 (Ubuntu 18.04).
Running Sphinx v2.4.3
loading pickled environment... done
building [mo]: targets for 0 po files that are out of date
building [pdf]: targets for 1 source files that are out of date
updating environment: 0 added, 0 changed, 0 removed
looking for now-outdated files... none found
processing testRst2Pdf...
index
resolving references...
done
writing testRst2Pdf...
done
build succeeded.
I see "I am PDF! LaTeX! HTML!" that includes all the three items.
Is there any way to get either "I am PDF!" or "I am LaTeX!" in the PDF file?
Note.
Before reporting this behavior as a bug, someone help me check if it's unexpected behavior or as-designed.
This question is derived from the other I asked earlier: StackOverflow: "Sphinx: Use a different directive for a different output format".

rst2pdf does not really have conditionals, but you might find the --strip-elements-with-class switch useful? Put the optional pieces into a class name and then if that class doesn't make sense for this format, remove it with the switch.
Manual is here https://rst2pdf.org/static/manual.html#command-line-options and I also blogged (basically a longer version of this first paragraph) about this https://rst2pdf.org/static/manual.html#command-line-options if more information would be useful.

Related

How to modify documentation built with sphinx via a script in readthedocs build

I am trying to run a script to modify the documentation built by sphinx hosted by Read the Docs (because some links are not properly handled). The script works when I try to build it locally, but either fails on the Read the Docs build or the changes do not get propagated to the web site.
The script I'm trying to run is super simple, it replaces some html links that are not properly converted by sphinx-markdown-tables:
#!/bin/bash
# fix_table_links.sh
FILE="_build/html/api_reference.html"
if [[ "$1" != "" ]]; then
FILE="$1"
fi
sed -E 's/a href="(.*)\.md"/a href="\1\.html"/g' -i ${FILE}
My readthedocs.yml looks like this:
# Required
version: 2
# Build documentation in the docs/ directory with Sphinx
sphinx:
configuration: docs/conf.py
# Optionally build your docs in additional formats such as PDF and ePub
formats: all
# Optionally set the version of Python and requirements required to build your docs
python:
install:
- requirements: docs/requirements.readthedocs.txt
build:
os: ubuntu-20.04
tools:
python: "3.8"
jobs:
post_build:
- echo "Running post-build commands."
- bash docs/fix_table_links.sh _readthedocs/html/api_reference.html
There are two cases:
Case 1) Using the readthedocs.yml as above, the build fails because _readthedocs/html/api_reference.html does not exist, despite this directory being the place the documentation claims will get uploaded from here. An example failure of this run is here.
Case 2) If I change the final of readthedocs.yml to bash docs/fix_table_links.sh docs/_build/html/api_reference.html, then the build passes (example here). But the links are not updated on the Read the Docs site: they still point to markdown pages rather than their corresponding HTML pages, so it must not be the version that gets uploaded to the Read the Docs web site.
Wading through documentation, I can't figure out how do this. Has anybody done this before or have a better grasp on how Read the Docs builds work? Thanks!
If you're willing to rewrite the script as a Python function, then you can do this super easily by connecting it as an event handler for the build-finished event.
I've done something similar in one of my own repos, except I post-process a .rst file. It's not actually used on RTD, but I can see it works in the build logs. So it should work to post-process your HTML files as well, since the build-finished event would occur after they've been generated.
First, define the script as a function in your conf.py. It needs to have app and exception as parameters.
def replace_html_links(app, exception):
with open(FILE, 'r') as f:
html = f.read()
# stuff to edit and save the html
Then either define or add to your setup function:
def setup(app):
app.connect('build-finished', replace_html_links)
And that's it!

In R markdown in RStudio, how can I prevent the source code from running off a pdf page when bash language is used?

I'm writing a technical book using Bookdown and RStudio. My code chunks are mainly using bash. Everything works fine except when I export the book to pdf, then the source code is partially out of the "box" and even the page if this is long enough. I have read a lot of solutions when r language is used, but none of these solutions works when bash language is used.
Here is my code at the beginning of the .Rmd file:
```{r, global_options, include=FALSE}
knitr::opts_chunk$set(message=FALSE, eval=FALSE,
tidy.opts=list(width.cutoff=60), tidy=TRUE)
```
And then when I write the code chunk:
```{bash}
mongodump --uri="mongodb+srv://cluster0.rh6qzzz.mongodb.net/" --db sample_mflix --username my_username
```
The outputs were produced as shown below (see the end of line):
I would like to avoid this, but I have not found the solution.

Use custom citation style in markdown using YAML header

I am trying to use a custom citation style in a markdown file, but the citation uses the default (Chicago) style each time I knit. I have tried changing the output format from a JS reveal presentation to an HTML document to a PDF document, but it still does not work. I am using the knitcitations package to cite using the document's DOI, and the bibliography() function to write the bibliography. I have also tried using the apa.csl style found on Zotero, yet the citation is still done in the default styple. The apa.csl file is stored in the same folder as the file that I am trying to use citations in, as is the newbiblio.bib file, in which I have stored the bibliographical information for the item I want to cite.
Below is my markdown code:
---
title: "htmlcitetest"
citation_package: natbib
csl: "apa.csl"
output:
pdf_document:
pandoc_args: ["--natbib"]
biblio-style: unsrt
bibliography: newbiblio.bib
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(bibtex)
library(knitcitations)
options("citation_format" = "pandoc")
library(RefManageR)
cleanbib()
```
## R Markdown
- This is a citation [^1]
[^1]: `r citet("10.1098/rspb.2013.1372")`
```{r, message=FALSE}
bibliography()
```
This link (http://rmarkdown.rstudio.com/authoring_bibliographies_and_citations.html)
says that I should be able to format my YAML header like this:
---
title: "Sample Document"
output: html_document
bibliography: newbiblio.bib
csl: apa.csl
---
However, when I do that, the file knits to a markdown (.md) file, but it is not processed into the output. I recieve this error:
pandoc-citeproc: 23:3-23:10: Expected end element for: Name {nameLocalName = "category", nameNamespace = Just "http://purl.org/net/xbiblio/csl", namePrefix = Nothing}, but received: EventEndElement (Name {nameLocalName = "info", nameNamespace = Just "http://purl.org/net/xbiblio/csl", namePrefix = Nothing})
pandoc: Error running filter /Applications/RStudio.app/Contents/MacOS/pandoc/pandoc-citeproc
Filter returned error status 1
Error: pandoc document conversion failed with error 83
Execution halted
The contents of my .bib file are:
#Article{Boettiger_2013,
doi = {10.1098/rspb.2013.1372},
url = {http://dx.doi.org/10.1098/rspb.2013.1372},
year = {2013},
month = {jul},
publisher = {The Royal Society},
volume = {280},
number = {1766},
pages = {20131372--20131372},
author = {C. Boettiger and A. Hastings},
title = {No early warning signals for stochastic transitions: insights from large deviation theory},
journal = {Proceedings of the Royal Society B: Biological Sciences},
}
I also do not understand why the biblio-style option in the YAML header does not to do anything. Essentially, all I need is a way to use a custom citation style I have already made with a markdown document. Any help would be greatly appreciated!
Without a reproducible example, it is hard to know exactly what is happening, but it looks like you are mixing two different configurations.
Method 1: Specifying a custom CSL file
The method of using a CSL file only works if you are using pandoc-citeproc. For example, I have downloaded the IEEE style, and saved it in the same directory as my RMarkdown file as ieee.csl. This MWE builds a separate bibliography file:
---
output: pdf_document
bibliography: test.bib
csl: ieee.csl
---
```{r}
knitr::write_bib(x = c("knitr", "rmarkdown") , file = "test.bib")
```
Some ref [#R-knitr]
Some again [#R-knitr]
Another ref [#R-rmarkdown]
# References
Method 2: Specifying styles in Natbib
If you want to use natbib to build the citations and bibliography, you have to use the biblio-style option. This following example should work without downloading anything:
---
output:
pdf_document:
citation_package: natbib
bibliography: test.bib
biblio-style: humannat
---
```{r}
knitr::write_bib(x = c("knitr", "rmarkdown") , file = "test.bib")
```
Some ref [#R-knitr]
Another ref [#R-rmarkdown]
# References
Unless you have a particular reason, I would probably go down the route of using pandoc-citeproc and a csl file. It integrates well with the RMarkdown world. Using Natbib just gets a bit more confusing, and from my experience is more prone to throwing errors.
I was having the same error message you are having (pandoc-citeproc: ParseError {errorContexts = [], errorMessage = "Failed reading: takeWhile1"...). And I discovered the solution conveying information from two other internet forums. Basically, the problem was that I had downloaded my custom citation "csl" file from GitLab in a way that it was an HTML version of the original raw xml file. I had to download the raw xml file instead. When I googled the error, I saw that many people was having the same issue.
Within Git-page, where you downloaded your "csl" file from, instead of clicking in the download button, you should right click in the "open raw" button, and then, "save link as". Then it should work.
In the below image, instead of clicking in button "1", right click in button "2" and save the link as:

How to resemble the PDF-output of AsciidocFX using a Gradle build-script?

I have the following Asciidoc-document:
= Test
:doctype: article
:notitle:
:!toc:
AsciidocFX shows links in PDFs as footnotes http://stackoverflow.com[SO].
.Asciidoc in PDF does not work in Asciidoctor, but works in AsciidocFX.
[cols="2,5a"]
|===
|Line with Asciidoc code
|here comes a list:
* item 1
* item 2
* item 3
http://stackoverflow.com[Get Answers]!
|Line
|with a footnotefootnote:[footnotes do work in AsciidocFX's PDF output (but not in the preview).]
|===
When generating a PDF using asciidoctor, the output is as follows:
The problems are:
footnotes are shown inline (see: https://github.com/asciidoctor/asciidoctor-pdf/issues/73)
Asciidoc-content in tables cells is not interpreted: https://github.com/asciidoctor/asciidoctor-pdf/issues/6
Link targets are not shown as Footnotes (this would be nice to have)
Using https://github.com/asciidocfx/AsciidocFX shows everything correctly:
Now, I'd like to have the same output that AsciidocFX produces, but still like to use my Gradle build-script.
From https://github.com/asciidoctor/asciidoctor-pdf/issues/73#issuecomment-224327058 I learned, that AsciidoctorFX uses https://github.com/asciidoctor/asciidoctor-fopub[asciidoctor-fopub] under the hood. But how can I this pipeline in my build.gradle. Do I have to generate epub in a first task and use the output in another task? Or is there a direkt way?
Sorry that I am a tad late (almost 7 years!!) to answer your question, but perhaps it will help others.
Perhaps you need to upgrade. When I run your .adoc verbatim, the foootnotes come out perfectly. In fact the output is exactly as you posted correct version of output. Here is the syntax that I use:
asciidoctor-pdf -a pdf-themesdir=/path/to/themes -a pdf-theme=your-pdf-theme-file.yml -a pdf-fontsdir=/path/to/your/fonts/directory/ your_test_file.adoc
I put this syntax in a bash script with the adoc file as an argument.
I am using:
linux Pop!_OS 22.04 LTS (close derivative of ubuntu)
ruby 3.1.2p20
asciidoctor-pdf-2.3.0b
Ironically, I am amazed with is your AsciidoctorFX output. AsciidoctorFX pdf output looks horrible for me and there is no simple way of changing the output style, like editing the asciidoctor-pdf yaml.
Cheers, Joe

pandoc document conversion failed with error 43 : pdflatex: The memory dump file could not be found

RStudio : 0.98.994
OS: Microsoft Windows 7 Ultimate Edition, 64-bit Service Pack 1
MiKTeX: 2.9.4503
Hi,
I get the following error when I try to knit a PDF document.
pandoc.exe: Error producing PDF from TeX source.
This is pdfTeX, Version 3.1415926-1.40.11 (MiKTeX 2.9)
pdflatex: The memory dump file could not be found.
pdflatex: Data: pdflatex.fmt
I also tried devtools::install_github('rstudio/rmarkdown') but was still getting an error when I added 'fig.align='center' to a ggplot2 plot in my document. It would work as HTML, but not as PDF.
After seeing isomorphismes's post I clicked on the gear symbol next to the knit PDF button, then under the advanced tab I changed the LaTeX Engine to xelatex. After that I no longer received the error message and my PDF document was created without problems.
Thank you.
I found the answer here: http://rmarkdown.rstudio.com/tufte_handout_format.html#comment-1582377678
The problem is that you need to add \usepackage[utf8]{inputnc} to the preamble of the tufte-handout.tex file in the rmarkdown package.
This was fixed here: https://github.com/rstudio/rmarkdown/commit/484d5b8e903e0e0c75c82f707efa35f9fd9a52b0
To update your rmarkdown package, you can use directly in the RStudio command line
devtools::install_github("rstudio/rmarkdown")
None of the above worked for me when knitting to PDF (and I wanted to keep the scientific notation). The problem was that latex code was generated that included "\times" without the necessary bracketing by $. In the markdown I simply bracketed the inline R code with $'s, like so:
$p = `r signif(cor.HF$p.value, 2)`$
Voila!
happy to share with you my solution.
---
title: "Untitled"
author: "-----"
date: "21/6/2017"
output:
pdf_document:
latex_engine: xelatex
---
I was able to fix it in my case. I experienced that error when generate PDF from Rmd if I added float values into a text that R tried to display as a scientific notation. For example, instead of "520274.72" it tried to add text "5.2027472 e10-5" which leads to latex code \textbf{5.2027472\times 10\^{}{5}} that was not compiling. I fixed it by wrapping it with format(....,scientific=FALSE).
replace
r round(txn_pd,2)
with
r format(round(txn_pd,2),scientific=FALSE)
I had the same problem and devtools::install_github('rstudio/rmarkdown') didn't work for me. I needed to
rmarkdown::render('in.md',
output_format=pdf_document(latex_engine='xelatex')
)
with the novel command (use xelatex) on its own line.
I encountered this problem while I was trying to add an in-line r code r test1$p.value, which is a very small p-value from t test. The error information is as following:
> ! Missing $ inserted.
> <inserted text>
> $
>l.147 9.0044314\times
>
>pandoc: Error producing PDF
>Error: pandoc document conversion failed with error 43
>Execution halted
I think the problem is the pdflatex engine has a trouble in displaying the small p-value in exponential notation.
I solved the problem by clicking on the gear symbol next to the knit button, then under output options, advanced tab I changed the LaTeX Engine to lualatex, or you can just report the p-value as p < 0.001.
If you are using inline values from your R code which are in the scientific format (too small or too big), format them like:
replace r x
with r format(x, digits=n) where n is whatever.
for me it was because on my headers I was putting + signs. For example gene + treatment. This errors but when I removed it, it works.
In my case it was solved simply by editing the author field in:
---
title: "Document Title"
author: '-----'
date: "21-03-2017"
output: pdf_document
---
the default '-----' would yield the error, but replacing it with anything (for example 'Juan') solved the issue.
I just ran into this problem and already solved it. I didn't use any code as other people did in their posts.
I will assume that you have installed all these basic stuff: R, RStudio, the rmarkdown package, the knitr package, and the MikTex basic installation (I know this is very basic, but I want those first timers know that you need these stuff to make this happen).
If you run into this problem, go to R GUI, upgrade the rmarkdown package and it should work then. Note that if you change the LaTeX Engine to xelatex as the poster of the highest vote did, it may not work for you, at least it did not for me. I leave my latex engine as it is (pdflatex).
I had a similar issue. My solution was to remove the "leading" period in the YAML title argument:
Does not work:
---
title: “1. Title”
output: pdf_document
---
output file: example.knit.md
! Argument of \reserved#a has an extra }.
\par l.79 \end{enumerate}}
pandoc: Error producing PDF Error: pandoc document conversion failed
with error 43 Execution halted
Works:
---
title: “1 Title”
output: pdf_document
---
I did try to use the xelatex engine but still, I got the error that xetex.def is not found. This is another to work around.
output:
pdf_document:
keep_tex: yes
latex_engine: xelatex
Then open .tex file in your TEX editor and build pdf as usual.
I faced a similar issue. In my case, the error occurred because of putting a percentage inside the $ sign.
Like this,
$95%$, I removed the % sign, and everything worked fine.

Resources