aceEditor.js 33 KB

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