diff --git a/IPython/testing/iptest.py b/IPython/testing/iptest.py
index 0b17ced..094e928 100644
--- a/IPython/testing/iptest.py
+++ b/IPython/testing/iptest.py
@@ -146,7 +146,7 @@ have['zmq'] = test_for('zmq.pyzmq_version_info', min_zmq, callback=lambda x: x()
test_group_names = ['core',
'extensions', 'lib', 'terminal', 'testing', 'utils',
- 'html', 'nbconvert'
+ 'html',
]
class TestSection(object):
@@ -239,22 +239,9 @@ sec.exclude('static')
sec.exclude('tasks')
if not have['jinja2']:
sec.exclude('notebookapp')
-if not have['pygments'] or not have['jinja2']:
- sec.exclude('nbconvert')
if not have['terminado']:
sec.exclude('terminal')
-# nbconvert:
-sec = test_sections['nbconvert']
-sec.requires('pygments', 'jinja2', 'jsonschema', 'mistune')
-# Exclude nbconvert directories containing config files used to test.
-# Executing the config files with iptest would cause an exception.
-sec.exclude('tests.files')
-sec.exclude('exporters.tests.files')
-if not have['tornado']:
- sec.exclude('nbconvert.post_processors.serve')
- sec.exclude('nbconvert.post_processors.tests.test_serve')
-
#-----------------------------------------------------------------------------
# Functions and classes
diff --git a/jupyter_nbconvert/__init__.py b/jupyter_nbconvert/__init__.py
deleted file mode 100755
index 9a915c8..0000000
--- a/jupyter_nbconvert/__init__.py
+++ /dev/null
@@ -1,7 +0,0 @@
-"""Utilities for converting notebooks to and from different formats."""
-
-from .exporters import *
-from . import filters
-from . import preprocessors
-from . import postprocessors
-from . import writers
diff --git a/jupyter_nbconvert/__main__.py b/jupyter_nbconvert/__main__.py
deleted file mode 100644
index 8f0dd72..0000000
--- a/jupyter_nbconvert/__main__.py
+++ /dev/null
@@ -1,2 +0,0 @@
-from .nbconvertapp import launch_new_instance
-launch_new_instance()
diff --git a/jupyter_nbconvert/exporters/__init__.py b/jupyter_nbconvert/exporters/__init__.py
deleted file mode 100644
index c3fee7c..0000000
--- a/jupyter_nbconvert/exporters/__init__.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from .export import *
-from .html import HTMLExporter
-from .slides import SlidesExporter
-from .templateexporter import TemplateExporter
-from .latex import LatexExporter
-from .markdown import MarkdownExporter
-from .notebook import NotebookExporter
-from .pdf import PDFExporter
-from .python import PythonExporter
-from .rst import RSTExporter
-from .exporter import Exporter, FilenameExtension
diff --git a/jupyter_nbconvert/exporters/export.py b/jupyter_nbconvert/exporters/export.py
deleted file mode 100644
index 4e78239..0000000
--- a/jupyter_nbconvert/exporters/export.py
+++ /dev/null
@@ -1,177 +0,0 @@
-"""Module containing single call export functions."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from functools import wraps
-
-from IPython.nbformat import NotebookNode
-from IPython.utils.decorators import undoc
-from IPython.utils.py3compat import string_types
-
-from .exporter import Exporter
-from .templateexporter import TemplateExporter
-from .html import HTMLExporter
-from .slides import SlidesExporter
-from .latex import LatexExporter
-from .pdf import PDFExporter
-from .markdown import MarkdownExporter
-from .python import PythonExporter
-from .rst import RSTExporter
-from .notebook import NotebookExporter
-from .script import ScriptExporter
-
-#-----------------------------------------------------------------------------
-# Classes
-#-----------------------------------------------------------------------------
-
-@undoc
-def DocDecorator(f):
-
- #Set docstring of function
- f.__doc__ = f.__doc__ + """
- nb : :class:`~IPython.nbformat.NotebookNode`
- The notebook to export.
- config : config (optional, keyword arg)
- User configuration instance.
- resources : dict (optional, keyword arg)
- Resources used in the conversion process.
-
- Returns
- -------
- tuple- output, resources, exporter_instance
- output : str
- Jinja 2 output. This is the resulting converted notebook.
- resources : dictionary
- Dictionary of resources used prior to and during the conversion
- process.
- exporter_instance : Exporter
- Instance of the Exporter class used to export the document. Useful
- to caller because it provides a 'file_extension' property which
- specifies what extension the output should be saved as.
-
- Notes
- -----
- WARNING: API WILL CHANGE IN FUTURE RELEASES OF NBCONVERT
- """
-
- @wraps(f)
- def decorator(*args, **kwargs):
- return f(*args, **kwargs)
-
- return decorator
-
-
-#-----------------------------------------------------------------------------
-# Functions
-#-----------------------------------------------------------------------------
-
-__all__ = [
- 'export',
- 'export_html',
- 'export_custom',
- 'export_slides',
- 'export_latex',
- 'export_pdf',
- 'export_markdown',
- 'export_python',
- 'export_script',
- 'export_rst',
- 'export_by_name',
- 'get_export_names',
- 'ExporterNameError'
-]
-
-
-class ExporterNameError(NameError):
- pass
-
-@DocDecorator
-def export(exporter, nb, **kw):
- """
- Export a notebook object using specific exporter class.
-
- Parameters
- ----------
- exporter : class:`~jupyter_nbconvert.exporters.exporter.Exporter` class or instance
- Class type or instance of the exporter that should be used. If the
- method initializes it's own instance of the class, it is ASSUMED that
- the class type provided exposes a constructor (``__init__``) with the same
- signature as the base Exporter class.
- """
-
- #Check arguments
- if exporter is None:
- raise TypeError("Exporter is None")
- elif not isinstance(exporter, Exporter) and not issubclass(exporter, Exporter):
- raise TypeError("exporter does not inherit from Exporter (base)")
- if nb is None:
- raise TypeError("nb is None")
-
- #Create the exporter
- resources = kw.pop('resources', None)
- if isinstance(exporter, Exporter):
- exporter_instance = exporter
- else:
- exporter_instance = exporter(**kw)
-
- #Try to convert the notebook using the appropriate conversion function.
- if isinstance(nb, NotebookNode):
- output, resources = exporter_instance.from_notebook_node(nb, resources)
- elif isinstance(nb, string_types):
- output, resources = exporter_instance.from_filename(nb, resources)
- else:
- output, resources = exporter_instance.from_file(nb, resources)
- return output, resources
-
-exporter_map = dict(
- custom=TemplateExporter,
- html=HTMLExporter,
- slides=SlidesExporter,
- latex=LatexExporter,
- pdf=PDFExporter,
- markdown=MarkdownExporter,
- python=PythonExporter,
- rst=RSTExporter,
- notebook=NotebookExporter,
- script=ScriptExporter,
-)
-
-def _make_exporter(name, E):
- """make an export_foo function from a short key and Exporter class E"""
- def _export(nb, **kw):
- return export(E, nb, **kw)
- _export.__doc__ = """Export a notebook object to {0} format""".format(name)
- return _export
-
-g = globals()
-
-for name, E in exporter_map.items():
- g['export_%s' % name] = DocDecorator(_make_exporter(name, E))
-
-@DocDecorator
-def export_by_name(format_name, nb, **kw):
- """
- Export a notebook object to a template type by its name. Reflection
- (Inspect) is used to find the template's corresponding explicit export
- method defined in this module. That method is then called directly.
-
- Parameters
- ----------
- format_name : str
- Name of the template style to export to.
- """
-
- function_name = "export_" + format_name.lower()
-
- if function_name in globals():
- return globals()[function_name](nb, **kw)
- else:
- raise ExporterNameError("template for `%s` not found" % function_name)
-
-
-def get_export_names():
- """Return a list of the currently supported export targets
-
- WARNING: API WILL CHANGE IN FUTURE RELEASES OF NBCONVERT"""
- return sorted(exporter_map.keys())
diff --git a/jupyter_nbconvert/exporters/exporter.py b/jupyter_nbconvert/exporters/exporter.py
deleted file mode 100644
index 6787582..0000000
--- a/jupyter_nbconvert/exporters/exporter.py
+++ /dev/null
@@ -1,280 +0,0 @@
-"""This module defines a base Exporter class. For Jinja template-based export,
-see templateexporter.py.
-"""
-
-
-from __future__ import print_function, absolute_import
-
-import io
-import os
-import copy
-import collections
-import datetime
-
-from IPython.config.configurable import LoggingConfigurable
-from IPython.config import Config
-from IPython import nbformat
-from IPython.utils.traitlets import MetaHasTraits, Unicode, List, TraitError
-from IPython.utils.importstring import import_item
-from IPython.utils import text, py3compat
-
-
-class ResourcesDict(collections.defaultdict):
- def __missing__(self, key):
- return ''
-
-
-class FilenameExtension(Unicode):
- """A trait for filename extensions."""
-
- default_value = u''
- info_text = 'a filename extension, beginning with a dot'
-
- def validate(self, obj, value):
- # cast to proper unicode
- value = super(FilenameExtension, self).validate(obj, value)
-
- # check that it starts with a dot
- if value and not value.startswith('.'):
- msg = "FileExtension trait '{}' does not begin with a dot: {!r}"
- raise TraitError(msg.format(self.name, value))
-
- return value
-
-
-class Exporter(LoggingConfigurable):
- """
- Class containing methods that sequentially run a list of preprocessors on a
- NotebookNode object and then return the modified NotebookNode object and
- accompanying resources dict.
- """
-
- file_extension = FilenameExtension(
- '.txt', config=True,
- help="Extension of the file that should be written to disk"
- )
-
- # MIME type of the result file, for HTTP response headers.
- # This is *not* a traitlet, because we want to be able to access it from
- # the class, not just on instances.
- output_mimetype = ''
-
- #Configurability, allows the user to easily add filters and preprocessors.
- preprocessors = List(config=True,
- help="""List of preprocessors, by name or namespace, to enable.""")
-
- _preprocessors = List()
-
- default_preprocessors = List(['jupyter_nbconvert.preprocessors.coalesce_streams',
- 'jupyter_nbconvert.preprocessors.SVG2PDFPreprocessor',
- 'jupyter_nbconvert.preprocessors.ExtractOutputPreprocessor',
- 'jupyter_nbconvert.preprocessors.CSSHTMLHeaderPreprocessor',
- 'jupyter_nbconvert.preprocessors.RevealHelpPreprocessor',
- 'jupyter_nbconvert.preprocessors.LatexPreprocessor',
- 'jupyter_nbconvert.preprocessors.ClearOutputPreprocessor',
- 'jupyter_nbconvert.preprocessors.ExecutePreprocessor',
- 'jupyter_nbconvert.preprocessors.HighlightMagicsPreprocessor'],
- config=True,
- help="""List of preprocessors available by default, by name, namespace,
- instance, or type.""")
-
-
- def __init__(self, config=None, **kw):
- """
- Public constructor
-
- Parameters
- ----------
- config : config
- User configuration instance.
- """
- with_default_config = self.default_config
- if config:
- with_default_config.merge(config)
-
- super(Exporter, self).__init__(config=with_default_config, **kw)
-
- self._init_preprocessors()
-
-
- @property
- def default_config(self):
- return Config()
-
- def from_notebook_node(self, nb, resources=None, **kw):
- """
- Convert a notebook from a notebook node instance.
-
- Parameters
- ----------
- nb : :class:`~IPython.nbformat.NotebookNode`
- Notebook node (dict-like with attr-access)
- resources : dict
- Additional resources that can be accessed read/write by
- preprocessors and filters.
- **kw
- Ignored (?)
- """
- nb_copy = copy.deepcopy(nb)
- resources = self._init_resources(resources)
-
- if 'language' in nb['metadata']:
- resources['language'] = nb['metadata']['language'].lower()
-
- # Preprocess
- nb_copy, resources = self._preprocess(nb_copy, resources)
-
- return nb_copy, resources
-
-
- def from_filename(self, filename, resources=None, **kw):
- """
- Convert a notebook from a notebook file.
-
- Parameters
- ----------
- filename : str
- Full filename of the notebook file to open and convert.
- """
-
- # Pull the metadata from the filesystem.
- if resources is None:
- resources = ResourcesDict()
- if not 'metadata' in resources or resources['metadata'] == '':
- resources['metadata'] = ResourcesDict()
- path, basename = os.path.split(filename)
- notebook_name = basename[:basename.rfind('.')]
- resources['metadata']['name'] = notebook_name
- resources['metadata']['path'] = path
-
- modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(filename))
- resources['metadata']['modified_date'] = modified_date.strftime(text.date_format)
-
- with io.open(filename, encoding='utf-8') as f:
- return self.from_notebook_node(nbformat.read(f, as_version=4), resources=resources, **kw)
-
-
- def from_file(self, file_stream, resources=None, **kw):
- """
- Convert a notebook from a notebook file.
-
- Parameters
- ----------
- file_stream : file-like object
- Notebook file-like object to convert.
- """
- return self.from_notebook_node(nbformat.read(file_stream, as_version=4), resources=resources, **kw)
-
-
- def register_preprocessor(self, preprocessor, enabled=False):
- """
- Register a preprocessor.
- Preprocessors are classes that act upon the notebook before it is
- passed into the Jinja templating engine. preprocessors are also
- capable of passing additional information to the Jinja
- templating engine.
-
- Parameters
- ----------
- preprocessor : preprocessor
- """
- if preprocessor is None:
- raise TypeError('preprocessor')
- isclass = isinstance(preprocessor, type)
- constructed = not isclass
-
- # Handle preprocessor's registration based on it's type
- if constructed and isinstance(preprocessor, py3compat.string_types):
- # Preprocessor is a string, import the namespace and recursively call
- # this register_preprocessor method
- preprocessor_cls = import_item(preprocessor)
- return self.register_preprocessor(preprocessor_cls, enabled)
-
- if constructed and hasattr(preprocessor, '__call__'):
- # Preprocessor is a function, no need to construct it.
- # Register and return the preprocessor.
- if enabled:
- preprocessor.enabled = True
- self._preprocessors.append(preprocessor)
- return preprocessor
-
- elif isclass and isinstance(preprocessor, MetaHasTraits):
- # Preprocessor is configurable. Make sure to pass in new default for
- # the enabled flag if one was specified.
- self.register_preprocessor(preprocessor(parent=self), enabled)
-
- elif isclass:
- # Preprocessor is not configurable, construct it
- self.register_preprocessor(preprocessor(), enabled)
-
- else:
- # Preprocessor is an instance of something without a __call__
- # attribute.
- raise TypeError('preprocessor')
-
-
- def _init_preprocessors(self):
- """
- Register all of the preprocessors needed for this exporter, disabled
- unless specified explicitly.
- """
- self._preprocessors = []
-
- # Load default preprocessors (not necessarly enabled by default).
- for preprocessor in self.default_preprocessors:
- self.register_preprocessor(preprocessor)
-
- # Load user-specified preprocessors. Enable by default.
- for preprocessor in self.preprocessors:
- self.register_preprocessor(preprocessor, enabled=True)
-
-
- def _init_resources(self, resources):
-
- #Make sure the resources dict is of ResourcesDict type.
- if resources is None:
- resources = ResourcesDict()
- if not isinstance(resources, ResourcesDict):
- new_resources = ResourcesDict()
- new_resources.update(resources)
- resources = new_resources
-
- #Make sure the metadata extension exists in resources
- if 'metadata' in resources:
- if not isinstance(resources['metadata'], ResourcesDict):
- new_metadata = ResourcesDict()
- new_metadata.update(resources['metadata'])
- resources['metadata'] = new_metadata
- else:
- resources['metadata'] = ResourcesDict()
- if not resources['metadata']['name']:
- resources['metadata']['name'] = 'Notebook'
-
- #Set the output extension
- resources['output_extension'] = self.file_extension
- return resources
-
-
- def _preprocess(self, nb, resources):
- """
- Preprocess the notebook before passing it into the Jinja engine.
- To preprocess the notebook is to apply all of the
-
- Parameters
- ----------
- nb : notebook node
- notebook that is being exported.
- resources : a dict of additional resources that
- can be accessed read/write by preprocessors
- """
-
- # Do a copy.deepcopy first,
- # we are never safe enough with what the preprocessors could do.
- nbc = copy.deepcopy(nb)
- resc = copy.deepcopy(resources)
-
- #Run each preprocessor on the notebook. Carry the output along
- #to each preprocessor
- for preprocessor in self._preprocessors:
- nbc, resc = preprocessor(nbc, resc)
- return nbc, resc
diff --git a/jupyter_nbconvert/exporters/html.py b/jupyter_nbconvert/exporters/html.py
deleted file mode 100644
index a4dbb02..0000000
--- a/jupyter_nbconvert/exporters/html.py
+++ /dev/null
@@ -1,57 +0,0 @@
-"""HTML Exporter class"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import os
-
-from jupyter_nbconvert.filters.highlight import Highlight2HTML
-from IPython.config import Config
-
-from .templateexporter import TemplateExporter
-
-#-----------------------------------------------------------------------------
-# Classes
-#-----------------------------------------------------------------------------
-
-class HTMLExporter(TemplateExporter):
- """
- Exports a basic HTML document. This exporter assists with the export of
- HTML. Inherit from it if you are writing your own HTML template and need
- custom preprocessors/filters. If you don't need custom preprocessors/
- filters, just change the 'template_file' config option.
- """
-
- def _file_extension_default(self):
- return '.html'
-
- def _default_template_path_default(self):
- return os.path.join("..", "templates", "html")
-
- def _template_file_default(self):
- return 'full'
-
- output_mimetype = 'text/html'
-
- @property
- def default_config(self):
- c = Config({
- 'NbConvertBase': {
- 'display_data_priority' : ['application/javascript', 'text/html', 'text/markdown', 'application/pdf', 'image/svg+xml', 'text/latex', 'image/png', 'image/jpeg', 'text/plain']
- },
- 'CSSHTMLHeaderPreprocessor':{
- 'enabled':True
- },
- 'HighlightMagicsPreprocessor': {
- 'enabled':True
- }
- })
- c.merge(super(HTMLExporter,self).default_config)
- return c
-
- def from_notebook_node(self, nb, resources=None, **kw):
- langinfo = nb.metadata.get('language_info', {})
- lexer = langinfo.get('pygments_lexer', langinfo.get('name', None))
- self.register_filter('highlight_code',
- Highlight2HTML(pygments_lexer=lexer, parent=self))
- return super(HTMLExporter, self).from_notebook_node(nb, resources, **kw)
diff --git a/jupyter_nbconvert/exporters/latex.py b/jupyter_nbconvert/exporters/latex.py
deleted file mode 100644
index be6c7f8..0000000
--- a/jupyter_nbconvert/exporters/latex.py
+++ /dev/null
@@ -1,96 +0,0 @@
-"""LaTeX Exporter class"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-# Stdlib imports
-import os
-
-# IPython imports
-from IPython.utils.traitlets import Unicode
-from IPython.config import Config
-
-from jupyter_nbconvert.filters.highlight import Highlight2Latex
-from .templateexporter import TemplateExporter
-
-#-----------------------------------------------------------------------------
-# Classes and functions
-#-----------------------------------------------------------------------------
-
-class LatexExporter(TemplateExporter):
- """
- Exports to a Latex template. Inherit from this class if your template is
- LaTeX based and you need custom tranformers/filters. Inherit from it if
- you are writing your own HTML template and need custom tranformers/filters.
- If you don't need custom tranformers/filters, just change the
- 'template_file' config option. Place your template in the special "/latex"
- subfolder of the "../templates" folder.
- """
-
- def _file_extension_default(self):
- return '.tex'
-
- def _template_file_default(self):
- return 'article'
-
- #Latex constants
- def _default_template_path_default(self):
- return os.path.join("..", "templates", "latex")
-
- def _template_skeleton_path_default(self):
- return os.path.join("..", "templates", "latex", "skeleton")
-
- #Special Jinja2 syntax that will not conflict when exporting latex.
- jinja_comment_block_start = Unicode("((=", config=True)
- jinja_comment_block_end = Unicode("=))", config=True)
- jinja_variable_block_start = Unicode("(((", config=True)
- jinja_variable_block_end = Unicode(")))", config=True)
- jinja_logic_block_start = Unicode("((*", config=True)
- jinja_logic_block_end = Unicode("*))", config=True)
-
- #Extension that the template files use.
- template_extension = Unicode(".tplx", config=True)
-
- output_mimetype = 'text/latex'
-
-
- @property
- def default_config(self):
- c = Config({
- 'NbConvertBase': {
- 'display_data_priority' : ['text/latex', 'application/pdf', 'image/png', 'image/jpeg', 'image/svg+xml', 'text/plain']
- },
- 'ExtractOutputPreprocessor': {
- 'enabled':True
- },
- 'SVG2PDFPreprocessor': {
- 'enabled':True
- },
- 'LatexPreprocessor': {
- 'enabled':True
- },
- 'SphinxPreprocessor': {
- 'enabled':True
- },
- 'HighlightMagicsPreprocessor': {
- 'enabled':True
- }
- })
- c.merge(super(LatexExporter,self).default_config)
- return c
-
- def from_notebook_node(self, nb, resources=None, **kw):
- langinfo = nb.metadata.get('language_info', {})
- lexer = langinfo.get('pygments_lexer', langinfo.get('name', None))
- self.register_filter('highlight_code',
- Highlight2Latex(pygments_lexer=lexer, parent=self))
- return super(LatexExporter, self).from_notebook_node(nb, resources, **kw)
diff --git a/jupyter_nbconvert/exporters/markdown.py b/jupyter_nbconvert/exporters/markdown.py
deleted file mode 100644
index 9c8abf5..0000000
--- a/jupyter_nbconvert/exporters/markdown.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""Markdown Exporter class"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from IPython.config import Config
-
-from .templateexporter import TemplateExporter
-
-#-----------------------------------------------------------------------------
-# Classes
-#-----------------------------------------------------------------------------
-
-class MarkdownExporter(TemplateExporter):
- """
- Exports to a markdown document (.md)
- """
-
- def _file_extension_default(self):
- return '.md'
-
- def _template_file_default(self):
- return 'markdown'
-
- output_mimetype = 'text/markdown'
-
- def _raw_mimetypes_default(self):
- return ['text/markdown', 'text/html', '']
-
- @property
- def default_config(self):
- c = Config({'ExtractOutputPreprocessor':{'enabled':True}})
- c.merge(super(MarkdownExporter,self).default_config)
- return c
diff --git a/jupyter_nbconvert/exporters/notebook.py b/jupyter_nbconvert/exporters/notebook.py
deleted file mode 100644
index 20bf32a..0000000
--- a/jupyter_nbconvert/exporters/notebook.py
+++ /dev/null
@@ -1,32 +0,0 @@
-"""NotebookExporter class"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from .exporter import Exporter
-from IPython import nbformat
-from IPython.utils.traitlets import Enum
-
-class NotebookExporter(Exporter):
- """Exports to an IPython notebook."""
-
- nbformat_version = Enum(list(nbformat.versions),
- default_value=nbformat.current_nbformat,
- config=True,
- help="""The nbformat version to write.
- Use this to downgrade notebooks.
- """
- )
- def _file_extension_default(self):
- return '.ipynb'
-
- output_mimetype = 'application/json'
-
- def from_notebook_node(self, nb, resources=None, **kw):
- nb_copy, resources = super(NotebookExporter, self).from_notebook_node(nb, resources, **kw)
- if self.nbformat_version != nb_copy.nbformat:
- resources['output_suffix'] = '.v%i' % self.nbformat_version
- else:
- resources['output_suffix'] = '.nbconvert'
- output = nbformat.writes(nb_copy, version=self.nbformat_version)
- return output, resources
diff --git a/jupyter_nbconvert/exporters/pdf.py b/jupyter_nbconvert/exporters/pdf.py
deleted file mode 100644
index 4e5095c..0000000
--- a/jupyter_nbconvert/exporters/pdf.py
+++ /dev/null
@@ -1,149 +0,0 @@
-"""Export to PDF via latex"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import subprocess
-import os
-import sys
-
-from IPython.utils.py3compat import which
-from IPython.utils.traitlets import Integer, List, Bool, Instance
-from IPython.utils.tempdir import TemporaryWorkingDirectory
-from .latex import LatexExporter
-
-
-class PDFExporter(LatexExporter):
- """Writer designed to write to PDF files"""
-
- latex_count = Integer(3, config=True,
- help="How many times latex will be called."
- )
-
- latex_command = List([u"pdflatex", u"{filename}"], config=True,
- help="Shell command used to compile latex."
- )
-
- bib_command = List([u"bibtex", u"{filename}"], config=True,
- help="Shell command used to run bibtex."
- )
-
- verbose = Bool(False, config=True,
- help="Whether to display the output of latex commands."
- )
-
- temp_file_exts = List(['.aux', '.bbl', '.blg', '.idx', '.log', '.out'], config=True,
- help="File extensions of temp files to remove after running."
- )
-
- writer = Instance("jupyter_nbconvert.writers.FilesWriter", args=())
-
- def run_command(self, command_list, filename, count, log_function):
- """Run command_list count times.
-
- Parameters
- ----------
- command_list : list
- A list of args to provide to Popen. Each element of this
- list will be interpolated with the filename to convert.
- filename : unicode
- The name of the file to convert.
- count : int
- How many times to run the command.
-
- Returns
- -------
- success : bool
- A boolean indicating if the command was successful (True)
- or failed (False).
- """
- command = [c.format(filename=filename) for c in command_list]
-
- # On windows with python 2.x there is a bug in subprocess.Popen and
- # unicode commands are not supported
- if sys.platform == 'win32' and sys.version_info < (3,0):
- #We must use cp1252 encoding for calling subprocess.Popen
- #Note that sys.stdin.encoding and encoding.DEFAULT_ENCODING
- # could be different (cp437 in case of dos console)
- command = [c.encode('cp1252') for c in command]
-
- # This will throw a clearer error if the command is not found
- cmd = which(command_list[0])
- if cmd is None:
- raise OSError("%s not found on PATH" % command_list[0])
-
- times = 'time' if count == 1 else 'times'
- self.log.info("Running %s %i %s: %s", command_list[0], count, times, command)
- with open(os.devnull, 'rb') as null:
- stdout = subprocess.PIPE if not self.verbose else None
- for index in range(count):
- p = subprocess.Popen(command, stdout=stdout, stdin=null)
- out, err = p.communicate()
- if p.returncode:
- if self.verbose:
- # verbose means I didn't capture stdout with PIPE,
- # so it's already been displayed and `out` is None.
- out = u''
- else:
- out = out.decode('utf-8', 'replace')
- log_function(command, out)
- return False # failure
- return True # success
-
- def run_latex(self, filename):
- """Run pdflatex self.latex_count times."""
-
- def log_error(command, out):
- self.log.critical(u"%s failed: %s\n%s", command[0], command, out)
-
- return self.run_command(self.latex_command, filename,
- self.latex_count, log_error)
-
- def run_bib(self, filename):
- """Run bibtex self.latex_count times."""
- filename = os.path.splitext(filename)[0]
-
- def log_error(command, out):
- self.log.warn('%s had problems, most likely because there were no citations',
- command[0])
- self.log.debug(u"%s output: %s\n%s", command[0], command, out)
-
- return self.run_command(self.bib_command, filename, 1, log_error)
-
- def clean_temp_files(self, filename):
- """Remove temporary files created by pdflatex/bibtex."""
- self.log.info("Removing temporary LaTeX files")
- filename = os.path.splitext(filename)[0]
- for ext in self.temp_file_exts:
- try:
- os.remove(filename+ext)
- except OSError:
- pass
-
- def from_notebook_node(self, nb, resources=None, **kw):
- latex, resources = super(PDFExporter, self).from_notebook_node(
- nb, resources=resources, **kw
- )
- with TemporaryWorkingDirectory() as td:
- notebook_name = "notebook"
- tex_file = self.writer.write(latex, resources, notebook_name=notebook_name)
- self.log.info("Building PDF")
- rc = self.run_latex(tex_file)
- if not rc:
- rc = self.run_bib(tex_file)
- if not rc:
- rc = self.run_latex(tex_file)
-
- pdf_file = notebook_name + '.pdf'
- if not os.path.isfile(pdf_file):
- raise RuntimeError("PDF creating failed")
- self.log.info('PDF successfully created')
- with open(pdf_file, 'rb') as f:
- pdf_data = f.read()
-
- # convert output extension to pdf
- # the writer above required it to be tex
- resources['output_extension'] = '.pdf'
-
- return pdf_data, resources
-
diff --git a/jupyter_nbconvert/exporters/python.py b/jupyter_nbconvert/exporters/python.py
deleted file mode 100644
index e1218da..0000000
--- a/jupyter_nbconvert/exporters/python.py
+++ /dev/null
@@ -1,31 +0,0 @@
-"""Python script Exporter class"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from .templateexporter import TemplateExporter
-
-#-----------------------------------------------------------------------------
-# Classes
-#-----------------------------------------------------------------------------
-
-class PythonExporter(TemplateExporter):
- """
- Exports a Python code file.
- """
- def _file_extension_default(self):
- return '.py'
-
- def _template_file_default(self):
- return 'python'
-
- output_mimetype = 'text/x-python'
diff --git a/jupyter_nbconvert/exporters/rst.py b/jupyter_nbconvert/exporters/rst.py
deleted file mode 100644
index 731e978..0000000
--- a/jupyter_nbconvert/exporters/rst.py
+++ /dev/null
@@ -1,40 +0,0 @@
-"""restructuredText Exporter class"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from IPython.config import Config
-
-from .templateexporter import TemplateExporter
-
-#-----------------------------------------------------------------------------
-# Classes
-#-----------------------------------------------------------------------------
-
-class RSTExporter(TemplateExporter):
- """
- Exports restructured text documents.
- """
-
- def _file_extension_default(self):
- return '.rst'
-
- def _template_file_default(self):
- return 'rst'
-
- output_mimetype = 'text/restructuredtext'
-
- @property
- def default_config(self):
- c = Config({'ExtractOutputPreprocessor':{'enabled':True}})
- c.merge(super(RSTExporter,self).default_config)
- return c
diff --git a/jupyter_nbconvert/exporters/script.py b/jupyter_nbconvert/exporters/script.py
deleted file mode 100644
index 52d2638..0000000
--- a/jupyter_nbconvert/exporters/script.py
+++ /dev/null
@@ -1,33 +0,0 @@
-"""Generic script exporter class for any kernel language"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from .templateexporter import TemplateExporter
-
-from IPython.utils.traitlets import Dict
-
-class ScriptExporter(TemplateExporter):
-
- _exporters = Dict()
-
- def _template_file_default(self):
- return 'script'
-
- def from_notebook_node(self, nb, resources=None, **kw):
- langinfo = nb.metadata.get('language_info', {})
-
- # delegate to custom exporter, if specified
- exporter_name = langinfo.get('nbconvert_exporter')
- if exporter_name and exporter_name != 'script':
- self.log.debug("Loading script exporter: %s", exporter_name)
- from .export import exporter_map
- if exporter_name not in self._exporters:
- Exporter = exporter_map[exporter_name]
- self._exporters[exporter_name] = Exporter(parent=self)
- exporter = self._exporters[exporter_name]
- return exporter.from_notebook_node(nb, resources, **kw)
-
- self.file_extension = langinfo.get('file_extension', '.txt')
- self.output_mimetype = langinfo.get('mimetype', 'text/plain')
- return super(ScriptExporter, self).from_notebook_node(nb, resources, **kw)
diff --git a/jupyter_nbconvert/exporters/slides.py b/jupyter_nbconvert/exporters/slides.py
deleted file mode 100644
index c2e5d03..0000000
--- a/jupyter_nbconvert/exporters/slides.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""HTML slide show Exporter class"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from jupyter_nbconvert import preprocessors
-from IPython.config import Config
-
-from .html import HTMLExporter
-
-#-----------------------------------------------------------------------------
-# Classes
-#-----------------------------------------------------------------------------
-
-class SlidesExporter(HTMLExporter):
- """Exports HTML slides with reveal.js"""
-
- def _file_extension_default(self):
- return '.slides.html'
-
- def _template_file_default(self):
- return 'slides_reveal'
-
- output_mimetype = 'text/html'
-
- @property
- def default_config(self):
- c = Config({
- 'RevealHelpPreprocessor': {
- 'enabled': True,
- },
- })
- c.merge(super(SlidesExporter,self).default_config)
- return c
diff --git a/jupyter_nbconvert/exporters/templateexporter.py b/jupyter_nbconvert/exporters/templateexporter.py
deleted file mode 100644
index ca488c8..0000000
--- a/jupyter_nbconvert/exporters/templateexporter.py
+++ /dev/null
@@ -1,321 +0,0 @@
-"""This module defines TemplateExporter, a highly configurable converter
-that uses Jinja2 to export notebook files into different formats.
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from __future__ import print_function, absolute_import
-
-# Stdlib imports
-import os
-
-# other libs/dependencies are imported at runtime
-# to move ImportErrors to runtime when the requirement is actually needed
-
-# IPython imports
-from IPython.utils.traitlets import MetaHasTraits, Unicode, List, Dict, Any
-from IPython.utils.importstring import import_item
-from IPython.utils import py3compat, text
-
-from jupyter_nbconvert import filters
-from .exporter import Exporter
-
-#-----------------------------------------------------------------------------
-# Globals and constants
-#-----------------------------------------------------------------------------
-
-#Jinja2 extensions to load.
-JINJA_EXTENSIONS = ['jinja2.ext.loopcontrols']
-
-default_filters = {
- 'indent': text.indent,
- 'markdown2html': filters.markdown2html,
- 'ansi2html': filters.ansi2html,
- 'filter_data_type': filters.DataTypeFilter,
- 'get_lines': filters.get_lines,
- 'highlight2html': filters.Highlight2HTML,
- 'highlight2latex': filters.Highlight2Latex,
- 'ipython2python': filters.ipython2python,
- 'posix_path': filters.posix_path,
- 'markdown2latex': filters.markdown2latex,
- 'markdown2rst': filters.markdown2rst,
- 'comment_lines': filters.comment_lines,
- 'strip_ansi': filters.strip_ansi,
- 'strip_dollars': filters.strip_dollars,
- 'strip_files_prefix': filters.strip_files_prefix,
- 'html2text' : filters.html2text,
- 'add_anchor': filters.add_anchor,
- 'ansi2latex': filters.ansi2latex,
- 'wrap_text': filters.wrap_text,
- 'escape_latex': filters.escape_latex,
- 'citation2latex': filters.citation2latex,
- 'path2url': filters.path2url,
- 'add_prompts': filters.add_prompts,
- 'ascii_only': filters.ascii_only,
- 'prevent_list_blocks': filters.prevent_list_blocks,
-}
-
-#-----------------------------------------------------------------------------
-# Class
-#-----------------------------------------------------------------------------
-
-class TemplateExporter(Exporter):
- """
- Exports notebooks into other file formats. Uses Jinja 2 templating engine
- to output new formats. Inherit from this class if you are creating a new
- template type along with new filters/preprocessors. If the filters/
- preprocessors provided by default suffice, there is no need to inherit from
- this class. Instead, override the template_file and file_extension
- traits via a config file.
-
- {filters}
- """
-
- # finish the docstring
- __doc__ = __doc__.format(filters = '- '+'\n - '.join(default_filters.keys()))
-
-
- template_file = Unicode(u'default',
- config=True,
- help="Name of the template file to use")
- def _template_file_changed(self, name, old, new):
- if new == 'default':
- self.template_file = self.default_template
- else:
- self.template_file = new
- self.template = None
- self._load_template()
-
- default_template = Unicode(u'')
- template = Any()
- environment = Any()
-
- template_path = List(['.'], config=True)
- def _template_path_changed(self, name, old, new):
- self._load_template()
-
- default_template_path = Unicode(
- os.path.join("..", "templates"),
- help="Path where the template files are located.")
-
- template_skeleton_path = Unicode(
- os.path.join("..", "templates", "skeleton"),
- help="Path where the template skeleton files are located.")
-
- #Jinja block definitions
- jinja_comment_block_start = Unicode("", config=True)
- jinja_comment_block_end = Unicode("", config=True)
- jinja_variable_block_start = Unicode("", config=True)
- jinja_variable_block_end = Unicode("", config=True)
- jinja_logic_block_start = Unicode("", config=True)
- jinja_logic_block_end = Unicode("", config=True)
-
- #Extension that the template files use.
- template_extension = Unicode(".tpl", config=True)
-
- filters = Dict(config=True,
- help="""Dictionary of filters, by name and namespace, to add to the Jinja
- environment.""")
-
- raw_mimetypes = List(config=True,
- help="""formats of raw cells to be included in this Exporter's output."""
- )
- def _raw_mimetypes_default(self):
- return [self.output_mimetype, '']
-
-
- def __init__(self, config=None, extra_loaders=None, **kw):
- """
- Public constructor
-
- Parameters
- ----------
- config : config
- User configuration instance.
- extra_loaders : list[of Jinja Loaders]
- ordered list of Jinja loader to find templates. Will be tried in order
- before the default FileSystem ones.
- template : str (optional, kw arg)
- Template to use when exporting.
- """
- super(TemplateExporter, self).__init__(config=config, **kw)
-
- #Init
- self._init_template()
- self._init_environment(extra_loaders=extra_loaders)
- self._init_filters()
-
-
- def _load_template(self):
- """Load the Jinja template object from the template file
-
- This is a no-op if the template attribute is already defined,
- or the Jinja environment is not setup yet.
-
- This is triggered by various trait changes that would change the template.
- """
- from jinja2 import TemplateNotFound
-
- if self.template is not None:
- return
- # called too early, do nothing
- if self.environment is None:
- return
- # Try different template names during conversion. First try to load the
- # template by name with extension added, then try loading the template
- # as if the name is explicitly specified, then try the name as a
- # 'flavor', and lastly just try to load the template by module name.
- try_names = []
- if self.template_file:
- try_names.extend([
- self.template_file + self.template_extension,
- self.template_file,
- ])
- for try_name in try_names:
- self.log.debug("Attempting to load template %s", try_name)
- try:
- self.template = self.environment.get_template(try_name)
- except (TemplateNotFound, IOError):
- pass
- except Exception as e:
- self.log.warn("Unexpected exception loading template: %s", try_name, exc_info=True)
- else:
- self.log.debug("Loaded template %s", try_name)
- break
-
- def from_notebook_node(self, nb, resources=None, **kw):
- """
- Convert a notebook from a notebook node instance.
-
- Parameters
- ----------
- nb : :class:`~IPython.nbformat.NotebookNode`
- Notebook node
- resources : dict
- Additional resources that can be accessed read/write by
- preprocessors and filters.
- """
- nb_copy, resources = super(TemplateExporter, self).from_notebook_node(nb, resources, **kw)
- resources.setdefault('raw_mimetypes', self.raw_mimetypes)
-
- self._load_template()
-
- if self.template is not None:
- output = self.template.render(nb=nb_copy, resources=resources)
- else:
- raise IOError('template file "%s" could not be found' % self.template_file)
- return output, resources
-
-
- def register_filter(self, name, jinja_filter):
- """
- Register a filter.
- A filter is a function that accepts and acts on one string.
- The filters are accesible within the Jinja templating engine.
-
- Parameters
- ----------
- name : str
- name to give the filter in the Jinja engine
- filter : filter
- """
- if jinja_filter is None:
- raise TypeError('filter')
- isclass = isinstance(jinja_filter, type)
- constructed = not isclass
-
- #Handle filter's registration based on it's type
- if constructed and isinstance(jinja_filter, py3compat.string_types):
- #filter is a string, import the namespace and recursively call
- #this register_filter method
- filter_cls = import_item(jinja_filter)
- return self.register_filter(name, filter_cls)
-
- if constructed and hasattr(jinja_filter, '__call__'):
- #filter is a function, no need to construct it.
- self.environment.filters[name] = jinja_filter
- return jinja_filter
-
- elif isclass and isinstance(jinja_filter, MetaHasTraits):
- #filter is configurable. Make sure to pass in new default for
- #the enabled flag if one was specified.
- filter_instance = jinja_filter(parent=self)
- self.register_filter(name, filter_instance )
-
- elif isclass:
- #filter is not configurable, construct it
- filter_instance = jinja_filter()
- self.register_filter(name, filter_instance)
-
- else:
- #filter is an instance of something without a __call__
- #attribute.
- raise TypeError('filter')
-
-
- def _init_template(self):
- """
- Make sure a template name is specified. If one isn't specified, try to
- build one from the information we know.
- """
- self._template_file_changed('template_file', self.template_file, self.template_file)
-
-
- def _init_environment(self, extra_loaders=None):
- """
- Create the Jinja templating environment.
- """
- from jinja2 import Environment, ChoiceLoader, FileSystemLoader
- here = os.path.dirname(os.path.realpath(__file__))
- loaders = []
- if extra_loaders:
- loaders.extend(extra_loaders)
-
- paths = self.template_path
- paths.extend([os.path.join(here, self.default_template_path),
- os.path.join(here, self.template_skeleton_path)])
- loaders.append(FileSystemLoader(paths))
-
- self.environment = Environment(
- loader= ChoiceLoader(loaders),
- extensions=JINJA_EXTENSIONS
- )
-
- #Set special Jinja2 syntax that will not conflict with latex.
- if self.jinja_logic_block_start:
- self.environment.block_start_string = self.jinja_logic_block_start
- if self.jinja_logic_block_end:
- self.environment.block_end_string = self.jinja_logic_block_end
- if self.jinja_variable_block_start:
- self.environment.variable_start_string = self.jinja_variable_block_start
- if self.jinja_variable_block_end:
- self.environment.variable_end_string = self.jinja_variable_block_end
- if self.jinja_comment_block_start:
- self.environment.comment_start_string = self.jinja_comment_block_start
- if self.jinja_comment_block_end:
- self.environment.comment_end_string = self.jinja_comment_block_end
-
-
- def _init_filters(self):
- """
- Register all of the filters required for the exporter.
- """
-
- #Add default filters to the Jinja2 environment
- for key, value in default_filters.items():
- self.register_filter(key, value)
-
- #Load user filters. Overwrite existing filters if need be.
- if self.filters:
- for key, user_filter in self.filters.items():
- self.register_filter(key, user_filter)
diff --git a/jupyter_nbconvert/exporters/tests/__init__.py b/jupyter_nbconvert/exporters/tests/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/jupyter_nbconvert/exporters/tests/__init__.py
+++ /dev/null
diff --git a/jupyter_nbconvert/exporters/tests/base.py b/jupyter_nbconvert/exporters/tests/base.py
deleted file mode 100644
index efc2ae5..0000000
--- a/jupyter_nbconvert/exporters/tests/base.py
+++ /dev/null
@@ -1,38 +0,0 @@
-"""Base TestCase class for testing Exporters"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import os
-
-from ...tests.base import TestsBase
-
-all_raw_mimetypes = {
- 'text/x-python',
- 'text/markdown',
- 'text/html',
- 'text/restructuredtext',
- 'text/latex',
-}
-
-class ExportersTestsBase(TestsBase):
- """Contains base test functions for exporters"""
-
- exporter_class = None
- should_include_raw = None
-
- def _get_notebook(self, nb_name='notebook2.ipynb'):
- return os.path.join(self._get_files_path(), nb_name)
-
- def test_raw_cell_inclusion(self):
- """test raw cell inclusion based on raw_mimetype metadata"""
- if self.should_include_raw is None:
- return
- exporter = self.exporter_class()
- (output, resources) = exporter.from_filename(self._get_notebook('rawtest.ipynb'))
- for inc in self.should_include_raw:
- self.assertIn('raw %s' % inc, output, "should include %s" % inc)
- self.assertIn('no raw_mimetype metadata', output)
- for exc in all_raw_mimetypes.difference(self.should_include_raw):
- self.assertNotIn('raw %s' % exc, output, "should exclude %s" % exc)
- self.assertNotIn('never be included', output)
diff --git a/jupyter_nbconvert/exporters/tests/cheese.py b/jupyter_nbconvert/exporters/tests/cheese.py
deleted file mode 100644
index f4a42ce..0000000
--- a/jupyter_nbconvert/exporters/tests/cheese.py
+++ /dev/null
@@ -1,48 +0,0 @@
-"""
-Contains CheesePreprocessor
-"""
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from ...preprocessors.base import Preprocessor
-
-#-----------------------------------------------------------------------------
-# Classes
-#-----------------------------------------------------------------------------
-
-class CheesePreprocessor(Preprocessor):
- """
- Adds a cheese tag to the resources object
- """
-
-
- def __init__(self, **kw):
- """
- Public constructor
- """
- super(CheesePreprocessor, self).__init__(**kw)
-
-
- def preprocess(self, nb, resources):
- """
- Sphinx preprocessing to apply on each notebook.
-
- Parameters
- ----------
- nb : NotebookNode
- Notebook being converted
- resources : dictionary
- Additional resources used in the conversion process. Allows
- preprocessors to pass variables into the Jinja engine.
- """
- resources['cheese'] = 'real'
- return nb, resources
diff --git a/jupyter_nbconvert/exporters/tests/files/notebook2.ipynb b/jupyter_nbconvert/exporters/tests/files/notebook2.ipynb
deleted file mode 100644
index 08fbd35..0000000
--- a/jupyter_nbconvert/exporters/tests/files/notebook2.ipynb
+++ /dev/null
@@ -1,178 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# NumPy and Matplotlib examples"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "First import NumPy and Matplotlib:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\n",
- "Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.kernel.zmq.pylab.backend_inline].\n",
- "For more information, type 'help(pylab)'.\n"
- ]
- }
- ],
- "source": [
- "%pylab inline"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "import numpy as np"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Now we show some very basic examples of how they can be used."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "a = np.random.uniform(size=(100,100))"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "(100, 100)"
- ]
- },
- "execution_count": 7,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "a.shape"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "evs = np.linalg.eigvals(a)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "(100,)"
- ]
- },
- "execution_count": 10,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "evs.shape"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Here is a cell that has both text and PNG output:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "(array([95, 4, 0, 0, 0, 0, 0, 0, 0, 1]),\n",
- " array([ -2.93566063, 2.35937011, 7.65440086, 12.9494316 ,\n",
- " 18.24446235, 23.53949309, 28.83452384, 34.12955458,\n",
- " 39.42458533, 44.71961607, 50.01464682]),\n",
- " )"
- ]
- },
- "execution_count": 14,
- "metadata": {},
- "output_type": "execute_result"
- },
- {
- "data": {
- "image/png": "iVBORw0KGgoAAAANSUhEUgA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1v7IetNN\nN+nLL7/80/YNGzakz+H90V9dMsl18qPHi5eoJpNJLVmyRO3t7Zo0aZKn9iEvL0+ffPKJjh07psWL\nF2vu3LmemH/Hjh267LLL5Pf7h7y93wuz/+q9997TzJkz1dPTo4aGBlVXV3tm/sHBQfX29mrTpk2q\nq6vTypUr9dJLL7maP2tH8Hv37tWnn376p9vfxV2SAoGADh8+nL5/5MgRVVVVZWukrKmqqtKRI0fS\n97u7u1VTUzOGE7lTVVWlnp4eSVJPT8+4/F3/3tmzZ3X77bdr+fLlCoVCkry3D9L5P/gtXrxYsVjM\nE/O///772r59u6666iotXbpUb731lpYvX+6J2X81c+ZMSVJpaaluueUWvfbaa56Z/5prrlFJSYka\nGho0ceJELV26VLt373Y1f85P0fz+Vai6ulp79uxRf3+/otGo8vLyNHny5FyP9K9Mub4/EAgoEoko\nlUopEomM6xcpx3HU3Nysa6+9VmvWrElv98o+fPPNN/ruu+8kSd9++63eeOMNhUIhT8y/YcMGHT9+\nXF988YW2bdum2tpabd261ROzS9KZM2fSf8v7+uuvtWfPHtXX13tmfkkqLi5WLBbTuXPntHPnTtXV\n1bmb38mBV155xSkqKnImTJjgFBYWOvX19envPfroo87VV1/tlJaWOvv378/FOK5Eo1HH5/M5V199\ntbN58+axHudf3Xnnnc7MmTOdiy66yCkqKnIikYhz+vRp55ZbbnEuv/xyJxQKOclkcqzH/Fvvvvuu\nY1mWU1FR4VRWVjqVlZXOrl27PLMPXV1djt/vd+bMmeMsWrTIefbZZx3HcTwz/6+i0ajT0NDgOI53\nZv/888+diooKp6KiwqmtrXW2bNniOI535nccx/nss8+cQCDgVFRUOA8++KAzMDDgav6c/5usAIDc\n4F90AgBDEXgAMBSBBwBDEXgAMBSBBwBDEXgAMNT/AQKseNIf7mhWAAAAAElFTkSuQmCC\n",
- "text/plain": [
- " Here is a plain paragraph that should be unaffected. It contains simple
-relations like 1<2 & 4>5. Here is a plain paragraph that should be unaffected. It contains simple
-relations like 1<2 & 4>5.%s
\n' % \
- mistune.escape(code)
-
- formatter = HtmlFormatter()
- return highlight(code, lexer, formatter)
-
- def header(self, text, level, raw=None):
- html = super(IPythonRenderer, self).header(text, level, raw=raw)
- return add_anchor(html)
-
- # Pass math through unaltered - mathjax does the rendering in the browser
- def block_math(self, text):
- return '$$%s$$' % text
-
- def latex_environment(self, name, text):
- return r'\begin{%s}%s\end{%s}' % (name, text, name)
-
- def inline_math(self, text):
- return '$%s$' % text
-
-def markdown2html_mistune(source):
- """Convert a markdown string to HTML using mistune"""
- return MarkdownWithMath(renderer=IPythonRenderer()).render(source)
diff --git a/jupyter_nbconvert/filters/marked.js b/jupyter_nbconvert/filters/marked.js
deleted file mode 100644
index aa98ac7..0000000
--- a/jupyter_nbconvert/filters/marked.js
+++ /dev/null
@@ -1,63 +0,0 @@
-// Node.js script for markdown to html conversion
-// This applies the same math extraction and marked settings
-// that we use in the live notebook.
-
-// IPython static_path dir relative to here:
-var static_path = __dirname + "/../../html/static/";
-
-// Excerpt from the example in require.js docs
-// http://requirejs.org/docs/node.html
-var requirejs = require('requirejs');
-requirejs.config({
- //Pass the top-level main.js/index.js require
- //function to requirejs so that node modules
- //are loaded relative to the top-level JS file.
- nodeRequire: require,
- baseUrl: static_path,
-});
-
-requirejs([
- 'fs',
- 'components/marked/lib/marked',
- 'components/highlight.js/build/highlight.pack',
- 'base/js/utils',
- 'notebook/js/mathjaxutils',
- ], function(fs, marked, hljs, utils, mathjaxutils) {
-
- // this is copied from notebook.main. Should it be moved somewhere we can reuse it?
- marked.setOptions({
- gfm : true,
- tables: true,
- langPrefix: "language-",
- highlight: function(code, lang) {
- if (!lang) {
- // no language, no highlight
- return code;
- }
- var highlighted;
- try {
- highlighted = hljs.highlight(lang, code, false);
- } catch(err) {
- highlighted = hljs.highlightAuto(code);
- }
- return highlighted.value;
- }
- });
-
- // read the markdown from stdin
- var md='';
- process.stdin.on("data", function (data) {
- md += data;
- });
-
- // perform the md2html transform once stdin is complete
- process.stdin.on("end", function () {
- var text_and_math = mathjaxutils.remove_math(md);
- var text = text_and_math[0];
- var math = text_and_math[1];
- var html = marked.parser(marked.lexer(text));
- html = mathjaxutils.replace_math(html, math);
- process.stdout.write(html);
- });
-
-});
diff --git a/jupyter_nbconvert/filters/strings.py b/jupyter_nbconvert/filters/strings.py
deleted file mode 100755
index 03c053a..0000000
--- a/jupyter_nbconvert/filters/strings.py
+++ /dev/null
@@ -1,221 +0,0 @@
-# coding: utf-8
-"""String filters.
-
-Contains a collection of useful string manipulation filters for use in Jinja
-templates.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import os
-import re
-import textwrap
-try:
- from urllib.parse import quote # Py 3
-except ImportError:
- from urllib2 import quote # Py 2
-from xml.etree import ElementTree
-
-from IPython.core.interactiveshell import InteractiveShell
-from IPython.utils import py3compat
-
-
-__all__ = [
- 'wrap_text',
- 'html2text',
- 'add_anchor',
- 'strip_dollars',
- 'strip_files_prefix',
- 'comment_lines',
- 'get_lines',
- 'ipython2python',
- 'posix_path',
- 'path2url',
- 'add_prompts',
- 'ascii_only',
- 'prevent_list_blocks',
-]
-
-
-def wrap_text(text, width=100):
- """
- Intelligently wrap text.
- Wrap text without breaking words if possible.
-
- Parameters
- ----------
- text : str
- Text to wrap.
- width : int, optional
- Number of characters to wrap to, default 100.
- """
-
- split_text = text.split('\n')
- wrp = map(lambda x:textwrap.wrap(x,width), split_text)
- wrpd = map('\n'.join, wrp)
- return '\n'.join(wrpd)
-
-
-def html2text(element):
- """extract inner text from html
-
- Analog of jQuery's $(element).text()
- """
- if isinstance(element, py3compat.string_types):
- try:
- element = ElementTree.fromstring(element)
- except Exception:
- # failed to parse, just return it unmodified
- return element
-
- text = element.text or ""
- for child in element:
- text += html2text(child)
- text += (element.tail or "")
- return text
-
-
-def add_anchor(html):
- """Add an anchor-link to an html header
-
- For use on markdown headings
- """
- try:
- h = ElementTree.fromstring(py3compat.cast_bytes_py2(html, encoding='utf-8'))
- except Exception:
- # failed to parse, just return it unmodified
- return html
- link = html2text(h).replace(' ', '-')
- h.set('id', link)
- a = ElementTree.Element("a", {"class" : "anchor-link", "href" : "#" + link})
- a.text = u'¶'
- h.append(a)
-
- # Known issue of Python3.x, ElementTree.tostring() returns a byte string
- # instead of a text string. See issue http://bugs.python.org/issue10942
- # Workaround is to make sure the bytes are casted to a string.
- return py3compat.decode(ElementTree.tostring(h), 'utf-8')
-
-
-def add_prompts(code, first='>>> ', cont='... '):
- """Add prompts to code snippets"""
- new_code = []
- code_list = code.split('\n')
- new_code.append(first + code_list[0])
- for line in code_list[1:]:
- new_code.append(cont + line)
- return '\n'.join(new_code)
-
-
-def strip_dollars(text):
- """
- Remove all dollar symbols from text
-
- Parameters
- ----------
- text : str
- Text to remove dollars from
- """
-
- return text.strip('$')
-
-
-files_url_pattern = re.compile(r'(src|href)\=([\'"]?)/?files/')
-markdown_url_pattern = re.compile(r'(!?)\[(?P Test
Foo """:
-r""" \cite{asdf}Test
Foo """,
-
-# LXML errors
-r"""Foo
-\begin{eqnarray}
-1 & bar1 \\
-3 & 4 \\
-\end{eqnarray}""":
-r"""Foo
-\begin{eqnarray}
-1 & \cite{bar} \\
-3 & 4 \\
-\end{eqnarray}""",
-
-r"""
-1<2 is true, but 3>4 is false.
-
-$1<2$ is true, but $3>4$ is false.
-
-1<2 it is even worse if it is alone in a line.""":
-r"""
-1<2 is true, but 3>4 is false.
-
-$1<2$ is true, but $3>4$ is false.
-
-1<2 it is even worse if it is alone in a line.""",
-
-r"""
-1 < 2 is true, but 3 > 4 is false
-
-$1 < 2$ is true, but $3 > 4$ is false
-
-1 < 2 it is even worse if it is alone in a line.
-""":
-r"""
-1 < 2 is true, but 3 > 4 is false
-
-$1 < 2$ is true, but $3 > 4$ is false
-
-1 < 2 it is even worse if it is alone in a line.
-"""}
-
-def test_citation2latex():
- """Are citations parsed properly?"""
- for input, output in test_md.items():
- yield (assert_equal, citation2latex(input), output)
diff --git a/jupyter_nbconvert/filters/tests/test_datatypefilter.py b/jupyter_nbconvert/filters/tests/test_datatypefilter.py
deleted file mode 100644
index 1deaf78..0000000
--- a/jupyter_nbconvert/filters/tests/test_datatypefilter.py
+++ /dev/null
@@ -1,27 +0,0 @@
-"""Module with tests for DataTypeFilter"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from ...tests.base import TestsBase
-from ..datatypefilter import DataTypeFilter
-
-
-class TestDataTypeFilter(TestsBase):
- """Contains test functions for datatypefilter.py"""
-
- def test_constructor(self):
- """Can an instance of a DataTypeFilter be created?"""
- DataTypeFilter()
-
- def test_junk_types(self):
- """Can the DataTypeFilter pickout a useful type from a list of junk types?"""
- filter = DataTypeFilter()
- assert "image/png" in filter(["hair", "water", "image/png", "rock"])
- assert "application/pdf" in filter(["application/pdf", "hair", "water", "png", "rock"])
- self.assertEqual(filter(["hair", "water", "rock"]), [])
-
- def test_null(self):
- """Will the DataTypeFilter fail if no types are passed in?"""
- filter = DataTypeFilter()
- self.assertEqual(filter([]), [])
diff --git a/jupyter_nbconvert/filters/tests/test_highlight.py b/jupyter_nbconvert/filters/tests/test_highlight.py
deleted file mode 100644
index 3eb7c75..0000000
--- a/jupyter_nbconvert/filters/tests/test_highlight.py
+++ /dev/null
@@ -1,90 +0,0 @@
-"""
-Module with tests for Highlight
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from ...tests.base import TestsBase
-from ..highlight import Highlight2HTML, Highlight2Latex
-from IPython.config import Config
-import xml
-
-#-----------------------------------------------------------------------------
-# Class
-#-----------------------------------------------------------------------------
-
-highlight2html = Highlight2HTML()
-highlight2latex = Highlight2Latex()
-highlight2html_ruby = Highlight2HTML(pygments_lexer='ruby')
-
-class TestHighlight(TestsBase):
- """Contains test functions for highlight.py"""
-
- #Hello world test, magics test, blank string test
- tests = [
- """
- #Hello World Example
-
- import foo
-
- def say(text):
- foo.bar(text)
-
- end
-
- say('Hello World!')
- """,
- """
- %%pylab
- plot(x,y, 'r')
- """
- ]
-
- tokens = [
- ['Hello World Example', 'say', 'text', 'import', 'def'],
- ['pylab', 'plot']]
-
-
- def test_highlight2html(self):
- """highlight2html test"""
- for index, test in enumerate(self.tests):
- self._try_highlight(highlight2html, test, self.tokens[index])
-
-
- def test_highlight2latex(self):
- """highlight2latex test"""
- for index, test in enumerate(self.tests):
- self._try_highlight(highlight2latex, test, self.tokens[index])
-
- def test_parse_html_many_lang(self):
-
- ht = highlight2html(self.tests[0])
- rb = highlight2html_ruby(self.tests[0])
-
- for lang,tkns in [
- ( ht, ('def', )),
- ( rb, ('def','end' ) )
- ]:
- print(tkns)
- print(lang)
- root = xml.etree.ElementTree.fromstring(lang)
- self.assertEqual(self._extract_tokens(root,'k'), set(tkns))
-
- def _extract_tokens(self, root, cls):
- return set(map(lambda x:x.text,root.findall(".//*[@class='"+cls+"']")))
-
- def _try_highlight(self, method, test, tokens):
- """Try highlighting source, look for key tokens"""
- results = method(test)
- for token in tokens:
- assert token in results
diff --git a/jupyter_nbconvert/filters/tests/test_latex.py b/jupyter_nbconvert/filters/tests/test_latex.py
deleted file mode 100644
index 3438f07..0000000
--- a/jupyter_nbconvert/filters/tests/test_latex.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""
-Module with tests for Latex
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from ...tests.base import TestsBase
-from ..latex import escape_latex
-
-
-#-----------------------------------------------------------------------------
-# Class
-#-----------------------------------------------------------------------------
-
-class TestLatex(TestsBase):
-
-
- def test_escape_latex(self):
- """escape_latex test"""
- tests = [
- (r'How are \you doing today?', r'How are \textbackslash{}you doing today?'),
- (r'\escapechar=`\A\catcode`\|=0 |string|foo', r'\textbackslash{}escapechar=`\textbackslash{}A\textbackslash{}catcode`\textbackslash{}|=0 |string|foo'),
- (r'# $ % & ~ _ ^ \ { }', r'\# \$ \% \& \textasciitilde{} \_ \^{} \textbackslash{} \{ \}'),
- ('...', r'{\ldots}'),
- ('','')]
-
- for test in tests:
- self._try_escape_latex(test[0], test[1])
-
-
- def _try_escape_latex(self, test, result):
- """Try to remove latex from string"""
- self.assertEqual(escape_latex(test), result)
diff --git a/jupyter_nbconvert/filters/tests/test_markdown.py b/jupyter_nbconvert/filters/tests/test_markdown.py
deleted file mode 100644
index f627421..0000000
--- a/jupyter_nbconvert/filters/tests/test_markdown.py
+++ /dev/null
@@ -1,186 +0,0 @@
-# coding: utf-8
-"""Tests for conversions from markdown to other formats"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import re
-from copy import copy
-
-from IPython.utils.py3compat import string_types
-from IPython.testing import decorators as dec
-
-from ...tests.base import TestsBase
-from ..markdown import markdown2latex, markdown2html, markdown2rst
-
-from jinja2 import Environment
-
-class TestMarkdown(TestsBase):
-
- tests = [
- '*test',
- '**test',
- '*test*',
- '_test_',
- '__test__',
- '__*test*__',
- '**test**',
- '#test',
- '##test',
- 'test\n----',
- 'test [link](https://google.com/)',
- ]
-
- tokens = [
- '*test',
- '**test',
- 'test',
- 'test',
- 'test',
- 'test',
- 'test',
- 'test',
- 'test',
- 'test',
- ('test', 'https://google.com/'),
- ]
-
-
- @dec.onlyif_cmds_exist('pandoc')
- def test_markdown2latex(self):
- """markdown2latex test"""
- for index, test in enumerate(self.tests):
- self._try_markdown(markdown2latex, test, self.tokens[index])
-
- @dec.onlyif_cmds_exist('pandoc')
- def test_markdown2latex_markup(self):
- """markdown2latex with markup kwarg test"""
- # This string should be passed through unaltered with pandoc's
- # markdown_strict reader
- s = '1) arabic number with parenthesis'
- self.assertEqual(markdown2latex(s, markup='markdown_strict'), s)
- # This string should be passed through unaltered with pandoc's
- # markdown_strict+tex_math_dollars reader
- s = r'$\alpha$ latex math'
- # sometimes pandoc uses $math$, sometimes it uses \(math\)
- expected = re.compile(r'(\$|\\\()\\alpha(\$|\\\)) latex math')
- try:
- # py3
- assertRegex = self.assertRegex
- except AttributeError:
- # py2
- assertRegex = self.assertRegexpMatches
- assertRegex(
- markdown2latex(s, markup='markdown_strict+tex_math_dollars'),
- expected)
-
- @dec.onlyif_cmds_exist('pandoc')
- def test_pandoc_extra_args(self):
- # pass --no-wrap
- s = '\n'.join([
- "#latex {{long_line | md2l('markdown', ['--no-wrap'])}}",
- "#rst {{long_line | md2r(['--columns', '5'])}}",
- ])
- long_line = ' '.join(['long'] * 30)
- env = Environment()
- env.filters.update({
- 'md2l': markdown2latex,
- 'md2r': markdown2rst,
- })
- tpl = env.from_string(s)
- rendered = tpl.render(long_line=long_line)
- _, latex, rst = rendered.split('#')
-
- self.assertEqual(latex.strip(), 'latex %s' % long_line)
- self.assertEqual(rst.strip(), 'rst %s' % long_line.replace(' ', '\n'))
-
- def test_markdown2html(self):
- """markdown2html test"""
- for index, test in enumerate(self.tests):
- self._try_markdown(markdown2html, test, self.tokens[index])
-
- def test_markdown2html_heading_anchors(self):
- for md, tokens in [
- ('# test',
- ('test', 'id="test"', u'¶
;9UZ}TX1tX~0X!(0*WHU>vD3ddwgZ^iJP
z5lKz*sgH2m*;!dr;jO)X$&oNvFN&&M3(U&Se(D4#79L*S3jm1xRo3zH
z{Gbh|F+q<#<<4HS{Is+*`gHh^OGzSn&qId2-s$IY3=dnXmb!Yf87GOIwzl@gGm|L*
zu%sOsH`pZjml-9+&~4!aHyKkImuAt_l2}zTX<8tK0
zM{T9O7gB5XfAihgoL0RrIXn9#UWVkyJ3$YQ5m0zvWpPQU+7kFA=h#EMU%-M^m!TD`6;hkF}uy}-^2fAOoTt>i>f5;nz
zfy5?oC2Jv$-N9bA(j8fTmES(zdh9lRf1nXtd76z(i~XcCj(G@K@tlaIgvlH{p1CA`
z=wTM-So(C*i3~s_3;jRX*pQe8|2>5wOCC_m1CYwk$h!3c^=e`LzWiKCK+d|IN?hDQ}Q(hJzd4~
diff --git a/jupyter_nbconvert/preprocessors/tests/test_clearoutput.py b/jupyter_nbconvert/preprocessors/tests/test_clearoutput.py
deleted file mode 100644
index 78db651..0000000
--- a/jupyter_nbconvert/preprocessors/tests/test_clearoutput.py
+++ /dev/null
@@ -1,33 +0,0 @@
-"""
-Module with tests for the clearoutput preprocessor.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from .base import PreprocessorTestsBase
-from ..clearoutput import ClearOutputPreprocessor
-
-
-class TestClearOutput(PreprocessorTestsBase):
- """Contains test functions for clearoutput.py"""
-
-
- def build_preprocessor(self):
- """Make an instance of a preprocessor"""
- preprocessor = ClearOutputPreprocessor()
- preprocessor.enabled = True
- return preprocessor
-
- def test_constructor(self):
- """Can a ClearOutputPreprocessor be constructed?"""
- self.build_preprocessor()
-
- def test_output(self):
- """Test the output of the ClearOutputPreprocessor"""
- nb = self.build_notebook()
- res = self.build_resources()
- preprocessor = self.build_preprocessor()
- nb, res = preprocessor(nb, res)
- assert nb.cells[0].outputs == []
- assert nb.cells[0].execution_count is None
diff --git a/jupyter_nbconvert/preprocessors/tests/test_coalescestreams.py b/jupyter_nbconvert/preprocessors/tests/test_coalescestreams.py
deleted file mode 100644
index bded340..0000000
--- a/jupyter_nbconvert/preprocessors/tests/test_coalescestreams.py
+++ /dev/null
@@ -1,58 +0,0 @@
-"""Tests for the coalescestreams preprocessor"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from IPython.nbformat import v4 as nbformat
-
-from .base import PreprocessorTestsBase
-from ..coalescestreams import coalesce_streams
-
-
-class TestCoalesceStreams(PreprocessorTestsBase):
- """Contains test functions for coalescestreams.py"""
-
- def test_coalesce_streams(self):
- """coalesce_streams preprocessor output test"""
- nb = self.build_notebook()
- res = self.build_resources()
- nb, res = coalesce_streams(nb, res)
- outputs = nb.cells[0].outputs
- self.assertEqual(outputs[0].text, "a")
- self.assertEqual(outputs[1].output_type, "display_data")
- self.assertEqual(outputs[2].text, "cd")
- self.assertEqual(outputs[3].text, "ef")
-
- def test_coalesce_sequenced_streams(self):
- """Can the coalesce streams preprocessor merge a sequence of streams?"""
- outputs = [nbformat.new_output(output_type="stream", name="stdout", text="0"),
- nbformat.new_output(output_type="stream", name="stdout", text="1"),
- nbformat.new_output(output_type="stream", name="stdout", text="2"),
- nbformat.new_output(output_type="stream", name="stdout", text="3"),
- nbformat.new_output(output_type="stream", name="stdout", text="4"),
- nbformat.new_output(output_type="stream", name="stdout", text="5"),
- nbformat.new_output(output_type="stream", name="stdout", text="6"),
- nbformat.new_output(output_type="stream", name="stdout", text="7")]
- cells=[nbformat.new_code_cell(source="# None", execution_count=1,outputs=outputs)]
-
- nb = nbformat.new_notebook(cells=cells)
- res = self.build_resources()
- nb, res = coalesce_streams(nb, res)
- outputs = nb.cells[0].outputs
- self.assertEqual(outputs[0].text, u'01234567')
-
- def test_coalesce_replace_streams(self):
- """Are \\r characters handled?"""
- outputs = [nbformat.new_output(output_type="stream", name="stdout", text="z"),
- nbformat.new_output(output_type="stream", name="stdout", text="\ra"),
- nbformat.new_output(output_type="stream", name="stdout", text="\nz\rb"),
- nbformat.new_output(output_type="stream", name="stdout", text="\nz"),
- nbformat.new_output(output_type="stream", name="stdout", text="\rc\n"),
- nbformat.new_output(output_type="stream", name="stdout", text="z\rz\rd")]
- cells=[nbformat.new_code_cell(source="# None", execution_count=1,outputs=outputs)]
-
- nb = nbformat.new_notebook(cells=cells)
- res = self.build_resources()
- nb, res = coalesce_streams(nb, res)
- outputs = nb.cells[0].outputs
- self.assertEqual(outputs[0].text, u'a\nb\nc\nd')
diff --git a/jupyter_nbconvert/preprocessors/tests/test_csshtmlheader.py b/jupyter_nbconvert/preprocessors/tests/test_csshtmlheader.py
deleted file mode 100644
index c259bad..0000000
--- a/jupyter_nbconvert/preprocessors/tests/test_csshtmlheader.py
+++ /dev/null
@@ -1,47 +0,0 @@
-"""
-Module with tests for the csshtmlheader preprocessor
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from .base import PreprocessorTestsBase
-from ..csshtmlheader import CSSHTMLHeaderPreprocessor
-
-
-#-----------------------------------------------------------------------------
-# Class
-#-----------------------------------------------------------------------------
-
-class TestCSSHTMLHeader(PreprocessorTestsBase):
- """Contains test functions for csshtmlheader.py"""
-
-
- def build_preprocessor(self):
- """Make an instance of a preprocessor"""
- preprocessor = CSSHTMLHeaderPreprocessor()
- preprocessor.enabled = True
- return preprocessor
-
-
- def test_constructor(self):
- """Can a CSSHTMLHeaderPreprocessor be constructed?"""
- self.build_preprocessor()
-
-
- def test_output(self):
- """Test the output of the CSSHTMLHeaderPreprocessor"""
- nb = self.build_notebook()
- res = self.build_resources()
- preprocessor = self.build_preprocessor()
- nb, res = preprocessor(nb, res)
- assert 'css' in res['inlining']
diff --git a/jupyter_nbconvert/preprocessors/tests/test_execute.py b/jupyter_nbconvert/preprocessors/tests/test_execute.py
deleted file mode 100644
index 2464650..0000000
--- a/jupyter_nbconvert/preprocessors/tests/test_execute.py
+++ /dev/null
@@ -1,151 +0,0 @@
-"""
-Module with tests for the execute preprocessor.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import copy
-import glob
-import io
-import os
-import re
-
-try:
- from queue import Empty # Py 3
-except ImportError:
- from Queue import Empty # Py 2
-
-from IPython import nbformat
-
-from .base import PreprocessorTestsBase
-from ..execute import ExecutePreprocessor
-
-from jupyter_nbconvert.filters import strip_ansi
-from nose.tools import assert_raises
-
-addr_pat = re.compile(r'0x[0-9a-f]{7,9}')
-
-class TestExecute(PreprocessorTestsBase):
- """Contains test functions for execute.py"""
-
- @staticmethod
- def normalize_output(output):
- """
- Normalizes outputs for comparison.
- """
- output = dict(output)
- if 'metadata' in output:
- del output['metadata']
- if 'text' in output:
- output['text'] = re.sub(addr_pat, '