Skip to content

Commit 11b5441

Browse files
authoredJan 17, 2023
Improve Jedi file completions for directories (#337)
1 parent 52a0d54 commit 11b5441

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed
 

‎pylsp/plugins/jedi_completion.py

+12-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# Copyright 2021- Python Language Server Contributors.
33

44
import logging
5-
import os.path as osp
5+
import os
66

77
import parso
88

@@ -219,10 +219,20 @@ def _format_completion(d, markup_kind: str, include_params=True, resolve=False,
219219
if resolve:
220220
completion = _resolve_completion(completion, d, markup_kind)
221221

222+
# Adjustments for file completions
222223
if d.type == 'path':
223-
path = osp.normpath(d.name)
224+
path = os.path.normpath(d.name)
224225
path = path.replace('\\', '\\\\')
225226
path = path.replace('/', '\\/')
227+
228+
# If the completion ends with os.sep, it means it's a directory. So we add an escaped os.sep
229+
# at the end to ease additional file completions.
230+
if d.name.endswith(os.sep):
231+
if os.name == 'nt':
232+
path = path + '\\\\'
233+
else:
234+
path = path + '\\/'
235+
226236
completion['insertText'] = path
227237

228238
if include_params and not is_exception_class(d.name):

‎test/plugins/test_completion.py

+23
Original file line numberDiff line numberDiff line change
@@ -528,3 +528,26 @@ def foo():
528528
com_position = {'line': 1, 'character': 10}
529529
completions = pylsp_jedi_completions(doc._config, doc, com_position)
530530
assert completions[0]['label'] == 'foo()'
531+
532+
533+
def test_file_completions(workspace, tmpdir):
534+
# Create directory and a file to get completions for them.
535+
# Note: `tmpdir`` is the root dir of the `workspace` fixture. That's why we use
536+
# it here.
537+
tmpdir.mkdir('bar')
538+
file = tmpdir.join('foo.txt')
539+
file.write('baz')
540+
541+
# Content of doc to test completion
542+
doc_content = '"'
543+
doc = Document(DOC_URI, workspace, doc_content)
544+
545+
# Request for completions
546+
com_position = {'line': 0, 'character': 1}
547+
completions = pylsp_jedi_completions(doc._config, doc, com_position)
548+
549+
# Check completions
550+
assert len(completions) == 2
551+
assert [c['kind'] == lsp.CompletionItemKind.File for c in completions]
552+
assert completions[0]['insertText'] == ('bar' + '\\\\') if os.name == 'nt' else ('bar' + '\\/')
553+
assert completions[1]['insertText'] == 'foo.txt"'

0 commit comments

Comments
 (0)