1"""A simple completer for the qtconsole"""
2
3# Copyright (c) Jupyter Development Team.
4# Distributed under the terms of the Modified BSD License.
5
6from qtpy import QtCore, QtGui, QtWidgets
7import ipython_genutils.text as text
8
9
10class CompletionPlain(QtWidgets.QWidget):
11    """ A widget for tab completion,  navigable by arrow keys """
12
13    #--------------------------------------------------------------------------
14    # 'QObject' interface
15    #--------------------------------------------------------------------------
16
17    def __init__(self, console_widget):
18        """ Create a completion widget that is attached to the specified Qt
19            text edit widget.
20        """
21        assert isinstance(console_widget._control, (QtWidgets.QTextEdit, QtWidgets.QPlainTextEdit))
22        super().__init__()
23
24        self._text_edit = console_widget._control
25        self._console_widget = console_widget
26
27        self._text_edit.installEventFilter(self)
28
29    def eventFilter(self, obj, event):
30        """ Reimplemented to handle keyboard input and to auto-hide when the
31            text edit loses focus.
32        """
33        if obj == self._text_edit:
34            etype = event.type()
35
36            if etype in( QtCore.QEvent.KeyPress, QtCore.QEvent.FocusOut ):
37                self.cancel_completion()
38
39        return super().eventFilter(obj, event)
40
41    #--------------------------------------------------------------------------
42    # 'CompletionPlain' interface
43    #--------------------------------------------------------------------------
44    def cancel_completion(self):
45        """Cancel the completion, reseting internal variable, clearing buffer """
46        self._console_widget._clear_temporary_buffer()
47
48
49    def show_items(self, cursor, items, prefix_length=0):
50        """ Shows the completion widget with 'items' at the position specified
51            by 'cursor'.
52        """
53        if not items :
54            return
55        self.cancel_completion()
56        strng = text.columnize(items)
57        # Move cursor to start of the prefix to replace it
58        # when a item is selected
59        cursor.movePosition(QtGui.QTextCursor.Left, n=prefix_length)
60        self._console_widget._fill_temporary_buffer(cursor, strng, html=False)
61