48
Sphinx Documentation, Release 1.4.1
7.6.2 Includes
.. literalinclude:: filename
Longer displays of verbatim text may be included by storing the example text in an external file
containing only plain text. The file may be included using the literalinclude directive.
1
For
example, to include thePython source fileexample.py, use:
.. literalinclude:: example.py
The file name is usually relative to the current file’s path. However, if itis absolute (starting with /),
it is relative to thetop source directory.
Tabs in the input areexpanded ifyou give a tab-width option with the desired tab width.
Likecode-block, the directive supports the linenos flag option to switch on line numbers, the
lineno-start option to select the first line number, the emphasize-lines option to emphasize
particularlines,and alanguage option toselecta language differentfrom thecurrentfile’s standard
language. Example with options:
.. literalinclude:: example.rb
:language: ruby
:emphasize-lines: 12,15-18
:linenos:
Includefilesareassumed tobeencoded inthesource_encoding. If thefilehasadifferentencoding,
you can specify itwith theencoding option:
.. literalinclude:: example.py
:encoding: latin-1
The directive also supports including only parts of the file. If it is a Python module, you can select a
class, function or method to include using the pyobject option:
.. literalinclude:: example.py
:pyobject: Timer.start
This would only include the codelines belonging to the start() method in the Timer class within
the file.
Alternately, you can specifyexactly which lines toincludebygiving alines option:
.. literalinclude:: example.py
:lines: 1,3,5-10,20-
This includes thelines 1, 3, 5 to 10 and lines 20 tothe last line.
Anotherwaytocontrol whichpartofthefileis included istousethestart-afterandend-before
options (oronly one of them). If start-after is given as a string option, only lines that follow the
first line containing that string are included. If end-before is given as a string option, only lines
that precede the firstlines containing thatstring are included.
When specifyingparticularparts of a filetodisplay, itcanbeuseful to displayexactly which lines are
beingpresented. This can be done using thelineno-match option.
You can prepend and/orappend a lineto theincluded code, usingthe prepend and append option,
respectively. Thisisusefule.g. forhighlightingPHPcodethatdoesn’tincludethe<?php/?>markers.
Ifyou want toshow the diff of the code, you can specify theold filebygiving adiff option:
1
Thereis astandard..
includedirective,but itraiseserrors ifthefile isnotfound. Thisone only emitsawarning.
36
Chapter 7. Sphinx Markup Constructs