cursor.ts 975 B

123456789101112131415161718192021222324252627
  1. import { EditorView } from '@codemirror/view'
  2. import { EditorSelection } from '@codemirror/state'
  3. export const cloneSelectionVertically =
  4. (forward: boolean, cumulative: boolean) => (view: EditorView) => {
  5. const { main, ranges, mainIndex } = view.state.selection
  6. const { anchor, head, goalColumn } = main
  7. const start = EditorSelection.range(anchor, head, goalColumn)
  8. const nextRange = view.moveVertically(start, forward)
  9. let filteredRanges = [...ranges]
  10. if (!cumulative && filteredRanges.length > 1) {
  11. // remove the current main range
  12. filteredRanges.splice(mainIndex, 1)
  13. }
  14. // prevent duplication when going in the opposite direction
  15. filteredRanges = filteredRanges.filter(
  16. item => item.from !== nextRange.from && item.to !== nextRange.to
  17. )
  18. const selection = EditorSelection.create(
  19. filteredRanges.concat(nextRange),
  20. filteredRanges.length
  21. )
  22. view.dispatch({ selection })
  23. return true
  24. }