5
5
"""
6
6
7
7
from nbconvert .preprocessors import Preprocessor
8
+ from traitlets import Bool , Unicode
8
9
9
10
10
11
class CodeFoldingPreprocessor (Preprocessor ):
11
12
"""
12
13
:mod:`nbconvert` Preprocessor for the code_folding nbextension.
13
14
14
- Folds codecells as displayed in the notebook.
15
+ Folds codecells as displayed in the notebook. The hidden code below the fold gets removed.
15
16
16
17
The preprocessor is installed by default. To enable codefolding with
17
18
NbConvert, you need to set the configuration parameter
18
- `NbConvertApp.codefolding =True`.
19
+ `CodeFoldingPreprocessor.remove_folded_code =True`.
19
20
This can be done either in the `jupyter_nbconvert_config.py` file::
20
21
21
- c.NbConvertApp.codefolding = True
22
+ c.CodeFoldingPreprocessor.remove_folded_code=True = True
22
23
23
24
or using a command line parameter when calling NbConvert::
24
25
25
- $ jupyter nbconvert --to html --NbConvertApp.codefolding=True mynotebook.ipynb
26
+ $ jupyter nbconvert --to html --CodeFoldingPreprocessor.remove_folded_code=True mynotebook.ipynb
27
+
28
+ The folding mark can be configured using
29
+ c.CodeFoldingPreprocessor.fold_mark = '<->'
26
30
27
31
""" # noqa: E501
28
32
29
- fold_mark = u'↔'
33
+ remove_folded_code = Bool (False , help = "Remove code that was folded" ).tag (config = True )
34
+ fold_mark = Unicode (u'↔' , help = "Symbol for folded code" ).tag (config = True )
30
35
31
36
def fold_cell (self , cell , folded ):
32
37
"""
@@ -54,10 +59,16 @@ def fold_cell(self, cell, folded):
54
59
fcell += l
55
60
return fcell
56
61
62
+ def preprocess (self , nb , resources ):
63
+ """Skip preprocessor if not enabled"""
64
+ if self .remove_folded_code :
65
+ return super (CodeFoldingPreprocessor , self ).preprocess (nb , resources )
66
+ else :
67
+ return nb , resources
68
+
57
69
def preprocess_cell (self , cell , resources , index ):
58
70
"""
59
71
Read cell metadata and remove lines marked as `folded`.
60
- Requires configuration parameter 'NbConvertApp.codefolding = True'
61
72
62
73
Parameters
63
74
----------
@@ -69,10 +80,10 @@ def preprocess_cell(self, cell, resources, index):
69
80
index : int
70
81
Index of the cell being processed (see base.py)
71
82
"""
72
- dofolding = self .config .NbConvertApp .get ('codefolding' , False ) is True
73
- if hasattr (cell , 'source' ) and cell .cell_type == 'code' and dofolding :
83
+ if hasattr (cell , 'source' ) and cell .cell_type == 'code' :
74
84
if hasattr (cell ['metadata' ], 'code_folding' ):
75
85
folded = cell ['metadata' ]['code_folding' ]
76
86
if len (folded ) > 0 :
87
+ self .log .debug ('Removing folded code in cell' )
77
88
cell .source = self .fold_cell (cell .source , folded )
78
89
return cell , resources
0 commit comments