Skip to content

Improve Jedi file completions for directories #337

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions pylsp/plugins/jedi_completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# Copyright 2021- Python Language Server Contributors.

import logging
import os.path as osp
import os

import parso

Expand Down Expand Up @@ -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):
Expand Down
23 changes: 23 additions & 0 deletions test/plugins/test_completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"'