File: syntax.rst

package info (click to toggle)
sphinx-gallery 0.19.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,340 kB
  • sloc: python: 10,346; makefile: 216; lisp: 15; sh: 11; cpp: 9
file content (232 lines) | stat: -rw-r--r-- 8,792 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
.. _python_script_syntax:

=============================================
Structuring Python scripts for Sphinx-Gallery
=============================================

This page describes the structure and syntax that can be used in Python scripts
to generate rendered HTML gallery pages.

A simple example
================

Sphinx-Gallery expects each Python file to have two things:

1. **A docstring**, written in reST, that defines the
   header for the example. It must begin by defining a reST title. The title
   may contain any punctuation mark but cannot start with the same punctuation
   mark repeated more than 3 times. For example::

    """
    "This" is my example-script
    ===========================

    This example doesn't do much, it just makes a simple plot
    """
2. **Python code**. This can be any valid Python code that you wish. Any
   Matplotlib images that are generated will be saved to disk, and
   the reST generated will display these images with the built examples. By
   default only images generated by Matplotlib, or packages based on Matplotlib
   (e.g., Seaborn or Yellowbrick) are saved and displayed. However, you can
   change this to include other packages, see :ref:`image_scrapers`.

For a quick reference have a look at the example
:ref:`sphx_glr_auto_examples_plot_0_sin.py`

.. _embedding_rst:

Embed reST in your example Python files
=======================================

Additionally, you may embed reST syntax within your Python scripts. reST
allows you to easily add formatted text, math equations and reference links,
including :ref:`cross referencing other examples <cross_ref_example>`. This
will be rendered in-line with the Python code and its outputs, similar to how
Jupyter Notebooks are structured (in fact, Sphinx-Gallery also **creates** a
Jupyter Notebook for each example that is built).

You can embed reST in your Python examples by including a line of >= 20 ``#``
symbols, ``#%%``, or ``# %%``. For consistency, it is recommended that you use
only one of the above three 'block splitter' options in your project. If using
a line of ``#``'s, we recommend using 79 ``#``'s, like this::

  ###############################################################################

Any commented lines (line beginning with ``#`` followed by a space, to
be PEP8-compliant) that immediately follow a block splitter will be rendered as
reST in the built gallery examples. To switch back to writing code, either
stop starting lines with ``#`` and a space or leave an empty line before writing
code comments. You can thus easily alternate between text and code 'blocks'.
For example::

  # This is commented python
  myvariable = 2
  print("my variable is {}".format(myvariable))

  # %%
  # This is a section header
  # ------------------------
  #
  # In the built documentation, it will be rendered as reST. All reST lines
  # must begin with '# ' (note the space) including underlines below section
  # headers.

  # These lines won't be rendered as reST because there is a gap after the last
  # commented reST block. Instead, they'll resolve as regular Python comments.
  # Normal Python code can follow these comments.
  print('my variable plus 2 is {}'.format(myvariable + 2))

The ``#%%`` and ``# %%`` syntax is consistent with the 'code block' (or
'code cell') separator syntax in `Visual Studio Code Python extension
<https://code.visualstudio.com/docs/python/jupyter-support-py#_jupyter-code-cells>`_,
`Visual Studio Python Tools
<https://learn.microsoft.com/en-us/visualstudio/python/python-interactive-repl-in-visual-studio?view=vs-2019#work-with-code-cells>`_,
`Jupytext
<https://jupytext.readthedocs.io/en/latest/formats.html#the-percent-format>`_,
`Pycharm Professional
<https://www.jetbrains.com/help/pycharm/running-jupyter-notebook-cells.html>`_,
`Hydrogen plugin (for Atom)
<https://nteract.gitbooks.io/hydrogen/content/docs/Usage/Cells.html#example-definitions>`_
and `Spyder
<https://docs.spyder-ide.org/current/panes/editor.html#defining-code-cells>`_.
Note that although the documentation of these editors/IDEs
may only mention one of ``#%%`` or ``# %%``, in practice both
work. With these editors/IDEs, ``#%%`` or
``# %%`` at the start of a line signifies the start of a new code block.
Code blocks allow you to separate your code into chunks, like in Jupyter
Notebooks. All the code within a code block can be easily executed together.
This functionality can be helpful when writing a Sphinx-Gallery ``.py``
example as
the blocks allow you to easily create pairs of subsequent Sphinx-Gallery text
and code blocks.

Here are the contents of an example Python file using the 'code block'
functionality::

  """
  This is my example script
  =========================

  This example doesn't do much, it just makes a simple plot
  """

  # %%
  # This is a section header
  # ------------------------
  # This is the first section!
  # The `#%%` signifies to Sphinx-Gallery that this text should be rendered as
  # reST and if using one of the above IDE/plugin's, also signifies the start of a
  # 'code block'.

  # This line won't be rendered as reST because there's a space after the last block.
  myvariable = 2
  print("my variable is {}".format(myvariable))
  # This is the end of the 'code block' (if using an above IDE). All code within
  # this block can be easily executed all at once.

  # %%
  # This is another section header
  # ------------------------------
  #
  # In the built documentation, it will be rendered as reST after the code above!
  # This is also another code block.

  print('my variable plus 2 is {}'.format(myvariable + 2))

For a clear example refer to the rendered example
:ref:`sphx_glr_tutorials_plot_parse.py` and compare it to the generated
:download:`original python script <tutorials/plot_parse.py>`

.. _non_python_source:

Examples in other programming languages
=======================================

Sphinx-Gallery also supports rendering HTML pages for examples written in programming
languages other than Python, although these examples are not currently executed or
scanned for output. See :ref:`filename/ignore patterns <build_pattern>` for
configuration settings.

For such examples, the header for the example is defined by the first comment block in
the file, which must contain a reST title, and may contain any additional reST content
that should appear above the first code block. For example, a C++ example could start
with:

.. code:: C++

  // My Awesome Example
  // ==================
  //
  // The description continues as long as there are lines
  // that start with a comment character.

reST content can likewise be embedded in comments that are marked with a special
delimiter, where that delimiter depends on the comment characters used by the language
of the example. Valid special delimiters are:

1. The comment character followed by ``%%``. For example ``//%%`` for C++.
2. The comment character followed by a space, followed by ``%%``. For example, ``// %%``
   for C++.
3. A line of at least 20 comment characters. For example, ``////////////////////`` for
   C++.

Any text following the special delimiter on the same line will be converted into a reST
heading (underlined with ``-``). The reST block continues until a line that does not
start with a comment character is encountered. Some examples:

.. code:: C++

  // %% Important Heading
  // This is some text in a reST block in C++, appearing underneath a heading.
  //
  // * Start a list
  // * Check it twice

.. code:: Fortran

  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  ! This is the start of a reST block in Fortran 90.
  !
  ! It can contain multiple paragraphs.

For languages that use C-style multiline comments, the following styles are supported:

.. code:: C

  /* %%
   * Subheading
   * ----------
   *
   * Description
   */

  int y = 3;

  /**************************/
  /* Another subheading     */
  /* ------------------     */
  /*                        */
  /* Description            */
  /**************************/
  double z = 1.5;

Finally, for compatibility with Matlab's use of a simple ``%%`` delimiter to mark code
sections, this is allowed as a special delimiter in Matlab source files, in addition to
the multi-language syntax described above:

.. code:: Matlab

  %% Heading
  % some text below the heading

.. _plain_rst:

Plain reST examples
===================

Sphinx-Gallery generates examples from Python scripts,
so examples written in plain reST files are not supported.
If you're looking to generate hyperlinks for functions (linking to their
corresponding online documentation) in code blocks of ordinary reST
documentation, you might find
`sphinx-codeautolink <https://sphinx-codeautolink.readthedocs.io/en/latest/>`_ helpful.