Exemplo n.º 1
0
def test_loading_unicode_files_with_bad_global_charset(monkeypatch, tmpdir):
    dirname = str(tmpdir.mkdir('jedi-test'))
    filename1 = os.path.join(dirname, 'test1.py')
    filename2 = os.path.join(dirname, 'test2.py')
    if sys.version_info < (3, 0):
        data = "# coding: latin-1\nfoo = 'm\xf6p'\n"
    else:
        data = "# coding: latin-1\nfoo = 'm\xf6p'\n".encode("latin-1")

    with open(filename1, "wb") as f:
        f.write(data)
    s = Script("from test1 import foo\nfoo.", line=2, column=4, path=filename2)
    s.completions()
Exemplo n.º 2
0
def test_loading_unicode_files_with_bad_global_charset(monkeypatch, tmpdir):
    dirname = str(tmpdir.mkdir('jedi-test'))
    filename1 = os.path.join(dirname, 'test1.py')
    filename2 = os.path.join(dirname, 'test2.py')
    if sys.version_info < (3, 0):
        data = "# coding: latin-1\nfoo = 'm\xf6p'\n"
    else:
        data = "# coding: latin-1\nfoo = 'm\xf6p'\n".encode("latin-1")

    with open(filename1, "wb") as f:
        f.write(data)
    s = Script("from test1 import foo\nfoo.",
               line=2, column=4, path=filename2)
    s.completions()
Exemplo n.º 3
0
    def show_completion(self, tab):
        """Method shows code completion window

        Args:
            tab (obj): tab reference

        Returns:
            void

        """

        if (self._win is not None):
            self._win.destroy()

        suffix = tab.path.split('.')[-1]
        if (suffix in ['py', 'jedi', 'padawan']):
            self._tab = tab
            row, col = tab.text.index(tk.INSERT).split('.')

            try:
                script = Script(tab.text.get('1.0', 'end-1c'), int(row),
                                int(col))
                completions = script.completions()
            except ValueError:
                return

            cnt = len(completions)
            if (cnt == 0):
                return

            if (cnt == 1):
                self._complete(completion=completions[0])
            else:
                self._set_gui(completions)
Exemplo n.º 4
0
 def __init__(self, area, *args, **kwargs):
     source      = area.get('1.0', 'end')
     source      = area.get('1.0', 'end')
     line, col   = area.indcur()
     script      = Script(source, line, col, area.filename)
     completions = script.completions()
     CompletionWindow.__init__(self, area, completions, *args, **kwargs)
Exemplo n.º 5
0
 def __init__(self, area, *args, **kwargs):
     source      = area.get('1.0', 'end')
     source      = area.get('1.0', 'end')
     line, col   = area.indcur()
     script      = Script(source, line, col, area.filename)
     completions = script.completions()
     CompletionWindow.__init__(self, area, completions, *args, **kwargs)
     self.bind('<F1>', lambda event: sys.stdout.write('%s\n%s\n' % ('#' * 80, self.box.selection_docs())))
Exemplo n.º 6
0
    def do_complete(self, data):
        file_ = self.db.get_file(self.current_file)
        file_ = to_unicode(file_)
        lines = file_.splitlines()
        lno = self.current['lno']
        line_before = ''
        if len(lines) >= lno:
            line_before = lines[lno - 1]
        indent = len(line_before) - len(line_before.lstrip())
        segments = data.splitlines()
        for segment in reversed(segments):
            line = u(' ') * indent + segment
            lines.insert(lno - 1, line)
        script = Script(
            u('\n').join(lines), lno - 1 + len(segments),
            len(segments[-1]) + indent, '')
        try:
            completions = script.completions()
        except:
            self.db.send('Suggest')
            self.notify_exc('Completion failed for %s' %
                            ('\n'.join(reversed(segments))))
            return

        try:
            funs = script.call_signatures() or []
        except:
            self.db.send('Suggest')
            self.notify_exc('Completion of function failed for %s' %
                            ('\n'.join(reversed(segments))))
            return

        try:
            suggest_obj = {
                'params': [{
                    'params':
                    [p.get_code().replace('\n', '') for p in fun.params],
                    'index':
                    fun.index,
                    'module':
                    fun.module.path,
                    'call_name':
                    fun.call_name
                } for fun in funs],
                'completions': [{
                    'base':
                    comp.name[:len(comp.name) - len(comp.complete)],
                    'complete':
                    comp.complete,
                    'description':
                    comp.description
                } for comp in completions if comp.name.endswith(comp.complete)]
            }
            self.db.send('Suggest|%s' % dump(suggest_obj))
        except:
            self.db.send('Suggest')
            self.notify_exc('Completion generation failed for %s' %
                            ('\n'.join(reversed(segments))))
Exemplo n.º 7
0
    def do_completion(self):
        source = self.area.get('1.0', 'end')
        line   = self.area.indcur()[0]
        size   = len(self.area.get('insert linestart', 'insert'))
        script = Script(source, line, size, self.area.filename)
        completions = script.completions()

        for ind in completions:
            self.insert('end', ind.name)
Exemplo n.º 8
0
    def do_completion(self):
        source = self.area.get("1.0", "end")
        line = self.area.indcur()[0]
        size = len(self.area.get("insert linestart", "insert"))
        script = Script(source, line, size, self.area.filename)
        completions = script.completions()

        for ind in completions:
            self.insert("end", ind.name)
Exemplo n.º 9
0
    def feed(self):
        source      = self.area.get('1.0', 'end')
        line        = self.area.indcur()[0]
        size        = len(self.area.get('insert linestart', 'insert'))
        script      = Script(source, line, size, self.area.filename)
        completions = script.completions()

        for ind in completions:
            self.box.insert('end', ind.name)
def get_completions(source, line, column, get_full_desc=False):
    """
    Get a list of dict of completions for the given source
    """
    source = Script(source, line+1, column+1)
    completions = source.completions()

    data = list(
        map(lambda c: extract_completion_data(c, get_full_desc), completions)
    )
    return data
Exemplo n.º 11
0
Arquivo: utils.py Projeto: dev0p0/vy
    def __init__(self, area, *args, **kwargs):
        CompleteBox.__init__(self, area, *args, **kwargs)

        source      = self.area.get('1.0', 'end')
        line        = self.area.indcur()[0]
        size        = len(self.area.get('insert linestart', 'insert'))
        script      = Script(source, line, size, self.area.filename)
        completions = script.completions()

        for ind in completions:
            self.insert('end', ind.name)
Exemplo n.º 12
0
Arquivo: ui.py Projeto: Avinash9/wdb
    def do_complete(self, data):
        file_ = self.db.get_file(self.current_file)
        file_ = to_unicode(file_)
        lines = file_.splitlines()
        lno = self.current['lno']
        line_before = ''
        if len(lines) >= lno:
            line_before = lines[lno - 1]
        indent = len(line_before) - len(line_before.lstrip())
        segments = data.splitlines()
        for segment in reversed(segments):
            line = u(' ') * indent + segment
            lines.insert(lno - 1, line)
        script = Script(
            u('\n').join(lines), lno - 1 + len(segments),
            len(segments[-1]) + indent, '')
        try:
            completions = script.completions()
        except Exception:
            self.db.send('Suggest')
            self.notify_exc('Completion failed for %s' % (
                '\n'.join(reversed(segments))))
            return

        try:
            funs = script.call_signatures() or []
        except Exception:
            self.db.send('Suggest')
            self.notify_exc('Completion of function failed for %s' % (
                '\n'.join(reversed(segments))))
            return

        try:
            suggest_obj = {
                'params': [{
                    'params': [p.get_code().replace('\n', '')
                               for p in fun.params],
                    'index': fun.index,
                    'module': fun.module.path,
                    'call_name': fun.call_name} for fun in funs],
                'completions': [{
                    'base': comp.name[
                        :len(comp.name) - len(comp.complete)],
                    'complete': comp.complete,
                    'description': comp.description
                } for comp in completions if comp.name.endswith(
                    comp.complete)]
            }
            self.db.send('Suggest|%s' % dump(suggest_obj))
        except Exception:
            self.db.send('Suggest')
            self.notify_exc('Completion generation failed for %s' % (
                '\n'.join(reversed(segments))))
Exemplo n.º 13
0
def test_nested_namedtuples():
    """
    From issue #730.
    """
    s = Script(
        dedent('''
        import collections
        Dataset = collections.namedtuple('Dataset', ['data'])
        Datasets = collections.namedtuple('Datasets', ['train'])
        train_x = Datasets(train=Dataset('data_value'))
        train_x.train.'''))
    assert 'data' in [c.name for c in s.completions()]
Exemplo n.º 14
0
def _get_completions(source, func, line=None, column=None):
    try:
        num_lines = len(source.split('\n'))
        if line is None:
            line = num_lines
        s = Script(source, line=line, column=column)
        completions = s.completions()
        # print('### input:')
        # print(source)
        # print('### completions:')
        # print('\n'.join([c.name for c in completions]))
    except:
        print('Exception in completions thread')
        traceback.print_exc()
        completions = []

    mainthread(WrappablePartial(func, [c for c in completions]))()
Exemplo n.º 15
0
doc = 'def a():\n    pa\n'


class DummyString(str):
    def __init__(self, doc):
        super(str)
        self._doc = doc

    def splitlines(self, keepends):
        return list(self._doc)

    def endswith(self, suffix):
        return False

    def __eq__(self, other):
        return False


# s = Script(doc)
# print(s.completions())

d = DummyString(doc.splitlines(True))
s = Script(d, 2, 6)
print(d._doc)
print(s.completions())

d._doc.insert(2, '\n')
d = DummyString(d._doc)
print(d._doc)
s = Script(d, 2, 6)
print(s.completions())