Skip to content

Commit 67e742d

Browse files
ehsan-fjjonathanslenders
authored andcommitted
#865: Add pattern to WorldCompleter's constructor
add pattern to WordCompleter's constructor in order to pass it to document.get_word_before_cursor in get_completions method. A test added for it.
1 parent b1c212c commit 67e742d

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

prompt_toolkit/completion/word_completer.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,11 @@ class WordCompleter(Completer):
2323
contain spaces. (Can not be used together with the WORD option.)
2424
:param match_middle: When True, match not only the start, but also in the
2525
middle of the word.
26+
:param pattern: Optional regex. When given, use this regex
27+
pattern instead of default one.
2628
"""
2729
def __init__(self, words, ignore_case=False, meta_dict=None, WORD=False,
28-
sentence=False, match_middle=False):
30+
sentence=False, match_middle=False, pattern=None):
2931
assert not (WORD and sentence)
3032
assert callable(words) or all(isinstance(w, string_types) for w in words)
3133

@@ -35,6 +37,7 @@ def __init__(self, words, ignore_case=False, meta_dict=None, WORD=False,
3537
self.WORD = WORD
3638
self.sentence = sentence
3739
self.match_middle = match_middle
40+
self.pattern = pattern
3841

3942
def get_completions(self, document, complete_event):
4043
# Get list of words.
@@ -46,7 +49,7 @@ def get_completions(self, document, complete_event):
4649
if self.sentence:
4750
word_before_cursor = document.text_before_cursor
4851
else:
49-
word_before_cursor = document.get_word_before_cursor(WORD=self.WORD)
52+
word_before_cursor = document.get_word_before_cursor(WORD=self.WORD, pattern=self.pattern)
5053

5154
if self.ignore_case:
5255
word_before_cursor = word_before_cursor.lower()

tests/test_completion.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import unicode_literals, absolute_import, print_function
22

33
import os
4+
import re
45
import shutil
56
import tempfile
67

@@ -320,6 +321,19 @@ def get_words():
320321
assert called[0] == 2
321322

322323

324+
def test_word_completer_pattern():
325+
# With a pattern which support '.'
326+
completer = WordCompleter(['abc', 'a.b.c', 'a.b', 'xyz'],
327+
pattern=re.compile(r'^([a-zA-Z0-9_.]+|[^a-zA-Z0-9_.\s]+)'))
328+
completions = completer.get_completions(Document('a.'), CompleteEvent())
329+
assert [c.text for c in completions] == ['a.b.c', 'a.b']
330+
331+
# Without pattern
332+
completer = WordCompleter(['abc', 'a.b.c', 'a.b', 'xyz'])
333+
completions = completer.get_completions(Document('a.'), CompleteEvent())
334+
assert [c.text for c in completions] == []
335+
336+
323337
def test_fuzzy_completer():
324338
collection = [
325339
'migrations.py',

0 commit comments

Comments
 (0)