Skip to content

Commit 91ffdea

Browse files
authored
Sort completions by input resemblance. (#2018)
* Sort completions by input resemblance. Fixes #2017 * Clean code
1 parent 2859e4f commit 91ffdea

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

AUTHORS.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ Code Contributors
6565
- Márcio Mazza (@marciomazza)
6666
- Martin Vielsmaier (@moser) <[email protected]>
6767
- TingJia Wu (@WutingjiaX) <[email protected]>
68+
- Nguyễn Hồng Quân <[email protected]>
6869

6970
And a few more "anonymous" contributors.
7071

jedi/api/completion.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,11 @@ def __init__(self, inference_state, module_context, code_lines, position,
138138

139139
self._fuzzy = fuzzy
140140

141+
# Return list of completions in this order:
142+
# - Beginning with what user is typing
143+
# - Public (alphabet)
144+
# - Private ("_xxx")
145+
# - Dunder ("__xxx")
141146
def complete(self):
142147
leaf = self._module_node.get_leaf_for_position(
143148
self._original_position,
@@ -176,7 +181,8 @@ def complete(self):
176181
return (
177182
# Removing duplicates mostly to remove False/True/None duplicates.
178183
_remove_duplicates(prefixed_completions, completions)
179-
+ sorted(completions, key=lambda x: (x.name.startswith('__'),
184+
+ sorted(completions, key=lambda x: (not x.name.startswith(self._like_name),
185+
x.name.startswith('__'),
180186
x.name.startswith('_'),
181187
x.name.lower()))
182188
)

test/test_api/test_api.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -321,10 +321,19 @@ def test_docstrings_for_completions(Script):
321321
assert isinstance(c.docstring(), str)
322322

323323

324+
def test_completions_order_most_resemblance_on_top(Script):
325+
"""Test that the completion which resembles the in-typing the most will come first."""
326+
code = "from pathlib import Path\npath = Path('hello.txt')\n\npat"
327+
script = Script(code)
328+
# User is typing "pat" and "path" is closer to it than "Path".
329+
assert ['path', 'Path'] == [comp.name for comp in script.complete()]
330+
331+
324332
def test_fuzzy_completion(Script):
325333
script = Script('string = "hello"\nstring.upper')
326-
assert ['isupper',
327-
'upper'] == [comp.name for comp in script.complete(fuzzy=True)]
334+
# 'isupper' is included because it is fuzzily matched.
335+
assert ['upper',
336+
'isupper'] == [comp.name for comp in script.complete(fuzzy=True)]
328337

329338

330339
def test_math_fuzzy_completion(Script, environment):

0 commit comments

Comments
 (0)