editor.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import * as CodeMirror
  4. from 'codemirror';
  5. import {
  6. IChangedArgs
  7. } from '../common/interfaces';
  8. import {
  9. loadModeByMIME
  10. } from './';
  11. import {
  12. CodeEditor
  13. } from '../codeeditor';
  14. import {
  15. CodeMirrorModel
  16. } from './model';
  17. /**
  18. * The class name added to CodeMirrorWidget instances.
  19. */
  20. const EDITOR_CLASS = 'jp-CodeMirrorWidget';
  21. /**
  22. * The name of the default CodeMirror theme
  23. */
  24. export
  25. const DEFAULT_CODEMIRROR_THEME = 'jupyter';
  26. /**
  27. * CodeMirror editor.
  28. */
  29. export
  30. class CodeMirrorEditor implements CodeEditor.IEditor {
  31. /**
  32. * The uuid of this editor;
  33. */
  34. readonly uuid: string;
  35. /**
  36. * The selection style of this editor.
  37. */
  38. readonly selectionStyle?: CodeEditor.ISelectionStyle;
  39. /**
  40. * Handle keydown events for the editor.
  41. */
  42. onKeyDown: CodeEditor.KeydownHandler | null = null;
  43. /**
  44. * Construct a CodeMirror editor.
  45. */
  46. constructor(host: HTMLElement, options: CodeMirrorEditor.IOptions) {
  47. host.classList.add(EDITOR_CLASS);
  48. this.uuid = this.uuid;
  49. this.selectionStyle = options.selectionStyle;
  50. this._model = new CodeMirrorModel();
  51. options.theme = (options.theme || DEFAULT_CODEMIRROR_THEME);
  52. options.value = this._model.doc;
  53. this._editor = CodeMirror(host, options);
  54. this._model.mimeTypeChanged.connect((model, args) => this._onMimeTypeChanged(model, args));
  55. this._model.selections.changed.connect((selections, args) => this._onSelectionsChanged(selections, args));
  56. CodeMirror.on(this.editor, 'keydown', (editor, event) => this._onKeyDown(editor, event));
  57. CodeMirror.on(this.editor, 'cursorActivity', () => this._onCursorActivity());
  58. }
  59. /**
  60. * Tests whether the editor is disposed.
  61. */
  62. get isDisposed(): boolean {
  63. return this._isDisposed;
  64. }
  65. /**
  66. * Dispose of the resources held by the widget.
  67. */
  68. dispose(): void {
  69. if (this.isDisposed) {
  70. return;
  71. }
  72. this._isDisposed = true;
  73. // FIXME: dispose selections
  74. this._editor = null;
  75. }
  76. /**
  77. * Get the editor wrapped by the widget.
  78. *
  79. * #### Notes
  80. * This is a ready-only property.
  81. */
  82. get editor(): CodeMirror.Editor {
  83. return this._editor;
  84. }
  85. /**
  86. * Control the rendering of line numbers.
  87. */
  88. get lineNumbers(): boolean {
  89. return this._editor.getOption('lineNumbers');
  90. }
  91. set lineNumbers(value: boolean) {
  92. this._editor.setOption('lineNumbers', value);
  93. }
  94. /**
  95. * Set to false for horizontal scrolling. Defaults to true.
  96. */
  97. get wordWrap(): boolean {
  98. return this._editor.getOption('wordWrap');
  99. }
  100. set wordWrap(value: boolean) {
  101. this._editor.setOption('wordWrap', value);
  102. }
  103. /**
  104. * Should the editor be read only.
  105. */
  106. get readOnly(): boolean {
  107. return this._editor.getOption('readOnly') === 'nocursor';
  108. }
  109. set readOnly(readOnly: boolean) {
  110. let option = readOnly ? 'nocursor' : false;
  111. this._editor.setOption('readOnly', option);
  112. }
  113. /**
  114. * Returns a model for this editor.
  115. */
  116. get model(): CodeEditor.IModel {
  117. return this._model;
  118. }
  119. /**
  120. * The height of a line in the editor in pixels.
  121. */
  122. get lineHeight(): number {
  123. return this._editor.defaultTextHeight();
  124. }
  125. /**
  126. * The widget of a character in the editor in pixels.
  127. */
  128. get charWidth(): number {
  129. return this._editor.defaultCharWidth();
  130. }
  131. /**
  132. * Brings browser focus to this editor text.
  133. */
  134. focus(): void {
  135. this._editor.focus();
  136. }
  137. /**
  138. * Test whether the editor has keyboard focus.
  139. */
  140. hasFocus(): boolean {
  141. return this._editor.hasFocus();
  142. }
  143. /**
  144. * Repaint editor.
  145. */
  146. refresh(): void {
  147. this._editor.refresh();
  148. }
  149. /**
  150. * Set the size of the editor in pixels.
  151. */
  152. setSize(dimension: CodeEditor.IDimension | null): void {
  153. if (dimension) {
  154. this._editor.setSize(dimension.width, dimension.height);
  155. } else {
  156. this._editor.setSize(null, null);
  157. }
  158. }
  159. /**
  160. * Reveal the given position in the editor.
  161. */
  162. revealPosition(position: CodeEditor.IPosition): void {
  163. const cmPosition = this.toCodeMirrorPosition(position);
  164. this._editor.scrollIntoView(cmPosition);
  165. }
  166. /**
  167. * Reveal the given selection in the editor.
  168. */
  169. revealSelection(selection: CodeEditor.IRange): void {
  170. const range = this.toCodeMirrorRange(selection);
  171. this._editor.scrollIntoView(range);
  172. }
  173. /**
  174. * Get the window coordinates given a cursor position.
  175. */
  176. getCoordinate(position: CodeEditor.IPosition): CodeEditor.ICoordinate {
  177. return this.editor.charCoords(this.toCodeMirrorPosition(position), 'page');
  178. }
  179. /**
  180. * Returns the primary position of the cursor, never `null`.
  181. */
  182. getCursorPosition(): CodeEditor.IPosition {
  183. const cursor = this._model.doc.getCursor();
  184. return this.toPosition(cursor);
  185. }
  186. /**
  187. * Set the primary position of the cursor. This will remove any secondary cursors.
  188. */
  189. setCursorPosition(position: CodeEditor.IPosition): void {
  190. const cursor = this.toCodeMirrorPosition(position);
  191. this._model.doc.setCursor(cursor);
  192. }
  193. /**
  194. * Returns the primary selection, never `null`.
  195. */
  196. getSelection(): CodeEditor.ITextSelection {
  197. return this.getSelections()[0];
  198. }
  199. /**
  200. * Set the primary selection. This will remove any secondary cursors.
  201. */
  202. setSelection(selection: CodeEditor.IRange): void {
  203. this.setSelections([selection]);
  204. }
  205. /**
  206. * Gets the selections for all the cursors, never `null` or empty.
  207. */
  208. getSelections(): CodeEditor.ITextSelection[] {
  209. const selections = this._model.doc.listSelections();
  210. if (selections.length > 0) {
  211. return selections.map(selection => this.toSelection(selection));
  212. }
  213. const cursor = this._model.doc.getCursor();
  214. const selection = this.toSelection({ anchor: cursor, head: cursor });
  215. return [selection];
  216. }
  217. /**
  218. * Sets the selections for all the cursors, should not be empty.
  219. * Cursors will be removed or added, as necessary.
  220. * Passing an empty array resets a cursor position to the start of a document.
  221. */
  222. setSelections(selections: CodeEditor.IRange[]): void {
  223. const cmSelections = this.toCodeMirrorSelections(selections);
  224. this._model.doc.setSelections(cmSelections, 0);
  225. }
  226. /**
  227. * Converts selections to code mirror selections.
  228. */
  229. protected toCodeMirrorSelections(selections: CodeEditor.IRange[]): CodeMirror.Selection[] {
  230. if (selections.length > 0) {
  231. return selections.map(selection => this.toCodeMirrorSelection(selection));
  232. }
  233. const position = { line: 0, ch: 0 };
  234. return [{ anchor: position, head: position }];
  235. }
  236. /**
  237. * Handles a mime type change.
  238. */
  239. protected _onMimeTypeChanged(model: CodeMirrorModel, args: IChangedArgs<string>): void {
  240. const mime = args.newValue;
  241. loadModeByMIME(this._editor, mime);
  242. }
  243. /**
  244. * Handles a selections change.
  245. */
  246. protected _onSelectionsChanged(selections: CodeEditor.ISelections, args: CodeEditor.ISelections.IChangedArgs): void {
  247. const uuid = args.uuid;
  248. if (uuid !== this.uuid) {
  249. this.cleanSelections(uuid);
  250. this.markSelections(uuid, args.newSelections);
  251. }
  252. }
  253. /**
  254. * Clean selections for the given uuid.
  255. */
  256. protected cleanSelections(uuid: string) {
  257. const markers = this.selectionMarkers[uuid];
  258. if (markers) {
  259. markers.forEach(marker => marker.clear());
  260. }
  261. delete this.selectionMarkers[uuid];
  262. }
  263. /**
  264. * Marks selections.
  265. */
  266. protected markSelections(uuid: string, selections: CodeEditor.ITextSelection[]) {
  267. const markers: CodeMirror.TextMarker[] = [];
  268. for (const selection of selections) {
  269. const { anchor, head } = this.toCodeMirrorSelection(selection);
  270. const markerOptions = this.toTextMarkerOptions(selection);
  271. this._model.doc.markText(anchor, head, markerOptions);
  272. }
  273. this.selectionMarkers[uuid] = markers;
  274. }
  275. /**
  276. * Handles a key down event.
  277. */
  278. protected _onKeyDown(editor: CodeMirror.Editor, event: KeyboardEvent): void {
  279. if (this.onKeyDown && this.onKeyDown(this, event)) {
  280. event.preventDefault();
  281. }
  282. }
  283. /**
  284. * Handles a cursor activity event.
  285. */
  286. protected _onCursorActivity(): void {
  287. const selections = this.getSelections();
  288. this.model.selections.setSelections(this.uuid, selections);
  289. }
  290. /**
  291. * Converts a code mirror selection to an editor selection.
  292. */
  293. protected toSelection(selection: CodeMirror.Selection): CodeEditor.ITextSelection {
  294. return {
  295. uuid: this.uuid,
  296. start: this.toPosition(selection.anchor),
  297. end: this.toPosition(selection.head),
  298. style: this.selectionStyle
  299. };
  300. }
  301. /**
  302. * Converts the selection style to a text marker options.
  303. */
  304. protected toTextMarkerOptions(style: CodeEditor.ISelectionStyle | undefined): CodeMirror.TextMarkerOptions | undefined {
  305. if (style) {
  306. return {
  307. className: style.className,
  308. title: style.displayName
  309. };
  310. }
  311. return undefined;
  312. }
  313. /**
  314. * Converts an editor selection to a code mirror selection.
  315. */
  316. protected toCodeMirrorSelection(selection: CodeEditor.IRange): CodeMirror.Selection {
  317. return {
  318. anchor: this.toCodeMirrorPosition(selection.start),
  319. head: this.toCodeMirrorPosition(selection.end)
  320. };
  321. }
  322. /**
  323. * Converts an editor selection to a code mirror selection.
  324. */
  325. protected toCodeMirrorRange(range: CodeEditor.IRange): CodeMirror.Range {
  326. return {
  327. from: this.toCodeMirrorPosition(range.start),
  328. to: this.toCodeMirrorPosition(range.end)
  329. };
  330. }
  331. /**
  332. * Convert a code mirror position to an editor position.
  333. */
  334. protected toPosition(position: CodeMirror.Position) {
  335. return {
  336. line: position.line,
  337. column: position.ch
  338. };
  339. }
  340. /**
  341. * Convert an editor position to a code mirror position.
  342. */
  343. protected toCodeMirrorPosition(position: CodeEditor.IPosition) {
  344. return {
  345. line: position.line,
  346. ch: position.column
  347. };
  348. }
  349. private _model: CodeMirrorModel;
  350. private _editor: CodeMirror.Editor;
  351. private _isDisposed = false;
  352. protected selectionMarkers: { [key: string]: CodeMirror.TextMarker[] | undefined } = {};
  353. }
  354. /**
  355. * A namespace for `CodeMirrorEditor`.
  356. */
  357. export
  358. namespace CodeMirrorEditor {
  359. /**
  360. * An initialization options for a code mirror editor.
  361. */
  362. export
  363. interface IOptions extends CodeMirror.EditorConfiguration {
  364. /**
  365. * The uuid of an editor.
  366. */
  367. readonly uuid: string;
  368. /**
  369. * A selection style.
  370. */
  371. readonly selectionStyle?: CodeEditor.ISelectionStyle;
  372. }
  373. }