-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
notebook.js
3508 lines (3190 loc) · 120 KB
/
notebook.js
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/**
* @module notebook
*/
"use strict";
define([
'jquery',
'base/js/namespace',
'underscore',
'base/js/utils',
'base/js/i18n',
'base/js/dialog',
'base/js/markdown',
'./cell',
'./textcell',
'./codecell',
'moment',
'services/config',
'services/sessions/session',
'./celltoolbar',
'codemirror/lib/codemirror',
'codemirror/addon/runmode/runmode',
'base/js/mathjaxutils',
'base/js/keyboard',
'./tooltip',
'./celltoolbarpresets/default',
'./celltoolbarpresets/rawcell',
'./celltoolbarpresets/slideshow',
'./celltoolbarpresets/attachments',
'./celltoolbarpresets/tags',
'./scrollmanager',
'./commandpalette',
'./shortcuteditor',
], function (
$,
IPython,
_,
utils,
i18n,
dialog,
markdown,
cellmod,
textcell,
codecell,
moment,
configmod,
session,
celltoolbar,
CodeMirror,
runMode,
mathjaxutils,
keyboard,
tooltip,
default_celltoolbar,
rawcell_celltoolbar,
slideshow_celltoolbar,
attachments_celltoolbar,
tags_celltoolbar,
scrollmanager,
commandpalette,
shortcuteditor
) {
var ShortcutEditor = shortcuteditor.ShortcutEditor;
var _SOFT_SELECTION_CLASS = 'jupyter-soft-selected';
function soft_selected(cell){
return cell.element.hasClass(_SOFT_SELECTION_CLASS);
}
/**
* Contains and manages cells.
* @class Notebook
* @param {string} selector
* @param {object} options - Dictionary of keyword arguments.
* @param {jQuery} options.events - selector of Events
* @param {KeyboardManager} options.keyboard_manager
* @param {Contents} options.contents
* @param {SaveWidget} options.save_widget
* @param {object} options.config
* @param {string} options.base_url
* @param {string} options.notebook_path
* @param {string} options.notebook_name
*/
function Notebook(selector, options) {
this.config = options.config;
this.config.loaded.then(this.validate_config.bind(this));
this.class_config = new configmod.ConfigWithDefaults(this.config,
Notebook.options_default, 'Notebook');
this.base_url = options.base_url;
this.notebook_path = options.notebook_path;
this.notebook_name = options.notebook_name;
this.events = options.events;
this.keyboard_manager = options.keyboard_manager;
this.contents = options.contents;
this.save_widget = options.save_widget;
this.tooltip = new tooltip.Tooltip(this.events);
this.ws_url = options.ws_url;
this._session_starting = false;
this.last_modified = null;
// debug 484
this._last_modified = 'init';
// Firefox workaround
this._ff_beforeunload_fired = false;
// Create default scroll manager.
this.scroll_manager = new scrollmanager.ScrollManager(this);
// TODO: This code smells (and the other `= this` line a couple lines down)
// We need a better way to deal with circular instance references.
this.keyboard_manager.notebook = this;
this.save_widget.notebook = this;
mathjaxutils.init();
this.element = $(selector);
this.element.scroll();
this.element.data("notebook", this);
this.session = null;
this.kernel = null;
this.kernel_busy = false;
this.clipboard = null;
this.clipboard_attachments = null;
this.undelete_backup_stack = [];
this.paste_enabled = false;
this.paste_attachments_enabled = false;
this.writable = false;
// It is important to start out in command mode to match the initial mode
// of the KeyboardManager.
this.mode = 'command';
this.set_dirty(false);
this.metadata = {};
this._checkpoint_after_save = false;
this.last_checkpoint = null;
this.checkpoints = [];
this.autosave_interval = 0;
this.autosave_timer = null;
// autosave *at most* every two minutes
this.minimum_autosave_interval = 120000;
this.notebook_name_blacklist_re = /[\/\\:]/;
this.nbformat = 4; // Increment this when changing the nbformat
this.nbformat_minor = this.current_nbformat_minor = 1; // Increment this when changing the nbformat
this.codemirror_mode = 'text';
this.create_elements();
this.bind_events();
this.kernel_selector = null;
this.dirty = null;
this.trusted = null;
this._changed_on_disk_dialog = null;
this._fully_loaded = false;
// Trigger cell toolbar registration.
default_celltoolbar.register(this);
rawcell_celltoolbar.register(this);
slideshow_celltoolbar.register(this);
attachments_celltoolbar.register(this);
tags_celltoolbar.register(this);
var that = this;
Object.defineProperty(this, 'line_numbers', {
get: function() {
var d = that.config.data || {};
var cmc = (d['Cell'] || {}) ['cm_config'] || {};
return cmc['lineNumbers'] || false;
},
set: function(value) {
that.config.update({
'Cell': {
'cm_config': {
'lineNumbers':value
}
}
});
}
});
Object.defineProperty(this, 'header', {
get: function() {
return that.class_config.get_sync('Header');
},
set: function(value) {
that.class_config.set('Header', value);
}
});
Object.defineProperty(this, 'toolbar', {
get: function() {
return that.class_config.get_sync('Toolbar');
},
set: function(value) {
that.class_config.set('Toolbar', value);
}
});
this.class_config.get('Header').then(function(header) {
if (header === false) {
that.keyboard_manager.actions.call('jupyter-notebook:hide-header');
}
});
this.class_config.get('Toolbar').then(function(toolbar) {
if (toolbar === false) {
that.keyboard_manager.actions.call('jupyter-notebook:hide-toolbar');
}
});
// prevent assign to miss-typed properties.
Object.seal(this);
}
Notebook.options_default = {
// can be any cell type, or the special values of
// 'above', 'below', or 'selected' to get the value from another cell.
default_cell_type: 'code',
Header: true,
Toolbar: true,
kill_kernel: false
};
Notebook.prototype.validate_config = function() {
var code_cell = this.config.data['CodeCell'] || {};
var cm_keymap = (code_cell['cm_config'] || {})['keyMap'];
if (cm_keymap && CodeMirror.keyMap[cm_keymap] === undefined) {
console.warn('CodeMirror keymap not found, ignoring: ' + cm_keymap);
delete code_cell.cm_config.keyMap;
}
};
/**
* Create an HTML and CSS representation of the notebook.
*/
Notebook.prototype.create_elements = function () {
var that = this;
this.element.attr('tabindex','-1');
this.container = $("<div/>").addClass("container").attr("id", "notebook-container");
// We add this end_space div to the end of the notebook div to:
// i) provide a margin between the last cell and the end of the notebook
// ii) to prevent the div from scrolling up when the last cell is being
// edited, but is too low on the page, which browsers will do automatically.
var end_space = $('<div/>')
.addClass('end_space');
end_space.dblclick(function () {
var ncells = that.ncells();
that.insert_cell_below('code',ncells-1);
});
this.element.append(this.container);
this.container.after(end_space);
};
/**
* Bind JavaScript events: key presses and custom Jupyter events.
*/
Notebook.prototype.bind_events = function () {
var that = this;
this.events.on('set_next_input.Notebook', function (event, data) {
if (data.replace) {
data.cell.set_text(data.text);
if (data.clear_output !== false) {
// default (undefined) is true to preserve prior behavior
data.cell.clear_output();
}
} else {
var index = that.find_cell_index(data.cell);
var new_cell = that.insert_cell_below('code',index);
new_cell.set_text(data.text);
}
that.dirty = true;
});
this.events.on('unrecognized_cell.Cell', function () {
that.warn_nbformat_minor();
});
this.events.on('unrecognized_output.OutputArea', function () {
that.warn_nbformat_minor();
});
this.events.on('set_dirty.Notebook', function (event, data) {
that.dirty = data.value;
});
this.events.on('trust_changed.Notebook', function (event, trusted) {
that.trusted = trusted;
});
this.events.on('select.Cell', function (event, data) {
var index = that.find_cell_index(data.cell);
that.select(index, !data.extendSelection);
});
this.events.on('edit_mode.Cell', function (event, data) {
that.handle_edit_mode(data.cell);
});
this.events.on('command_mode.Cell', function (event, data) {
that.handle_command_mode(data.cell);
});
this.events.on('spec_changed.Kernel', function(event, data) {
var existing_spec = that.metadata.kernelspec;
that.metadata.kernelspec = {
name: data.name,
display_name: data.spec.display_name,
language: data.spec.language,
};
if (!existing_spec || ! _.isEqual(existing_spec, that.metadata.kernelspec)) {
that.set_dirty(true);
}
// start a new session
that.start_session(data.name);
});
this.events.on('kernel_ready.Kernel', function(event, data) {
var kinfo = data.kernel.info_reply;
if (!kinfo.language_info) {
delete that.metadata.language_info;
return;
}
var existing_info = that.metadata.language_info;
var langinfo = kinfo.language_info;
that.metadata.language_info = langinfo;
if (!existing_info || ! _.isEqual(existing_info, langinfo)) {
that.set_dirty(true);
}
// Mode 'null' should be plain, unhighlighted text.
var cm_mode = langinfo.codemirror_mode || langinfo.name || 'null';
that.set_codemirror_mode(cm_mode);
});
this.events.on('kernel_idle.Kernel', function () {
that.kernel_busy = false;
});
this.events.on('kernel_busy.Kernel', function () {
that.kernel_busy = true;
});
var collapse_time = function (time) {
var app_height = $('#ipython-main-app').height(); // content height
var splitter_height = $('div#pager_splitter').outerHeight(true);
var new_height = app_height - splitter_height;
that.element.animate({height : new_height + 'px'}, time);
};
this.element.bind('collapse_pager', function (event, extrap) {
var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
collapse_time(time);
});
var expand_time = function (time) {
var app_height = $('#ipython-main-app').height(); // content height
var splitter_height = $('div#pager_splitter').outerHeight(true);
var pager_height = $('div#pager').outerHeight(true);
var new_height = app_height - pager_height - splitter_height;
that.element.animate({height : new_height + 'px'}, time);
};
this.element.bind('expand_pager', function (event, extrap) {
var time = (extrap !== undefined) ? ((extrap.duration !== undefined ) ? extrap.duration : 'fast') : 'fast';
expand_time(time);
});
// Firefox 22 broke $(window).on("beforeunload")
// I'm not sure why or how.
window.onbeforeunload = function () {
/* Make kill kernel configurable.
example in custom.js:
var notebook = Jupyter.notebook;
var config = notebook.config;
var patch = {
Notebook:{
kill_kernel: true
}
};
config.update(patch);
*/
var kill_kernel = that.class_config.get_sync("kill_kernel");
if (kill_kernel) {
that.session.delete();
}
if ( utils.browser[0] === "Firefox") {
// Workaround ancient Firefox bug showing beforeunload twice: https://bugzilla.mozilla.org/show_bug.cgi?id=531199
if (that._ff_beforeunload_fired) {
return; // don't show twice on FF
}
that._ff_beforeunload_fired = true;
// unset flag immediately after dialog is dismissed
setTimeout(function () {
that._ff_beforeunload_fired = false;
}, 1);
}
// if we are autosaving, trigger an autosave on nav-away.
// still warn, because if we don't the autosave may fail.
if (that.dirty) {
if ( that.autosave_interval ) {
// schedule autosave in a timeout
// this gives you a chance to forcefully discard changes
// by reloading the page if you *really* want to.
// the timer doesn't start until you *dismiss* the dialog.
setTimeout(function () {
if (that.dirty) {
that.save_notebook();
}
}, 1000);
return i18n.msg._("Autosave in progress, latest changes may be lost.");
} else {
return i18n.msg._("Unsaved changes will be lost.");
}
}
// if the kernel is busy, prompt the user if he’s sure
if (that.kernel_busy) {
return i18n.msg._("The Kernel is busy, outputs may be lost.");
}
// IE treats null as a string. Instead just return which will avoid the dialog.
return;
};
};
Notebook.prototype.show_command_palette = function() {
new commandpalette.CommandPalette(this);
};
Notebook.prototype.show_shortcuts_editor = function() {
new ShortcutEditor(this);
};
/**
* Trigger a warning dialog about missing functionality from newer minor versions
*/
Notebook.prototype.warn_nbformat_minor = function () {
var v = 'v' + this.nbformat + '.';
var orig_vs = v + this.nbformat_minor;
var this_vs = v + this.current_nbformat_minor;
var msg = i18n.msg.sprintf(i18n.msg._("This notebook is version %1$s, but we only fully support up to %2$s."),
orig_vs,this_vs) + " " +
i18n.msg._("You can still work with this notebook, but cell and output types introduced in later notebook versions will not be available.");
// This statement is used simply so that message extraction
// will pick up the strings. The actual setting of the text
// for the button is in dialog.js.
var button_labels = [
i18n.msg._("OK"),
i18n.msg._("Restart and Run All Cells"),
i18n.msg._("Restart and Clear All Outputs"),
i18n.msg._("Restart"),
i18n.msg._("Continue Running"),
i18n.msg._("Reload"),
i18n.msg._("Cancel"),
i18n.msg._("Overwrite"),
i18n.msg._("Trust"),
i18n.msg._("Revert")];
dialog.modal({
notebook: this,
keyboard_manager: this.keyboard_manager,
title : i18n.msg._("Newer Notebook"),
body : msg,
buttons : {
OK : {
"class" : "btn-danger"
}
}
});
};
/**
* Set the dirty flag, and trigger the set_dirty.Notebook event
*/
Notebook.prototype.set_dirty = function (value) {
if (value === undefined) {
value = true;
}
if (this.dirty === value) {
return;
}
this.events.trigger('set_dirty.Notebook', {value: value});
};
/**
* Scroll the top of the page to a given cell.
*
* @param {integer} index - An index of the cell to view
* @param {integer} time - Animation time in milliseconds
* @return {integer} Pixel offset from the top of the container
*/
Notebook.prototype.scroll_to_cell = function (index, time) {
return this.scroll_cell_percent(index, 0, time);
};
/**
* Scroll the middle of the page to a given cell.
*
* @param {integer} index - An index of the cell to view
* @param {integer} percent - 0-100, the location on the screen to scroll.
* 0 is the top, 100 is the bottom.
* @param {integer} time - Animation time in milliseconds
* @return {integer} Pixel offset from the top of the container
*/
Notebook.prototype.scroll_cell_percent = function (index, percent, time) {
var cells = this.get_cells();
time = time || 0;
percent = percent || 0;
index = Math.min(cells.length-1,index);
index = Math.max(0 ,index);
var sme = this.scroll_manager.element;
var h = sme.height();
var st = sme.scrollTop();
var t = sme.offset().top;
var ct = cells[index].element.offset().top;
var scroll_value = st + ct - (t + 0.01 * percent * h);
this.scroll_manager.element.animate({scrollTop:scroll_value}, time);
return scroll_value;
};
/**
* Scroll to the bottom of the page.
*/
Notebook.prototype.scroll_to_bottom = function () {
this.scroll_manager.element.animate({scrollTop:this.element.get(0).scrollHeight}, 0);
};
/**
* Scroll to the top of the page.
*/
Notebook.prototype.scroll_to_top = function () {
this.scroll_manager.element.animate({scrollTop:0}, 0);
};
// Edit Notebook metadata
/**
* Display a dialog that allows the user to edit the Notebook's metadata.
*/
Notebook.prototype.edit_metadata = function () {
var that = this;
dialog.edit_metadata({
md: this.metadata,
callback: function (new_md) {
if(!_.isEqual(that.metadata, new_md)){
that.set_dirty(true);
}
that.metadata = new_md;
},
name: 'Notebook',
notebook: this,
keyboard_manager: this.keyboard_manager});
};
// Cell indexing, retrieval, etc.
/**
* Get all cell elements in the notebook.
*
* @return {jQuery} A selector of all cell elements
*/
Notebook.prototype.get_cell_elements = function () {
var container = this.container || $('#notebook-container');
return container.find(".cell").not('.cell .cell');
};
/**
* Get a particular cell element.
*
* @param {integer} index An index of a cell to select
* @return {jQuery} A selector of the given cell.
*/
Notebook.prototype.get_cell_element = function (index) {
var result = null;
var e = this.get_cell_elements().eq(index);
if (e.length !== 0) {
result = e;
}
return result;
};
/**
* Try to get a particular cell by msg_id.
*
* @param {string} msg_id A message UUID
* @return {Cell} Cell or null if no cell was found.
*/
Notebook.prototype.get_msg_cell = function (msg_id) {
return codecell.CodeCell.msg_cells[msg_id] || null;
};
/**
* Count the cells in this notebook.
*
* @return {integer} The number of cells in this notebook
*/
Notebook.prototype.ncells = function () {
return this.get_cell_elements().length;
};
/**
* Get all cell objects in this notebook.
*
* @return {Array} This notebook's Cell objects
*/
Notebook.prototype.get_cells = function () {
// TODO: we are often calling cells as cells()[i], which we should optimize
// to cells(i) or a new method.
return this.get_cell_elements().toArray().map(function (e) {
return $(e).data("cell");
});
};
/**
* Get a cell object from this notebook.
*
* @param {integer} index - An index of a cell to retrieve
* @return {Cell} Cell or null if no cell was found.
*/
Notebook.prototype.get_cell = function (index) {
var result = null;
var ce = this.get_cell_element(index);
if (ce !== null) {
result = ce.data('cell');
}
return result;
};
/**
* Get the cell below a given cell.
*
* @param {Cell} cell
* @return {Cell} the next cell or null if no cell was found.
*/
Notebook.prototype.get_next_cell = function (cell) {
var result = null;
var index = this.find_cell_index(cell);
if (this.is_valid_cell_index(index+1)) {
result = this.get_cell(index+1);
}
return result;
};
/**
* Toggles the display of line numbers in all cells.
*/
Notebook.prototype.toggle_all_line_numbers = function () {
this.line_numbers = !this.line_numbers;
};
/**
* Reads direction settings (LTR/RTL) from notebook/cells metadata
* and applies them to display elements.
*/
Notebook.prototype.apply_directionality = function () {
var notebook_direction = this.metadata.direction || 'ltr';
// html
document.body.setAttribute('dir', notebook_direction);
// existing cells
this.get_cells().forEach( function(cell) {
if (cell.cell_type == 'markdown') {
cell.code_mirror.setOption('direction', cell.metadata.direction || notebook_direction);
cell.element.find('.rendered_html').attr('dir', cell.metadata.direction || notebook_direction);
} else if (cell.cell_type == 'code') {
cell.element.find('.output_text').attr('dir', cell.metadata.direction || 'auto');
}
});
// new cells
textcell.MarkdownCell.options_default.cm_config.direction = notebook_direction;
};
/**
* Get the cell above a given cell.
*
* @param {Cell} cell
* @return {Cell} The previous cell or null if no cell was found.
*/
Notebook.prototype.get_prev_cell = function (cell) {
var result = null;
var index = this.find_cell_index(cell);
if (index !== null && index > 0) {
result = this.get_cell(index-1);
}
return result;
};
/**
* Get the numeric index of a given cell.
*
* @param {Cell} cell
* @return {integer} The cell's numeric index or null if no cell was found.
*/
Notebook.prototype.find_cell_index = function (cell) {
var result = null;
this.get_cell_elements().filter(function (index) {
if ($(this).data("cell") === cell) {
result = index;
}
});
return result;
};
/**
* Return given index if defined, or the selected index if not.
*
* @param {integer} [index] - A cell's index
* @return {integer} cell index
*/
Notebook.prototype.index_or_selected = function (index) {
var i;
if (index === undefined || index === null) {
i = this.get_selected_index();
if (i === null) {
i = 0;
}
} else {
i = index;
}
return i;
};
/**
* Get the selected cells.
*
* @return {Cell} The selected cells or null if no cell was found.
*/
Notebook.prototype.get_selected_cells = function () {
return this.get_cells().filter(function(cell, index){ return cell.selected || soft_selected(cell) || cell.anchor;});
};
/**
* Get the selected cells.
*
* @return {array} cell indicies
*/
Notebook.prototype.get_selected_cells_indices = function () {
var result = [];
this.get_cells().filter(function (cell, index) {
if (cell.selected || soft_selected(cell) || cell.anchor) {
result.push(index);
}
});
return result;
};
/**
* Get the currently selected cell.
*
* @return {Cell} The selected cell
*/
Notebook.prototype.get_selected_cell = function () {
var index = this.get_selected_index();
return this.get_cell(index);
};
/**
* Check whether a cell index is valid.
*
* @param {integer} index - A cell index
* @return True if the index is valid, false otherwise
*/
Notebook.prototype.is_valid_cell_index = function (index) {
if (index !== null && index >= 0 && index < this.ncells()) {
return true;
} else {
return false;
}
};
/**
* Returns the index of the cell that the selection is currently anchored on.
*
* @return {integer} Index of first cell selected in selection
*/
Notebook.prototype.get_anchor_index = function () {
var result = null;
this.get_cell_elements().filter(function (index) {
if ($(this).data("cell").anchor === true) {
result = index;
}
});
return result;
};
/**
* Get the index of the currently selected cell.
*
* @return {integer} The selected cell's numeric index
*/
Notebook.prototype.get_selected_index = function () {
var result = null;
this.get_cell_elements().filter(function (index) {
if ($(this).data("cell").selected === true) {
result = index;
}
});
return result;
};
// Cell selection.
Notebook.prototype.extend_selection_by = function(delta) {
var index = this.get_selected_index();
// do not move anchor
return this.select(index+delta, false);
};
Notebook.prototype.update_soft_selection = function(){
var i1 = this.get_selected_index();
var i2 = this.get_anchor_index();
var low = Math.min(i1, i2);
var high = Math.max(i1, i2);
this.get_cells().map(function(cell, index, all){
if( low <= index && index <= high && low !== high){
cell.element.addClass(_SOFT_SELECTION_CLASS);
} else {
cell.element.removeClass(_SOFT_SELECTION_CLASS);
}
});
};
Notebook.prototype.select_all = function(){
this.select(0, true);
this.select(this.ncells()-1, false);
};
Notebook.prototype._contract_selection = function(){
var i = this.get_selected_index();
this.select(i, true);
};
/**
* Programmatically select a cell.
*
* @param {integer} index - A cell's index
* @param {boolean} moveanchor – whether to move the selection
* anchor, default to true.
* @return {Notebook} This notebook
*/
Notebook.prototype.select = function (index, moveanchor) {
moveanchor = (moveanchor===undefined)? true : moveanchor;
if (this.is_valid_cell_index(index)) {
var sindex = this.get_selected_index();
if (sindex !== null && index !== sindex) {
// If we are about to select a different cell, make sure we are
// first in command mode.
if (this.mode !== 'command') {
this.command_mode();
}
this.get_cell(sindex).unselect(moveanchor);
}
if(moveanchor){
this.get_cell(this.get_anchor_index()).unselect(moveanchor);
}
var cell = this.get_cell(index);
cell.select(moveanchor);
this.update_soft_selection();
if (cell.cell_type === 'heading') {
this.events.trigger('selected_cell_type_changed.Notebook',
{
'cell_type': cell.cell_type,
'level': cell.level,
'editable': cell.is_editable()
}
);
} else {
this.events.trigger('selected_cell_type_changed.Notebook',
{
'cell_type': cell.cell_type,
'editable': cell.is_editable()
}
);
}
}
return this;
};
/**
* Programmatically select the next cell.
*
* @param {bool} moveanchor – whether to move the selection
* anchor, default to true.
* @return {Notebook} This notebook
*/
Notebook.prototype.select_next = function (moveanchor) {
var index = this.get_selected_index();
this.select(index+1, moveanchor);
return this;
};
/**
* Programmatically select the previous cell.
*
* @return {Notebook} This notebook
*/
Notebook.prototype.select_prev = function (moveanchor) {
var index = this.get_selected_index();
this.select(index-1, moveanchor);
return this;
};
// Edit/Command mode
/**
* Gets the index of the cell that is in edit mode.
*
* @return {integer} index
*/
Notebook.prototype.get_edit_index = function () {
var result = null;
this.get_cell_elements().filter(function (index) {
if ($(this).data("cell").mode === 'edit') {
result = index;
}
});
return result;
};
/**
* Handle when a a cell blurs and the notebook should enter command mode.
*
* @param {Cell} [cell] - Cell to enter command mode on.
*/
Notebook.prototype.handle_command_mode = function (cell) {
if (this.mode !== 'command') {
cell.command_mode();
this.mode = 'command';
this.events.trigger('command_mode.Notebook');
this.keyboard_manager.command_mode();
}
};
/**
* Make the notebook enter command mode.
*/
Notebook.prototype.command_mode = function () {
var cell = this.get_cell(this.get_edit_index());
if (cell && this.mode !== 'command') {
// We don't call cell.command_mode, but rather blur the CM editor
// which will trigger the call to handle_command_mode.
cell.code_mirror.getInputField().blur();
}
};
/**
* Handle when a cell fires it's edit_mode event.
*
* @param {Cell} [cell] Cell to enter edit mode on.
*/
Notebook.prototype.handle_edit_mode = function (cell) {
this._contract_selection();
if (cell && this.mode !== 'edit') {
cell.edit_mode();
this.mode = 'edit';
this.events.trigger('edit_mode.Notebook');
this.keyboard_manager.edit_mode();
}
};
/**
* Make a cell enter edit mode.
*/
Notebook.prototype.edit_mode = function () {
this._contract_selection();
var cell = this.get_selected_cell();
if (cell && this.mode !== 'edit') {
cell.unrender();
cell.focus_editor();
}
};
/**
* Ensure either cell or codemirror is focused. If none
* is focused, focus the cell.
*/
Notebook.prototype.ensure_focused = function(){
var cell = this.get_selected_cell();
if (cell === null) {return;} // No cell is selected
cell.ensure_focused();
};
/**
* Focus the currently selected cell.
*/
Notebook.prototype.focus_cell = function () {
var cell = this.get_selected_cell();
if (cell === null) {return;} // No cell is selected
cell.focus_cell();
};
// Cell movement
/**