editor.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. define([
  4. 'jquery',
  5. 'base/js/utils',
  6. 'base/js/i18n',
  7. 'base/js/dialog',
  8. 'codemirror/lib/codemirror',
  9. 'codemirror/mode/meta',
  10. 'codemirror/addon/comment/comment',
  11. 'codemirror/addon/dialog/dialog',
  12. 'codemirror/addon/edit/closebrackets',
  13. 'codemirror/addon/edit/matchbrackets',
  14. 'codemirror/addon/search/searchcursor',
  15. 'codemirror/addon/search/search',
  16. 'codemirror/keymap/emacs',
  17. 'codemirror/keymap/sublime',
  18. 'codemirror/keymap/vim',
  19. ],
  20. function(
  21. $,
  22. utils,
  23. i18n,
  24. dialog,
  25. CodeMirror
  26. ) {
  27. "use strict";
  28. var Editor = function(selector, options) {
  29. var that = this;
  30. this.selector = selector;
  31. this.clean = false;
  32. this.contents = options.contents;
  33. this.events = options.events;
  34. this.base_url = options.base_url;
  35. this.file_path = options.file_path;
  36. this.config = options.config;
  37. this.file_extension_modes = options.file_extension_modes || {};
  38. this.last_modified = null;
  39. this._changed_on_disk_dialog = null;
  40. this.codemirror = new CodeMirror($(this.selector)[0]);
  41. this.codemirror.on('changes', function(cm, changes){
  42. that._clean_state();
  43. });
  44. this.generation = -1;
  45. // It appears we have to set commands on the CodeMirror class, not the
  46. // instance. I'd like to be wrong, but since there should only be one CM
  47. // instance on the page, this is good enough for now.
  48. CodeMirror.commands.save = $.proxy(this.save, this);
  49. this.save_enabled = false;
  50. this.config.loaded.then(function () {
  51. // load codemirror config
  52. var cfg = that.config.data.Editor || {};
  53. var cmopts = $.extend(true, {}, // true = recursive copy
  54. Editor.default_codemirror_options,
  55. cfg.codemirror_options || {}
  56. );
  57. that._set_codemirror_options(cmopts);
  58. that.events.trigger('config_changed.Editor', {config: that.config});
  59. if (cfg.file_extension_modes) {
  60. // check for file extension in user preferences
  61. var modename = cfg.file_extension_modes[that._get_file_extension()];
  62. if (modename) {
  63. var modeinfo = CodeMirror.findModeByName(modename);
  64. if (modeinfo) {
  65. that.set_codemirror_mode(modeinfo);
  66. }
  67. }
  68. }
  69. that._clean_state();
  70. });
  71. this.clean_sel = $('<div/>');
  72. $('.last_modified').before(this.clean_sel);
  73. this.clean_sel.addClass('dirty-indicator-dirty');
  74. };
  75. // default CodeMirror options
  76. Editor.default_codemirror_options = {
  77. extraKeys: {
  78. "Cmd-Right": "goLineRight",
  79. "End": "goLineRight",
  80. "Cmd-Left": "goLineLeft",
  81. "Tab": "indentMore",
  82. "Shift-Tab" : "indentLess",
  83. "Cmd-/" : "toggleComment",
  84. "Ctrl-/" : "toggleComment",
  85. },
  86. indentUnit: 4,
  87. theme: "ipython",
  88. lineNumbers: true,
  89. lineWrapping: true
  90. };
  91. Editor.prototype.load = function() {
  92. /** load the file */
  93. var that = this;
  94. var cm = this.codemirror;
  95. return this.contents.get(this.file_path, {type: 'file', format: 'text'})
  96. .then(function(model) {
  97. cm.setValue(model.content);
  98. // Setting the file's initial value creates a history entry,
  99. // which we don't want.
  100. cm.clearHistory();
  101. that._set_mode_for_model(model);
  102. that.save_enabled = true;
  103. that.generation = cm.changeGeneration();
  104. that.events.trigger("file_loaded.Editor", model);
  105. that._clean_state();
  106. that.last_modified = new Date(model.last_modified);
  107. }).catch(
  108. function(error) {
  109. that.events.trigger("file_load_failed.Editor", error);
  110. console.warn('Error loading: ', error);
  111. cm.setValue("Error! " + error.message +
  112. "\nSaving disabled.\nSee Console for more details.");
  113. cm.setOption('readOnly','nocursor');
  114. that.save_enabled = false;
  115. }
  116. );
  117. };
  118. Editor.prototype._set_mode_for_model = function (model) {
  119. /** Set the CodeMirror mode based on the file model */
  120. // Find and load the highlighting mode,
  121. // first by mime-type, then by file extension
  122. var modeinfo;
  123. var ext = this._get_file_extension();
  124. if (ext) {
  125. // check if a mode has been remembered for this extension
  126. var modename = this.file_extension_modes[ext];
  127. if (modename) {
  128. modeinfo = CodeMirror.findModeByName(modename);
  129. }
  130. }
  131. // prioritize CodeMirror's filename identification
  132. if (!modeinfo || modeinfo.mode === "null") {
  133. modeinfo = CodeMirror.findModeByFileName(model.name);
  134. // codemirror's filename identification is case-sensitive.
  135. // try once more with lowercase extension
  136. if (!modeinfo && ext) {
  137. // CodeMirror wants lowercase ext without leading '.'
  138. modeinfo = CodeMirror.findModeByExtension(ext.slice(1).toLowerCase());
  139. }
  140. }
  141. if (model.mimetype && (!modeinfo || modeinfo.mode === "null")) {
  142. // mimetype is not set on file rename
  143. modeinfo = CodeMirror.findModeByMIME(model.mimetype);
  144. }
  145. if (modeinfo) {
  146. this.set_codemirror_mode(modeinfo);
  147. }
  148. };
  149. Editor.prototype.set_codemirror_mode = function (modeinfo) {
  150. /** set the codemirror mode from a modeinfo struct */
  151. var that = this;
  152. utils.requireCodeMirrorMode(modeinfo, function () {
  153. that.codemirror.setOption('mode', modeinfo.mime);
  154. that.events.trigger("mode_changed.Editor", modeinfo);
  155. }, function(err) {
  156. console.log('Error getting CodeMirror mode: ' + err);
  157. });
  158. };
  159. Editor.prototype.save_codemirror_mode = function (modeinfo) {
  160. /** save the selected codemirror mode for the current extension in config */
  161. var update_mode_map = {};
  162. var ext = this._get_file_extension();
  163. // no extension, nothing to save
  164. // TODO: allow remembering no-extension things like Makefile?
  165. if (!ext) return;
  166. update_mode_map[ext] = modeinfo.name;
  167. return this.config.update({
  168. Editor: {
  169. file_extension_modes: update_mode_map,
  170. }
  171. });
  172. };
  173. Editor.prototype.get_filename = function () {
  174. return utils.url_path_split(this.file_path)[1];
  175. };
  176. Editor.prototype._get_file_extension = function () {
  177. /** return file extension *including* .
  178. Returns undefined if no extension is found.
  179. */
  180. var filename = this.get_filename();
  181. var ext_idx = filename.lastIndexOf('.');
  182. if (ext_idx < 0) {
  183. return;
  184. } else {
  185. return filename.slice(ext_idx);
  186. }
  187. };
  188. /**
  189. * Rename the file.
  190. * @param {string} new_name
  191. * @return {Promise} promise that resolves when the file is renamed.
  192. */
  193. Editor.prototype.rename = function (new_name) {
  194. /** rename the file */
  195. var that = this;
  196. var parent = utils.url_path_split(this.file_path)[0];
  197. var new_path = utils.url_path_join(parent, new_name);
  198. return this.contents.rename(this.file_path, new_path).then(
  199. function (model) {
  200. that.file_path = model.path;
  201. that.events.trigger('file_renamed.Editor', model);
  202. that.last_modified = new Date(model.last_modified);
  203. that._set_mode_for_model(model);
  204. that._clean_state();
  205. }
  206. );
  207. };
  208. /**
  209. * Save this file on the server.
  210. *
  211. * @param {boolean} check_last_modified - checks if file has been modified on disk
  212. * @return {Promise} - promise that resolves when the notebook is saved.
  213. */
  214. Editor.prototype.save = function (check_last_modified) {
  215. /** save the file */
  216. if (!this.save_enabled) {
  217. console.log("Not saving, save disabled");
  218. return;
  219. }
  220. // used to check for last modified saves
  221. if (check_last_modified === undefined) {
  222. check_last_modified = true;
  223. }
  224. var model = {
  225. path: this.file_path,
  226. type: 'file',
  227. format: 'text',
  228. content: this.codemirror.getValue(),
  229. };
  230. var that = this;
  231. var _save = function () {
  232. that.events.trigger("file_saving.Editor");
  233. return that.contents.save(that.file_path, model).then(function(data) {
  234. // record change generation for isClean
  235. that.generation = that.codemirror.changeGeneration();
  236. that.events.trigger("file_saved.Editor", data);
  237. that.last_modified = new Date(data.last_modified);
  238. that._clean_state();
  239. });
  240. };
  241. /*
  242. * Gets the current working file, and checks if the file has been modified on disk. If so, it
  243. * creates & opens a modal that issues the user a warning and prompts them to overwrite the file.
  244. *
  245. * If it can't get the working file, it builds a new file and saves.
  246. */
  247. if (check_last_modified) {
  248. return this.contents.get(that.file_path, {content: false}).then(
  249. function check_if_modified(data) {
  250. var last_modified = new Date(data.last_modified);
  251. // We want to check last_modified (disk) > that.last_modified (our last save)
  252. // In some cases the filesystem reports an inconsistent time,
  253. // so we allow 0.5 seconds difference before complaining.
  254. if ((last_modified.getTime() - that.last_modified.getTime()) > 500) { // 500 ms
  255. console.warn("Last saving was done on `"+that.last_modified+"`("+that._last_modified+"), "+
  256. "while the current file seem to have been saved on `"+data.last_modified+"`");
  257. if (that._changed_on_disk_dialog !== null) {
  258. // since the modal's event bindings are removed when destroyed, we reinstate
  259. // save & reload callbacks on the confirmation & reload buttons
  260. that._changed_on_disk_dialog.find('.save-confirm-btn').click(_save);
  261. that._changed_on_disk_dialog.find('.btn-warning').click(function () {window.location.reload()});
  262. // redisplay existing dialog
  263. that._changed_on_disk_dialog.modal('show');
  264. } else {
  265. // create new dialog
  266. that._changed_on_disk_dialog = dialog.modal({
  267. keyboard_manager: that.keyboard_manager,
  268. title: i18n.msg._("File changed"),
  269. body: i18n.msg._("The file has changed on disk since the last time we opened or saved it. "
  270. + "Do you want to overwrite the file on disk with the version open here, or load "
  271. + "the version on disk (reload the page)?"),
  272. buttons: {
  273. Reload: {
  274. class: 'btn-warning',
  275. click: function () {
  276. window.location.reload();
  277. }
  278. },
  279. Cancel: {},
  280. Overwrite: {
  281. class: 'btn-danger save-confirm-btn',
  282. click: function () {
  283. _save();
  284. }
  285. },
  286. }
  287. });
  288. }
  289. } else {
  290. return _save();
  291. }
  292. }, function (error) {
  293. console.log(error);
  294. // maybe it has been deleted or renamed? Go ahead and save.
  295. return _save();
  296. })
  297. } else {
  298. return _save();
  299. }
  300. };
  301. Editor.prototype._clean_state = function(){
  302. var clean = this.codemirror.isClean(this.generation);
  303. if (clean === this.clean){
  304. return;
  305. } else {
  306. this.clean = clean;
  307. }
  308. if(clean){
  309. this.events.trigger("save_status_clean.Editor");
  310. this.clean_sel.attr('class','dirty-indicator-clean').attr('title','No changes to save');
  311. } else {
  312. this.events.trigger("save_status_dirty.Editor");
  313. this.clean_sel.attr('class','dirty-indicator-dirty').attr('title','Unsaved changes');
  314. }
  315. };
  316. Editor.prototype._set_codemirror_options = function (options) {
  317. // update codemirror options from a dict
  318. var codemirror = this.codemirror;
  319. $.map(options, function (value, opt) {
  320. if (value === null) {
  321. value = CodeMirror.defaults[opt];
  322. }
  323. codemirror.setOption(opt, value);
  324. });
  325. var that = this;
  326. };
  327. Editor.prototype.update_codemirror_options = function (options) {
  328. /** update codemirror options locally and save changes in config */
  329. var that = this;
  330. this._set_codemirror_options(options);
  331. return this.config.update({
  332. Editor: {
  333. codemirror_options: options
  334. }
  335. }).then(
  336. that.events.trigger('config_changed.Editor', {config: that.config})
  337. );
  338. };
  339. return {Editor: Editor};
  340. });