|  | 
|  | 1 | +#!/usr/bin/env python | 
|  | 2 | +""" | 
|  | 3 | +Autocompletion example with cursor position not at the end of the completion. | 
|  | 4 | +
 | 
|  | 5 | +Press [Tab] to complete the current word. | 
|  | 6 | +- The first Tab press fills in the common part of all completions | 
|  | 7 | + and shows all the completions. (In the menu) | 
|  | 8 | +- Any following tab press cycles through all the possible completions. | 
|  | 9 | +""" | 
|  | 10 | +from __future__ import unicode_literals | 
|  | 11 | +from collections import namedtuple | 
|  | 12 | + | 
|  | 13 | +from prompt_toolkit import prompt, completion | 
|  | 14 | +from prompt_toolkit.completion import Completer, Completion | 
|  | 15 | + | 
|  | 16 | +CompletionWithCursorPosition = namedtuple('CompletionWithCursorPosition', | 
|  | 17 | + 'text cursor_position') | 
|  | 18 | + | 
|  | 19 | +class CursorPositionCompleter(Completer): | 
|  | 20 | + """ | 
|  | 21 | + Simple autocompletion on a list of words with associated cursor positions. | 
|  | 22 | +
 | 
|  | 23 | + :param completions: List of CompletionWithCursorPosition namedtuples. | 
|  | 24 | + """ | 
|  | 25 | + def __init__(self, completions): | 
|  | 26 | + self.completions = completions | 
|  | 27 | + | 
|  | 28 | + def get_completions(self, document, complete_event): | 
|  | 29 | + before_cursor = document.get_word_before_cursor() | 
|  | 30 | + return (Completion(c.text, -len(before_cursor), cursor_position=c.cursor_position) | 
|  | 31 | + for c in self.completions | 
|  | 32 | + if c.text.startswith(before_cursor)) | 
|  | 33 | + | 
|  | 34 | +completions = { | 
|  | 35 | + CompletionWithCursorPosition('upper_case()', 1), | 
|  | 36 | + CompletionWithCursorPosition('lower_case()', 1), | 
|  | 37 | + CompletionWithCursorPosition('list_add(list:=, element:=)', len(', element:=)')), | 
|  | 38 | + CompletionWithCursorPosition('<html></html>', len('</html>')) | 
|  | 39 | +} | 
|  | 40 | + | 
|  | 41 | +comp = CursorPositionCompleter(completions) | 
|  | 42 | + | 
|  | 43 | +def main(): | 
|  | 44 | + text = prompt('Input: ', completer=comp, | 
|  | 45 | + complete_while_typing=False) | 
|  | 46 | + print('You said: %s' % text) | 
|  | 47 | + | 
|  | 48 | + | 
|  | 49 | +if __name__ == '__main__': | 
|  | 50 | + main() | 
0 commit comments