position.ts 465 B

1234567891011121314151617181920212223
  1. import { Text } from '@codemirror/state'
  2. export const findValidPosition = (
  3. doc: Text,
  4. lineNumber: number, // 1-indexed
  5. columnNumber = 0 // 0-indexed
  6. ): number => {
  7. if (lineNumber < 1) {
  8. return 0
  9. }
  10. const lines = doc.lines
  11. if (lineNumber > lines) {
  12. // end of the doc
  13. return doc.length
  14. }
  15. const line = doc.line(lineNumber)
  16. // requested line and column, or the end of the line
  17. return Math.min(line.from + columnNumber, line.to)
  18. }