scoop:scoop.readline:0.1.0
src/render/decoration.scoop
Selected production source · src/render/decoration.scoop
1
package scoop.readline3
import scoop.charset.graphemes5
internal struct StyledGrapheme(val plain: String, val decoration: String)7
// Only SGR styling is invisible. User input controls remain visible text.8
private fun decorationEnd(text: String, start: Long): Long {9
if (start + 2L >= text.charLength || text.getCharAt(start) != '\u001b' || text.getCharAt(start + 1L) != '[') return start10
var index = start + 2L11
while (index < text.charLength) {12
val character = text.getCharAt(index)13
if (character == 'm') return index + 1L14
if ((character < '0' || character > '9') && character != ';' && character != ':') return start15
index += 1L16
}17
return start18
}20
internal fun stripDecoration(text: String): String {21
val result = StringBuilder()22
var index = 0L23
while (index < text.charLength) {24
val end = decorationEnd(text, index)25
if (end > index) index = end26
else { result.append(text.getCharAt(index)); index += 1L }27
}28
return result.toString()29
}31
internal fun styledGraphemes(plain: String, styled: String): Array<StyledGrapheme> {32
val result = ArrayList<StyledGrapheme>()33
var index = 0L34
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 = end42
}43
if (index >= styled.charLength || styled.getCharAt(index) != character) {44
throw IllegalArgumentException(Some("highlighter changed visible text"))45
}46
index += 1L47
}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 = end56
}57
if (trailing.toString().byteLength > 0L) result.add(StyledGrapheme("", trailing.toString()))58
return result.toArray()59
}