Skip to content

Commit

Permalink
Fix completion formatter (#1271)
Browse files Browse the repository at this point in the history
## Changes

Fixed bug with incorrect formatting of strings with cursor in the middle
of the line.
Fixes #1133

## Test plan

Unit test added
  • Loading branch information
pkukielka committed Apr 2, 2024
1 parent dcb8e02 commit 131daa0
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,13 @@ class CodyAutocompleteManager {
}

defaultItem.insertText = formattedInsertText
val completionText = formattedInsertText.removePrefix(originalText)
val cursorPositionInOriginalText = offset - range.startOffset
val originalTextBeforeCursor = originalText.substring(0, cursorPositionInOriginalText)
val originalTextAfterCursor = originalText.substring(cursorPositionInOriginalText)
val completionText =
formattedInsertText
.removePrefix(originalTextBeforeCursor)
.removeSuffix(originalTextAfterCursor)
if (completionText.trim().isBlank()) return

val lineBreaks = listOf("\r\n", "\n", "\r")
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/com/sourcegraph/utils/CodyFormatter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class CodyFormatter {
existingStart + addition + psiFile.text.substring(cursor)
} else psiFile.text
return formattedText.substring(
range.startOffset, cursor + formattedText.length - document.textLength)
range.startOffset, range.endOffset + formattedText.length - document.textLength)
}
}
}
10 changes: 10 additions & 0 deletions src/test/kotlin/utils/CodyFormatterTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package utils

import com.intellij.openapi.util.TextRange
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import com.intellij.util.text.findTextRange
import com.sourcegraph.utils.CodyFormatter
import junit.framework.TestCase

Expand Down Expand Up @@ -82,4 +83,13 @@ class CodyFormatterTest : BasePlatformTestCase() {
.trimMargin(),
formatText(completion, rangeEnd, TextRange(rangeStart, rangeEnd), testFileContent))
}

fun `test formatting with cursor in the middle of the line`() {
val existingLine = "VirtualFile vcsRoot = VcsUtil.getVcsRootFor(project, file);"
val testFileContent = testFileContent.replace("// MAIN", existingLine)
val range = testFileContent.findTextRange(existingLine)
val offset = testFileContent.indexOf("file")

TestCase.assertEquals(existingLine, formatText(existingLine, offset, range, testFileContent))
}
}

0 comments on commit 131daa0

Please sign in to comment.