为Juptyer笔记本添加reStructuredText支持

问题描述 投票:0回答:1

我需要在JupyterLab中查看reStructuredText文件,到目前为止,我发现最好的是@akaihola's answer到相关的issue on github

我添加了一种解决方法,可以在不查看源代码的情况下呈现文件,如下所示。

jupyter-notebook restructuredtext jupyter-lab ipython-magic
1个回答
0
投票

如果其他人可能需要它,这是我目前正在使用的解决方案:

import docutils.core
import docutils.writers.html5_polyglot
from IPython.core.magic import register_cell_magic, register_line_magic
from IPython.display import HTML

@register_cell_magic
def rst(line, cell):
    "Render ReStructuredText"
    writer = docutils.writers.html5_polyglot.Writer()
    return HTML(docutils.core.publish_string(cell, writer=writer).decode('UTF-8'))

@register_line_magic
def rstfile(filename):
    "Render ReStructuredText"
    writer = docutils.writers.html5_polyglot.Writer()
    with open(filename, 'r') as file:
        cell = file.read()
    return HTML(docutils.core.publish_string(cell, writer=writer).decode('UTF-8'))

要查看rst文件,而没有源:

%rstfile <your-rst-filename>

要使用原始解决方案,作为rst单元,同时显示ReStructuredText源和呈现的输出:

%%rst
============
 Main title
============

Some **heavy** markup.
© www.soinside.com 2019 - 2024. All rights reserved.