aceEditor.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. /* eslint-disable
  2. camelcase,
  3. max-len
  4. */
  5. define([
  6. 'base',
  7. 'ace/ace',
  8. 'ace/ext-searchbox',
  9. 'ace/ext-modelist',
  10. 'ace/keybinding-vim',
  11. 'ide/editor/directives/aceEditor/undo/UndoManager',
  12. 'ide/editor/directives/aceEditor/auto-complete/AutoCompleteManager',
  13. 'ide/editor/directives/aceEditor/spell-check/SpellCheckManager',
  14. 'ide/editor/directives/aceEditor/spell-check/SpellCheckAdapter',
  15. 'ide/editor/directives/aceEditor/highlights/HighlightsManager',
  16. 'ide/editor/directives/aceEditor/cursor-position/CursorPositionManager',
  17. 'ide/editor/directives/aceEditor/cursor-position/CursorPositionAdapter',
  18. 'ide/editor/directives/aceEditor/track-changes/TrackChangesManager',
  19. 'ide/editor/directives/aceEditor/track-changes/TrackChangesAdapter',
  20. 'ide/editor/directives/aceEditor/metadata/MetadataManager',
  21. 'ide/metadata/services/metadata',
  22. 'ide/graphics/services/graphics',
  23. 'ide/preamble/services/preamble',
  24. 'ide/files/services/files'
  25. ], function(
  26. App,
  27. Ace,
  28. _ignore1,
  29. _ignore2,
  30. _ignore3,
  31. UndoManager,
  32. AutoCompleteManager,
  33. SpellCheckManager,
  34. SpellCheckAdapter,
  35. HighlightsManager,
  36. CursorPositionManager,
  37. CursorPositionAdapter,
  38. TrackChangesManager,
  39. TrackChangesAdapter,
  40. MetadataManager
  41. ) {
  42. let syntaxValidationEnabled
  43. const { EditSession } = ace.require('ace/edit_session')
  44. const ModeList = ace.require('ace/ext/modelist')
  45. const { Vim } = ace.require('ace/keyboard/vim')
  46. const SearchBox = ace.require('ace/ext/searchbox')
  47. // Set the base path that ace will fetch modes/snippets/workers from
  48. if (window.aceBasePath !== '') {
  49. syntaxValidationEnabled = true
  50. ace.config.set('basePath', `${window.aceBasePath}`)
  51. } else {
  52. syntaxValidationEnabled = false
  53. }
  54. // By default, don't use workers - enable them per-session as required
  55. ace.config.setDefaultValue('session', 'useWorker', false)
  56. // Ace loads its script itself, so we need to hook in to be able to clear
  57. // the cache.
  58. if (ace.config._moduleUrl == null) {
  59. ace.config._moduleUrl = ace.config.moduleUrl
  60. ace.config.moduleUrl = function(...args) {
  61. const url = ace.config._moduleUrl(...Array.from(args || []))
  62. return url
  63. }
  64. }
  65. App.directive('aceEditor', function(
  66. $timeout,
  67. $compile,
  68. $rootScope,
  69. eventTracking,
  70. localStorage,
  71. $cacheFactory,
  72. metadata,
  73. graphics,
  74. preamble,
  75. files,
  76. $http,
  77. $q,
  78. $window
  79. ) {
  80. monkeyPatchSearch($rootScope, $compile)
  81. return {
  82. scope: {
  83. theme: '=',
  84. showPrintMargin: '=',
  85. keybindings: '=',
  86. fontSize: '=',
  87. autoComplete: '=',
  88. autoPairDelimiters: '=',
  89. sharejsDoc: '=',
  90. spellCheck: '=',
  91. spellCheckLanguage: '=',
  92. highlights: '=',
  93. text: '=',
  94. readOnly: '=',
  95. annotations: '=',
  96. navigateHighlights: '=',
  97. fileName: '=',
  98. onCtrlEnter: '=', // Compile
  99. onCtrlJ: '=', // Toggle the review panel
  100. onCtrlShiftC: '=', // Add a new comment
  101. onCtrlShiftA: '=', // Toggle track-changes on/off
  102. onSave: '=', // Cmd/Ctrl-S or :w in Vim
  103. syntaxValidation: '=',
  104. reviewPanel: '=',
  105. eventsBridge: '=',
  106. trackChanges: '=',
  107. docId: '=',
  108. rendererData: '=',
  109. lineHeight: '=',
  110. fontFamily: '='
  111. },
  112. link(scope, element, attrs) {
  113. // Don't freak out if we're already in an apply callback
  114. let spellCheckManager
  115. scope.$originalApply = scope.$apply
  116. scope.$apply = function(fn) {
  117. if (fn == null) {
  118. fn = function() {}
  119. }
  120. const phase = this.$root.$$phase
  121. if (phase === '$apply' || phase === '$digest') {
  122. return fn()
  123. } else {
  124. return this.$originalApply(fn)
  125. }
  126. }
  127. const editor = ace.edit(element.find('.ace-editor-body')[0])
  128. editor.$blockScrolling = Infinity
  129. // auto-insertion of braces, brackets, dollars
  130. editor.setOption('behavioursEnabled', scope.autoPairDelimiters || false)
  131. editor.setOption('wrapBehavioursEnabled', false)
  132. scope.$watch('autoPairDelimiters', autoPairDelimiters => {
  133. if (autoPairDelimiters) {
  134. return editor.setOption('behavioursEnabled', true)
  135. } else {
  136. return editor.setOption('behavioursEnabled', false)
  137. }
  138. })
  139. if (!window._debug_editors) {
  140. window._debug_editors = []
  141. }
  142. window._debug_editors.push(editor)
  143. scope.name = attrs.aceEditor
  144. if (scope.spellCheck) {
  145. // only enable spellcheck when explicitly required
  146. spellCheckManager = new SpellCheckManager(
  147. scope,
  148. $cacheFactory,
  149. $http,
  150. $q,
  151. new SpellCheckAdapter(editor)
  152. )
  153. }
  154. /* eslint-disable no-unused-vars */
  155. const undoManager = new UndoManager(editor)
  156. const highlightsManager = new HighlightsManager(scope, editor, element)
  157. const cursorPositionManager = new CursorPositionManager(
  158. scope,
  159. new CursorPositionAdapter(editor),
  160. localStorage
  161. )
  162. const trackChangesManager = new TrackChangesManager(
  163. scope,
  164. editor,
  165. element,
  166. new TrackChangesAdapter(editor)
  167. )
  168. const metadataManager = new MetadataManager(
  169. scope,
  170. editor,
  171. element,
  172. metadata
  173. )
  174. const autoCompleteManager = new AutoCompleteManager(
  175. scope,
  176. editor,
  177. element,
  178. metadataManager,
  179. graphics,
  180. preamble,
  181. files
  182. )
  183. // prevent user entering null and non-BMP unicode characters in Ace
  184. const BAD_CHARS_REGEXP = /[\0\uD800-\uDFFF]/g
  185. const BAD_CHARS_REPLACEMENT_CHAR = '\uFFFD'
  186. // the 'exec' event fires for ace functions before they are executed.
  187. // you can modify the input or reject the event with e.preventDefault()
  188. editor.commands.on('exec', function(e) {
  189. // replace bad characters in paste content
  190. if (e.command && e.command.name === 'paste') {
  191. BAD_CHARS_REGEXP.lastIndex = 0 // reset stateful regexp for this usage
  192. if (e.args && BAD_CHARS_REGEXP.test(e.args.text)) {
  193. e.args.text = e.args.text.replace(
  194. BAD_CHARS_REGEXP,
  195. BAD_CHARS_REPLACEMENT_CHAR
  196. )
  197. }
  198. }
  199. // replace bad characters in keyboard input
  200. if (e.command && e.command.name === 'insertstring') {
  201. BAD_CHARS_REGEXP.lastIndex = 0 // reset stateful regexp for this usage
  202. if (e.args && BAD_CHARS_REGEXP.test(e.args)) {
  203. e.args = e.args.replace(
  204. BAD_CHARS_REGEXP,
  205. BAD_CHARS_REPLACEMENT_CHAR
  206. )
  207. }
  208. }
  209. })
  210. /* eslint-enable no-unused-vars */
  211. scope.$watch('onSave', function(callback) {
  212. if (callback != null) {
  213. Vim.defineEx('write', 'w', callback)
  214. editor.commands.addCommand({
  215. name: 'save',
  216. bindKey: {
  217. win: 'Ctrl-S',
  218. mac: 'Command-S'
  219. },
  220. exec: callback,
  221. readOnly: true
  222. })
  223. // Not technically 'save', but Ctrl-. recompiles in OL v1
  224. // so maintain compatibility
  225. return editor.commands.addCommand({
  226. name: 'recompile_v1',
  227. bindKey: {
  228. win: 'Ctrl-.',
  229. mac: 'Ctrl-.'
  230. },
  231. exec: callback,
  232. readOnly: true
  233. })
  234. }
  235. })
  236. editor.commands.removeCommand('transposeletters')
  237. editor.commands.removeCommand('showSettingsMenu')
  238. editor.commands.removeCommand('foldall')
  239. // For European keyboards, the / is above 7 so needs Shift pressing.
  240. // This comes through as Command-Shift-/ on OS X, which is mapped to
  241. // toggleBlockComment.
  242. // This doesn't do anything for LaTeX, so remap this to togglecomment to
  243. // work for European keyboards as normal.
  244. // On Windows, the key combo comes as Ctrl-Shift-7.
  245. editor.commands.removeCommand('toggleBlockComment')
  246. editor.commands.removeCommand('togglecomment')
  247. editor.commands.addCommand({
  248. name: 'togglecomment',
  249. bindKey: {
  250. win: 'Ctrl-/|Ctrl-Shift-7',
  251. mac: 'Command-/|Command-Shift-/'
  252. },
  253. exec(editor) {
  254. return editor.toggleCommentLines()
  255. },
  256. multiSelectAction: 'forEachLine',
  257. scrollIntoView: 'selectionPart'
  258. })
  259. // Trigger search AND replace on CMD+F
  260. editor.commands.addCommand({
  261. name: 'find',
  262. bindKey: {
  263. win: 'Ctrl-F',
  264. mac: 'Command-F'
  265. },
  266. exec(editor) {
  267. return SearchBox.Search(editor, true)
  268. },
  269. readOnly: true
  270. })
  271. // Bold text on CMD+B
  272. editor.commands.addCommand({
  273. name: 'bold',
  274. bindKey: {
  275. win: 'Ctrl-B',
  276. mac: 'Command-B'
  277. },
  278. exec(editor) {
  279. const selection = editor.getSelection()
  280. if (selection.isEmpty()) {
  281. editor.insert('\\textbf{}')
  282. return editor.navigateLeft(1)
  283. } else {
  284. const text = editor.getCopyText()
  285. return editor.insert(`\\textbf{${text}}`)
  286. }
  287. },
  288. readOnly: false
  289. })
  290. // Italicise text on CMD+I
  291. editor.commands.addCommand({
  292. name: 'italics',
  293. bindKey: {
  294. win: 'Ctrl-I',
  295. mac: 'Command-I'
  296. },
  297. exec(editor) {
  298. const selection = editor.getSelection()
  299. if (selection.isEmpty()) {
  300. editor.insert('\\textit{}')
  301. return editor.navigateLeft(1)
  302. } else {
  303. const text = editor.getCopyText()
  304. return editor.insert(`\\textit{${text}}`)
  305. }
  306. },
  307. readOnly: false
  308. })
  309. scope.$watch('onCtrlEnter', function(callback) {
  310. if (callback != null) {
  311. return editor.commands.addCommand({
  312. name: 'compile',
  313. bindKey: {
  314. win: 'Ctrl-Enter',
  315. mac: 'Command-Enter'
  316. },
  317. exec: editor => {
  318. return callback()
  319. },
  320. readOnly: true
  321. })
  322. }
  323. })
  324. scope.$watch('onCtrlJ', function(callback) {
  325. if (callback != null) {
  326. return editor.commands.addCommand({
  327. name: 'toggle-review-panel',
  328. bindKey: {
  329. win: 'Ctrl-J',
  330. mac: 'Command-J'
  331. },
  332. exec: editor => {
  333. return callback()
  334. },
  335. readOnly: true
  336. })
  337. }
  338. })
  339. scope.$watch('onCtrlShiftC', function(callback) {
  340. if (callback != null) {
  341. return editor.commands.addCommand({
  342. name: 'add-new-comment',
  343. bindKey: {
  344. win: 'Ctrl-Shift-C',
  345. mac: 'Command-Shift-C'
  346. },
  347. exec: editor => {
  348. return callback()
  349. },
  350. readOnly: true
  351. })
  352. }
  353. })
  354. scope.$watch('onCtrlShiftA', function(callback) {
  355. if (callback != null) {
  356. return editor.commands.addCommand({
  357. name: 'toggle-track-changes',
  358. bindKey: {
  359. win: 'Ctrl-Shift-A',
  360. mac: 'Command-Shift-A'
  361. },
  362. exec: editor => {
  363. return callback()
  364. },
  365. readOnly: true
  366. })
  367. }
  368. })
  369. // Make '/' work for search in vim mode.
  370. editor.showCommandLine = arg => {
  371. if (arg === '/') {
  372. return SearchBox.Search(editor, true)
  373. }
  374. }
  375. const getCursorScreenPosition = function() {
  376. const session = editor.getSession()
  377. const cursorPosition = session.selection.getCursor()
  378. const sessionPos = session.documentToScreenPosition(
  379. cursorPosition.row,
  380. cursorPosition.column
  381. )
  382. return (
  383. sessionPos.row * editor.renderer.lineHeight - session.getScrollTop()
  384. )
  385. }
  386. if (attrs.resizeOn != null) {
  387. for (let event of Array.from(attrs.resizeOn.split(','))) {
  388. scope.$on(event, function() {
  389. scope.$applyAsync(() => {
  390. const previousScreenPosition = getCursorScreenPosition()
  391. editor.resize()
  392. // Put cursor back to same vertical position on screen
  393. const newScreenPosition = getCursorScreenPosition()
  394. const session = editor.getSession()
  395. return session.setScrollTop(
  396. session.getScrollTop() +
  397. newScreenPosition -
  398. previousScreenPosition
  399. )
  400. })
  401. })
  402. }
  403. }
  404. scope.$on(`${scope.name}:set-scroll-size`, function(e, size) {
  405. // Make sure that the editor has enough scroll margin above and below
  406. // to scroll the review panel with the given size
  407. const marginTop = size.overflowTop
  408. const { maxHeight } = editor.renderer.layerConfig
  409. const marginBottom = Math.max(size.height - maxHeight, 0)
  410. return setScrollMargins(marginTop, marginBottom)
  411. })
  412. var setScrollMargins = function(marginTop, marginBottom) {
  413. let marginChanged = false
  414. if (editor.renderer.scrollMargin.top !== marginTop) {
  415. editor.renderer.scrollMargin.top = marginTop
  416. marginChanged = true
  417. }
  418. if (editor.renderer.scrollMargin.bottom !== marginBottom) {
  419. editor.renderer.scrollMargin.bottom = marginBottom
  420. marginChanged = true
  421. }
  422. if (marginChanged) {
  423. return editor.renderer.updateFull()
  424. }
  425. }
  426. const resetScrollMargins = () => setScrollMargins(0, 0)
  427. scope.$watch('theme', value => editor.setTheme(`ace/theme/${value}`))
  428. scope.$watch('showPrintMargin', value =>
  429. editor.setShowPrintMargin(value)
  430. )
  431. scope.$watch('keybindings', function(value) {
  432. if (['vim', 'emacs'].includes(value)) {
  433. return editor.setKeyboardHandler(`ace/keyboard/${value}`)
  434. } else {
  435. return editor.setKeyboardHandler(null)
  436. }
  437. })
  438. scope.$watch('fontSize', value =>
  439. element.find('.ace_editor, .ace_content').css({
  440. 'font-size': value + 'px'
  441. })
  442. )
  443. scope.$watch('fontFamily', function(value) {
  444. const monospaceFamilies = [
  445. 'Monaco',
  446. 'Menlo',
  447. 'Ubuntu Mono',
  448. 'Consolas',
  449. 'source-code-pro',
  450. 'monospace'
  451. ]
  452. if (value != null) {
  453. switch (value) {
  454. case 'monaco':
  455. return editor.setOption(
  456. 'fontFamily',
  457. monospaceFamilies.join(', ')
  458. )
  459. case 'lucida':
  460. return editor.setOption(
  461. 'fontFamily',
  462. '"Lucida Console", monospace'
  463. )
  464. default:
  465. return editor.setOption('fontFamily', null)
  466. }
  467. }
  468. })
  469. scope.$watch('lineHeight', function(value) {
  470. if (value != null) {
  471. switch (value) {
  472. case 'compact':
  473. editor.container.style.lineHeight = 1.33
  474. break
  475. case 'normal':
  476. editor.container.style.lineHeight = 1.6
  477. break
  478. case 'wide':
  479. editor.container.style.lineHeight = 2
  480. break
  481. default:
  482. editor.container.style.lineHeight = 1.6
  483. }
  484. return editor.renderer.updateFontSize()
  485. }
  486. })
  487. scope.$watch('sharejsDoc', function(sharejs_doc, old_sharejs_doc) {
  488. if (old_sharejs_doc != null) {
  489. scope.$broadcast('beforeChangeDocument')
  490. detachFromAce(old_sharejs_doc)
  491. }
  492. if (sharejs_doc != null) {
  493. attachToAce(sharejs_doc)
  494. }
  495. if (sharejs_doc != null && old_sharejs_doc != null) {
  496. return scope.$broadcast('afterChangeDocument')
  497. }
  498. })
  499. scope.$watch('text', function(text) {
  500. if (text != null) {
  501. editor.setValue(text, -1)
  502. const session = editor.getSession()
  503. return session.setUseWrapMode(true)
  504. }
  505. })
  506. scope.$watch('annotations', function(annotations) {
  507. const session = editor.getSession()
  508. return session.setAnnotations(annotations)
  509. })
  510. scope.$watch('readOnly', value => editor.setReadOnly(!!value))
  511. scope.$watch('syntaxValidation', function(value) {
  512. // ignore undefined settings here
  513. // only instances of ace with an explicit value should set useWorker
  514. // the history instance will have syntaxValidation undefined
  515. if (value != null && syntaxValidationEnabled) {
  516. const session = editor.getSession()
  517. return session.setOption('useWorker', value)
  518. }
  519. })
  520. editor.setOption('scrollPastEnd', true)
  521. let updateCount = 0
  522. const onChange = function() {
  523. updateCount++
  524. if (updateCount === 100) {
  525. eventTracking.send('editor-interaction', 'multi-doc-update')
  526. }
  527. return scope.$emit(`${scope.name}:change`)
  528. }
  529. const onScroll = function(scrollTop) {
  530. if (scope.eventsBridge == null) {
  531. return
  532. }
  533. const height = editor.renderer.layerConfig.maxHeight
  534. return scope.eventsBridge.emit('aceScroll', scrollTop, height)
  535. }
  536. const onScrollbarVisibilityChanged = function(event, vRenderer) {
  537. if (scope.eventsBridge == null) {
  538. return
  539. }
  540. return scope.eventsBridge.emit(
  541. 'aceScrollbarVisibilityChanged',
  542. vRenderer.scrollBarV.isVisible,
  543. vRenderer.scrollBarV.width
  544. )
  545. }
  546. if (scope.eventsBridge != null) {
  547. editor.renderer.on(
  548. 'scrollbarVisibilityChanged',
  549. onScrollbarVisibilityChanged
  550. )
  551. scope.eventsBridge.on('externalScroll', position =>
  552. editor.getSession().setScrollTop(position)
  553. )
  554. scope.eventsBridge.on('refreshScrollPosition', function() {
  555. const session = editor.getSession()
  556. session.setScrollTop(session.getScrollTop() + 1)
  557. return session.setScrollTop(session.getScrollTop() - 1)
  558. })
  559. }
  560. const onSessionChangeForSpellCheck = function(e) {
  561. spellCheckManager.onSessionChange()
  562. if (e.oldSession != null) {
  563. e.oldSession.getDocument().off('change', spellCheckManager.onChange)
  564. }
  565. e.session.getDocument().on('change', spellCheckManager.onChange)
  566. if (e.oldSession != null) {
  567. e.oldSession.off('changeScrollTop', spellCheckManager.onScroll)
  568. }
  569. return e.session.on('changeScrollTop', spellCheckManager.onScroll)
  570. }
  571. const initSpellCheck = function() {
  572. if (!spellCheckManager) return
  573. spellCheckManager.init()
  574. editor.on('changeSession', onSessionChangeForSpellCheck)
  575. onSessionChangeForSpellCheck({
  576. session: editor.getSession()
  577. }) // Force initial setup
  578. return editor.on('nativecontextmenu', spellCheckManager.onContextMenu)
  579. }
  580. const tearDownSpellCheck = function() {
  581. if (!spellCheckManager) return
  582. editor.off('changeSession', onSessionChangeForSpellCheck)
  583. return editor.off(
  584. 'nativecontextmenu',
  585. spellCheckManager.onContextMenu
  586. )
  587. }
  588. const initTrackChanges = function() {
  589. trackChangesManager.rangesTracker = scope.sharejsDoc.ranges
  590. // Force onChangeSession in order to set up highlights etc.
  591. trackChangesManager.onChangeSession()
  592. if (!trackChangesManager) return
  593. editor.on('changeSelection', trackChangesManager.onChangeSelection)
  594. // Selection also moves with updates elsewhere in the document
  595. editor.on('change', trackChangesManager.onChangeSelection)
  596. editor.on('changeSession', trackChangesManager.onChangeSession)
  597. editor.on('cut', trackChangesManager.onCut)
  598. editor.on('paste', trackChangesManager.onPaste)
  599. editor.renderer.on('resize', trackChangesManager.onResize)
  600. }
  601. const tearDownTrackChanges = function() {
  602. if (!trackChangesManager) return
  603. this.trackChangesManager.tearDown()
  604. editor.off('changeSelection', trackChangesManager.onChangeSelection)
  605. editor.off('change', trackChangesManager.onChangeSelection)
  606. editor.off('changeSession', trackChangesManager.onChangeSession)
  607. editor.off('cut', trackChangesManager.onCut)
  608. editor.off('paste', trackChangesManager.onPaste)
  609. editor.renderer.off('resize', trackChangesManager.onResize)
  610. }
  611. const initUndo = function() {
  612. // Emulate onChangeSession event. Note: listening to changeSession
  613. // event is unnecessary since this method is called when we switch
  614. // sessions (via ShareJS changing) anyway
  615. undoManager.onChangeSession(editor.getSession())
  616. editor.on('change', undoManager.onChange)
  617. }
  618. const tearDownUndo = function() {
  619. editor.off('change', undoManager.onChange)
  620. }
  621. const onSessionChangeForCursorPosition = function(e) {
  622. if (e.oldSession != null) {
  623. e.oldSession.selection.off(
  624. 'changeCursor',
  625. cursorPositionManager.onCursorChange
  626. )
  627. }
  628. return e.session.selection.on(
  629. 'changeCursor',
  630. cursorPositionManager.onCursorChange
  631. )
  632. }
  633. const onUnloadForCursorPosition = () =>
  634. cursorPositionManager.onUnload(editor.getSession())
  635. const initCursorPosition = function() {
  636. editor.on('changeSession', onSessionChangeForCursorPosition)
  637. // Force initial setup
  638. onSessionChangeForCursorPosition({ session: editor.getSession() })
  639. return $(window).on('unload', onUnloadForCursorPosition)
  640. }
  641. const tearDownCursorPosition = function() {
  642. editor.off('changeSession', onSessionChangeForCursorPosition)
  643. return $(window).off('unload', onUnloadForCursorPosition)
  644. }
  645. initCursorPosition()
  646. // Trigger the event once *only* - this is called after Ace is connected
  647. // to the ShareJs instance but this event should only be triggered the
  648. // first time the editor is opened. Not every time the docs opened
  649. const triggerEditorInitEvent = _.once(() =>
  650. scope.$broadcast('editorInit')
  651. )
  652. var attachToAce = function(sharejs_doc) {
  653. let mode
  654. const lines = sharejs_doc.getSnapshot().split('\n')
  655. let session = editor.getSession()
  656. if (session != null) {
  657. session.destroy()
  658. }
  659. // see if we can lookup a suitable mode from ace
  660. // but fall back to text by default
  661. try {
  662. if (/\.(Rtex|bbl|tikz)$/i.test(scope.fileName)) {
  663. // recognise Rtex and bbl as latex
  664. mode = 'ace/mode/latex'
  665. } else if (/\.(sty|cls|clo)$/.test(scope.fileName)) {
  666. // recognise some common files as tex
  667. mode = 'ace/mode/tex'
  668. } else {
  669. ;({ mode } = ModeList.getModeForPath(scope.fileName))
  670. // we prefer plain_text mode over text mode because ace's
  671. // text mode is actually for code and has unwanted
  672. // indenting (see wrapMethod in ace edit_session.js)
  673. if (mode === 'ace/mode/text') {
  674. mode = 'ace/mode/plain_text'
  675. }
  676. }
  677. } catch (error) {
  678. mode = 'ace/mode/plain_text'
  679. }
  680. // create our new session
  681. session = new EditSession(lines, mode)
  682. session.setUseWrapMode(true)
  683. // use syntax validation only when explicitly set
  684. if (
  685. scope.syntaxValidation != null &&
  686. syntaxValidationEnabled &&
  687. !/\.bib$/.test(scope.fileName)
  688. ) {
  689. session.setOption('useWorker', scope.syntaxValidation)
  690. }
  691. // set to readonly until document change handlers are attached
  692. editor.setReadOnly(true)
  693. // now attach session to editor
  694. editor.setSession(session)
  695. const doc = session.getDocument()
  696. doc.on('change', onChange)
  697. editor.initing = true
  698. sharejs_doc.attachToAce(editor)
  699. editor.initing = false
  700. // now ready to edit document
  701. // respect the readOnly setting, normally false
  702. editor.setReadOnly(scope.readOnly)
  703. triggerEditorInitEvent()
  704. if (!scope.readOnly) {
  705. initSpellCheck()
  706. }
  707. initTrackChanges()
  708. initUndo()
  709. resetScrollMargins()
  710. // need to set annotations after attaching because attaching
  711. // deletes and then inserts document content
  712. session.setAnnotations(scope.annotations)
  713. session.on('changeScrollTop', eventTracking.editingSessionHeartbeat)
  714. angular
  715. .element($window)
  716. .on('click', eventTracking.editingSessionHeartbeat)
  717. scope.$on('$destroy', () =>
  718. angular
  719. .element($window)
  720. .off('click', eventTracking.editingSessionHeartbeat)
  721. )
  722. if (scope.eventsBridge != null) {
  723. session.on('changeScrollTop', onScroll)
  724. }
  725. $rootScope.hasLintingError = false
  726. session.on('changeAnnotation', function() {
  727. // Both linter errors and compile logs are set as error annotations,
  728. // however when the user types something, the compile logs are
  729. // replaced with linter errors. When we check for lint errors before
  730. // autocompile we are guaranteed to get linter errors
  731. const hasErrors =
  732. session
  733. .getAnnotations()
  734. .filter(annotation => annotation.type !== 'info').length > 0
  735. if ($rootScope.hasLintingError !== hasErrors) {
  736. return ($rootScope.hasLintingError = hasErrors)
  737. }
  738. })
  739. setTimeout(() =>
  740. // Let any listeners init themselves
  741. onScroll(editor.renderer.getScrollTop())
  742. )
  743. return editor.focus()
  744. }
  745. var detachFromAce = function(sharejs_doc) {
  746. tearDownSpellCheck()
  747. tearDownTrackChanges()
  748. tearDownUndo()
  749. sharejs_doc.detachFromAce()
  750. sharejs_doc.off('remoteop.recordRemote')
  751. const session = editor.getSession()
  752. session.off('changeScrollTop')
  753. const doc = session.getDocument()
  754. return doc.off('change', onChange)
  755. }
  756. if (scope.rendererData != null) {
  757. editor.renderer.on('changeCharacterSize', () => {
  758. scope.$apply(
  759. () => (scope.rendererData.lineHeight = editor.renderer.lineHeight)
  760. )
  761. })
  762. }
  763. scope.$watch('rendererData', function(rendererData) {
  764. if (rendererData != null) {
  765. return (rendererData.lineHeight = editor.renderer.lineHeight)
  766. }
  767. })
  768. scope.$on('$destroy', function() {
  769. if (scope.sharejsDoc != null) {
  770. scope.$broadcast('changeEditor')
  771. tearDownSpellCheck()
  772. tearDownCursorPosition()
  773. tearDownUndo()
  774. detachFromAce(scope.sharejsDoc)
  775. const session = editor.getSession()
  776. if (session != null) {
  777. session.destroy()
  778. }
  779. return scope.eventsBridge.emit(
  780. 'aceScrollbarVisibilityChanged',
  781. false,
  782. 0
  783. )
  784. }
  785. })
  786. return scope.$emit(`${scope.name}:inited`, editor)
  787. },
  788. template: `\
  789. <div class="ace-editor-wrapper">
  790. <div
  791. class="undo-conflict-warning alert alert-danger small"
  792. ng-show="undo.show_remote_warning"
  793. >
  794. <strong>Watch out!</strong>
  795. We had to undo some of your collaborators changes before we could undo yours.
  796. <a
  797. href="#"
  798. class="pull-right"
  799. ng-click="undo.show_remote_warning = false"
  800. >Dismiss</a>
  801. </div>
  802. <div class="ace-editor-body"></div>
  803. <spell-menu
  804. open="spellMenu.open"
  805. top="spellMenu.top"
  806. left="spellMenu.left"
  807. layout-from-bottom="spellMenu.layoutFromBottom"
  808. highlight="spellMenu.highlight"
  809. replace-word="replaceWord(highlight, suggestion)"
  810. learn-word="learnWord(highlight)"
  811. ></spell-menu>
  812. <div
  813. class="annotation-label"
  814. ng-show="annotationLabel.show"
  815. ng-style="{
  816. position: 'absolute',
  817. left: annotationLabel.left,
  818. right: annotationLabel.right,
  819. bottom: annotationLabel.bottom,
  820. top: annotationLabel.top,
  821. 'background-color': annotationLabel.backgroundColor
  822. }"
  823. >
  824. {{ annotationLabel.text }}
  825. </div>
  826. <a
  827. href
  828. class="highlights-before-label btn btn-info btn-xs"
  829. ng-show="updateLabels.highlightsBefore > 0"
  830. ng-click="gotoHighlightAbove()"
  831. >
  832. <i class="fa fa-fw fa-arrow-up"></i>
  833. {{ updateLabels.highlightsBefore }} more update{{ updateLabels.highlightsBefore > 1 && "" || "s" }} above
  834. </a>
  835. <a
  836. href
  837. class="highlights-after-label btn btn-info btn-xs"
  838. ng-show="updateLabels.highlightsAfter > 0"
  839. ng-click="gotoHighlightBelow()"
  840. >
  841. <i class="fa fa-fw fa-arrow-down"></i>
  842. {{ updateLabels.highlightsAfter }} more update{{ updateLabels.highlightsAfter > 1 && "" || "s" }} below
  843. </a>
  844. </div>\
  845. `
  846. }
  847. })
  848. function monkeyPatchSearch($rootScope, $compile) {
  849. const searchHtml = `\
  850. <div class="ace_search right">
  851. <a href type="button" action="hide" class="ace_searchbtn_close">
  852. <i class="fa fa-fw fa-times"></i>
  853. </a>
  854. <div class="ace_search_form">
  855. <input class="ace_search_field form-control input-sm" placeholder="Search for" spellcheck="false"></input>
  856. <div class="btn-group">
  857. <button type="button" action="findNext" class="ace_searchbtn next btn btn-default btn-sm">
  858. <i class="fa fa-chevron-down fa-fw"></i>
  859. </button>
  860. <button type="button" action="findPrev" class="ace_searchbtn prev btn btn-default btn-sm">
  861. <i class="fa fa-chevron-up fa-fw"></i>
  862. </button>
  863. </div>
  864. </div>
  865. <div class="ace_replace_form">
  866. <input class="ace_search_field form-control input-sm" placeholder="Replace with" spellcheck="false"></input>
  867. <div class="btn-group">
  868. <button type="button" action="replaceAndFindNext" class="ace_replacebtn btn btn-default btn-sm">Replace</button>
  869. <button type="button" action="replaceAll" class="ace_replacebtn btn btn-default btn-sm">All</button>
  870. </div>
  871. </div>
  872. <div class="ace_search_options">
  873. <div class="btn-group">
  874. <button action="toggleRegexpMode" class="btn btn-default btn-sm" tooltip-placement="bottom" tooltip-append-to-body="true" tooltip="RegExp Search">.*</button>
  875. <button action="toggleCaseSensitive" class="btn btn-default btn-sm" tooltip-placement="bottom" tooltip-append-to-body="true" tooltip="CaseSensitive Search">Aa</button>
  876. <button action="toggleWholeWords" class="btn btn-default btn-sm" tooltip-placement="bottom" tooltip-append-to-body="true" tooltip="Whole Word Search">"..."</button>
  877. <button action="searchInSelection" class="btn btn-default btn-sm" tooltip-placement="bottom" tooltip-append-to-body="true" tooltip="Search Within Selection"><i class="fa fa-align-left"></i></button>
  878. </div>
  879. <span class="ace_search_counter"></span>
  880. </div>
  881. <div action="toggleReplace" class="hidden"></div>
  882. </div>\
  883. `
  884. // Remove Ace CSS
  885. $('#ace_searchbox').remove()
  886. const SB = SearchBox.SearchBox
  887. const { $init } = SB.prototype
  888. SB.prototype.$init = function() {
  889. this.element = $compile(searchHtml)($rootScope.$new())[0]
  890. return $init.apply(this)
  891. }
  892. }
  893. })