Pass code type to Sphinx `.. include::` directive - python-sphinx

I want to include full example scripts in Sphinx documentation. I originally simply duplicated an example file using a .. code:: directive, dropping in the entire python and json files for the example.
I then found the .. include:: directive, which lets to link to files by providing their relative path, and by using the code option, "The argument and the included content are passed to the code directive". This works fine for my python files, because the default decoding and highlighting for the code directive is python. But my json files are not highlighted as json. How do I indicate what code format the code directive should use to parse the code?
This is what I am using.
.. include:: ../../examples/my_example.json
:code:
I tried adding changing the second line to :code: json with no effect.
This is what I had originally, but want to replace so the example code does not have to be maintained in both the documentation and the examples.
.. code-block:: json
:name: my_example.json
:caption: my_example.json
{
"field1": "attribute1",
"field2": "attribute2",
"field3": true,
...
}

The solution is to instead use the literalinclude directive which has a language option. This is how it should look.
.. literalinclude:: ../../examples/my_example.json
:language: json
Note that literal include also supports options like linenos, lines, start-after, and end-before, caption, and name.

Related

How to include multiple rows of LaTeX code via the YAML header (header-includes field) in RMarkdown?

I need to include the following code in a .tex file that is generated from a custom template via RMarkdown, in order to get rid of an error. However, if I try it as below in the YAML heading:
header-includes:
\newenvironment{CSLReferences}%
{}%
{\par}
it gets parsed into the .tex file as single line, like \newenvironment{CSLReferences}% {}% {\par}, thus commenting out everything after %. So how can I change the YAML part so that it correctly gets interpreted as 3 different lines?
Instead of worrying about the markdown parsing, you can write the command in a single line:
header-includes:
\newenvironment{CSLReferences}{}{\par}
Alternatively avoid all these annoying problems with markdown parsing and put your definition in a .tex file which you can include via
includes:
in_header: header.tex
After some trials & searching this works (found a solution while writing the question):
header-includes:
- "\\newenvironment{CSLReferences}%"
- "{}%"
- "{\\par}"
Interestingly, I couldn't find much in the official documentation.
EDIT:
As #samcarter mentioned in the comments & an answer, in this particular case a single line would've been enough, as
header-includes:
\newenvironment{CSLReferences}{}{\par}

How to Link Local Python Help Documents Using Sphinx

How can I get my Sphinx RST file to include a link to the "contents.html" Python help page?
More Details
I have an RST help document (index.rst) in an offline environment. I have downloaded and successfully built the Python documentation using the command make.bat html. I then copied this documentation to C:\Temp\PyDoc.
I then updated my conf.py file to include the following Intersphinx mapping:
intersphinx_mapping = {'python': ('C:/Temp/PyDoc', None)}
Then, within my index.rst file, I have something like:
Contents:
.. toctree::
:maxdepth: 1
:ref:`Python <python:contents>`
The Python link is removed from the resulting documentation with the warning message:
WARNING: toctree contains reference to nonexisting document ':ref:`Python <python:contents>`'
I have verified that the output contains the text:
loading intersphinx inventory from C:/Temp/PyDoc/objects.inv...
I have also verified that the "contents" tag exists within the Python documentation by running:
python -m sphinx.ext.intersphinx "C:/Temp/PyDoc/objects.inv" | findstr contents
Which generates output that includes the line:
contents Python Documentation contents : contents.html
Does anyone know how to reference this external documentation from my RST file?
In the configuration for intersphinx, the dict's key's value is a tuple, which consists of comma-separated values, not colon-separated.
intersphinx_mapping = {'python': ('C:/Temp/PyDoc', None)}
EDIT
toctree entries need a valid target, which can be a file relative to the current file or absolute as starting from the documentation root where your conf.py resides. Also the target may be an URL. I suspect that the HTML you made is none of the above, so you need to move it to a place where Sphinx can find it.
The syntax should be for documentation, not a Python object, because the page is a table of contents. I did not try this example because I don't have the Python docs downloaded and built, so I doubt it will work.
.. toctree::
:maxdepth: 1
:doc:`Python <python:contents>`
Or you can just use the URL (or similar relative or absolute target). This works for me with a fully qualified URL.
.. toctree::
:maxdepth: 1
Python <https://docs.python.org/3/contents.html>
Finally you could try an include, but I think that is not what you really want.

What is the equivalent of ` tag in restructured text? [duplicate]

I know reStructuredText has this directive:
.. code:: bash
gedit pohl.m
which renders a code block. Is there some way to get syntax highlighting for inline snippets like this:
Do edit the file, type ``gedit pohl.m`` into a terminal.
The backticks mark it as code, but I'd like to highlight it with pygments like the block. Is this possible?
Having looked into this some more I stumbled upon the document reStructuredText Interpreted Text Roles. From this document:
Interpreted text uses backquotes (`) around the text. An explicit role marker may optionally appear before or after the text, delimited with colons. For example:
This is `interpreted text` using the default role.
This is :title:`interpreted text` using an explicit role.
It seems that there is a code role, so you can simply type
:code:`a = b + c`
to render an inline code block. To get syntax highlighting you can define a custom role. For example
.. role:: bash(code)
:language: bash
which you can then use like so:
Here is some awesome bash code :bash:`a = b + c`.
Note that the role definition must be placed before references to the role.
Note, the document I link to makes no mention of the version of docutils to which it refers. The code role is not available in docutils 0.8.1 (which is the only version I have to test against).
For me I had to create a docutils.conf file in the Sphinx's configuration directory (where conf.py resides).
It had the following contents:
[restructuredtext parser]
syntax_highlight = short
See this answer for more information on the above
To set the role globally, in the conf.py file, I created a rst_prolog variable. The string inside it will be included at the beginning of every source file that is read.
rst_prolog = """
.. role:: python(code)
:language: python
:class: highlight
"""
In this highlight class was necessary for proper Python highlighting.
See this answer for more information on the above

WARNING: document isn't included in any toctree for included file

I'm getting the warning:
WARNING: document isn't included in any toctree
for files that exist in the document because they've been explicitly included. So I have the index file:
.. toctree::
:maxdepth: 2
pages/0010-foo
pages/0020-bar
In the file 0020-bar.rst, I'm specifically including a number of other files, as in:
.. contents:: :local:
.. include:: /pages/reference-architecture/technical-considerations/0070-baz.rst
But when I build the project, I still get a warning that 0070-baz.rst isn't in any toctree, as in:
/home/nick/Documents/myProject/docs/pages/reference-architecture/technical-considerations/0070-baz.rst:: WARNING: document isn't included in any toctree
The weird thing is that I can see the content in the output. Is this normal? Does this warning always appear for files that are explicitly included rather than included via toctree?
If you only want to ..include:: a document in another document, without having it appear in any toctree.
Add :orphan: to the top of your document to get rid of the warning.
This is a File-wide metadata option. Read more from the Sphinx documentation.
Sphinx will complain about this whether the file is included or not.
However, you can specifically exclude files by using the exclude_patterns config value.
So for your case you might try to change Sphinx's conf.py file with something like:
exclude_patterns = ['pages/reference-architecture', 'some/other/file.txt']
You can exclude individual files, directories, or use file globbing patterns to match groups of files this way.
EDIT: See: Joakim's answer for another option that was added after this answer was created.
I had a situation where I couldn't edit the documents I wanted to be brought in as a git submodule. The documents already had their own structure including TOC page written in Markdown and I did want them to be processed by sphinx for consistency of formatting.
What I found I could do is specify a hidden toctree to make toctree aware of the documents, but not clutter up the toctree or add a bunch of errors to my sphinx build output.
* :doc:`Additional Book <external/index>`
.. toctree::
:hidden:
external/documentA.md
external/documentB.md
Indentation worked:
toctree::
:maxdepth: 2
hello <h.rst>
abc <your.rst>

How to do output-format dependent substitution in Sphinx

Using Sphinx, how can I make a substitution depending on the output-format?
Basically, I would like to have something like
if html:
|CLICK| unicode:: U+21E8
elif latex:
|CLICK| raw:: latex
$\LongRightArrow$
but I cannot seem to get the syntax right.
Use the .. only:: directive instead. While it is normally used with flags (or tags as sphinx puts it), the output format is made available as a tag as well:
.. only:: html
.. raw:: html
google
.. only:: latex
latex specific
Official documentation:
https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#including-content-based-on-tags

Resources