File size: 9,865 Bytes
745e7ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// Allow codefolding in code cells
//
// This extension enables the CodeMirror feature
// It works by adding a gutter area to each code cell.
// Fold-able code is marked using small triangles in the gutter.
//
// The current folding state is saved in the cell metadata as an array
// of line numbers.
// Format: cell.metadata.code_folding = [ line1, line2, line3, ...]
//

define([
    'base/js/namespace',
    'jquery',
    'require',
    'base/js/events',
    'services/config',
    'notebook/js/codecell',
    'codemirror/lib/codemirror',
    'codemirror/addon/fold/foldcode',
    'codemirror/addon/fold/foldgutter',
    'codemirror/addon/fold/brace-fold',
    'codemirror/addon/fold/indent-fold'
], function (Jupyter, $, requirejs, events, configmod, codecell, CodeMirror) {
    "use strict";

    // define default config parameter values
    var params = {
        codefolding_hotkey : 'Alt-f',
        init_delay : 1000
    };

    // updates default params with any specified in the provided config data
    var update_params = function (config_data) {
        for (var key in params) {
            if (config_data.hasOwnProperty(key)) {
                params[key] = config_data[key];
            }
        }
    };

    var on_config_loaded = function () {
        if (Jupyter.notebook !== undefined) {
            // register actions with ActionHandler instance
            var prefix = 'auto';
            var name = 'toggle-codefolding';
            var action = {
                icon: 'fa-comment-o',
                help    : 'Toggle codefolding',
                help_index : 'ec',
                id : 'toggle_codefolding',
                handler : toggleFolding
            };
            var action_full_name = Jupyter.keyboard_manager.actions.register(action, name, prefix);

            // define keyboard shortcuts
            var edit_mode_shortcuts = {};
            edit_mode_shortcuts[params.codefolding_hotkey] = action_full_name;

            // register keyboard shortcuts with keyboard_manager
            Jupyter.notebook.keyboard_manager.edit_shortcuts.add_shortcuts(edit_mode_shortcuts);
            Jupyter.notebook.keyboard_manager.command_shortcuts.add_shortcuts(edit_mode_shortcuts);
        }
        else {
            // we're in edit view
            var extraKeys = Jupyter.editor.codemirror.getOption('extraKeys');
            extraKeys[params.codefolding_hotkey] = toggleFolding;
            CodeMirror.normalizeKeyMap(extraKeys);
            console.log('[codefolding] binding hotkey', params.codefolding_hotkey);
            Jupyter.editor.codemirror.setOption('extraKeys', extraKeys);
        }
    };

    /*
     * Toggle folding on/off at current line
     *
     * @param cm CodeMirror instance
     *
     */
    function toggleFolding () {
        var cm;
        var pos = {line: 0, ch: 0, xRel: 0};
        if (Jupyter.notebook !== undefined) {
            cm = Jupyter.notebook.get_selected_cell().code_mirror;
            if (Jupyter.notebook.mode === 'edit') {
                pos = cm.getCursor();
            }
        }
        else {
            cm = Jupyter.editor.codemirror;
            pos = cm.getCursor();
        }
        var opts = cm.state.foldGutter.options;
        cm.foldCode(pos, opts.rangeFinder);
    }

    /**
     * Update cell metadata with folding info, so folding state can be restored after reloading notebook
     *
     * @param cm CodeMirror instance
     */
    function updateMetadata (cm) {
        var list = cm.getAllMarks();
        var lines = [];
        for (var i = 0; i < list.length; i++) {
            if (list[i].__isFold) {
                var range = list[i].find();
                lines.push(range.from.line);
            }
        }
        /* User can click on gutter of unselected cells, so make sure we store metadata in the correct cell */
        var cell = Jupyter.notebook.get_selected_cell();
        if (cell.code_mirror !== cm) {
            var cells = Jupyter.notebook.get_cells();
            var ncells = Jupyter.notebook.ncells();
            for (var k = 0; k < ncells; k++) {
                var _cell = cells[k];
                if (_cell.code_mirror === cm ) { cell = _cell; break; }
            }
        }
        cell.metadata.code_folding = lines;
    }

    /**
     * Activate codefolding in CodeMirror options, don't overwrite other settings
     *
     * @param cm codemirror instance
     */
    function activate_cm_folding (cm) {
        var gutters = cm.getOption('gutters').slice();
        if ( $.inArray("CodeMirror-foldgutter", gutters) < 0) {
                gutters.push('CodeMirror-foldgutter');
                cm.setOption('gutters', gutters);
            }

        /* set indent or brace folding */
        var opts = true;
        if (Jupyter.notebook) {
            opts = {
                rangeFinder: new CodeMirror.fold.combine(
                    CodeMirror.fold.firstline,
                    CodeMirror.fold.magic,
                    CodeMirror.fold.blockcomment,
                    cm.getMode().fold === 'indent' ? CodeMirror.fold.indent : CodeMirror.fold.brace
                )
            };
        }
        cm.setOption('foldGutter', opts);
    }

    /**
     * Restore folding status from metadata
     * @param cell
     */
    var restoreFolding = function (cell) {
        if (cell.metadata.code_folding === undefined || !(cell instanceof codecell.CodeCell)) {
            return;
        }
        // visit in reverse order, as otherwise nested folds un-fold outer ones
        var lines = cell.metadata.code_folding.slice().sort();
        for (var idx = lines.length - 1; idx >= 0; idx--) {
            var line = lines[idx];
            var opts = cell.code_mirror.state.foldGutter.options;
            var linetext = cell.code_mirror.getLine(line);
            if (linetext !== undefined) {
                cell.code_mirror.foldCode(CodeMirror.Pos(line, 0), opts.rangeFinder);
            }
            else {
                // the line doesn't exist, so we should remove it from metadata
                cell.metadata.code_folding = lines.slice(0, idx);
            }
            cell.code_mirror.refresh();
        }
    };

    /**
     * Add codefolding gutter to a new cell
     *
     * @param event
     * @param nbcell
     *
     */
    var createCell = function (event, nbcell) {
        var cell = nbcell.cell;
        if ((cell instanceof codecell.CodeCell)) {
            activate_cm_folding(cell.code_mirror);
            cell.code_mirror.on('fold', updateMetadata);
            cell.code_mirror.on('unfold', updateMetadata);
            // queue restoring folding, to run once metadata is set, hopefully.
            // This can be useful if cells are un-deleted, for example.
            setTimeout(function () { restoreFolding(cell); }, 500);
        }
    };

    /*
     * Initialize gutter in existing cells
     *
     */
    var initExistingCells = function () {
        var cells = Jupyter.notebook.get_cells();
        var ncells = Jupyter.notebook.ncells();
        for (var i = 0; i < ncells; i++) {
            var cell = cells[i];
            if ((cell instanceof codecell.CodeCell)) {
                activate_cm_folding(cell.code_mirror);
                /* restore folding state if previously saved */
                restoreFolding(cell);
                cell.code_mirror.on('fold', updateMetadata);
                cell.code_mirror.on('unfold', updateMetadata);
            }
        }
        events.on('create.Cell', createCell);
    };

    /**
     * Load my own CSS file
     *
     * @param name off CSS file
     *
     */
    var load_css = function (name) {
        var link = document.createElement("link");
        link.type = "text/css";
        link.rel = "stylesheet";
        link.href = requirejs.toUrl(name, 'css');
        document.getElementsByTagName("head")[0].appendChild(link);
    };

    /**
     * Initialize extension
     *
     */
    var load_extension = function () {
        // first, check which view we're in, in order to decide whether to load
        var conf_sect;
        if (Jupyter.notebook) {
            // we're in notebook view
            conf_sect = Jupyter.notebook.config;
        }
        else if (Jupyter.editor) {
            // we're in file-editor view
            conf_sect = new configmod.ConfigSection('notebook', {base_url: Jupyter.editor.base_url});
            conf_sect.load();
        }
        else {
            // we're some other view like dashboard, terminal, etc, so bail now
            return;
        }

        load_css('codemirror/addon/fold/foldgutter.css');
        /* change default gutter width */
        load_css( './foldgutter.css');

        conf_sect.loaded
        .then(function () { update_params(conf_sect.data); })
        .then(on_config_loaded);

        if (Jupyter.notebook) {
            /* require our additional custom codefolding modes before initialising fully */
            requirejs(['./firstline-fold', './magic-fold', './blockcomment-fold'], function () {
                if (Jupyter.notebook._fully_loaded) {
                    setTimeout(function () {
                        console.log('Codefolding: Wait for', params.init_delay, 'ms');
                        initExistingCells();
                    }, params.init_delay);
                }
                else {
                    events.one('notebook_loaded.Notebook', initExistingCells);
                }
            });
        }
        else {
            activate_cm_folding(Jupyter.editor.codemirror);
            setTimeout(function () {
                console.log('Codefolding: Wait for', params.init_delay, 'ms');
                Jupyter.editor.codemirror.refresh();
            }, params.init_delay);
        }
    };

    return {load_ipython_extension : load_extension};
});