aceEditor.js 31 KB

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