Scoop API

scoop:scoop.readline:0.1.0

src/render/decoration.scoop

Selected production source · src/render/decoration.scoop

1package scoop.readline
3import scoop.charset.graphemes
5internal struct StyledGrapheme(val plain: String, val decoration: String)
7// Only SGR styling is invisible. User input controls remain visible text.
8private fun decorationEnd(text: String, start: Long): Long {
9 if (start + 2L >= text.charLength || text.getCharAt(start) != '\u001b' || text.getCharAt(start + 1L) != '[') return start
10 var index = start + 2L
11 while (index < text.charLength) {
12 val character = text.getCharAt(index)
13 if (character == 'm') return index + 1L
14 if ((character < '0' || character > '9') && character != ';' && character != ':') return start
15 index += 1L
16 }
17 return start
20internal fun stripDecoration(text: String): String {
21 val result = StringBuilder()
22 var index = 0L
23 while (index < text.charLength) {
24 val end = decorationEnd(text, index)
25 if (end > index) index = end
26 else { result.append(text.getCharAt(index)); index += 1L }
27 }
28 return result.toString()
31internal fun styledGraphemes(plain: String, styled: String): Array<StyledGrapheme> {
32 val result = ArrayList<StyledGrapheme>()
33 var index = 0L
34 for (cluster in graphemes(plain)) {
35 val decoration = StringBuilder()
36 for (character in cluster) {
37 while (index < styled.charLength && styled.getCharAt(index) != character) {
38 val end = decorationEnd(styled, index)
39 if (end == index) throw IllegalArgumentException(Some("highlighter changed visible text"))
40 decoration.append(styled.slice(index, end))
41 index = end
42 }
43 if (index >= styled.charLength || styled.getCharAt(index) != character) {
44 throw IllegalArgumentException(Some("highlighter changed visible text"))
45 }
46 index += 1L
47 }
48 result.add(StyledGrapheme(cluster, decoration.toString()))
49 }
50 val trailing = StringBuilder()
51 while (index < styled.charLength) {
52 val end = decorationEnd(styled, index)
53 if (end == index) throw IllegalArgumentException(Some("highlighter changed visible text"))
54 trailing.append(styled.slice(index, end))
55 index = end
56 }
57 if (trailing.toString().byteLength > 0L) result.add(StyledGrapheme("", trailing.toString()))
58 return result.toArray()