openrat-cms

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

pos.js (1528B)


      1 import { getLine } from "./utils_line.js"
      2 
      3 // A Pos instance represents a position within the text.
      4 export function Pos(line, ch, sticky = null) {
      5   if (!(this instanceof Pos)) return new Pos(line, ch, sticky)
      6   this.line = line
      7   this.ch = ch
      8   this.sticky = sticky
      9 }
     10 
     11 // Compare two positions, return 0 if they are the same, a negative
     12 // number when a is less, and a positive number otherwise.
     13 export function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
     14 
     15 export function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
     16 
     17 export function copyPos(x) {return Pos(x.line, x.ch)}
     18 export function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
     19 export function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
     20 
     21 // Most of the external API clips given positions to make sure they
     22 // actually exist within the document.
     23 export function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
     24 export function clipPos(doc, pos) {
     25   if (pos.line < doc.first) return Pos(doc.first, 0)
     26   let last = doc.first + doc.size - 1
     27   if (pos.line > last) return Pos(last, getLine(doc, last).text.length)
     28   return clipToLen(pos, getLine(doc, pos.line).text.length)
     29 }
     30 function clipToLen(pos, linelen) {
     31   let ch = pos.ch
     32   if (ch == null || ch > linelen) return Pos(pos.line, linelen)
     33   else if (ch < 0) return Pos(pos.line, 0)
     34   else return pos
     35 }
     36 export function clipPosArray(doc, array) {
     37   let out = []
     38   for (let i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i])
     39   return out
     40 }