Referencing figures with numbers in Sphinx and reStructuredText - restructuredtext

When writing RST that will be processed with Sphinx, I can't get Sphinx LaTeX output to use figure numbers when referencing figures. For instance, this code:
The lemmings are attacking, as can be seen in :ref:`figlem`.
.. _figlem:
.. figure:: _static/lemming_invasion.*
They're coming!
Will be converted into this:
The lemmings are attacking, as can be
seen in They're coming!
/image goes here/
Figure 1.1: They're coming!
But what I want is the "standard" LaTeX way of referencing figures, like this:
The lemmings are attacking, as can be
seen in Figure 1.1
How do I achieve this? The code I'm currently using is what the Sphinx manual recommends, but it doesn't produce the output I want.

In the latest versions of Sphinx (1.3+), numbering figures and referencing them from text got a bit easier as support for it is now built-in.
In your text, you can do something like:
.. _label:
.. figure:: images/figure.*
At :numref:`label` you can see...
The end result should be something like "At Fig 1.1 you can see...". This technique works both with the default HTML output and the LaTeX output.
In your conf.py file, make sure to set the flag numfig = True. There are also configuration options for the references' text format (numfig_format and numfig_secnum_depth).
References:
http://www.sphinx-doc.org/en/stable/config.html#confval-numfig
https://www.sphinx-doc.org/en/master/usage/restructuredtext/roles.html#cross-referencing-figures-by-figure-number

The numfig extension does exactly this. I tried it and it worked for me.

To expand on the accepted answer, you can quickly get this set up as follows. Put the numfig.py file in your source directory. Then open conf.py and uncomment the line that says
sys.path.insert(0, os.path.abspath('.'))
Then add 'numfig' to the extensions list.
To use in your rst document, first label your figure (e.g., fig-main):
.. _fig-main:
.. figure:: main.png
This is the figure caption.
Finally, you can reference its figure number using the :num: directive, like this:
Refer to the main figure (Figure :num:`fig-main`).

I think referencing Figures is not yet implemented in reST, but here is workaround http://article.gmane.org/gmane.text.docutils.user/5623 that gets you closer.

One can use raw latex code, inline. For the example above, a role for raw latex code is first defined and than used to refer to the figure with the \ref{} latex command, and to set a label to the figure with the \label{} latex command.
The following should work:
.. role:: raw-latex(raw)
:format: latex
The lemmings are attacking, as can be seen in :ref:`figlem`
on figure :raw-latex:`\ref{pic:lem}`.
.. _figlem:
.. figure:: _static/lemming_invasion.*
They're coming! :raw-latex:`\label{pic:lem}`
Note that the \label{} command will appear inside the caption in the tex file, but it is still acceptable, at least by pdflatex. Also note that there should be at least one space before :raw-latex.

Related

What is the best way to write down in-line math equations in a jupyter notebook to have best LaTeX results?

When I am writing math equations in a markdown cell of a jupyter notebook, I casually put all of that in $ ... $. Today, I converted an .ipynb file to .tex, and realized most of these equations are converted into messy stuff in the output pdf. For instance, I realized it is converting all '$'s into '$'s.
This is an example of what has happened:
Jupyter Notebook markdown:
$ \nabla ^{2} f(x) = \frac{-1}{(x+1)^{2}} $
Tex Output:
\$ \nabla \^{}\{2\} f(x) = \frac{-1}{(x+1)^{2}} \$
Does anyone have any ideas why this is happening? Is there a better way to write down in-line math equations so that it is more compatible with LaTeX?
If you are eventually going to LaTeX version, the traditional advice is spelled out in minrk's comment from November 8 of 2012:
"The best solution for that right now would be to use 'raw' cells instead of markdown, and just type LaTeX as you would. Then use nbconvert to turn the ipynb to TeX (code, figures and all), and run latex to render that to PDF, etc. You don't get live-rendered TeX in the browser like you do with MathJax / Markdown, but you do still have TeX / code in one document."
The step where you are converting now is probably using nbconvert under the hood even if you aren't directly. (You may be using it directly since you tagged with 'nbconvert`.)
Alternatively, if you are going to LaTeX ultimately, you may want to use a code cell and use the LaTeX magic cell line at the start of that cell. See here and here about %%latex cell magic. (You'll note it is also mentioned among the StackOverflow thread I referenced earlier.) In regards to the %%latex cell magic, I suggest actually consulting the link that leads use in an example notebook in this post because it seems it has to be full-blown LaTeX code and not just simple equations that work easily elsewhere with just dollar signs bracketing them, i.e., MathJax.
I tried that option with your equation and when I output the notebook as LaTeX, I didn't see additional backslashes added. (I didn't however actually try rendering the LaTeX, and so I cannot address if all the cruft/boilerplate that Jupyter is adding causes any issues for downstream useability.)

Xaringan: Math renders as inline code in footnote class

Using the default Xaringan CSS, if $math$ is placed in a footnote, it appears to be rendered as inline code, rather than rendering as math. I was not able to find information about this - is this just a natural limitation in Xaringan or remark.js? Or perhaps I am doing something wrong?
See basic example below:
# A Test
- This is a test<sup>1</sup>
.footnote[<sup>1</sup> This includes $\delta+\frac{2}{3}$ math.]
This will render the math between the $$ as if it were between backticks.
[UPDATE 17/12/2019] Another way to circumvent this is to replace the maths expression $\delta+\frac{2}{3}$ with \(\delta+\frac{2}{3}\) which bypasses any need for remark.js to convert $ and thus avoiding the bug there.
Yes I noticed this too. I think somehow remark.js is interfering with mathjax but I don't really know. To get around this I use the html code directly instead. So below should work:
# A Test
- This is a test<sup>1</sup>
<span class="footnote"><sup>1</sup> This includes $\delta+\frac{2}{3}$ math.</span>
[UPDATE]
The explanation of why this happens can be found here. TL;DR: remark.js removes the brackets necessary for mathjax to detect the maths.
Yihui also provided an alternate hack if the use of .footnote[] is desirable which involves adding the brackets to the inline math code:
.footnote[<sup>1</sup> This includes `\\(\delta+\frac{2}{3}\\)` math.]

RStudio: Code sections and compiled notebooks

I really like RStudio's code sections because they help me keep my code organized and makes navigation very easy. So, the code/comment line for code sections look like this (the key for RStudio to recognize the code section is that the comment should end with four or more #, - or =).
# Section One ---------------------------------
# Section Two =================================
### Section Three #############################
Now, I also find very useful "Compiling Notebooks from R Scripts" because you can produce reports directly from your script (which I find much more comfortable working with) without having to write an RMarkdown document. You simply have to use roxygen2-style comments (using #' as prefix) and they will be converted to markdown and/or use #+ or #- prefixes to control RMarkdown chunk options.
Now, I want the best of both worlds but I cannot find a way to get it. I want to have code sections (recognizable for RStudio) in the report (with the proper markdown for headings #, but without the extra #### at the end of the line). Seems like an impossible task to me. If I use #' prefix, I get the section in the report but RStudio does not recognize it as a code section. If I do not use roxygen2-style comments, RStudio recognizes the code section but it does not appear in the report (ok, it appears but as an ugly comment in the formatted code). The best solution I have found so far is to use the #+ prefix and simulate a code chunk label. That way I can get RStudio to recognize it as a code section, and it does not appear in the report as an ugly comment.
Any ideas on how to do this better?

Right align (an address) in Pandoc

Right alignment comes handy for letter addresses. Unfortunately, according to the author John MacFarlane:
The pandoc document model does not allow for alignment other than in tables, so the alignment information is simply ignored.
We can resort to raw LaTeX.
Upon trial and error (and googling) I found that this TeX syntax works as intended:
\rightline{Address 1}
\rightline{Address 2}
\rightline{etc}
Also the LaTeX equivalent does:
\begin{flushright}
Address 1\\
Address 2\\
etc
\end{flushright}
The less invasive syntax, based on the LaTeX command raggedleft, unfortunately does not work:
{\raggedleft
Address 1\\
Address 2\\
etc\\
}
This is because braces are passed verbatim (\{, \}) and not as raw LaTeX.
With reference to centre alignment, I found a user claiming that markdown supports this native (beautiful) syntax:
-> This is center align <-
but I didn't find an editor/converter supporting it.
Indeed my working examples are all against the John Gruber markdown philosophy:
A Markdown-formatted document should be publishable as-is, as plain text, without looking like it’s been marked up with tags or formatting instructions.
Can you find a better way?
Particularly is it possible to simply write a Pandoc template to redefine the alignment of a header, say: ###### Right aligned?
For those that are looking for a similar question here's how to left align/right align on the same line:
**Some bolded text** **\hfill some right aligned on same line bolded text**
You'll have to imagine the result since I'm not sure how to recreate it on SO.
The best way to handle this is to put the address in a YAML metadata block (supported by pandoc 1.12+), and do the alignment in a custom template. Then your source document will be clean, without raw LaTeX, and you can modify templates to get the desired look in any output format.
Source document could look like this:
---
address:
| 23 Main St.
| Somewhere, MT 23434
...
Dear so and so,
Then in your LaTeX template you'd have something like:
\begin{flushright}
$address$
\end{flushright}
If you're writing a letter, though, it would probably be better to write a template using the LaTeX letter class.

Sweave syntax highlighting in output

Has anyone managed to get color syntax-highlighting working in the output of Sweave documents? I've been able to customize the output style by adding boxes, etc. in the Sweave.sty file as follows:
\DefineVerbatimEnvironment{Sinput}{Verbatim}{fontseries=bc,frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{frame=leftline}
\DefineVerbatimEnvironment{Scode}{Verbatim}{fontseries=bc}
And I can get the minted package to do syntax highlighting of verbatim-code blocks in my document like so:
\begin{minted}{perl}
use Foo::Bar;
...
\end{minted}
but I'm not sure how to combine the two for R input sections. I tried the following:
\DefineVerbatimEnvironment{Sinput}{minted}{r}
\DefineVerbatimEnvironment{Scode}{minted}{r}
Any suggestions?
Yes, look at some of the vignettes for Rcpp as for example (to pick just one) the Rcpp-FAQ pdf.
We use the highlight by Romain which itself can farm out to the hightlight binary by Andre Simon. It makes everything a little more involved---Makefiles for the vignettes etc pp---but we get colourful output from R and C/C++ code. Which makes it worth it.
I have a solution that has worked for me, I have not tried it on any other systems though so things may not work out of the box for you. I've posted some code at https://gist.github.com/797478 that is a set of modified Rweave driver functions that make use of minted blocks instead of verbatim blocks.
To use this driver just specify it when calling the Sweave function with the driver=RweaveLatexMinted() option.
Here's how I've ended up solving it, starting from #daroczig's suggestion.
\usepackage{minted}
\renewenvironment{Sinput}{\minted[frame=single]{r}}{\endminted}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{frame=leftline}
\DefineVerbatimEnvironment{Scode}{Verbatim}{}
While I was at it, I needed to get caching working because I'm using large data sets and one chunk was taking around 3 minutes to complete. So I wrote this zsh shell function to process an .Rnw file with caching:
function sweaveCache() {
Rscript -e "library(cacheSweave); setCacheDir(getwd()); Sweave('$1.Rnw', driver = cacheSweaveDriver)" &&
pdflatex --shell-escape $1.tex &&
open $1.pdf
}
Now I just do sweaveCache myFile and I get the result opened in Preview (on OS X).
This topic on tex.StackExchange might be interesting for you, as it suggest loading the SweaveListingUtils package in R for easy solution.

Resources