在sphinx中显示源代码示例

标准的rest文本块由 :: 在上一段末尾,用缩进分隔。

突出显示指令

默认的突出显示语言是python:可以使用 highlight 文档中的指令:

.. highlight:: html

The literal blocks are now highlighted as HTML, until a new directive is found.

::
   <html><head></head>
   <body>This is a text.</body>
   </html>

The following directive changes the hightlight language to SQL.

.. highlight:: sql

::
   SELECT * FROM mytable

.. highlight:: none

From here on no highlighting will be done.

::
   SELECT * FROM mytable

代码块指令

这个 code-block 指令可用于声明块中要使用的特定语言,而不管突出显示的语言是什么:

The following is a SQL statement.

.. code-block:: sql
   :linenos:

   SELECT * FROM mytable

行号对于长块(如此块)很有用:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
-- http://www.postgresonline.com/journal/index.php?/archives/97-SQL-Coding-Standards-To-Each-His-Own-Part-II.html
SELECT persons.id, persons.first_name, persons.last_name, forums.category,
   COUNT(DISTINCT posts.id) as num_posts,
   COALESCE(MAX(comments.rating), 0) AS highest_rating,
   COALESCE(MIN(comments.rating), 0) AS lowest_rating
FROM persons JOIN posts ON persons.id = posts.author
   JOIN forums on posts.forum = forums.id
   LEFT OUTER JOIN comments ON posts.id = comments.post
WHERE persons.status > 0
   AND forums.ratings = TRUE
   AND comments.post_date > ( now() - INTERVAL '1 year')
GROUP BY persons.id, persons.first_name, persons.last_name, forums.category
HAVING count(DISTINCT posts.id) > 0
ORDER BY persons.last_name, persons.first_name;

文本包含指令

另一个选项是包含给定源代码文件的一部分,如:

.. literalinclude:: filename
   :linenos:
   :language:
   :lines:
   :start-after:
   :end-before:
   :emphasize-lines:

下面是一个例子:

Literalinclude directive
************************

Another option is to include part of a given source code file, like this::

不使用行号(可以更改),可以使用选项 :start-after:end-before: 在包含的文件中搜索包含指定文本的行。例如::

.. literalinclude:: ShowingCodeExamplesInSphinx.rst
   :language: rst
   :start-after: Instead of using
   :end-before: For example

产生这个结果:

use the options ``:start-after`` and ``:end-before:``
that search the included file for lines containing the specified text.

Pygments雷克萨斯

语法突出显示由 Pygments (如果已安装):任何 `Pygments language lexers`_ 可以使用。

下表列出了一些有用的lexer(没有特定的顺序)。

莱克塞

短名称

结构化查询语言

SQL

SQL的PostgreSQL方言

波斯特雷斯尔

PostgreSQL程序语言

PLPGSQL

PostgreSQL控制台会话

PSQL

重新构造的文本

RST

Tex和 Latex

Latex

DOS/Windows批处理文件

蝙蝠

Windows PowerShell

PowerShell

bash shell脚本

猛击

bash shell会话

慰问

层叠样式表

CSS

HTML 4和XHTML 1

HTML

XML

XML

XSLT

XSLT

XQuery

XML查询语言

JavaScript

javascript

JSON数据结构

json

PHP源代码

PHP

HTML中嵌入的PHP

HTML+PHP

Python 2

Python

python 2回溯

PYTB

python控制台

皮康

Java

爪哇

Java属性格式中的配置文件

J属性

Apache配置文件格式的配置文件

阿帕切科夫

R源代码(或S或S-PLUS)

R

R控制台

溃败

Matlab

MATLAB

Matlab会话

数据库会话

NumPy

numpy