@@ -147,6 +147,31 @@ define([
147
147
cm . setOption ( 'foldGutter' , opts ) ;
148
148
}
149
149
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
+
150
175
/**
151
176
* Add codefolding gutter to a new cell
152
177
*
@@ -160,6 +185,9 @@ define([
160
185
activate_cm_folding ( cell . code_mirror ) ;
161
186
cell . code_mirror . on ( 'fold' , updateMetadata ) ;
162
187
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 ) ;
163
191
}
164
192
} ;
165
193
@@ -175,20 +203,7 @@ define([
175
203
if ( ( cell instanceof codecell . CodeCell ) ) {
176
204
activate_cm_folding ( cell . code_mirror ) ;
177
205
/* 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 ) ;
192
207
cell . code_mirror . on ( 'fold' , updateMetadata ) ;
193
208
cell . code_mirror . on ( 'unfold' , updateMetadata ) ;
194
209
}
0 commit comments