utils_line.js (2573B)
1 import { indexOf } from "../util/misc.js" 2 3 // Find the line object corresponding to the given line number. 4 export function getLine(doc, n) { 5 n -= doc.first 6 if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.") 7 let chunk = doc 8 while (!chunk.lines) { 9 for (let i = 0;; ++i) { 10 let child = chunk.children[i], sz = child.chunkSize() 11 if (n < sz) { chunk = child; break } 12 n -= sz 13 } 14 } 15 return chunk.lines[n] 16 } 17 18 // Get the part of a document between two positions, as an array of 19 // strings. 20 export function getBetween(doc, start, end) { 21 let out = [], n = start.line 22 doc.iter(start.line, end.line + 1, line => { 23 let text = line.text 24 if (n == end.line) text = text.slice(0, end.ch) 25 if (n == start.line) text = text.slice(start.ch) 26 out.push(text) 27 ++n 28 }) 29 return out 30 } 31 // Get the lines between from and to, as array of strings. 32 export function getLines(doc, from, to) { 33 let out = [] 34 doc.iter(from, to, line => { out.push(line.text) }) // iter aborts when callback returns truthy value 35 return out 36 } 37 38 // Update the height of a line, propagating the height change 39 // upwards to parent nodes. 40 export function updateLineHeight(line, height) { 41 let diff = height - line.height 42 if (diff) for (let n = line; n; n = n.parent) n.height += diff 43 } 44 45 // Given a line object, find its line number by walking up through 46 // its parent links. 47 export function lineNo(line) { 48 if (line.parent == null) return null 49 let cur = line.parent, no = indexOf(cur.lines, line) 50 for (let chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { 51 for (let i = 0;; ++i) { 52 if (chunk.children[i] == cur) break 53 no += chunk.children[i].chunkSize() 54 } 55 } 56 return no + cur.first 57 } 58 59 // Find the line at the given vertical position, using the height 60 // information in the document tree. 61 export function lineAtHeight(chunk, h) { 62 let n = chunk.first 63 outer: do { 64 for (let i = 0; i < chunk.children.length; ++i) { 65 let child = chunk.children[i], ch = child.height 66 if (h < ch) { chunk = child; continue outer } 67 h -= ch 68 n += child.chunkSize() 69 } 70 return n 71 } while (!chunk.lines) 72 let i = 0 73 for (; i < chunk.lines.length; ++i) { 74 let line = chunk.lines[i], lh = line.height 75 if (h < lh) break 76 h -= lh 77 } 78 return n + i 79 } 80 81 export function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} 82 83 export function lineNumberFor(options, i) { 84 return String(options.lineNumberFormatter(i + options.firstLineNumber)) 85 }