Skip to content

Commit 2164f14

Browse files
committed
Find import position based on longest matching package
1 parent 1355290 commit 2164f14

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

server/src/main/kotlin/org/javacs/kt/completion/Completions.kt

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,13 +103,23 @@ private fun indexCompletionItems(parsedFile: KtFile, index: SymbolIndex, partial
103103

104104
/** Finds a good insertion position for a new import of the given fully-qualified name. */
105105
private fun findImportInsertionPosition(parsedFile: KtFile, fqName: FqName): Position =
106-
// TODO: Insert lexicographically instead of at the end
107-
(parsedFile.importDirectives.lastOrNull() as? KtElement ?: parsedFile.packageDirective as? KtElement)
106+
(closestImport(parsedFile.importDirectives, fqName) as? KtElement ?: parsedFile.packageDirective as? KtElement)
108107
?.let(::location)
109108
?.range
110109
?.end
111110
?: Position(0, 0)
112111

112+
// TODO: Lexicographic insertion
113+
private fun closestImport(imports: List<KtImportDirective>, fqName: FqName): KtImportDirective? =
114+
imports
115+
.asReversed()
116+
.maxByOrNull { it.importedFqName?.let { matchingPrefixLength(it, fqName) } ?: 0 }
117+
118+
private fun matchingPrefixLength(left: FqName, right: FqName): Int =
119+
left.pathSegments().asSequence().zip(right.pathSegments().asSequence())
120+
.takeWhile { it.first == it.second }
121+
.count()
122+
113123
/** Finds keyword completions starting with the given partial identifier. */
114124
private fun keywordCompletionItems(partial: String): Sequence<CompletionItem> =
115125
(KtTokens.SOFT_KEYWORDS.getTypes() + KtTokens.KEYWORDS.getTypes()).asSequence()

0 commit comments

Comments
 (0)