aceEditor.js 33 KB

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