editor.js
74 lines
| 2.3 KiB
| application/javascript
|
JavascriptLexer
Thomas Kluyver
|
r19013 | // Copyright (c) IPython Development Team. | ||
// Distributed under the terms of the Modified BSD License. | ||||
define([ | ||||
'jquery', | ||||
'base/js/utils', | ||||
'codemirror/lib/codemirror', | ||||
'codemirror/mode/meta', | ||||
Thomas Kluyver
|
r19014 | 'codemirror/addon/search/search' | ||
Thomas Kluyver
|
r19013 | ], | ||
function($, | ||||
utils, | ||||
CodeMirror | ||||
) { | ||||
var Editor = function(selector, options) { | ||||
this.selector = selector; | ||||
this.contents = options.contents; | ||||
this.events = options.events; | ||||
this.base_url = options.base_url; | ||||
this.file_path = options.file_path; | ||||
this.codemirror = CodeMirror($(this.selector)[0]); | ||||
Thomas Kluyver
|
r19020 | // It appears we have to set commands on the CodeMirror class, not the | ||
// instance. I'd like to be wrong, but since there should only be one CM | ||||
// instance on the page, this is good enough for now. | ||||
CodeMirror.commands.save = $.proxy(this.save, this); | ||||
Thomas Kluyver
|
r19015 | this.save_enabled = false; | ||
Thomas Kluyver
|
r19013 | }; | ||
Editor.prototype.load = function() { | ||||
Thomas Kluyver
|
r19015 | var that = this; | ||
Thomas Kluyver
|
r19013 | var cm = this.codemirror; | ||
Thomas Kluyver
|
r19015 | this.contents.get(this.file_path, {type: 'file', format: 'text'}) | ||
.then(function(model) { | ||||
cm.setValue(model.content); | ||||
// Find and load the highlighting mode | ||||
var modeinfo = CodeMirror.findModeByMIME(model.mimetype); | ||||
if (modeinfo) { | ||||
utils.requireCodeMirrorMode(modeinfo.mode, function() { | ||||
cm.setOption('mode', modeinfo.mode); | ||||
}); | ||||
Thomas Kluyver
|
r19013 | } | ||
Thomas Kluyver
|
r19015 | that.save_enabled = true; | ||
}, | ||||
function(error) { | ||||
cm.setValue("Error! " + error.message + | ||||
"\nSaving disabled."); | ||||
that.save_enabled = false; | ||||
Thomas Kluyver
|
r19013 | } | ||
Thomas Kluyver
|
r19015 | ); | ||
Thomas Kluyver
|
r19013 | }; | ||
Editor.prototype.save = function() { | ||||
Thomas Kluyver
|
r19015 | if (!this.save_enabled) { | ||
console.log("Not saving, save disabled"); | ||||
return; | ||||
} | ||||
Thomas Kluyver
|
r19013 | var model = { | ||
Thomas Kluyver
|
r19015 | path: this.file_path, | ||
Thomas Kluyver
|
r19013 | type: 'file', | ||
format: 'text', | ||||
content: this.codemirror.getValue(), | ||||
}; | ||||
var that = this; | ||||
Thomas Kluyver
|
r19017 | this.contents.save(this.file_path, model).then(function() { | ||
that.events.trigger("save_succeeded.TextEditor"); | ||||
Thomas Kluyver
|
r19013 | }); | ||
}; | ||||
return {Editor: Editor}; | ||||
}); | ||||