Skip to content

Commit

Permalink
Add 'notebook' reST directive
Browse files Browse the repository at this point in the history
  • Loading branch information
tbekolay committed Apr 5, 2016
1 parent 9dc9051 commit 212ea73
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions nbsphinx.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@

import copy
import docutils
from docutils import io
from docutils.parsers import rst
from docutils.parsers.rst import directives
import jinja2
import nbconvert
import nbformat
Expand Down Expand Up @@ -541,6 +543,45 @@ def run(self):
return [container]


class Notebook(rst.Directive):
"""Insert a notebook into a reST document."""
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {}

def run(self):
if not self.state.document.settings.file_insertion_enabled:
raise self.warning('"%s" directive disabled.' % self.name)

# Read the notebook to a string
path = directives.path(self.arguments[0])
rst_file = self.state_machine.document.attributes['source']
rst_dir = os.path.abspath(os.path.dirname(rst_file))
path = os.path.normpath(os.path.join(rst_dir, path))
e_handler = self.state.document.settings.input_encoding_error_handler
try:
self.state.document.settings.record_dependencies.add(path)
include_file = io.FileInput(source_path=path,
encoding='utf-8',
error_handler=e_handler)
except IOError as error:
raise self.severe(u'Problems with "%s" directive path:\n%s.' %
(self.name, error))
try:
rawtext = include_file.read()
except UnicodeError as error:
raise self.severe(u'Problem with "%s" directive:\n%s' %
(self.name, error))

# Use the NotebookParser to convert to reST and evaluate if needed
nbparser = NotebookParser()
# Inject the reST right into the document
nbparser.parse(rawtext, self.state.document)
# Nothing needs to be returned as the document is directly modified
return []


def _extract_toctree(cell):
"""Extract links from Markdown cell and create toctree."""
lines = ['.. toctree::']
Expand Down Expand Up @@ -848,6 +889,7 @@ def setup(app):

app.add_directive('nbinput', NbInput)
app.add_directive('nboutput', NbOutput)
app.add_directive('notebook', Notebook)
app.add_node(CodeNode,
html=(do_nothing, depart_code_html),
latex=(visit_code_latex, depart_code_latex))
Expand Down

0 comments on commit 212ea73

Please sign in to comment.