literal-block¶
To show code example as block element, the most basic is the literal block. They are fast to type, but doesn’t support advanced features as a syntax highlighting.
Basic (expanded) syntax¶
Simplest are literal blocks that has two colons ::
followed by a indented content block. Above and bellow content must be the blank line. Block ends with a line back at to the original indentation.
1Build project with
2
3::
4
5 $ make html
6
7command.
Build project with
$ make html
command.
Paragraph followed by literal block¶
Ending paragraph with colon followed by code example is very common. reStructuredText has special literal block syntax for it. If it find two colons at the end of paragraph followed by intented block, colons will replaced with one.
1Build project with::
2
3 $ make html
4
5command.
Build project with:
$ make html
command.
Consider alternatives¶
The plain literal block may not suffice for you. For example, if you want syntax highlighting, see code-block.
Others may prefer putting code examples into external files and including them with iteralinclude.
Common issues¶
No empty line between ::
and content¶
Omitting separatating content from ::
with empty line
::
$ make html
not cause any warning because it actually creates definition-list with term “:” and definition “$ make html”.
Fixed:
::
$ make html
No indented content¶
Another typical issue is to forgot indent content after ::
. Fortunatelly, Sphinx will tell you with WARNING: Literal block expected; none found.
.
For example, the result will be three plain paragraphs:
1When showing examples like
2
3::
4
5return one + two
6
7don't forgot to content indentation.
When showing examples like
return one + two
don’t forgot to content indentation.
But interesting accidents can happen. For example, the following snippet will cause the same warning and, because the function is now normal text, it creates the definition-list that has, by coincedence, the same syntax as the function (a term followed by :
, newline, and an indented definition).
1When showing examples like
2
3::
4
5def add(one, two):
6 return one + two
7
8don't forgot to content indentation.
When showing examples like
- def add(one, two):
return one + two
don’t forgot to content indentation.
Previous: inline literal | Next: note