Skip to content

Commit

Permalink
Prevent inserting whitespace element as first or last element in a co…
Browse files Browse the repository at this point in the history
…mposite node

In such cases insert the whitespace just before or after the composite element (recursively if needed)

Closes #2688
  • Loading branch information
paul-dingemans committed Jun 25, 2024
1 parent 9a93fdc commit 39ebb36
Showing 1 changed file with 18 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -238,13 +238,17 @@ public fun ASTNode.upsertWhitespaceBeforeMe(text: String) {
return replaceWhitespaceWith(text)
}
val previous = treePrev ?: prevLeaf()
if (previous != null && previous.elementType == WHITE_SPACE) {
previous.replaceWhitespaceWith(text)
} else {
if (treeParent.firstChildNode == this) {
when {
previous?.elementType == WHITE_SPACE -> {
previous.replaceWhitespaceWith(text)
}

treeParent.firstChildNode == this -> {
// Never insert a whitespace node as first node in a composite node
treeParent.upsertWhitespaceBeforeMe(text)
} else {
}

else -> {
PsiWhiteSpaceImpl(text).also { psiWhiteSpace ->
(psi as LeafElement).rawInsertBeforeMe(psiWhiteSpace)
}
Expand Down Expand Up @@ -289,13 +293,17 @@ public fun ASTNode.upsertWhitespaceAfterMe(text: String) {
return replaceWhitespaceWith(text)
}
val next = treeNext ?: nextLeaf()
if (next != null && next.elementType == WHITE_SPACE) {
next.replaceWhitespaceWith(text)
} else {
if (treeParent.lastChildNode == this) {
when {
next?.elementType == WHITE_SPACE -> {
next.replaceWhitespaceWith(text)
}

treeParent.lastChildNode == this -> {
// Never insert a whitespace as last node in a composite node
treeParent.upsertWhitespaceAfterMe(text)
} else {
}

else -> {
PsiWhiteSpaceImpl(text).also { psiWhiteSpace ->
(psi as LeafElement).rawInsertAfterMe(psiWhiteSpace)
}
Expand Down

0 comments on commit 39ebb36

Please sign in to comment.