Example #1
0
    def complete(self, fn, offset, src, func_name_only):
        comps = []
        autocomplete_tests = gs.setting('autocomplete_tests', False)
        autocomplete_closures = gs.setting('autocomplete_closures', False)
        ents, err = mg9.complete(fn, src, offset)
        if err:
            gs.notice(DOMAIN, err)

        name_fx = None
        name_fx_pat = gs.setting('autocomplete_filter_name')
        if name_fx_pat:
            try:
                name_fx = re.compile(name_fx_pat)
            except Exception as ex:
                gs.notice(DOMAIN, 'Cannot filter completions: %s' % ex)

        for ent in ents:
            if name_fx and name_fx.search(ent['name']):
                continue

            tn = ent['type']
            cn = ent['class']
            nm = ent['name']
            is_func = (cn == 'func')
            is_func_type = (cn == 'type' and tn.startswith('func('))

            if is_func:
                if nm in ('main', 'init'):
                    continue

                if not autocomplete_tests and nm.startswith(
                    ('Test', 'Benchmark', 'Example')):
                    continue

            if is_func or is_func_type:
                s_sfx = u'\u0282'
                t_sfx = gs.CLASS_PREFIXES.get('type', '')
                f_sfx = gs.CLASS_PREFIXES.get('func', '')
                params, ret = declex(tn)
                decl = []
                for i, p in enumerate(params):
                    n, t = p
                    if t.startswith('...'):
                        n = '...'
                    decl.append('${%d:%s}' % (i + 1, n))
                decl = ', '.join(decl)
                ret = ret.strip('() ')

                if is_func:
                    if func_name_only:
                        comps.append((
                            '%s\t%s %s' % (nm, ret, f_sfx),
                            nm,
                        ))
                    else:
                        comps.append((
                            '%s\t%s %s' % (nm, ret, f_sfx),
                            '%s(%s)' % (nm, decl),
                        ))
                else:
                    comps.append((
                        '%s\t%s %s' % (nm, tn, t_sfx),
                        nm,
                    ))

                    if autocomplete_closures:
                        comps.append((
                            '%s {}\tfunc() {...} %s' % (nm, s_sfx),
                            '%s {\n\t${0}\n}' % tn,
                        ))
            elif cn != 'PANIC':
                comps.append((
                    '%s\t%s %s' % (nm, tn, self.typeclass_prefix(cn, tn)),
                    nm,
                ))
        return comps
Example #2
0
	def tip(self, edit):
		view = self.view
		pt = gs.sel(view).begin()
		if view.substr(sublime.Region(pt-1, pt)) == '(':
			depth = 1
		else:
			depth = 0
		c = ''
		while True:
			line = view.line(pt)
			scope = view.scope_name(pt)
			if 'string' in scope or 'comment' in scope:
				pt = view.extract_scope(pt).begin() - 1
				continue

			c = view.substr(sublime.Region(pt-1, pt))
			if not c:
				pt = -1
				break

			if c.isalpha() and depth >= 0:
				while c.isalpha() or c == '.':
					pt += 1
					c = view.substr(sublime.Region(pt-1, pt))

				# curly braces ftw
				break # break outer while loop
			if c == ')':
				depth -= 1
			elif c == '(':
				depth += 1
				i = pt
				while True:
					pc = view.substr(sublime.Region(i-1, i))
					if pc == '.' or pc.isalpha():
						i -= 1
					else:
						break

				if i != pt:
					pt = i
					continue

			pt -= 1
			if pt <= line.begin():
				pt = -1
				break

		while not c.isalpha() and pt > 0:
			pt -= 1
			c = view.substr(sublime.Region(pt-1, pt))

		if pt <= 0 or view.scope_name(pt).strip() == 'source.go':
			return ({}, "can't find selector")

		line = view.line(pt)
		line_start = line.begin()

		s = view.substr(line)
		if not s:
			return ({}, 'no source')

		scopes = [
			'support.function.any-method.go',
			'meta.function-call.go',
			'support.function.builtin.go',
		]
		found = False
		while True:
			scope = view.scope_name(pt).strip()
			for s in scopes:
				if scope.endswith(s):
					found = True
					break

			if found or pt <= line_start:
				break

			pt -= 1

		if not found:
			return ({}, "can't find function call")

		s = view.substr(sublime.Region(line_start, pt))
		m = END_SELECTOR_PAT.match(s)
		if not m:
			return ({}, "can't match selector")

		offset = (line_start + m.end())
		sel = m.group(1)
		name = m.group(2)
		candidates = []
		src = view.substr(sublime.Region(0, view.size()))
		fn = view.file_name()
		candidates, err = mg9.complete(fn, src, offset)
		if err:
			gs.notice(DOMAIN, err)
		else:
			c = {}
			for i in candidates:
				if i['name'] == name:
					if c:
						c = None
						break
					c = i

			if c:
				return (c, '')

			return ({}, 'no candidates found')
Example #3
0
	def complete(self, fn, offset, src, func_name_only):
		comps = []
		autocomplete_tests = gs.setting('autocomplete_tests', False)
		autocomplete_closures = gs.setting('autocomplete_closures', False)
		ents, err = mg9.complete(fn, src, offset)
		if err:
			gs.notice(DOMAIN, err)

		name_fx = None
		name_fx_pat = gs.setting('autocomplete_filter_name')
		if name_fx_pat:
			try:
				name_fx = re.compile(name_fx_pat)
			except Exception as ex:
				gs.notice(DOMAIN, 'Cannot filter completions: %s' % ex)

		for ent in ents:
			if name_fx and name_fx.search(ent['name']):
				continue

			tn = ent['type']
			cn = ent['class']
			nm = ent['name']
			is_func = (cn == 'func')
			is_func_type = (cn == 'type' and tn.startswith('func('))

			if is_func:
				if nm in ('main', 'init'):
					continue

				if not autocomplete_tests and nm.startswith(('Test', 'Benchmark', 'Example')):
					continue

			if is_func or is_func_type:
				s_sfx = u'\u0282'
				t_sfx = gs.CLASS_PREFIXES.get('type', '')
				f_sfx = gs.CLASS_PREFIXES.get('func', '')
				params, ret = declex(tn)
				decl = []
				for i, p in enumerate(params):
					n, t = p
					if t.startswith('...'):
						n = '...'
					decl.append('${%d:%s}' % (i+1, n))
				decl = ', '.join(decl)
				ret = ret.strip('() ')

				if is_func:
					if func_name_only:
						comps.append((
							'%s\t%s %s' % (nm, ret, f_sfx),
							nm,
						))
					else:
						comps.append((
							'%s\t%s %s' % (nm, ret, f_sfx),
							'%s(%s)' % (nm, decl),
						))
				else:
					comps.append((
						'%s\t%s %s' % (nm, tn, t_sfx),
						nm,
					))

					if autocomplete_closures:
						comps.append((
							'%s {}\tfunc() {...} %s' % (nm, s_sfx),
							'%s {\n\t${0}\n}' % tn,
						))
			elif cn != 'PANIC':
				comps.append((
					'%s\t%s %s' % (nm, tn, self.typeclass_prefix(cn, tn)),
					nm,
				))
		return comps
Example #4
0
    def complete(self, fn, offset, src, func_name_only):
        """Go completion via gocode (called from mg9.py).
        """
        comps = []
        autocomplete_tests = gs.setting("autocomplete_tests", False)
        autocomplete_closures = gs.setting("autocomplete_closures", False)
        ents, err = mg9.complete(fn, src, offset)
        if err:
            gs.notice(DOMAIN, err)

        name_fx = None
        name_fx_pat = gs.setting("autocomplete_filter_name")
        if name_fx_pat:
            try:
                name_fx = re.compile(name_fx_pat)
            except Exception as ex:
                gs.notice(DOMAIN, "Cannot filter completions: %s" % ex)

        # TODO: Remove Regexes and move to Go.
        for ent in ents:
            if name_fx and name_fx.search(ent["name"]):
                continue

            tn = ent["type"]
            cn = ent["class"]
            nm = ent["name"]
            is_func = cn == "func"
            is_func_type = cn == "type" and tn.startswith("func(")

            if is_func:
                if nm in ("main", "init"):
                    continue

                if not autocomplete_tests and nm.startswith(
                    ("Test", "Benchmark", "Example")
                ):
                    continue

            if is_func or is_func_type:
                s_sfx = u"\u0282"
                t_sfx = gs.CLASS_PREFIXES.get("type", "")
                f_sfx = gs.CLASS_PREFIXES.get("func", "")
                params, ret = declex(tn)
                decl = []
                for i, p in enumerate(params):
                    n, t = p
                    if t.startswith("..."):
                        n = "..."
                    decl.append("${%d:%s}" % (i + 1, n))
                decl = ", ".join(decl)
                ret = ret.strip("() ")

                if is_func:
                    if func_name_only:
                        comps.append(("%s\t%s %s" % (nm, ret, f_sfx), nm))
                    else:
                        comps.append(
                            ("%s\t%s %s" % (nm, ret, f_sfx), "%s(%s)" % (nm, decl))
                        )
                else:
                    comps.append(("%s\t%s %s" % (nm, tn, t_sfx), nm))

                    if autocomplete_closures:
                        comps.append(
                            (
                                "%s {}\tfunc() {...} %s" % (nm, s_sfx),
                                "%s {\n\t${0}\n}" % tn,
                            )
                        )
            elif cn != "PANIC":
                comps.append(
                    ("%s\t%s %s" % (nm, tn, self.typeclass_prefix(cn, tn)), nm)
                )
        return comps
Example #5
0
	def complete(self, fn, offset, src, func_name_only):
		comps = []
		autocomplete_tests = gs.setting('autocomplete_tests', False)
		autocomplete_closures = gs.setting('autocomplete_closures', False)
		res, err = mg9.complete(fn, src, offset)
		if err:
			ui.error(DOMAIN, err)

		ents = res['Candidates']
		if not ents and gs.setting('autocomplete_suggest_imports') is True:
			self.suggest(res['Suggestions'])

		name_fx = None
		name_fx_pat = gs.setting('autocomplete_filter_name')
		if name_fx_pat:
			try:
				name_fx = re.compile(name_fx_pat)
			except Exception as ex:
				ui.error(DOMAIN, 'Cannot filter completions: %s' % ex)

		in_iface = GoSublime.current_interface['name'] in GoSublime.INTERFACES and src[offset-1:offset] == '.'
		for ent in ents:
			if name_fx and name_fx.search(ent['name']):
				continue

			tn = ent['type']
			cn = ent['class']
			nm = ent['name']
			is_func = (cn == 'func')
			is_func_type = (cn == 'type' and tn.startswith('func('))
			
			if cn == 'type' and tn == 'interface' and nm not in GoSublime.INTERFACES:
				GoSublime.INTERFACES.append(nm)

			if in_iface:
				tmpl = '//Implementing %s·%s\nfunc (${1:this} ${2:*struct_name}) %s%s {\n\t$0\n}\n'
				if cn == 'func' and tn != 'built-in':
					sig = tmpl % (GoSublime.current_interface['name'], nm, nm, tn[4:])
					GoSublime.current_interface['funcs'].append(sig)

			if is_func:
				if nm in ('main', 'init'):
					continue

				if not autocomplete_tests and nm.startswith(('Test', 'Benchmark', 'Example')):
					continue

			if is_func or is_func_type:
				s_sfx = u'\u0282'
				t_sfx = gs.CLASS_PREFIXES.get('type', '')
				f_sfx = gs.CLASS_PREFIXES.get('func', '')
				params, ret = declex(tn)
				decl = []
				for i, p in enumerate(params):
					n, t = p
					if t.startswith('...'):
						n = '...'
					decl.append('${%d:%s}' % (i+1, n))
				decl = ', '.join(decl)
				ret = ret.strip('() ')

				if is_func:
					if func_name_only:
						comps.append((
							'%s\t%s %s' % (nm, ret, f_sfx),
							nm,
						))
					else:
						comps.append((
							'%s\t%s %s' % (nm, ret, f_sfx),
							'%s(%s)' % (nm, decl),
						))
				else:
					comps.append((
						'%s\t%s %s' % (nm, tn, t_sfx),
						nm,
					))

					if autocomplete_closures:
						comps.append((
							'%s {}\tfunc() {...} %s' % (nm, s_sfx),
							'%s {\n\t${0}\n}' % tn,
						))
			elif cn != 'PANIC':
				comps.append((
					'%s\t%s %s' % (nm, tn, self.typeclass_prefix(cn, tn)),
					nm,
				))
		if len(GoSublime.current_interface['funcs']) > 0 :
			comps.insert(0,('Implement Interface','\n'.join(GoSublime.current_interface['funcs']) + '\n'))
		else:
			self.not_in_scope = True
			# GoSublime.current_interface = []

		return comps
Example #6
0
    def run(self, edit):
        view = self.view
        pt = gs.sel(view).begin()
        if view.substr(sublime.Region(pt - 1, pt)) == '(':
            depth = 1
        else:
            depth = 0
        c = ''
        while True:
            line = view.line(pt)
            scope = view.scope_name(pt)
            if 'string' in scope or 'comment' in scope:
                pt = view.extract_scope(pt).begin() - 1
                continue

            c = view.substr(sublime.Region(pt - 1, pt))
            if not c:
                pt = -1
                break

            if c.isalpha() and depth >= 0:
                while c.isalpha() or c == '.':
                    pt += 1
                    c = view.substr(sublime.Region(pt - 1, pt))

                # curly braces ftw
                break  # break outer while loop
            if c == ')':
                depth -= 1
            elif c == '(':
                depth += 1
                i = pt
                while True:
                    pc = view.substr(sublime.Region(i - 1, i))
                    if pc == '.' or pc.isalpha():
                        i -= 1
                    else:
                        break

                if i != pt:
                    pt = i
                    continue

            pt -= 1
            if pt <= line.begin():
                pt = -1
                break

        while not c.isalpha() and pt > 0:
            pt -= 1
            c = view.substr(sublime.Region(pt - 1, pt))

        if pt <= 0 or view.scope_name(pt).strip() == 'source.go':
            self.show_hint("// can't find selector")
            return

        line = view.line(pt)
        line_start = line.begin()

        s = view.substr(line)
        if not s:
            self.show_hint('// no source')
            return

        scopes = [
            'support.function.any-method.go',
            'meta.function-call.go',
            'support.function.builtin.go',
        ]
        found = False
        while True:
            scope = view.scope_name(pt).strip()
            for s in scopes:
                if scope.endswith(s):
                    found = True
                    break

            if found or pt <= line_start:
                break

            pt -= 1

        if not found:
            self.show_hint("// can't find function call")
            return

        s = view.substr(sublime.Region(line_start, pt))
        m = END_SELECTOR_PAT.match(s)
        if not m:
            self.show_hint("// can't match selector")
            return

        offset = (line_start + m.end())
        sel = m.group(1)
        name = m.group(2)
        candidates = []
        src = view.substr(sublime.Region(0, view.size()))
        fn = view.file_name()
        candidates, err = mg9.complete(fn, src, offset)
        if err:
            gs.notice(DOMAIN, err)
        else:
            c = {}
            for i in candidates:
                if i['name'] == name:
                    if c:
                        c = None
                        break
                    c = i

            if not c:
                self.show_hint('// no candidates found')
                return

            s = '// %s %s\n%s' % (c['name'], c['class'], c['type'])
            self.show_hint(s)