aceEditor.js 31 KB

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