1"""NotebookExporter class"""
2
3# Copyright (c) IPython Development Team.
4# Distributed under the terms of the Modified BSD License.
5
6import nbformat
7from traitlets import Enum, default
8
9from .exporter import Exporter
10
11
12class NotebookExporter(Exporter):
13 """Exports to an IPython notebook.
14
15 This is useful when you want to use nbconvert's preprocessors to operate on
16 a notebook (e.g. to execute it) and then write it back to a notebook file.
17 """
18
19 nbformat_version = Enum(
20 list(nbformat.versions),
21 default_value=nbformat.current_nbformat,
22 help="""The nbformat version to write.
23 Use this to downgrade notebooks.
24 """,
25 ).tag(config=True)
26
27 @default("file_extension")
28 def _file_extension_default(self):
29 return ".ipynb"
30
31 output_mimetype = "application/json"
32 export_from_notebook = "Notebook"
33
34 def from_notebook_node(self, nb, resources=None, **kw):
35 """Convert from notebook node."""
36 nb_copy, resources = super().from_notebook_node(nb, resources, **kw)
37 if self.nbformat_version != nb_copy.nbformat:
38 resources["output_suffix"] = ".v%i" % self.nbformat_version
39 else:
40 resources["output_suffix"] = ".nbconvert"
41 output = nbformat.writes(nb_copy, version=self.nbformat_version)
42 if not output.endswith("\n"):
43 output = output + "\n"
44 return output, resources