mirror of
https://github.com/wassname/jupyter_contrib_nbextensions.git
synced 2026-08-11 11:19:52 +08:00
Thes preprocessor removes folded lines in codecells as defined by the cell metadata
62 lines
2.1 KiB
Python
62 lines
2.1 KiB
Python
"""This preprocessor removes lines in code cells that have been marked as `folded`
|
|
by the codefolding extension
|
|
"""
|
|
|
|
#-----------------------------------------------------------------------------
|
|
# Copyright (c) 2014, Juergen Hasch
|
|
#
|
|
# Distributed under the terms of the Modified BSD License.
|
|
#
|
|
#-----------------------------------------------------------------------------
|
|
|
|
from IPython.nbconvert.preprocessors import *
|
|
import StringIO
|
|
|
|
class CodeFoldingPreprocessor(Preprocessor):
|
|
|
|
def fold_cell(self,cell,folded):
|
|
"""
|
|
Remove folded lines and add a '<->' at the parent line
|
|
"""
|
|
f = StringIO.StringIO(cell)
|
|
lines = f.readlines()
|
|
|
|
if folded[0] == 0 and lines[0][0] == '#':
|
|
self.log.info("folded: %s, %s" % (folded[0],lines[0][0]))
|
|
return lines[0].rstrip('\n') + '<->\n'
|
|
fold_indent = 0
|
|
fold = False
|
|
fcell = ""
|
|
for i,l in enumerate(lines):
|
|
indent = len(l)-len(l.lstrip(' '))
|
|
if indent <= fold_indent:
|
|
fold = False
|
|
fold_indent = 0
|
|
if i in folded:
|
|
fold = True
|
|
fold_indent = indent
|
|
fcell += l.rstrip('\n') + '<->\n'
|
|
if fold is False:
|
|
fcell += l
|
|
return fcell
|
|
|
|
def preprocess_cell(self, cell, resources, index):
|
|
"""
|
|
Read out metadata and remove lines if marked as `folded` in cell metadata.
|
|
|
|
Parameters
|
|
----------
|
|
cell : NotebookNode cell
|
|
Notebook cell being processed
|
|
resources : dictionary
|
|
Additional resources used in the conversion process. Allows
|
|
preprocessors to pass variables into the Jinja engine.
|
|
cell_index : int
|
|
Index of the cell being processed (see base.py)
|
|
"""
|
|
if hasattr(cell, "input") and cell.cell_type == "code":
|
|
if hasattr(cell['metadata'], 'code_folding'):
|
|
folded = cell['metadata']['code_folding']
|
|
cell.input = self.fold_cell(cell.input, folded)
|
|
return cell, resources
|