indent.ts 1.4 KB

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