prepare-lines.ts 995 B

123456789101112131415161718192021222324252627282930313233
  1. /**
  2. * Adapted from CodeMirror 6 (@codemirror/autocomplete), licensed under the MIT license:
  3. * https://github.com/codemirror/autocomplete/blob/08f63add9f470a032d3802a4599caa86c75de5cb/src/snippet.ts#L29-L45
  4. */
  5. import { indentUnit } from '@codemirror/language'
  6. import { EditorState } from '@codemirror/state'
  7. // apply correct indentation to passed lines
  8. export function prepareLines(
  9. lines: (string | null)[],
  10. state: EditorState,
  11. pos: number
  12. ) {
  13. const text = []
  14. const lineStart = [pos]
  15. const lineObj = state.doc.lineAt(pos)
  16. const baseIndent = /^\s*/.exec(lineObj.text)![0]
  17. for (let line of lines) {
  18. if (line === null) continue
  19. if (text.length) {
  20. let indent = baseIndent
  21. const tabs = /^\t*/.exec(line)![0].length
  22. for (let i = 0; i < tabs; i++) indent += state.facet(indentUnit)
  23. lineStart.push(pos + indent.length - tabs)
  24. line = indent + line.slice(tabs)
  25. }
  26. text.push(line)
  27. pos += line.length + 1
  28. }
  29. return text.join('\n')
  30. }