indent.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { EditorSelection } from '@codemirror/state'
  2. import { getIndentUnit, indentString, indentUnit } from '@codemirror/language'
  3. import { EditorView } from '@codemirror/view'
  4. export const indentMore = (view: EditorView) => {
  5. view.dispatch(
  6. view.state.changeByRange(range => {
  7. const doc = view.state.doc
  8. const changes = []
  9. if (range.empty) {
  10. // insert space(s) at the cursor
  11. const line = doc.lineAt(range.from)
  12. const unit = getIndentUnit(view.state)
  13. const offset = range.from - line.from
  14. const cols = unit - (offset % unit)
  15. const insert = indentString(view.state, cols)
  16. changes.push({ from: range.from, insert })
  17. } else {
  18. // indent selected lines
  19. const insert = view.state.facet(indentUnit)
  20. let previousLineNumber = -1
  21. for (let pos = range.from; pos <= range.to; pos++) {
  22. const line = doc.lineAt(pos)
  23. if (previousLineNumber === line.number) {
  24. continue
  25. }
  26. changes.push({ from: line.from, insert })
  27. previousLineNumber = line.number
  28. }
  29. }
  30. const changeSet = view.state.changes(changes)
  31. return {
  32. changes: changeSet,
  33. range: EditorSelection.range(
  34. changeSet.mapPos(range.anchor, 1),
  35. changeSet.mapPos(range.head, 1)
  36. ),
  37. }
  38. })
  39. )
  40. return true
  41. }