1"""Base class for preprocessors"""
2
3# Copyright (c) IPython Development Team.
4# Distributed under the terms of the Modified BSD License.
5
6from traitlets import Bool
7
8from nbconvert.utils.base import NbConvertBase
9
10
11class Preprocessor(NbConvertBase):
12 """A configurable preprocessor
13
14 Inherit from this class if you wish to have configurability for your
15 preprocessor.
16
17 Any configurable traitlets this class exposed will be configurable in
18 profiles using c.SubClassName.attribute = value
19
20 You can overwrite `preprocess_cell()` to apply a transformation
21 independently on each cell or `preprocess()` if you prefer your own
22 logic. See corresponding docstring for information.
23
24 Disabled by default and can be enabled via the config by
25 'c.YourPreprocessorName.enabled = True'
26 """
27
28 enabled = Bool(False).tag(config=True)
29
30 def __init__(self, **kw):
31 """
32 Public constructor
33
34 Parameters
35 ----------
36 config : Config
37 Configuration file structure
38 `**kw`
39 Additional keyword arguments passed to parent
40 """
41
42 super().__init__(**kw)
43
44 def __call__(self, nb, resources):
45 """Apply the preprocessor."""
46 if self.enabled:
47 self.log.debug("Applying preprocessor: %s", self.__class__.__name__)
48 return self.preprocess(nb, resources)
49 return nb, resources
50
51 def preprocess(self, nb, resources):
52 """
53 Preprocessing to apply on each notebook.
54
55 Must return modified nb, resources.
56
57 If you wish to apply your preprocessing to each cell, you might want
58 to override preprocess_cell method instead.
59
60 Parameters
61 ----------
62 nb : NotebookNode
63 Notebook being converted
64 resources : dictionary
65 Additional resources used in the conversion process. Allows
66 preprocessors to pass variables into the Jinja engine.
67 """
68 for index, cell in enumerate(nb.cells):
69 nb.cells[index], resources = self.preprocess_cell(cell, resources, index)
70 return nb, resources
71
72 def preprocess_cell(self, cell, resources, index):
73 """
74 Override if you want to apply some preprocessing to each cell.
75 Must return modified cell and resource dictionary.
76
77 Parameters
78 ----------
79 cell : NotebookNode cell
80 Notebook cell being processed
81 resources : dictionary
82 Additional resources used in the conversion process. Allows
83 preprocessors to pass variables into the Jinja engine.
84 index : int
85 Index of the cell being processed
86 """
87 msg = "should be implemented by subclass"
88 raise NotImplementedError(msg)