Skip to content

Commit ed4bda0

Browse files
committed
[codefolding] fix restoration of nested folds
by processing them in reverse order
1 parent 6998d21 commit ed4bda0

File tree

1 file changed

+29
-14
lines changed
  • src/jupyter_contrib_nbextensions/nbextensions/codefolding

1 file changed

+29
-14
lines changed

src/jupyter_contrib_nbextensions/nbextensions/codefolding/main.js

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,31 @@ define([
147147
cm.setOption('foldGutter', opts);
148148
}
149149

150+
/**
151+
* Restore folding status from metadata
152+
* @param cell
153+
*/
154+
var restoreFolding = function (cell) {
155+
if (cell.metadata.code_folding === undefined || !(cell instanceof codecell.CodeCell)) {
156+
return;
157+
}
158+
// visit in reverse order, as otherwise nested folds un-fold outer ones
159+
var lines = cell.metadata.code_folding.slice().sort();
160+
for (var idx = lines.length - 1; idx >= 0; idx--) {
161+
var line = lines[idx];
162+
var opts = cell.code_mirror.state.foldGutter.options;
163+
var linetext = cell.code_mirror.getLine(line);
164+
if (linetext !== undefined) {
165+
cell.code_mirror.foldCode(CodeMirror.Pos(line, 0), opts.rangeFinder);
166+
}
167+
else {
168+
// the line doesn't exist, so we should remove it from metadata
169+
cell.metadata.code_folding = lines.slice(0, idx);
170+
}
171+
cell.code_mirror.refresh();
172+
}
173+
};
174+
150175
/**
151176
* Add codefolding gutter to a new cell
152177
*
@@ -160,6 +185,9 @@ define([
160185
activate_cm_folding(cell.code_mirror);
161186
cell.code_mirror.on('fold', updateMetadata);
162187
cell.code_mirror.on('unfold', updateMetadata);
188+
// queue restoring folding, to run once metadata is set, hopefully.
189+
// This can be useful if cells are un-deleted, for example.
190+
setTimeout(function () { restoreFolding(cell); }, 500);
163191
}
164192
};
165193

@@ -175,20 +203,7 @@ define([
175203
if ((cell instanceof codecell.CodeCell)) {
176204
activate_cm_folding(cell.code_mirror);
177205
/* restore folding state if previously saved */
178-
if (cell.metadata.code_folding !== undefined) {
179-
for (var idx = 0; idx < cell.metadata.code_folding.length; idx++) {
180-
var line = cell.metadata.code_folding[idx];
181-
var opts = cell.code_mirror.state.foldGutter.options;
182-
var linetext = cell.code_mirror.getLine(line);
183-
if (linetext !== undefined) {
184-
cell.code_mirror.foldCode(CodeMirror.Pos(line, 0), opts.rangeFinder);
185-
} else {
186-
cell.metadata.code_folding = [];
187-
break;
188-
}
189-
cell.code_mirror.refresh();
190-
}
191-
}
206+
restoreFolding(cell);
192207
cell.code_mirror.on('fold', updateMetadata);
193208
cell.code_mirror.on('unfold', updateMetadata);
194209
}

0 commit comments

Comments
 (0)