如何在 reStructuredText 的代码块中强制使用空格
在 RST 中,我们在块前面使用一些空格来表示这是一个代码块。因为 Python 也使用空格来缩进代码块,所以如果我正在编写 Python 代码,我希望我的 RST 代码块保留这些空格。我怎样才能做到这一点?
假设我们有一个类:
class Test(object):
我们想要编写一个名为 __init__ 的方法,它是该类的成员。该方法属于另一个代码块,但我们希望有一些视觉线索,以便读者知道第二个代码块是前一个代码块的延续。目前,我使用#
来标记代码块的垂直引导线,如下所示:
def __init__(self):
pass
#
没有#
,def __init__(self)
将以与class Test(object)
相同的缩进级别打印。必须有更优雅的方式。
In RST, we use some whitespaces in front of a block to say this is a code block. Because Python also uses whitespace to indent a code block, I would like my RST code block to preserve those whitespaces if I were writing Python code. How can I do that?
Let's say we have a class:
class Test(object):
And we want to write a method called __init__
that is a member of this class. This method belongs to another code block but we want to have some visual clue so that readers know that this second block is a continuation of the previous one. At the moment, I use #
to mark the vertical guide line of a code block like this:
def __init__(self):
pass
#
Without the #
, def __init__(self)
would be printed at the same indentation level as class Test(object)
. There's gotta be more elegant way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要定义自己的指令(确实,标准
.. code::
指令会占用空格,但您可以创建自己的指令,但不会):您当然可以覆盖标准
.. code::
指令也与此相同。You need to define your own directive (it's true that the standard
.. code::
directive gobbles spaces but you can make your own directive that doesn't):You could of course overwrite the standard
.. code::
directive with this, too.啊...我以前遇到过这个;)。 # 技巧是我通常使用的,唉。如果您阅读规范,听起来它总是会取消前导缩进。 [1]
您还可以使用替代语法:
以“>”开头这将保留领先空间。
[1]:http://docutils.sourceforge.net /docs/ref/rst/restructedtext.html#indented-literal-blocks
编辑
刚刚挖掘了 docutils 代码(这也一直困扰着我)并可以确认它总是会去掉常见的缩进,不问任何问题。通过修改来改变这种行为很容易,但这会使生成的重组文本变得非标准。
Ah... I've run into this before ;). The # trick is usually what I use, alas. If you read the spec it sounds like it will always take away the leading indent. [1]
You could also use an alternate syntax:
With the leading ">" that will preserve leading space.
[1] : http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#indented-literal-blocks
EDIT
Just dug through the docutils code (this has been bugging me a lot too) and can confirm that it will always strip out the common indent, no questions asked. It would be easy to modify to change this behavior but that would make the resulting restructured text non-standard.
您还可以尝试 行块,如下所示:
尽管它们并不特定于代码示例。
You can also try Line Blocks which look like this:
though they aren't specific to code examples.