ranges.ts 23 KB

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