def run(self, edit):
        view = self.view
        pos = gs.sel(view).begin()
        line = view.line(pos)
        wd = view.settings().get('9o.wd')

        ln = view.substr(line).split('#', 1)
        if len(ln) == 2:
            cmd = ln[1].strip()
            if cmd:
                vs = view.settings()
                lc_key = '%s.last_command' % DOMAIN
                if cmd.startswith('#'):
                    rep = vs.get(lc_key, '')
                    if rep:
                        view.replace(edit, line,
                                     ('%s# %s %s' %
                                      (ln[0], rep, cmd.lstrip('# \t'))))
                    return
                elif cmd == '!!':
                    cmd = vs.get(lc_key, '')
                else:
                    vs.set(lc_key, cmd)

            if not cmd:
                view.run_command('gs9o_init')
                return

            view.replace(edit, line, (u'[ %s %s ]' % (cmd, HOURGLASS)))
            rkey = '9o.exec.%s' % uuid.uuid4()
            view.add_regions(rkey, [sublime.Region(line.begin(), view.size())],
                             '')
            view.run_command('gs9o_init')

            cli = cmd.split(' ', 1)

            # todo: move this into margo
            if cli[0] == 'sh':

                def on_done(c):
                    out = gs.ustr('\n'.join(c.consume_outq()))
                    sublime.set_timeout(lambda: push_output(view, rkey, out),
                                        0)

                c = gsshell.Command(cmd=cli[1], shell=True, cwd=wd)
                c.on_done = on_done
                c.start()
                return

            f = globals().get('cmd_%s' % cli[0])
            if f:
                args = shlex.split(gs.astr(cli[1])) if len(cli) == 2 else []
                f(view, edit, args, wd, rkey)
            else:
                push_output(view, rkey, 'Invalid command %s' % cli)
        else:
            view.insert(edit, gs.sel(view).begin(), '\n')
Beispiel #2
0
	def run(self, edit):
		view = self.view
		pos = gs.sel(view).begin()
		line = view.line(pos)
		wd = view.settings().get('9o.wd')

		ln = view.substr(line).split('#', 1)
		if len(ln) == 2:
			cmd = ln[1].strip()
			if cmd:
				vs = view.settings()
				lc_key = '%s.last_command' % DOMAIN
				if cmd.startswith('#'):
					rep = vs.get(lc_key, '')
					if rep:
						view.replace(edit, line, ('%s# %s %s' % (ln[0], rep, cmd.lstrip('# \t'))))
					return
				elif cmd == '!!':
					cmd = vs.get(lc_key, '')
				else:
					vs.set(lc_key, cmd)

			if not cmd:
				view.run_command('gs9o_init')
				return

			view.replace(edit, line, (u'[ %s %s ]' % (cmd, HOURGLASS)))
			rkey = '9o.exec.%s' % uuid.uuid4()
			view.add_regions(rkey, [sublime.Region(line.begin(), view.size())], '')
			view.run_command('gs9o_init')

			cli = cmd.split(' ', 1)

			# todo: move this into margo
			if cli[0] == 'sh':
				def on_done(c):
					out = gs.ustr('\n'.join(c.consume_outq()))
					sublime.set_timeout(lambda: push_output(view, rkey, out), 0)

				c = gsshell.Command(cmd=cli[1], shell=True, cwd=wd)
				c.on_done = on_done
				c.start()
				return

			f = globals().get('cmd_%s' % cli[0])
			if f:
				args = shlex.split(gs.astr(cli[1])) if len(cli) == 2 else []
				f(view, edit, args, wd, rkey)
			else:
				push_output(view, rkey, 'Invalid command %s' % cli)
		else:
			view.insert(edit, gs.sel(view).begin(), '\n')
 def on_query_completions(self, view, prefix, locations):
     pos = gs.sel(view).begin()
     if view.score_selector(pos, 'text.9o') == 0:
         return []
     cl = []
     cl.extend(DEFAULT_CL)
     return (cl, AC_OPTS)
	def run(self, edit):
		v = self.view
		pos = gs.sel(v).begin()
		inscope = lambda p: v.score_selector(p, 'path.gscommander') > 0
		if not inscope(pos):
			pos -= 1
			if not inscope(pos):
				return

		path = v.substr(v.extract_scope(pos))
		if URL_PATH_PAT.match(path):
			try:
				if not URL_SCHEME_PAT.match(path):
					path = 'http://%s' % path
				gs.notice(DOMAIN, 'open url: %s' % path)
				webbrowser.open_new_tab(path)
			except Exception:
				gs.notice(DOMAIN, gs.traceback())
		else:
			wd = v.settings().get('gscommander.wd') or active_wd()
			m = SPLIT_FN_POS_PAT.match(path)
			path = gs.apath((m.group(1) if m else path), wd)
			row = max(0, int(m.group(2))-1 if (m and m.group(2)) else 0)
			col = max(0, int(m.group(3))-1 if (m and m.group(3)) else 0)

			if os.path.exists(path):
				gs.focus(path, row, col, win=self.view.window())
			else:
				gs.notice(DOMAIN, "Invalid path `%s'" % path)
Beispiel #5
0
 def run(self, edit):
     view = self.view
     if gs.is_go_source_view(view):
         if not gstest.handle_action(view, "left-click"):
             view.run_command("gs_doc", {"mode": "goto"})
     elif view.score_selector(gs.sel(view).begin(), "text.9o") > 0:
         view.window().run_command("gs9o_open_selection")
Beispiel #6
0
    def run(self, edit):
        v = self.view
        pos = gs.sel(v).begin()
        inscope = lambda p: v.score_selector(p, 'path.9o') > 0
        if not inscope(pos):
            pos -= 1
            if not inscope(pos):
                return

        path = v.substr(v.extract_scope(pos))
        if URL_PATH_PAT.match(path):
            if path.lower().startswith('gs.packages://'):
                path = os.path.join(sublime.packages_path(), path[14:])
            else:
                try:
                    if not URL_SCHEME_PAT.match(path):
                        path = 'http://%s' % path
                    gs.notify(DOMAIN, 'open url: %s' % path)
                    webbrowser.open_new_tab(path)
                except Exception:
                    gs.error_traceback(DOMAIN)

                return

        wd = v.settings().get('9o.wd') or active_wd()
        m = SPLIT_FN_POS_PAT.match(path)
        path = gs.apath((m.group(1) if m else path), wd)
        row = max(0, int(m.group(2)) - 1 if (m and m.group(2)) else 0)
        col = max(0, int(m.group(3)) - 1 if (m and m.group(3)) else 0)

        if os.path.exists(path):
            gs.focus(path, row, col, win=self.view.window())
        else:
            gs.notify(DOMAIN, "Invalid path `%s'" % path)
Beispiel #7
0
	def run(self, edit):
		v = self.view
		pos = gs.sel(v).begin()
		inscope = lambda p: v.score_selector(p, 'path.9o') > 0
		if not inscope(pos):
			pos -= 1
			if not inscope(pos):
				return

		path = v.substr(v.extract_scope(pos))
		if URL_PATH_PAT.match(path):
			try:
				if not URL_SCHEME_PAT.match(path):
					path = 'http://%s' % path
				gs.notice(DOMAIN, 'open url: %s' % path)
				webbrowser.open_new_tab(path)
			except Exception:
				gs.notice(DOMAIN, gs.traceback())
		else:
			wd = v.settings().get('9o.wd') or active_wd()
			m = SPLIT_FN_POS_PAT.match(path)
			path = gs.apath((m.group(1) if m else path), wd)
			row = max(0, int(m.group(2))-1 if (m and m.group(2)) else 0)
			col = max(0, int(m.group(3))-1 if (m and m.group(3)) else 0)

			if os.path.exists(path):
				gs.focus(path, row, col, win=self.view.window())
			else:
				gs.notice(DOMAIN, "Invalid path `%s'" % path)
Beispiel #8
0
	def on_query_completions(self, view, prefix, locations):
		pos = gs.sel(view).begin()
		if view.score_selector(pos, 'text.9o') == 0:
			return []
		cl = []
		cl.extend(DEFAULT_CL)
		return (cl, AC_OPTS)
Beispiel #9
0
	def run(self, edit, after=True):
		insln = lambda: self.view.insert(edit, gs.sel(self.view).begin(), "\n")
		if after:
			self.view.run_command("move_to", {"to": "hardeol"})
			insln()
		else:
			self.view.run_command("move_to", {"to": "hardbol"})
			insln()
			self.view.run_command("move", {"by": "lines", "forward": False})
Beispiel #10
0
 def run(self, edit, after=True):
     insln = lambda: self.view.insert(edit, gs.sel(self.view).begin(), "\n")
     if after:
         self.view.run_command("move_to", {"to": "hardeol"})
         insln()
     else:
         self.view.run_command("move_to", {"to": "hardbol"})
         insln()
         self.view.run_command("move", {"by": "lines", "forward": False})
Beispiel #11
0
	def run(self, _, mode=''):
		view = self.view
		if (not gs.is_go_source_view(view)) or (mode not in ['goto', 'hint']):
			return

		pt = gs.sel(view).begin()
		src = view.substr(sublime.Region(0, view.size()))
		def f(docs, err):
			doc = ''
			if err:
				self.show_output('// Error: %s' % err)
			elif docs:
				if mode == "goto":
					fn = ''
					flags = 0
					if len(docs) > 0:
						d = docs[0]
						fn = d.get('fn', '')
						row = d.get('row', 0)
						col = d.get('col', 0)
						if fn:
							gs.println('opening %s:%s:%s' % (fn, row, col))
							gs.focus(fn, row, col)
							return
					self.show_output("%s: cannot find definition" % DOMAIN)
				elif mode == "hint":
					s = []
					for d in docs:
						name = d.get('name', '')
						if name:
							kind = d.get('kind', '')
							pkg = d.get('pkg', '')
							if pkg:
								name = '%s.%s' % (pkg, name)
							src = d.get('src', '')
							if src:
								src = '\n//\n%s' % src
							doc = '// %s %s%s' % (name, kind, src)

						s.append(doc)
					doc = '\n\n\n'.join(s).strip()
			self.show_output(doc or "// %s: no docs found" % DOMAIN)

		margo.call(
			path='/doc',
			args={
				'fn': view.file_name(),
				'src': src,
				'offset': pt,
			},
			default=[],
			cb=f,
			message='fetching docs'
		)
Beispiel #12
0
    def run(self, _, mode=''):
        view = self.view
        if (not gs.is_go_source_view(view)) or (mode not in ['goto', 'hint']):
            return

        pt = gs.sel(view).begin()
        src = view.substr(sublime.Region(0, view.size()))

        def f(docs, err):
            doc = ''
            if err:
                self.show_output('// Error: %s' % err)
            elif docs:
                if mode == "goto":
                    fn = ''
                    flags = 0
                    if len(docs) > 0:
                        d = docs[0]
                        fn = d.get('fn', '')
                        row = d.get('row', 0)
                        col = d.get('col', 0)
                        if fn:
                            gs.println('opening %s:%s:%s' % (fn, row, col))
                            gs.focus(fn, row, col)
                            return
                    self.show_output("%s: cannot find definition" % DOMAIN)
                elif mode == "hint":
                    s = []
                    for d in docs:
                        name = d.get('name', '')
                        if name:
                            kind = d.get('kind', '')
                            pkg = d.get('pkg', '')
                            if pkg:
                                name = '%s.%s' % (pkg, name)
                            src = d.get('src', '')
                            if src:
                                src = '\n//\n%s' % src
                            doc = '// %s %s%s' % (name, kind, src)

                        s.append(doc)
                    doc = '\n\n\n'.join(s).strip()
            self.show_output(doc or "// %s: no docs found" % DOMAIN)

        margo.call(path='/doc',
                   args={
                       'fn': view.file_name(),
                       'src': src,
                       'offset': pt,
                   },
                   default=[],
                   cb=f,
                   message='fetching docs')
Beispiel #13
0
    def run(self, _, mode=""):
        view = self.view
        if (not gs.is_go_source_view(view)) or (mode not in ["goto", "hint"]):
            return

        pt = gs.sel(view).begin()
        src = view.substr(sublime.Region(0, view.size()))

        def f(docs, err):
            doc = ""
            if err:
                self.show_output("// Error: %s" % err)
            elif docs:
                if mode == "goto":
                    fn = ""
                    flags = 0
                    if len(docs) > 0:
                        d = docs[0]
                        fn = d.get("fn", "")
                        row = d.get("row", 0)
                        col = d.get("col", 0)
                        if fn:
                            gs.println("opening %s:%s:%s" % (fn, row, col))
                            gs.focus(fn, row, col)
                            return
                    self.show_output("%s: cannot find definition" % DOMAIN)
                elif mode == "hint":
                    s = []
                    for d in docs:
                        name = d.get("name", "")
                        if name:
                            kind = d.get("kind", "")
                            pkg = d.get("pkg", "")
                            if pkg:
                                name = "%s.%s" % (pkg, name)
                            src = d.get("src", "")
                            if src:
                                src = "\n//\n%s" % src
                            doc = "// %s %s%s" % (name, kind, src)

                        s.append(doc)
                    doc = "\n\n\n".join(s).strip()
            self.show_output(doc or "// %s: no docs found" % DOMAIN)

        margo.call(
            path="/doc",
            args={"fn": view.file_name(), "src": src, "offset": pt},
            default=[],
            cb=f,
            message="fetching docs",
        )
Beispiel #14
0
	def on_query_completions(self, view, prefix, locations):
		pos = gs.sel(view).begin()
		if view.score_selector(pos, 'text.9o') == 0:
			return []

		cl = []

		hkey = '9o.hist.%s' % view.settings().get('9o.wd', '')
		for i, cmd in enumerate(reversed(gs.dval(gs.aso().get(hkey), []))):
			if not cmd in cl:
				cl.append(('^%d %s' % (i+1, cmd), cmd+' '))

		cl.extend(DEFAULT_CL)

		return (cl, AC_OPTS)
Beispiel #15
0
    def on_query_completions(self, view, prefix, locations):
        pos = gs.sel(view).begin()
        if view.score_selector(pos, 'text.9o') == 0:
            return []

        cl = []

        hkey = '9o.hist.%s' % view.settings().get('9o.wd', '')
        for i, cmd in enumerate(reversed(gs.dval(gs.aso().get(hkey), []))):
            if not cmd in cl:
                cl.append(('^%d %s' % (i + 1, cmd), cmd + ' '))

        cl.extend(DEFAULT_CL)

        return (cl, AC_OPTS)
def handle_action(view, action):
    prefix, name = match_prefix_name(view.substr(view.word(gs.sel(view))))
    ok = prefix != ''
    if ok:
        if action == 'right-click':
            pat = '^%s.*' % prefix
        else:
            pat = '^%s$' % name

        if prefix == 'Benchmark':
            cmd = ['go', 'test', '-test.run=none', '-test.bench="%s"' % pat]
        else:
            cmd = ['go', 'test', '-test.run="%s"' % pat]

        view.run_command('gs9o_open', {'run': cmd})

    return ok
Beispiel #17
0
def handle_action(view, action):
	prefix, name = match_prefix_name(view.substr(view.word(gs.sel(view))))
	ok = prefix != ''
	if ok:
		if action == 'right-click':
			pat = '^%s.*' % prefix
		else:
			pat = '^%s$' % name

		if prefix == 'Benchmark':
			cmd = ['go', 'test', '-test.run=none', '-test.bench="%s"' % pat]
		else:
			cmd = ['go', 'test', '-test.run="%s"' % pat]

		view.run_command('gs9o_open', {'run': cmd})

	return ok
Beispiel #18
0
def highlight(fr):
    sel = gs.sel(fr.view).begin()
    row, _ = fr.view.rowcol(sel)

    if fr.state == 1:
        fr.state = 0
        cleanup(fr.view)

        regions = []
        regions0 = []
        domain0 = DOMAIN + '-zero'
        for r in fr.reports.values():
            line = fr.view.line(fr.view.text_point(r.row, 0))
            pos = line.begin() + r.col
            if pos >= line.end():
                pos = line.end()
            if pos == line.begin():
                regions0.append(sublime.Region(pos, pos))
            else:
                regions.append(sublime.Region(pos, pos))

        if regions:
            fr.view.add_regions(DOMAIN, regions, 'comment', 'dot',
                                sublime.DRAW_EMPTY_AS_OVERWRITE)
        else:
            fr.view.erase_regions(DOMAIN)

        if regions0:
            fr.view.add_regions(domain0, regions0, 'comment', 'dot',
                                sublime.HIDDEN)
        else:
            fr.view.erase_regions(domain0)

    msg = ''
    reps = fr.reports.copy()
    l = len(reps)
    if l > 0:
        msg = '%s (%d)' % (DOMAIN, l)
        r = reps.get(row)
        if r and r.msg:
            msg = '%s: %s' % (msg, r.msg)

    if fr.state != 0:
        msg = u'\u231B %s' % msg

    fr.view.set_status(DOMAIN, msg)
Beispiel #19
0
def handle_action(view, action):
    fn = view.file_name()
    prefix, name = match_prefix_name(view.substr(view.word(gs.sel(view))))
    ok = prefix and fn and fn.endswith("_test.go")
    if ok:
        if action == "right-click":
            pat = "^%s.*" % prefix
        else:
            pat = "^%s$" % name

        if prefix == "Benchmark":
            cmd = ["go", "test", "-test.run=none", '-test.bench="%s"' % pat]
        else:
            cmd = ["go", "test", '-test.run="%s"' % pat]

        view.run_command("gs9o_open", {"run": cmd})

    return ok
Beispiel #20
0
def highlight(fr):
	sel = gs.sel(fr.view).begin()
	row, _ = fr.view.rowcol(sel)

	if fr.state == 1:
		fr.state = 0
		cleanup(fr.view)

		regions = []
		regions0 = []
		domain0 = DOMAIN+'-zero'
		for r in fr.reports.values():
			line = fr.view.line(fr.view.text_point(r.row, 0))
			pos = line.begin() + r.col
			if pos >= line.end():
				pos = line.end()
			if pos == line.begin():
				regions0.append(sublime.Region(pos, pos))
			else:
				regions.append(sublime.Region(pos, pos))

		if regions:
			fr.view.add_regions(DOMAIN, regions, 'comment', 'dot', sublime.DRAW_EMPTY_AS_OVERWRITE)
		else:
			fr.view.erase_regions(DOMAIN)

		if regions0:
			fr.view.add_regions(domain0, regions0, 'comment', 'dot', sublime.HIDDEN)
		else:
			fr.view.erase_regions(domain0)

	msg = ''
	reps = fr.reports.copy()
	l = len(reps)
	if l > 0:
		msg = '%s (%d)' % (DOMAIN, l)
		r = reps.get(row)
		if r and r.msg:
			msg = '%s: %s' % (msg, r.msg)

	if fr.state != 0:
		msg = u'\u231B %s' % msg

	fr.view.set_status(DOMAIN, msg)
Beispiel #21
0
	def run(self, edit):
		if gs.is_go_source_view(self.view):
			self.view.run_command('gs_doc', {"mode": "goto"})
		elif self.view.score_selector(gs.sel(self.view).begin(), "text.9o") > 0:
			self.view.window().run_command("gs9o_open_selection")
Beispiel #22
0
    def run(self, edit, save_hist=False):
        view = self.view
        pos = gs.sel(view).begin()
        line = view.line(pos)
        wd = view.settings().get('9o.wd')

        ln = view.substr(line).split('#', 1)
        if len(ln) == 2:
            cmd = ln[1].strip()
            if cmd:
                vs = view.settings()
                aso = gs.aso()
                hkey = '9o.hist.%s' % wd
                hist = gs.dval(aso.get(hkey), [])

                m = HIST_EXPAND_PAT.match(cmd)
                if m:
                    pfx = m.group(1)
                    hl = len(hist)
                    idx = hl - int(m.group(2))
                    cmd = ''
                    if idx >= 0 and idx < hl:
                        cmd = hist[idx]

                    if pfx == '^' or not cmd:
                        view.replace(edit, line, ('%s# %s' % (ln[0], cmd)))
                        return
                elif save_hist:
                    try:
                        hist.remove(cmd)
                    except ValueError:
                        pass
                    hist.append(cmd)
                    aso.set(hkey, hist)
                    gs.save_aso()

            if not cmd:
                view.run_command('gs9o_init')
                return

            view.replace(edit, line, (u'[ `%s` %s ]' % (cmd, HOURGLASS)))
            rkey = '9o.exec.%s' % uuid.uuid4()
            view.add_regions(rkey, [sublime.Region(line.begin(), view.size())],
                             '')
            view.run_command('gs9o_init')

            cli = cmd.split(' ', 1)

            # todo: move this into margo
            if cli[0] == 'sh':

                def on_done(c):
                    out = gs.ustr('\n'.join(c.consume_outq()))
                    sublime.set_timeout(lambda: push_output(view, rkey, out),
                                        0)

                c = gsshell.Command(cmd=cli[1], shell=True, cwd=wd)
                c.on_done = on_done
                c.start()
                return

            f = globals().get('cmd_%s' % cli[0])
            if f:
                args = shlex.split(gs.astr(cli[1])) if len(cli) == 2 else []
                f(view, edit, args, wd, rkey)
            else:
                push_output(view, rkey, 'Invalid command %s' % cli)
        else:
            view.insert(edit, gs.sel(view).begin(), '\n')
Beispiel #23
0
 def is_enabled(self):
     pos = gs.sel(self.view).begin()
     return self.view.score_selector(pos, 'text.9o') > 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())
		coffset = 'c%d' % offset
		sel = m.group(1)
		name = m.group(2)
		candidates = []
		src = view.substr(sublime.Region(0, view.size()))
		fn = view.file_name() or '<stdin>'
		cmd = gs.setting('gocode_cmd', 'gocode')
		args = [cmd, "-f=json", "autocomplete", fn, coffset]
		js, err, _ = gs.runcmd(args, src)
		if err:
			gs.notice(DOMAIN, err)
		else:
			try:
				js = json.loads(js)
				if js and js[1]:
					candidates = js[1]
			except:
				pass

		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)
Beispiel #25
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)
Beispiel #26
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)
Beispiel #27
0
	def run(self, edit):
		view = self.view
		pos = gs.sel(view).begin()
		line = view.line(pos)
		wd = view.settings().get('9o.wd')

		ln = view.substr(line).split('#', 1)
		if len(ln) == 2:
			cmd = ln[1].strip()
			if cmd:
				vs = view.settings()
				aso = gs.aso()
				hkey = '9o.hist.%s' % wd
				hist = gs.dval(aso.get(hkey), [])

				m = HIST_EXPAND_PAT.match(cmd)
				if m:
					pfx = m.group(1)
					idx = int(m.group(2))-1
					cmd = hist[-idx] if idx < len(hist) else ''
					if pfx == '^' or not cmd:
						view.replace(edit, line, ('%s# %s' % (ln[0], cmd)))
						return
				else:
					try:
						hist.remove(cmd)
					except ValueError:
						pass
					hist.append(cmd)
					aso.set(hkey, hist)
					gs.save_aso()

			if not cmd:
				view.run_command('gs9o_init')
				return

			view.replace(edit, line, (u'[ `%s` %s ]' % (cmd, HOURGLASS)))
			rkey = '9o.exec.%s' % uuid.uuid4()
			view.add_regions(rkey, [sublime.Region(line.begin(), view.size())], '')
			view.run_command('gs9o_init')

			cli = cmd.split(' ', 1)

			# todo: move this into margo
			if cli[0] == 'sh':
				def on_done(c):
					out = gs.ustr('\n'.join(c.consume_outq()))
					sublime.set_timeout(lambda: push_output(view, rkey, out), 0)

				c = gsshell.Command(cmd=cli[1], shell=True, cwd=wd)
				c.on_done = on_done
				c.start()
				return

			f = globals().get('cmd_%s' % cli[0])
			if f:
				args = shlex.split(gs.astr(cli[1])) if len(cli) == 2 else []
				f(view, edit, args, wd, rkey)
			else:
				push_output(view, rkey, 'Invalid command %s' % cli)
		else:
			view.insert(edit, gs.sel(view).begin(), '\n')
Beispiel #28
0
	def is_enabled(self):
		pos = gs.sel(self.view).begin()
		return self.view.score_selector(pos, 'text.9o') > 0
Beispiel #29
0
 def run(self, edit):
     if gs.is_go_source_view(self.view):
         self.view.run_command('gs_doc', {"mode": "goto"})
     elif self.view.score_selector(gs.sel(self.view).begin(),
                                   "text.9o") > 0:
         self.view.window().run_command("gs9o_open_selection")