Untitled

 avatar
unknown
kotlin
a year ago
1.1 kB
3
Indexable
import javax.swing.text.AttributeSet
import javax.swing.text.DocumentFilter

class EditorFilter : DocumentFilter() {
    override fun insertString(fb: FilterBypass, offset: Int, string: String?, attr: AttributeSet?) {
        if (string != null && !string.contains('\n') && canModifyLine(fb, offset)) {
            super.insertString(fb, offset, string, attr)
        }
    }

    override fun remove(fb: FilterBypass, offset: Int, length: Int) {
        val text = fb.document.getText(offset, length)
        if (!text.contains('\n') && canModifyLine(fb, offset)) {
            super.remove(fb, offset, length)
        }
    }

    override fun replace(fb: FilterBypass, offset: Int, length: Int, text: String?, attrs: AttributeSet?) {
        if (text != null && !text.contains('\n') && canModifyLine(fb, offset)) {
            super.replace(fb, offset, length, text, attrs)
        }
    }

    private fun canModifyLine(fb: FilterBypass, offset: Int): Boolean {
        val lineIndex = fb.document.defaultRootElement.getElementIndex(offset)
        return lineIndex % 3 == 1
    }
}
Editor is loading...
Leave a Comment