aceEditor.js 33 KB

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