Add reStructuredText support for Juptyer notebooks

I needed to view reStructuredText files in JupyterLab, and the best I found so far was @akaihola's answer to a related issue on github.

I added a work around that would allow rendering the file without viewing the source, provided below.

1 answer

  • answered 2020-01-14 01:19 eldad-a

    In case anyone else may need it, here's the solution I am working with for now:

    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'))
    

    To view the rst file, without the source:

    %rstfile <your-rst-filename>
    

    To use the original solution, as an rst cell, showing both the ReStructuredText source and the rendered output:

    %%rst
    ============
     Main title
    ============
    
    Some **heavy** markup.