Skip to content

Commit

Permalink
Improve Jedi file completions for directories (#337)
Browse files Browse the repository at this point in the history
  • Loading branch information
ccordoba12 authored Jan 17, 2023
1 parent 52a0d54 commit 11b5441
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
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"'

0 comments on commit 11b5441

Please sign in to comment.