zzz
zzz

Reputation: 93

Multiple colors in TextField not working for all words in Kotlin

I'm making an IDE for Kotlin, I want to be able to color the keywords with blue color but it doesn't filter the second or the third ... etc from the beginning as follows:

enter image description here

I tried different regex patterns but didn't get what I desired.

Here is my function :

fun buildAnnotatedStringWithColors(code: String): AnnotatedString {
    val pattern = "[ \\t]"
    val words: List<String> = code.split(pattern.toRegex())
    val builder = AnnotatedString.Builder()
    for (word in words) {
        when (word) {
            in keywordList -> {
                builder.withStyle(
                    style = SpanStyle(
                        color = funKeyWords,
                        fontWeight = FontWeight.Bold
                    )
                ) {
                    append("$word ")
                }
            }
            else -> {
                builder.withStyle(
                    style = SpanStyle(
                        color = PrimaryColor,
                        fontWeight = FontWeight.Bold
                    )
                ) {
                    append("$word ")
                }
            }
        }
    }
    return builder.toAnnotatedString()
}

I want to be able to have white spaces, and new lines, and be colored at the same time so [\\s] doesn't work for me.

Upvotes: 0

Views: 59

Answers (1)

Ivo
Ivo

Reputation: 23357

I think something like this might work

fun buildAnnotatedStringWithColors(code: String): AnnotatedString {
    val pattern = "(?<=[\\s])"
    val words: List<String> = code.split(pattern.toRegex())
    val builder = AnnotatedString.Builder()
    for (word in words) {
        when (word.trim()) {
            in keywordList -> {
                builder.withStyle(
                    style = SpanStyle(
                        color = funKeyWords,
                        fontWeight = FontWeight.Bold
                    )
                ) {
                    append(word)
                }
            }
            else -> {
                builder.withStyle(
                    style = SpanStyle(
                        color = PrimaryColor,
                        fontWeight = FontWeight.Bold
                    )
                ) {
                    append(word)
                }
            }
        }
    }
    return builder.toAnnotatedString()
}

Upvotes: 1

Related Questions