diff --git a/pylsp/plugins/jedi_completion.py b/pylsp/plugins/jedi_completion.py index 4c4bc94e..90b4c191 100644 --- a/pylsp/plugins/jedi_completion.py +++ b/pylsp/plugins/jedi_completion.py @@ -2,7 +2,7 @@ # Copyright 2021- Python Language Server Contributors. import logging -import os.path as osp +import os import parso @@ -219,10 +219,20 @@ def _format_completion(d, markup_kind: str, include_params=True, resolve=False, if resolve: completion = _resolve_completion(completion, d, markup_kind) + # Adjustments for file completions if d.type == 'path': - path = osp.normpath(d.name) + path = os.path.normpath(d.name) path = path.replace('\\', '\\\\') path = path.replace('/', '\\/') + + # If the completion ends with os.sep, it means it's a directory. So we add an escaped os.sep + # at the end to ease additional file completions. + if d.name.endswith(os.sep): + if os.name == 'nt': + path = path + '\\\\' + else: + path = path + '\\/' + completion['insertText'] = path if include_params and not is_exception_class(d.name): diff --git a/test/plugins/test_completion.py b/test/plugins/test_completion.py index 16e278e0..fc22c34f 100644 --- a/test/plugins/test_completion.py +++ b/test/plugins/test_completion.py @@ -528,3 +528,26 @@ def foo(): com_position = {'line': 1, 'character': 10} completions = pylsp_jedi_completions(doc._config, doc, com_position) assert completions[0]['label'] == 'foo()' + + +def test_file_completions(workspace, tmpdir): + # Create directory and a file to get completions for them. + # Note: `tmpdir`` is the root dir of the `workspace` fixture. That's why we use + # it here. + tmpdir.mkdir('bar') + file = tmpdir.join('foo.txt') + file.write('baz') + + # Content of doc to test completion + doc_content = '"' + doc = Document(DOC_URI, workspace, doc_content) + + # Request for completions + com_position = {'line': 0, 'character': 1} + completions = pylsp_jedi_completions(doc._config, doc, com_position) + + # Check completions + assert len(completions) == 2 + assert [c['kind'] == lsp.CompletionItemKind.File for c in completions] + assert completions[0]['insertText'] == ('bar' + '\\\\') if os.name == 'nt' else ('bar' + '\\/') + assert completions[1]['insertText'] == 'foo.txt"'