ranges.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. import { EditorView } from '@codemirror/view'
  2. import { EditorSelection, EditorState, SelectionRange } from '@codemirror/state'
  3. import {
  4. ensureSyntaxTree,
  5. foldedRanges,
  6. foldEffect,
  7. syntaxTree,
  8. } from '@codemirror/language'
  9. import { SyntaxNode } from '@lezer/common'
  10. import {
  11. ancestorOfNodeWithType,
  12. isUnknownCommandWithName,
  13. } from '../utils/tree-query'
  14. import { lastAncestorAtEndPosition } from '../utils/tree-operations/ancestors'
  15. export const wrapRanges =
  16. (
  17. prefix: string,
  18. suffix: string,
  19. wrapWholeLine = false,
  20. selection?: (range: SelectionRange) => SelectionRange
  21. ) =>
  22. (view: EditorView): boolean => {
  23. if (view.state.readOnly) {
  24. return false
  25. }
  26. view.dispatch(
  27. view.state.changeByRange(range => {
  28. const insert = { prefix, suffix }
  29. if (wrapWholeLine) {
  30. const line = view.state.doc.lineAt(range.anchor)
  31. if (range.empty) {
  32. // expand range to cover the whole line
  33. range = EditorSelection.range(line.from, line.to)
  34. }
  35. // add a newline at the start if needed
  36. if (range.from !== line.from) {
  37. insert.prefix = `\n${prefix}`
  38. }
  39. // add a newline at the end if needed
  40. if (range.to !== line.to) {
  41. insert.suffix = `${suffix}\n`
  42. }
  43. }
  44. const content = view.state.sliceDoc(range.from, range.to)
  45. // map through the prefix only
  46. const changedRange = range.map(
  47. view.state.changes([
  48. { from: range.from, insert: `${insert.prefix}` },
  49. ]),
  50. 1
  51. )
  52. return {
  53. range: selection ? selection(changedRange) : changedRange,
  54. // create a single change, including the content
  55. changes: [
  56. {
  57. from: range.from,
  58. to: range.to,
  59. insert: `${insert.prefix}${content}${insert.suffix}`,
  60. },
  61. ],
  62. }
  63. }),
  64. { scrollIntoView: true }
  65. )
  66. return true
  67. }
  68. export const changeCase =
  69. (upper = true) =>
  70. (view: EditorView) => {
  71. if (view.state.readOnly) {
  72. return false
  73. }
  74. view.dispatch(
  75. view.state.changeByRange(range => {
  76. // ignore empty ranges
  77. if (range.empty) {
  78. return { range }
  79. }
  80. const text = view.state.doc.sliceString(range.from, range.to)
  81. return {
  82. range,
  83. changes: [
  84. {
  85. from: range.from,
  86. to: range.to,
  87. insert: upper ? text.toUpperCase() : text.toLowerCase(),
  88. },
  89. ],
  90. }
  91. })
  92. )
  93. return true
  94. }
  95. export const duplicateSelection = (view: EditorView) => {
  96. if (view.state.readOnly) {
  97. return false
  98. }
  99. const foldedRangesInDocument = foldedRanges(view.state)
  100. view.dispatch(
  101. view.state.changeByRange(range => {
  102. const folds: { offset: number; base: number; length: number }[] = []
  103. if (range.empty) {
  104. const line = view.state.doc.lineAt(range.from)
  105. let lineStart = line.from
  106. let lineEnd = line.to
  107. // Calculate line start/end including folded ranges
  108. //
  109. // Note that at each iteration of the while loop, new folded ranges
  110. // can be included. This happens when there are multiple folded ranges
  111. // on a single editor line (but spanning multiple actual lines)
  112. //
  113. // For example, the following document:
  114. // 1: \begin{document}
  115. // 2: test
  116. // 3: \end{document}\begin{document}
  117. // 4: test
  118. // 5: \end{document}
  119. //
  120. // Can be folded to:
  121. // \begin{document}<...>\end{document}\begin{document}<...>\end{document}
  122. //
  123. // In this case, the first iterations of the while loop below will only
  124. // include lines 3-5, since the overlapping folded range for line 5
  125. // is only the fold on lines 3-5. Hence in the while loop, we expand the
  126. // selection until we include all the ranges.
  127. let changed
  128. do {
  129. changed = false
  130. foldedRangesInDocument.between(lineStart, lineEnd, (from, to) => {
  131. const newLineStart = Math.min(
  132. view.state.doc.lineAt(from).from,
  133. lineStart
  134. )
  135. const newLineEnd = Math.max(view.state.doc.lineAt(to).to, lineEnd)
  136. if (newLineStart !== lineStart || newLineEnd !== lineEnd) {
  137. changed = true
  138. lineStart = newLineStart
  139. lineEnd = newLineEnd
  140. }
  141. })
  142. } while (changed)
  143. // Collect information needed to fold duplicated lines
  144. foldedRangesInDocument.between(lineStart, lineEnd, (from, to) => {
  145. folds.push({
  146. offset: from - lineStart,
  147. base: lineEnd + view.state.lineBreak.length,
  148. length: to - from,
  149. })
  150. })
  151. // Duplicate the selected lines downwards
  152. return {
  153. range,
  154. changes: [
  155. {
  156. from: lineEnd,
  157. insert:
  158. view.state.lineBreak + view.state.doc.slice(lineStart, lineEnd),
  159. },
  160. ],
  161. // Add a fold effect for each fold in the original line
  162. effects: folds.map(fold =>
  163. foldEffect.of({
  164. from: fold.base + fold.offset,
  165. to: fold.base + fold.offset + fold.length,
  166. })
  167. ),
  168. }
  169. } else {
  170. // Duplicate selected text at head of selection
  171. let newSelectionRange = range
  172. if (range.head > range.anchor) {
  173. // Duplicating to the right, so we need to update the selected range
  174. newSelectionRange = EditorSelection.range(
  175. range.head,
  176. range.head + (range.to - range.from)
  177. )
  178. }
  179. return {
  180. // The new range is the duplicated section, placed at the head of the
  181. // original selection
  182. range: newSelectionRange,
  183. changes: [
  184. {
  185. from: range.head,
  186. insert: view.state.doc.slice(range.from, range.to),
  187. },
  188. ],
  189. }
  190. }
  191. })
  192. )
  193. return true
  194. }
  195. function getParentNode(
  196. position: number | SyntaxNode,
  197. state: EditorState,
  198. assoc: 0 | 1 | -1 = 1
  199. ): SyntaxNode | undefined {
  200. const tree = ensureSyntaxTree(state, 1000)
  201. let node: SyntaxNode | undefined | null = null
  202. if (typeof position === 'number') {
  203. node = tree?.resolveInner(position, assoc)?.parent
  204. const ancestorAtEndPos = lastAncestorAtEndPosition(node, position)
  205. if (ancestorAtEndPos?.parent) {
  206. node = ancestorAtEndPos.parent
  207. }
  208. } else {
  209. node = position?.parent
  210. }
  211. while (
  212. ['LongArg', 'TextArgument', 'OpenBrace', 'CloseBrace'].includes(
  213. node?.type.name || ''
  214. )
  215. ) {
  216. node = node!.parent
  217. }
  218. return node || undefined
  219. }
  220. function wrapRangeInCommand(
  221. state: EditorState,
  222. range: SelectionRange,
  223. command: string
  224. ) {
  225. const content = state.sliceDoc(range.from, range.to)
  226. const changes = state.changes([
  227. {
  228. from: range.from,
  229. to: range.to,
  230. insert: `${command}{${content}}`,
  231. },
  232. ])
  233. return {
  234. changes,
  235. range: moveRange(
  236. range,
  237. range.from + command.length + 1,
  238. range.from + command.length + content.length + 1
  239. ),
  240. }
  241. }
  242. function moveRange(range: SelectionRange, newFrom: number, newTo: number) {
  243. const forwards = range.from === range.anchor
  244. return forwards
  245. ? EditorSelection.range(newFrom, newTo)
  246. : EditorSelection.range(newTo, newFrom)
  247. }
  248. function validateReplacement(expected: string, actual: string) {
  249. if (expected !== actual) {
  250. throw new Error(
  251. `Replacement in toggleRange failed validation. Expected ${expected} got ${actual}`
  252. )
  253. }
  254. }
  255. function getWrappingAncestor(
  256. node: SyntaxNode,
  257. command: string,
  258. state: EditorState
  259. ): SyntaxNode | null {
  260. for (
  261. let ancestor: SyntaxNode | null = node;
  262. ancestor;
  263. ancestor = ancestor.parent
  264. ) {
  265. if (isUnknownCommandWithName(ancestor, command, state)) {
  266. return ancestor
  267. }
  268. if (ancestor.type.is('UnknownCommand')) {
  269. // We could multiple levels deep in bold/non-bold. So bail out in this case
  270. return null
  271. }
  272. }
  273. return null
  274. }
  275. function adjustRangeIfNeeded(
  276. command: string,
  277. range: SelectionRange,
  278. state: EditorState
  279. ) {
  280. // Try to adjust the selection, if it is either
  281. // 1. \textbf<{test>}
  282. // 2. \textbf{<test}>
  283. // 3. \textbf<{test}>
  284. // 4. <\textbf{test}>
  285. // 4. \textbf<>{test}
  286. const tree = syntaxTree(state)
  287. if (tree.length < range.to) {
  288. return range
  289. }
  290. const nodeLeft = tree.resolveInner(range.from, 1)
  291. const nodeRight = tree.resolveInner(range.to, -1)
  292. const parentLeft = getWrappingAncestor(nodeLeft, command, state)
  293. const parentRight = getWrappingAncestor(nodeRight, command, state)
  294. const parent = getParentNode(nodeLeft, state)
  295. if (parent?.type.is('UnknownCommand') && spansWholeArgument(parent, range)) {
  296. return bubbleUpRange(
  297. command,
  298. ancestorOfNodeWithType(nodeLeft, 'UnknownCommand'),
  299. range,
  300. state
  301. )
  302. }
  303. if (!parentLeft) {
  304. // We're not trying to unbold, so don't bother adjusting range
  305. return bubbleUpRange(
  306. command,
  307. ancestorOfNodeWithType(nodeLeft, 'UnknownCommand'),
  308. range,
  309. state
  310. )
  311. }
  312. if (nodeLeft.type.is('CtrlSeq') && range.from === range.to) {
  313. const command = nodeLeft.parent?.parent
  314. if (!command) {
  315. return range
  316. }
  317. return EditorSelection.cursor(command.from)
  318. }
  319. let { from, to } = range
  320. if (nodeLeft.type.is('CtrlSeq')) {
  321. from = nodeLeft.to + 1
  322. }
  323. if (nodeLeft.type.is('OpenBrace')) {
  324. from = nodeLeft.to
  325. }
  326. // We know that parentLeft is the UnknownCommand, so now we check if we're
  327. // to the right of the closing brace. (parent is TextArgument, grandparent is
  328. // UnknownCommand)
  329. if (parentLeft === parentRight && nodeRight.type.is('CloseBrace')) {
  330. to = nodeRight.from
  331. }
  332. return bubbleUpRange(command, parentLeft, moveRange(range, from, to), state)
  333. }
  334. function spansWholeArgument(
  335. commandNode: SyntaxNode | null,
  336. range: SelectionRange
  337. ): boolean {
  338. const argument = commandNode?.getChild('TextArgument')?.getChild('LongArg')
  339. const res = Boolean(
  340. argument && argument.from === range.from && argument.to === range.to
  341. )
  342. return res
  343. }
  344. function bubbleUpRange(
  345. command: string,
  346. node: SyntaxNode | null,
  347. range: SelectionRange,
  348. state: EditorState
  349. ) {
  350. let currentRange = range
  351. for (
  352. let ancestorCommand: SyntaxNode | null = ancestorOfNodeWithType(
  353. node,
  354. 'UnknownCommand'
  355. );
  356. spansWholeArgument(ancestorCommand, currentRange);
  357. ancestorCommand = ancestorOfNodeWithType(
  358. ancestorCommand.parent,
  359. 'UnknownCommand'
  360. )
  361. ) {
  362. if (!ancestorCommand) {
  363. break
  364. }
  365. currentRange = moveRange(
  366. currentRange,
  367. ancestorCommand.from,
  368. ancestorCommand.to
  369. )
  370. if (isUnknownCommandWithName(ancestorCommand, command, state)) {
  371. const argumentNode = ancestorCommand
  372. .getChild('TextArgument')
  373. ?.getChild('LongArg')
  374. if (!argumentNode) {
  375. return range
  376. }
  377. return moveRange(range, argumentNode.from, argumentNode.to)
  378. }
  379. }
  380. return range
  381. }
  382. export function toggleRanges(command: string) {
  383. /* There are a number of situations we need to handle in this function.
  384. * In the following examples, the selection range is marked within <>
  385. * 1. If the parent node at start and end of selection is different -> do
  386. * nothing & show error. Case 8 is an exception to this.
  387. * -> For good and bad, this disallows \textbf{this <is} weird
  388. * \textit{to> do}
  389. * 2. If selection contains a BlankLine (i.e. two newlines in a row) -> do
  390. * nothing & show error
  391. * -> \textbf doesn't allow paragraph breaks).
  392. * 3. If the selection is not within a \textbf -> wrap it in a \textbf
  393. * 4. If selection is at the beginning of a \textbf -> shrink the \textbf
  394. * command
  395. * -> e.g. \textbf{<this is> a test} → <this is>\textbf{ a test}
  396. * 5. Similarly for selection at end of \textbf command
  397. * 6. If selection is in the middle of a \textbf command -> split the command
  398. * into two
  399. * -> e.g. \textbf{this <is a> test} → \textbf{this }<is a>\textbf{ test}
  400. * 7. If the selection is a whole \textbf command → remove the wrapping
  401. * command.
  402. * 8. If the selection spans two \textbf's with the same parent then join the
  403. * two
  404. * -> e.g. \textbf{this <is} a \textbf{te>st} → \textbf{this <is a te>st}
  405. * 9. If the selection spans the end of a \textbf, into the parent of the
  406. * command, then extend the \textbf.
  407. * -> e.g. \textbf{this <is} a test> → \textbf{this <is a test>}
  408. * 10. Similarly for selections spanning the beginning of the selection
  409. */
  410. return (view: EditorView): boolean => {
  411. if (view.state.readOnly) {
  412. return false
  413. }
  414. view.dispatch(
  415. view.state.changeByRange(initialRange => {
  416. const range = adjustRangeIfNeeded(command, initialRange, view.state)
  417. const content = view.state.sliceDoc(range.from, range.to)
  418. const ancestorAtStartOfRange = getParentNode(
  419. range.from,
  420. view.state,
  421. range.from === 0 ? 1 : -1
  422. )
  423. const ancestorAtEndOfRange = range.empty
  424. ? ancestorAtStartOfRange
  425. : getParentNode(
  426. range.to,
  427. view.state,
  428. range.to === view.state.doc.length ? -1 : 1
  429. )
  430. if (ancestorAtStartOfRange !== ancestorAtEndOfRange) {
  431. // But handle the exception of case 8
  432. const ancestorAtStartIsWrappingCommand =
  433. ancestorAtStartOfRange &&
  434. isUnknownCommandWithName(
  435. ancestorAtStartOfRange,
  436. command,
  437. view.state
  438. )
  439. const ancestorAtEndIsWrappingCommand =
  440. ancestorAtEndOfRange &&
  441. isUnknownCommandWithName(ancestorAtEndOfRange, command, view.state)
  442. if (
  443. ancestorAtStartIsWrappingCommand &&
  444. ancestorAtEndIsWrappingCommand &&
  445. ancestorAtStartOfRange?.parent?.parent &&
  446. ancestorAtEndOfRange?.parent?.parent
  447. ) {
  448. // Test for case 8
  449. const nextAncestorAtStartOfRange =
  450. ancestorAtStartOfRange.parent.parent
  451. const nextAncestorAtEndOfRange = ancestorAtEndOfRange.parent.parent
  452. if (nextAncestorAtStartOfRange === nextAncestorAtEndOfRange) {
  453. // Join the two ranges
  454. const textBetweenRanges = view.state.sliceDoc(
  455. ancestorAtStartOfRange.to,
  456. ancestorAtEndOfRange.from
  457. )
  458. const ancestorStartArgumentNode =
  459. ancestorAtStartOfRange.lastChild?.getChild('LongArg')
  460. const ancestorEndArgumentNode =
  461. ancestorAtEndOfRange.lastChild?.getChild('LongArg')
  462. if (!ancestorStartArgumentNode || !ancestorEndArgumentNode) {
  463. throw new Error("Can't find argument node")
  464. }
  465. const actualContent = view.state.sliceDoc(
  466. ancestorAtStartOfRange.from,
  467. ancestorAtEndOfRange.to
  468. )
  469. const firstCommandArgument = view.state.sliceDoc(
  470. ancestorStartArgumentNode.from,
  471. ancestorStartArgumentNode.to
  472. )
  473. const secondCommandArgument = view.state.sliceDoc(
  474. ancestorEndArgumentNode.from,
  475. ancestorEndArgumentNode.to
  476. )
  477. validateReplacement(
  478. `${command}{${firstCommandArgument}}${textBetweenRanges}${command}{${secondCommandArgument}}`,
  479. actualContent
  480. )
  481. const changes = view.state.changes([
  482. {
  483. from: ancestorAtStartOfRange.from,
  484. to: ancestorAtEndOfRange.to,
  485. insert: `${command}{${firstCommandArgument}${textBetweenRanges}${secondCommandArgument}}`,
  486. },
  487. ])
  488. return {
  489. changes,
  490. range: moveRange(
  491. range,
  492. range.from,
  493. range.to - command.length - 1 - 1
  494. ),
  495. }
  496. }
  497. }
  498. if (
  499. ancestorAtEndIsWrappingCommand &&
  500. ancestorAtEndOfRange.parent?.parent === ancestorAtStartOfRange
  501. ) {
  502. // Extend to the left. Case 10
  503. const contentUpToCommand = view.state.sliceDoc(
  504. range.from,
  505. ancestorAtEndOfRange.from
  506. )
  507. const ancestorEndArgumentNode =
  508. ancestorAtEndOfRange.lastChild?.getChild('LongArg')
  509. if (!ancestorEndArgumentNode) {
  510. throw new Error("Can't find argument node")
  511. }
  512. const commandContent = view.state.sliceDoc(
  513. ancestorEndArgumentNode.from,
  514. ancestorEndArgumentNode.to
  515. )
  516. const actualContent = view.state.sliceDoc(
  517. range.from,
  518. ancestorAtEndOfRange.to
  519. )
  520. validateReplacement(
  521. `${contentUpToCommand}${command}{${commandContent}}`,
  522. actualContent
  523. )
  524. const changes = view.state.changes([
  525. {
  526. from: range.from,
  527. to: ancestorAtEndOfRange.to,
  528. insert: `${command}{${contentUpToCommand}${commandContent}}`,
  529. },
  530. ])
  531. return {
  532. changes,
  533. range: moveRange(
  534. range,
  535. range.from + command.length + 1,
  536. range.to
  537. ),
  538. }
  539. }
  540. if (
  541. ancestorAtStartIsWrappingCommand &&
  542. ancestorAtStartOfRange.parent?.parent === ancestorAtEndOfRange
  543. ) {
  544. // Extend to the right. Case 9
  545. const contentAfterCommand = view.state.sliceDoc(
  546. ancestorAtStartOfRange.to,
  547. range.to
  548. )
  549. const ancestorStartArgumentNode =
  550. ancestorAtStartOfRange.lastChild?.getChild('LongArg')
  551. if (!ancestorStartArgumentNode) {
  552. throw new Error("Can't find argument node")
  553. }
  554. const commandContent = view.state.sliceDoc(
  555. ancestorStartArgumentNode.from,
  556. ancestorStartArgumentNode.to
  557. )
  558. const actualContent = view.state.sliceDoc(
  559. ancestorAtStartOfRange.from,
  560. range.to
  561. )
  562. validateReplacement(
  563. `${command}{${commandContent}}${contentAfterCommand}`,
  564. actualContent
  565. )
  566. const changes = view.state.changes([
  567. {
  568. from: ancestorAtStartOfRange.from,
  569. to: range.to,
  570. insert: `${command}{${commandContent}${contentAfterCommand}}`,
  571. },
  572. ])
  573. return {
  574. changes,
  575. range: moveRange(range, range.from, range.to - 1),
  576. }
  577. }
  578. // Bail out in case 1
  579. // TODO: signal error to the user
  580. return { range }
  581. }
  582. const ancestor = ancestorAtStartOfRange
  583. // Bail out in case 2
  584. if (content.includes('\n\n')) {
  585. // TODO: signal error to the user
  586. return { range }
  587. }
  588. const isCursorBeforeAncestor =
  589. range.empty &&
  590. ancestor &&
  591. range.from === ancestor.from &&
  592. isUnknownCommandWithName(ancestor, command, view.state)
  593. // If we can't find an ancestor node, or if the parent is not an exsting
  594. // \textbf, then we just wrap it in a range. Case 3.
  595. if (
  596. isCursorBeforeAncestor ||
  597. !ancestor ||
  598. !isUnknownCommandWithName(ancestor, command, view.state)
  599. ) {
  600. return wrapRangeInCommand(view.state, range, command)
  601. }
  602. const argumentNode = ancestor.lastChild?.getChild('LongArg')
  603. if (!argumentNode) {
  604. throw new Error("Can't find argument node")
  605. }
  606. // We should trim from the beginning. Case 4
  607. if (range.from === argumentNode.from && range.to !== argumentNode.to) {
  608. const textAfterSelection = view.state.sliceDoc(
  609. range.to,
  610. argumentNode.to
  611. )
  612. const wholeCommand = view.state.sliceDoc(ancestor.from, ancestor.to)
  613. validateReplacement(
  614. `${command}{${content}${textAfterSelection}}`,
  615. wholeCommand
  616. )
  617. const changes = view.state.changes([
  618. {
  619. from: ancestor.from,
  620. to: ancestor.to,
  621. insert: `${content}${command}{${textAfterSelection}}`,
  622. },
  623. ])
  624. return {
  625. range: moveRange(
  626. range,
  627. range.from - command.length - 1,
  628. range.to - command.length - 1
  629. ),
  630. changes,
  631. }
  632. }
  633. // We should trim from the end. Case 5
  634. if (range.to === argumentNode.to && range.from !== argumentNode.from) {
  635. const textBeforeSelection = view.state.sliceDoc(
  636. ancestor.from,
  637. range.from
  638. )
  639. const wholeCommand = view.state.sliceDoc(ancestor.from, ancestor.to)
  640. validateReplacement(`${textBeforeSelection}${content}}`, wholeCommand)
  641. const changes = view.state.changes([
  642. {
  643. from: ancestor.from,
  644. to: ancestor.to,
  645. insert: `${textBeforeSelection}}${content}`,
  646. },
  647. ])
  648. // We should shift selection forward by the } we insert
  649. return {
  650. range: moveRange(range, range.from + 1, range.to + 1),
  651. changes,
  652. }
  653. }
  654. // We should split the command in two. Case 6
  655. if (range.from !== argumentNode.from && range.to !== argumentNode.to) {
  656. const textBeforeSelection = view.state.sliceDoc(
  657. ancestor.from,
  658. range.from
  659. )
  660. const textAfterSelection = view.state.sliceDoc(range.to, ancestor.to)
  661. const wholeCommand = view.state.sliceDoc(ancestor.from, ancestor.to)
  662. validateReplacement(
  663. `${textBeforeSelection}${content}${textAfterSelection}`,
  664. wholeCommand
  665. )
  666. const changes = view.state.changes([
  667. {
  668. from: ancestor.from,
  669. to: ancestor.to,
  670. insert: `${textBeforeSelection}}${content}${command}{${textAfterSelection}`,
  671. },
  672. ])
  673. return {
  674. range: moveRange(range, range.from + 1, range.to + 1),
  675. changes,
  676. }
  677. }
  678. // Remove the wrapping command. Case 7
  679. if (spansWholeArgument(ancestor, range)) {
  680. const argumentContent = view.state.sliceDoc(
  681. argumentNode.from,
  682. argumentNode.to
  683. )
  684. const wholeCommand = view.state.sliceDoc(ancestor.from, ancestor.to)
  685. validateReplacement(`${command}{${content}}`, wholeCommand)
  686. const changes = view.state.changes([
  687. { from: ancestor.from, to: ancestor.to, insert: argumentContent },
  688. ])
  689. return {
  690. range: moveRange(
  691. range,
  692. range.from - command.length - 1,
  693. range.to - command.length - 1
  694. ),
  695. changes,
  696. }
  697. }
  698. // Shouldn't happen, but default to just wrapping the content
  699. return wrapRangeInCommand(view.state, range, command)
  700. }),
  701. { scrollIntoView: true }
  702. )
  703. return true
  704. }
  705. }