コード例 #1
0
def imports(fn, src, toggle):
	return bcall('imports', {
		'fn': fn or '',
		'src': src or '',
		'toggle': toggle or [],
		'tabIndent': gs.setting('fmt_tab_indent'),
		'tabWidth': gs.setting('fmt_tab_width'),
	})
コード例 #2
0
ファイル: mg9.py プロジェクト: charlievieth/GoSubl
def complete(fn, src, pos):
    builtins = (
        gs.setting("autocomplete_builtins") is True
        or gs.setting("complete_builtins") is True
    )
    res, err = bcall("gocode_complete", _complete_opts(fn, src, pos, builtins))
    res = gs.dval(res.get("Candidates"), [])
    return res, err
コード例 #3
0
def fmt(fn, src):
	res, err = bcall('fmt', {
		'fn': fn or '',
		'src': src or '',
		'tabIndent': gs.setting('fmt_tab_indent'),
		'tabWidth': gs.setting('fmt_tab_width'),
	})
	return res.get('src', ''), err
コード例 #4
0
def watch():
    global file_refs
    global th

    view = gs.active_valid_go_view()

    if view is not None and (view.file_name()
                             and gs.setting('comp_lint_enabled') is True):
        fn = view.file_name()
        fr = ref(fn)
        with sem:
            if fr:
                fr.view = view
                highlight(fr)
        sublime.set_timeout(watch, 500)
        return

    if gs.setting('gslint_enabled') is not True:
        if view:
            with sem:
                for fn in file_refs:
                    fr = file_refs[fn]
                    cleanup(fr.view)
                file_refs = {}
        sublime.set_timeout(watch, 2000)
        return

    if view and not view.is_loading():
        fn = view.file_name()
        fr = ref(fn)
        with sem:
            if fr:
                # always use the active view (e.g in split-panes)
                fr.view = view
                highlight(fr)
            else:
                fr = FileRef(view)

            file_refs[fn] = fr
            if fr.state == 0:
                src = view.substr(sublime.Region(0, view.size()))
                if src != fr.src:
                    fr.src = src
                    fr.tm = time.time()

                if fr.tm > 0.0:
                    timeout = int(gs.setting('gslint_timeout', 500))
                    delta = int((time.time() - fr.tm) * 1000.0)
                    if delta >= timeout:
                        fr.tm = 0.0
                        fr.state = -1
                        if not th:
                            th = GsLintThread()
                            th.start()
                        th.putq(fn)

    sublime.set_timeout(watch, 500)
コード例 #5
0
ファイル: gslint.py プロジェクト: 905522052/GoSublime
def watch():
	global file_refs
	global th

	view = gs.active_valid_go_view()

	if view is not None and (view.file_name() and gs.setting('comp_lint_enabled') is True):
		fn = view.file_name()
		fr = ref(fn)
		with sem:
			if fr:
				fr.view = view
				highlight(fr)
		sublime.set_timeout(watch, 500)
		return


	if gs.setting('gslint_enabled') is not True:
		if view:
			with sem:
				for fn in file_refs:
					fr = file_refs[fn]
					cleanup(fr.view)
				file_refs = {}
		sublime.set_timeout(watch, 2000)
		return

	if view and not view.is_loading():
		fn = view.file_name()
		fr = ref(fn)
		with sem:
			if fr:
				# always use the active view (e.g in split-panes)
				fr.view = view
				highlight(fr)
			else:
				fr = FileRef(view)

			file_refs[fn] = fr
			if fr.state == 0:
				src = view.substr(sublime.Region(0, view.size()))
				if src != fr.src:
					fr.src = src
					fr.tm = time.time()

				if fr.tm > 0.0:
					timeout = int(gs.setting('gslint_timeout', 500))
					delta = int((time.time() - fr.tm) * 1000.0)
					if delta >= timeout:
						fr.tm = 0.0
						fr.state = -1
						if not th:
							th = GsLintThread()
							th.start()
						th.putq(fn)

	sublime.set_timeout(watch, 500)
コード例 #6
0
ファイル: mg9.py プロジェクト: vivicai/GoSublime
def imports(fn, src, toggle):
    return bcall(
        "imports",
        {
            "fn": fn or "",
            "src": src or "",
            "toggle": toggle or [],
            "tabIndent": gs.setting("fmt_tab_indent"),
            "tabWidth": gs.setting("fmt_tab_width"),
        },
    )
コード例 #7
0
ファイル: mg9.py プロジェクト: vivicai/GoSublime
def fmt(fn, src):
    res, err = bcall(
        "fmt",
        {
            "fn": fn or "",
            "src": src or "",
            "tabIndent": gs.setting("fmt_tab_indent"),
            "tabWidth": gs.setting("fmt_tab_width"),
        },
    )
    return res.get("src", ""), err
コード例 #8
0
ファイル: mg9.py プロジェクト: vivicai/GoSublime
def _complete_opts(fn, src, pos):
    home = gs.home_path()
    builtins = gs.setting("autocomplete_builtins") is True or gs.setting("complete_builtins") is True
    return {
        "Dir": gs.basedir_or_cwd(fn),
        "Builtins": builtins,
        "Fn": fn or "",
        "Src": src or "",
        "Pos": pos or 0,
        "Home": home,
        "Env": gs.env({"XDG_CONFIG_HOME": home}),
    }
コード例 #9
0
ファイル: mg9.py プロジェクト: charlievieth/GoSubl
def _complete_opts(fn, src, pos, builtins):
    nv = sh.env()
    return {
        "Dir": gs.basedir_or_cwd(fn),
        "Builtins": builtins,
        "Fn": fn or "",
        "Src": src or "",
        "Pos": pos or 0,
        "Home": sh.vdir(),
        "Autoinst": gs.setting("autoinst"),
        "InstallSuffix": gs.setting("installsuffix", ""),
        "Env": {"GOROOT": nv.get("GOROOT", ""), "GOPATH": nv.get("GOPATH", "")},
    }
コード例 #10
0
ファイル: mg9.py プロジェクト: campoy/GoSublime-next
def import_paths(fn, src, f):
	tid = gs.begin(DOMAIN, 'Fetching import paths')
	def cb(res, err):
		gs.end(tid)
		f(res, err)

	acall('import_paths', {
		'fn': fn or '',
		'src': src or '',
		'env': sh.env(),
		'WantPkgNames': gs.setting('use_named_imports'),
		'UseLegacyImports': gs.setting('use_legacy_imports'),
	}, cb)
コード例 #11
0
def _complete_opts(fn, src, pos):
	home = gs.home_path()
	builtins = (gs.setting('autocomplete_builtins') is True or gs.setting('complete_builtins') is True)
	return {
		'Dir': gs.basedir_or_cwd(fn),
		'Builtins': builtins,
		'Fn':  fn or '',
		'Src': src or '',
		'Pos': pos or 0,
		'Home': home,
		'Env': gs.env({
			'XDG_CONFIG_HOME': home,
		}),
	}
コード例 #12
0
def doc(fn, src, offset, f):
	tid = gs.begin(DOMAIN, 'Fetching doc info')
	def cb(res, err):
		gs.end(tid)
		f(res, err)

	acall('doc', {
		'fn': fn or '',
		'src': src or '',
		'offset': offset or 0,
		'env': gs.env(),
		'tabIndent': gs.setting('fmt_tab_indent'),
		'tabWidth': gs.setting('fmt_tab_width'),
	}, cb)
コード例 #13
0
ファイル: mg9.py プロジェクト: allanw1/Arianrhod
def doc(fn, src, offset, f):
	tid = gs.begin(DOMAIN, 'Fetching doc info')
	def cb(res, err):
		gs.end(tid)
		f(res, err)

	acall('doc', {
		'fn': fn or '',
		'src': src or '',
		'offset': offset or 0,
		'env': sh.env(),
		'tabIndent': gs.setting('fmt_tab_indent'),
		'tabWidth': gs.setting('fmt_tab_width'),
	}, cb)
コード例 #14
0
ファイル: mg9.py プロジェクト: charlievieth/GoSubl
def sanity_check(env={}, error_log=False):
    if not env:
        env = sh.env()

    ns = "(not set)"

    sl = [
        ("install state", _inst_state()),
        ("sublime.version", sublime.version()),
        ("sublime.channel", sublime.channel()),
        ("about.ann", gs.attr("about.ann", "")),
        ("about.version", gs.attr("about.version", "")),
        ("version", about.VERSION),
        ("platform", about.PLATFORM),
        ("~bin", "%s" % gs.home_dir_path("bin")),
        ("margo.exe", "%s (%s)" % _tp(_margo_bin())),
        ("go.exe", "%s (%s)" % _tp(sh.which("go") or "go")),
        ("go.version", sh.GO_VERSION),
        ("GOROOT", "%s" % env.get("GOROOT", ns)),
        ("GOPATH", "%s" % env.get("GOPATH", ns)),
        ("GOBIN", "%s (should usually be `%s`)" % (env.get("GOBIN", ns), ns)),
        ("set.shell", str(gs.lst(gs.setting("shell")))),
        ("env.shell", env.get("SHELL", "")),
        ("shell.cmd", str(sh.cmd("${CMD}"))),
    ]

    if error_log:
        try:
            with open(gs.home_path("log.txt"), "r") as f:
                s = f.read().strip()
                sl.append(("error log", s))
        except Exception:
            pass

    return sl
コード例 #15
0
ファイル: mg9.py プロジェクト: allanw1/Arianrhod
def sanity_check(env={}, error_log=False):
	if not env:
		env = sh.env()

	ns = '(not set)'

	sl = [
		('install state', _inst_state()),
		('sublime.version', sublime.version()),
		('sublime.channel', sublime.channel()),
		('about.ann', gs.attr('about.ann', '')),
		('about.version', gs.attr('about.version', '')),
		('version', about.VERSION),
		('platform', about.PLATFORM),
		('~bin', '%s' % gs.home_dir_path('bin')),
		('margo.exe', '%s (%s)' % _tp(_margo_bin())),
		('go.exe', '%s (%s)' % _tp(sh.which('go') or 'go')),
		('go.version', sh.GO_VERSION),
		('GOROOT', '%s' % env.get('GOROOT', ns)),
		('GOPATH', '%s' % env.get('GOPATH', ns)),
		('GOBIN', '%s (should usually be `%s`)' % (env.get('GOBIN', ns), ns)),
		('set.shell', str(gs.lst(gs.setting('shell')))),
		('env.shell', env.get('SHELL', '')),
		('shell.cmd', str(sh.cmd('${CMD}'))),
	]

	if error_log:
		try:
			with open(gs.home_path('log.txt'), 'r') as f:
				s = f.read().strip()
				sl.append(('error log', s))
		except Exception:
			pass

	return sl
コード例 #16
0
ファイル: gsdoc.py プロジェクト: dlclark/GoSublime
def show_pkgfiles(dirname):
	ents = []
	m = {}

	try:
		dirname = os.path.abspath(dirname)
		for fn in gs.list_dir_tree(dirname, ext_filter, gs.setting('fn_exclude_prefixes', [])):
			name = os.path.relpath(fn, dirname).replace('\\', '/')
			m[name] = fn
			ents.append(name)
	except Exception as ex:
		gs.notice(DOMAIN, 'Error: %s' % ex)

	if ents:
		ents.sort(key = lambda a: a.lower())

		try:
			s = " ../  ( current: %s )" % dirname
			m[s] = os.path.join(dirname, "..")
			ents.insert(0, s)
		except Exception:
			pass

		def cb(i, win):
			if i >= 0:
				fn = m[ents[i]]
				if os.path.isdir(fn):
					win.run_command("gs_browse_files", {"dir": fn})
				else:
					gs.focus(fn, 0, 0, win)
		gs.show_quick_panel(ents, cb)
	else:
		gs.show_quick_panel([['', 'No files found']])
コード例 #17
0
ファイル: mg9.py プロジェクト: sirithink/GoSublime
def sanity_check(env={}, error_log=False):
	if not env:
		env = sh.env()

	ns = '(not set)'

	sl = [
		('install state', _inst_state()),
		('sublime.version', sublime.version()),
		('sublime.channel', sublime.channel()),
		('about.ann', gs.attr('about.ann', '')),
		('about.version', gs.attr('about.version', '')),
		('version', about.VERSION),
		('platform', about.PLATFORM),
		('~bin', '%s' % gs.home_dir_path('bin')),
		('margo.exe', '%s (%s)' % _tp(_margo_bin())),
		('go.exe', '%s (%s)' % _tp(sh.which('go') or 'go')),
		('go.version', sh.GO_VERSION),
		('GOROOT', '%s' % env.get('GOROOT', ns)),
		('GOPATH', '%s' % env.get('GOPATH', ns)),
		('GOBIN', '%s (should usually be `%s`)' % (env.get('GOBIN', ns), ns)),
		('set.shell', str(gs.lst(gs.setting('shell')))),
		('env.shell', env.get('SHELL', '')),
		('shell.cmd', str(sh.cmd('${CMD}'))),
	]

	if error_log:
		try:
			with open(gs.home_path('log.txt'), 'r') as f:
				s = f.read().strip()
				sl.append(('error log', s))
		except Exception:
			pass

	return sl
コード例 #18
0
ファイル: mg9.py プロジェクト: AlekSi/GoSublime
def _complete_opts(fn, src, pos, builtins):
	nv = sh.env()
	return {
		'Dir': gs.basedir_or_cwd(fn),
		'Builtins': builtins,
		'Fn':  fn or '',
		'Src': src or '',
		'Pos': pos or 0,
		'Home': sh.vdir(),
		'Autoinst': gs.setting('autoinst'),
		'InstallSuffix': gs.setting('installsuffix', ''),
		'Env': {
			'GOROOT': nv.get('GOROOT', ''),
			'GOPATH': nv.get('GOPATH', ''),
		},
	}
コード例 #19
0
def show_pkgfiles(dirname):
    ents = []
    m = {}

    try:
        dirname = os.path.abspath(dirname)
        for fn in gs.list_dir_tree(dirname, ext_filter,
                                   gs.setting('fn_exclude_prefixes', [])):
            name = os.path.relpath(fn, dirname).replace('\\', '/')
            m[name] = fn
            ents.append(name)
    except Exception as ex:
        gs.notice(DOMAIN, 'Error: %s' % ex)

    if ents:
        ents.sort(key=lambda a: a.lower())

        try:
            s = " ../  ( current: %s )" % dirname
            m[s] = os.path.join(dirname, "..")
            ents.insert(0, s)
        except Exception:
            pass

        def cb(i, win):
            if i >= 0:
                fn = m[ents[i]]
                if os.path.isdir(fn):
                    win.run_command("gs_browse_files", {"dir": fn})
                else:
                    gs.focus(fn, 0, 0, win)

        gs.show_quick_panel(ents, cb)
    else:
        gs.show_quick_panel([['', 'No files found']])
コード例 #20
0
    def run(self, edit, wd=None):
        v = self.view
        vs = v.settings()

        if not wd:
            wd = vs.get('9o.wd', active_wd(win=v.window()))

        was_empty = v.size() == 0
        s = '[ %s ] # \n' % gs.simple_fn(wd)

        if was_empty:
            v.insert(
                edit, 0,
                'GoSublime %s 9o: type `help` for help and command documentation\n\n'
                % about.VERSION)

        if was_empty or v.substr(v.size() - 1) == '\n':
            v.insert(edit, v.size(), s)
        else:
            v.insert(edit, v.size(), '\n' + s)

        v.sel().clear()
        n = v.size() - 1
        v.sel().add(sublime.Region(n, n))
        vs.set("9o.wd", wd)
        vs.set("rulers", [])
        vs.set("fold_buttons", True)
        vs.set("fade_fold_buttons", False)
        vs.set("gutter", True)
        vs.set("margin", 0)
        # pad mostly so the completion menu shows on the first line
        vs.set("line_padding_top", 1)
        vs.set("line_padding_bottom", 1)
        vs.set("tab_size", 2)
        vs.set("word_wrap", True)
        vs.set("indent_subsequent_lines", True)
        vs.set("line_numbers", False)
        vs.set("auto_complete", True)
        vs.set("auto_complete_selector", "text")
        vs.set("highlight_line", True)
        vs.set("draw_indent_guides", True)
        vs.set("scroll_past_end", True)
        vs.set("indent_guide_options", ["draw_normal", "draw_active"])
        vs.set("word_separators", "./\\()\"'-:,.;<>~!@#$%&*|+=[]{}`~?")

        color_scheme = gs.setting("9o_color_scheme", "")
        if color_scheme:
            if color_scheme == "default":
                vs.erase("color_scheme")
            else:
                vs.set("color_scheme", color_scheme)
        else:
            vs.set("color_scheme", "")

        v.set_syntax_file(gs.tm_path('9o'))

        if was_empty:
            v.show(0)
        else:
            v.show(v.size() - 1)
コード例 #21
0
	def run(self):
		while True:
			fn = self.popq()
			fr = ref(fn, False)
			if fr:
				reports = {}
				res, _ = mg9.bcall('lint', {
					'dir': (os.path.dirname(fn) if fn else ''),
					'fn': fn,
					'src': fr.src,
					'filter': gs.setting('lint_filter', []),
				})
				res = gs.dval(res, {})
				for r in gs.dval(res.get('reports'), []):
					if fn and fn != '<stdin>' and r.get('Fn') != fn:
						continue

					kind = r.get('Kind', '')
					row = r.get('Row', 0)
					col = r.get('Col', 0)
					msg = r.get('Message', '')
					msg = '%s: %s' % (kind, msg)
					if row >= 0 and msg:
						reports[row] = Report(row, col, msg)

				fr = ref(fn, False)
				if fr:
					with sem:
						fr.state = 1
						fr.reports = reports
						file_refs[fn] = fr
コード例 #22
0
def _complete_opts(fn, src, pos, builtins):
    nv = sh.env()
    return {
        'Dir': gs.basedir_or_cwd(fn),
        'Builtins': builtins,
        'Fn': fn or '',
        'Src': src or '',
        'Pos': pos or 0,
        'Home': sh.vdir(),
        'Autoinst': gs.setting('autoinst'),
        'InstallSuffix': gs.setting('installsuffix', ''),
        'Env': {
            'GOROOT': nv.get('GOROOT', ''),
            'GOPATH': nv.get('GOPATH', ''),
        },
    }
コード例 #23
0
ファイル: gs9o.py プロジェクト: slene/GoSublime
	def run(self, edit, wd=None):
		v = self.view
		vs = v.settings()

		if not wd:
			wd = vs.get('9o.wd', active_wd(win=v.window()))

		was_empty = v.size() == 0
		s = '[ %s ] # \n' % gs.simple_fn(wd)

		if was_empty:
			v.insert(edit, 0, 'GoSublime %s 9o: type `help` for help and command documentation\n\n' % about.VERSION)

		if was_empty or v.substr(v.size()-1) == '\n':
			v.insert(edit, v.size(), s)
		else:
			v.insert(edit, v.size(), '\n'+s)

		v.sel().clear()
		n = v.size()-1
		v.sel().add(sublime.Region(n, n))
		vs.set("9o.wd", wd)
		vs.set("rulers", [])
		vs.set("fold_buttons", True)
		vs.set("fade_fold_buttons", False)
		vs.set("gutter", True)
		vs.set("margin", 0)
		# pad mostly so the completion menu shows on the first line
		vs.set("line_padding_top", 1)
		vs.set("line_padding_bottom", 1)
		vs.set("tab_size", 2)
		vs.set("word_wrap", True)
		vs.set("indent_subsequent_lines", True)
		vs.set("line_numbers", False)
		vs.set("auto_complete", True)
		vs.set("auto_complete_selector", "text")
		vs.set("highlight_line", True)
		vs.set("draw_indent_guides", True)
		vs.set("scroll_past_end", True)
		vs.set("indent_guide_options", ["draw_normal", "draw_active"])
		vs.set("word_separators", "./\\()\"'-:,.;<>~!@#$%&*|+=[]{}`~?")

		color_scheme = gs.setting("9o_color_scheme", "")
		if color_scheme:
			if color_scheme == "default":
				vs.erase("color_scheme")
			else:
				vs.set("color_scheme", color_scheme)
		else:
			vs.set("color_scheme", "")

		v.set_syntax_file(gs.tm_path('9o'))

		if was_empty:
			v.show(0)
		else:
			v.show(v.size()-1)

		os.chdir(wd)
コード例 #24
0
ファイル: gscomplete.py プロジェクト: OneOfOne/GoSublime-next
def _ct(view):
	if not gs.is_go_source_view(view):
		return

	if gs.setting('calltips') is True:
		view.run_command('gs_show_call_tip', {'set_status': True})
	else:
		view.erase_status(HINT_KEY)
コード例 #25
0
def complete(fn, src, pos):
	home = gs.home_path()
	builtins = (gs.setting('autocomplete_builtins') is True or gs.setting('complete_builtins') is True)
	res, err = bcall('gocode_complete', {
		'Dir': gs.basedir_or_cwd(fn),
		'Builtins': builtins,
		'Fn':  fn or '',
		'Src': src or '',
		'Pos': pos or 0,
		'Home': home,
		'Env': gs.env({
			'XDG_CONFIG_HOME': home,
		}),
	})

	res = gs.dval(res.get('completions'), [])
	return res, err
コード例 #26
0
ファイル: mg9.py プロジェクト: OlingCat/GoSublime
def complete(fn, src, pos):
	home = gs.home_path()
	builtins = (gs.setting('autocomplete_builtins') is True or gs.setting('complete_builtins') is True)
	res, err = bcall('gocode_complete', {
		'Dir': gs.basedir_or_cwd(fn),
		'Builtins': builtins,
		'Fn':  fn or '',
		'Src': src or '',
		'Pos': pos or 0,
		'Home': home,
		'Env': gs.env({
			'XDG_CONFIG_HOME': home,
		}),
	})

	res = gs.dval(res.get('completions'), [])
	return res, err
コード例 #27
0
def _ct(view):
    if not gs.is_go_source_view(view):
        return

    if gs.setting('calltips') is True:
        view.run_command('gs_show_call_tip', {'set_status': True})
    else:
        view.erase_status(HINT_KEY)
コード例 #28
0
	def is_enabled(self):
		fn = self.view.file_name()
		if fn:
			scope_ok = fn.lower().endswith('.go')
		else:
			scope_ok = gs.is_go_source_view(self.view)

		return scope_ok and gs.setting('fmt_enabled') is True
コード例 #29
0
def do_comp_lint(dirname, fn):
    fr = ref(fn, False)
    reports = {}
    if not fr:
        return

    fn = gs.apath(fn, dirname)
    bindir, _ = gs.temp_dir('bin')
    local_env = {
        'GOBIN': bindir,
    }

    pat = r'%s:(\d+)(?:[:](\d+))?\W+(.+)\s*' % re.escape(os.path.basename(fn))
    pat = re.compile(pat, re.IGNORECASE)
    for c in gs.setting('comp_lint_commands'):
        try:
            cmd = c.get('cmd')
            if not cmd:
                continue
            cmd_domain = ' '.join(cmd)

            shell = c.get('shell') is True
            env = {} if c.get('global') is True else local_env
            out, err, _ = gsshell.run(cmd=cmd,
                                      shell=shell,
                                      cwd=dirname,
                                      env=env)
            if err:
                gs.notice(DOMAIN, err)

            out = out.replace('\r',
                              '').replace('\n ',
                                          '\\n ').replace('\n\t', '\\n\t')
            for m in pat.findall(out):
                try:
                    row, col, msg = m
                    row = int(row) - 1
                    col = int(col) - 1 if col else 0
                    msg = msg.replace('\\n', '\n').strip()
                    if row >= 0 and msg:
                        msg = '%s: %s' % (cmd_domain, msg)
                        if reports.get(row):
                            reports[row].msg = '%s\n%s' % (reports[row].msg,
                                                           msg)
                            reports[row].col = max(reports[row].col, col)
                        else:
                            reports[row] = Report(row, col, msg)
                except:
                    pass
        except:
            gs.notice(DOMAIN, gs.traceback())

    def cb():
        fr.reports = reports
        fr.state = 1
        highlight(fr)

    sublime.set_timeout(cb, 0)
コード例 #30
0
ファイル: mg9.py プロジェクト: dlclark/GoSublime
def doc(fn, src, offset, f, mode='doc'):
	tid = gs.begin(DOMAIN, 'Fetching doc info')
	def cb(res, err):
		gs.end(tid)
		f(res, err)

	#default to doc
	if mode not in ['usage', 'doc']:
		mode = 'doc'

	acall(mode, {
		'fn': fn or '',
		'src': src or '',
		'offset': offset or 0,
		'env': sh.env(),
		'tabIndent': gs.setting('fmt_tab_indent'),
		'tabWidth': gs.setting('fmt_tab_width'),
	}, cb)
コード例 #31
0
ファイル: gs9o.py プロジェクト: Manrich121/GoSublime
def _save_all(win, wd):
	if gs.setting('autosave') is True and win is not None:
		for v in win.views():
			try:
				fn = v.file_name()
				if fn and v.is_dirty() and fn.endswith('.go') and os.path.dirname(fn) == wd:
					v.run_command('gs_fmt_save')
			except Exception:
				gs.error_traceback(DOMAIN)
コード例 #32
0
ファイル: gslint.py プロジェクト: charlievieth/GoSubl
    def run(self, edit):
        if gs.setting("comp_lint_enabled") is not True:
            return

        fn = self.view.file_name()
        fn = os.path.abspath(fn)
        if fn:
            file_refs[fn] = FileRef(self.view)
            mg9.acall("comp_lint", {"filename": fn}, do_comp_lint_callback)
コード例 #33
0
ファイル: gs9o.py プロジェクト: 905522052/GoSublime
def _save_all(win, wd):
	if gs.setting('autosave') is True and win is not None:
		for v in win.views():
			try:
				fn = v.file_name()
				if fn and v.is_dirty() and fn.endswith('.go') and os.path.dirname(fn) == wd:
					v.run_command('gs_fmt_save')
			except Exception:
				gs.error_traceback(DOMAIN)
コード例 #34
0
ファイル: gscomplete.py プロジェクト: charlievieth/GoSubl
def resolve_snippets(ctx):
    cl = set()
    types = [""] if ctx.get("local") else ctx.get("types", [""])
    vars = {}
    for k, v in ctx.items():
        if gs.is_a_string(v):
            vars[k] = v

    try:
        snips = []
        snips.extend(gs.setting("default_snippets", []))
        snips.extend(gs.setting("snippets", []))
        for m in snips:
            try:
                if snippet_match(ctx, m):
                    for ent in m.get("snippets", []):
                        text = ent.get("text", "")
                        title = ent.get("title", "")
                        value = ent.get("value", "")
                        if text and value:
                            for typename in types:
                                vars["typename"] = typename
                                if typename:
                                    if (
                                        len(typename) > 1
                                        and typename[0].islower()
                                        and typename[1].isupper()
                                    ):
                                        vars["typename_abbr"] = typename[1].lower()
                                    else:
                                        vars["typename_abbr"] = typename[0].lower()
                                else:
                                    vars["typename_abbr"] = ""

                                txt, ttl, val = expand_snippet_vars(
                                    vars, text, title, value
                                )
                                s = u"%s\t%s \u0282" % (txt, ttl)
                                cl.add((s, val))
            except:
                gs.notice(DOMAIN, gs.traceback())
    except:
        gs.notice(DOMAIN, gs.traceback())
    return list(cl)
コード例 #35
0
ファイル: gslint.py プロジェクト: 905522052/GoSublime
	def run(self, edit):
		if gs.setting('comp_lint_enabled') is not True:
			return

		fn = self.view.file_name()
		fn = os.path.abspath(fn)
		if fn:
			dirname = gs.basedir_or_cwd(fn)
			file_refs[fn] = FileRef(self.view)
			gsq.dispatch(CL_DOMAIN, lambda: do_comp_lint(dirname, fn), '')
コード例 #36
0
ファイル: mg9.py プロジェクト: charlievieth/GoSubl
def fmt(fn, src):
    x = gs.setting("fmt_cmd")
    if x:
        res, err = bcall(
            "sh",
            {"Env": sh.env(), "Cmd": {"Name": x[0], "Args": x[1:], "Input": src or ""}},
        )
        return res.get("out", ""), (err or res.get("err", ""))

    res, err = bcall(
        "fmt",
        {
            "Fn": fn or "",
            "Src": src or "",
            "TabIndent": gs.setting("fmt_tab_indent"),
            "TabWidth": gs.setting("fmt_tab_width"),
        },
    )
    return res, err
コード例 #37
0
    def run(self, edit):
        if gs.setting('comp_lint_enabled') is not True:
            return

        fn = self.view.file_name()
        fn = os.path.abspath(fn)
        if fn:
            dirname = gs.basedir_or_cwd(fn)
            file_refs[fn] = FileRef(self.view)
            gsq.dispatch(CL_DOMAIN, lambda: do_comp_lint(dirname, fn), '')
コード例 #38
0
ファイル: mg9.py プロジェクト: RazoRTR/Arianrhod
def _complete_opts(fn, src, pos, builtins, *, forceInstall=False):
    nv = sh.env()
    return {
        'Dir': gs.basedir_or_cwd(fn),
        'Builtins': builtins,
        'Fn': fn or '',
        'Src': src or '',
        'Pos': pos or 0,
        'Home': sh.vdir(),
        'Autoinst': gs.setting('autoinst'),
        'InstallSuffix': gs.setting('installsuffix', ''),
        'Env': {
            'GOROOT': nv.get('GOROOT', ''),
            'GOPATH': nv.get('GOPATH', ''),
            'TEMP': nv.get('TEMP', ''),
            'TMP': nv.get('TMP', ''),
            'FORCE_INSTALL': str(int(forceInstall)),
        },
    }
コード例 #39
0
ファイル: mg9.py プロジェクト: charlievieth/GoSubl
def doc(fn, src, offset, f):
    tid = gs.begin(DOMAIN, "Fetching doc info")

    def cb(res, err):
        gs.end(tid)
        f(res, err)

    acall(
        "doc",
        {
            "fn": fn or "",
            "src": src or "",
            "offset": offset or 0,
            "env": sh.env(),
            "tabIndent": gs.setting("fmt_tab_indent"),
            "tabWidth": gs.setting("fmt_tab_width"),
        },
        cb,
    )
コード例 #40
0
ファイル: mg9.py プロジェクト: allanw1/Arianrhod
def _complete_opts(fn, src, pos, builtins, *, forceInstall = False):
	nv = sh.env()
	return {
		'Dir': gs.basedir_or_cwd(fn),
		'Builtins': builtins,
		'Fn':  fn or '',
		'Src': src or '',
		'Pos': pos or 0,
		'Home': sh.vdir(),
		'Autoinst': gs.setting('autoinst'),
		'InstallSuffix': gs.setting('installsuffix', ''),
		'Env': {
			'GOROOT': nv.get('GOROOT', ''),
			'GOPATH': nv.get('GOPATH', ''),
			'TEMP': nv.get('TEMP', ''),
			'TMP': nv.get('TMP', ''),
			'FORCE_INSTALL': str(int(forceInstall)),
		},
	}
コード例 #41
0
ファイル: gscomplete.py プロジェクト: RazoRTR/Arianrhod
def resolve_snippets(ctx):
    cl = set()
    types = [''] if ctx.get('local') else ctx.get('types')
    vars = {}
    for k, v in ctx.items():
        if gs.is_a_string(v):
            vars[k] = v

    try:
        snips = []
        snips.extend(gs.setting('default_snippets', []))
        snips.extend(gs.setting('snippets', []))
        for m in snips:
            try:
                if snippet_match(ctx, m):
                    for ent in m.get('snippets', []):
                        text = ent.get('text', '')
                        title = ent.get('title', '')
                        value = ent.get('value', '')
                        if text and value:
                            for typename in types:
                                vars['typename'] = typename
                                if typename:
                                    if len(typename
                                           ) > 1 and typename[0].islower(
                                           ) and typename[1].isupper():
                                        vars['typename_abbr'] = typename[
                                            1].lower()
                                    else:
                                        vars['typename_abbr'] = typename[
                                            0].lower()
                                else:
                                    vars['typename_abbr'] = ''

                                txt, ttl, val = expand_snippet_vars(
                                    vars, text, title, value)
                                s = u'%s\t%s \u0282' % (txt, ttl)
                                cl.add((s, val))
            except:
                gs.notice(DOMAIN, gs.traceback())
    except:
        gs.notice(DOMAIN, gs.traceback())
    return list(cl)
コード例 #42
0
ファイル: mg9.py プロジェクト: AlekSi/GoSublime
def bcall(method, arg):
	if _inst_state() != "done":
		return {}, 'Blocking call(%s) aborted: Install is not done' % method

	q = gs.queue.Queue()
	acall(method, arg, lambda r,e: q.put((r, e)))
	try:
		res, err = q.get(True, gs.setting('ipc_timeout', 1))
		return res, err
	except:
		return {}, 'Blocking Call(%s): Timeout' % method
コード例 #43
0
ファイル: mg9.py プロジェクト: kpkhxlgy0/SublimeText3
def bcall(method, arg):
    if _inst_state() != "done":
        return {}, 'Blocking call(%s) aborted: Install is not done' % method

    q = gs.queue.Queue()
    acall(method, arg, lambda r, e: q.put((r, e)))
    try:
        res, err = q.get(True, gs.setting('ipc_timeout', 1))
        return res, err
    except:
        return {}, 'Blocking Call(%s): Timeout' % method
コード例 #44
0
ファイル: gscomplete.py プロジェクト: xiocode/config
def _ct_poller():
	try:
		view = sublime.active_window().active_view()
		if gs.setting('autocomplete_live_hint', False) is True:
			view.run_command('gs_show_call_tip', {'set_status': True})
		else:
			view.erase_status(HINT_KEY)
	except Exception:
		pass

	sublime.set_timeout(_ct_poller, 1000)
コード例 #45
0
ファイル: gscomplete.py プロジェクト: RazoRTR/Arianrhod
def _ct_poller():
    try:
        view = sublime.active_window().active_view()
        if gs.setting('calltips') is True:
            view.run_command('gs_show_call_tip', {'set_status': True})
        else:
            view.erase_status(HINT_KEY)
    except Exception:
        pass

    sublime.set_timeout(_ct_poller, 1000)
コード例 #46
0
        def f(im, err):
            if err:
                gs.notice(DOMAIN, err)
                return

            delete_imports = []
            add_imports = []
            paths = im.get('paths', {})
            use_named = gs.setting('use_named_imports') is True
            for path in paths:
                skipAdd = False
                for i in im.get('imports', []):
                    if i.get('path') == path:
                        skipAdd = True
                        name = i.get('name', '')
                        if not name:
                            name = basename(path)
                        if name == path:
                            delete_imports.append(
                                ('%sdelete: %s' % (indent, name), i))
                        else:
                            delete_imports.append(
                                ('%sdelete: %s ( %s )' % (indent, name, path),
                                 i))

                if not skipAdd:
                    title = paths[path]
                    s = '%s%s' % (indent, path)
                    m = {
                        'path': path,
                        'add': True,
                    }
                    name = title.split()[0] if title else ''
                    if name and name != path and not path.endswith(
                            '/%s' % name):
                        s = '%s (%s)' % (s, name)
                        if use_named:
                            m['name'] = name

                    if '[vendored]' in title:
                        s = s + ' [vendored]'

                    add_imports.append((s, m))

            for i in sorted(delete_imports):
                self.add_item(i[0], self.toggle_import, (view, i[1]))
            if len(delete_imports) > 0:
                self.add_item(' ', self.show_palette, 'imports')
            for i in sorted(add_imports):
                self.add_item(i[0], self.toggle_import, (view, i[1]))

            self.do_show_panel()
コード例 #47
0
def bcall(method, arg):
    if _inst_state() != "done":
        return {}, 'Blocking call(%s) aborted: Install is not done' % method

    q = gs.queue.Queue()
    acall(method, arg, lambda r, e: q.put((r, e)))
    timeout = gs.setting('ipc_timeout', 1)
    try:
        res, err = q.get(True, timeout)
        return res, err
    except:
        return {}, 'Blocking Call(%s) Timed out after %0.3f second(s). You might need to increase the `ipc_timeout` setting' % (
            method, timeout)
コード例 #48
0
def import_paths(fn, src, f):
    tid = gs.begin(DOMAIN, 'Fetching import paths')

    def cb(res, err):
        gs.end(tid)
        f(res, err)

    acall(
        'import_paths', {
            'fn': fn or '',
            'src': src or '',
            'env': sh.env(),
            'InstallSuffix': gs.setting('installsuffix', ''),
        }, cb)
コード例 #49
0
ファイル: gsev.py プロジェクト: eticzon/GoSublime
def do_post_save(view):
    if not gs.is_pkg_view(view):
        return

    for c in gs.setting('on_save', []):
        cmd = c.get('cmd', '')
        args = c.get('args', {})
        msg = 'running on_save command %s' % cmd
        tid = gs.begin(DOMAIN, msg, set_status=False)
        try:
            view.run_command(cmd, args)
        except Exception as ex:
            gs.notice(DOMAIN, 'Error %s' % ex)
        finally:
            gs.end(tid)
コード例 #50
0
ファイル: gspalette.py プロジェクト: metakeule/GoSublime-next
        def f(im, err):
            if err:
                ui.error(DOMAIN, err)
                return

            delete_imports = []
            add_imports = []
            paths = im.get('paths', {})
            for path in paths:
                skipAdd = False
                for i in im.get('imports', []):
                    if i.get('path') == path:
                        skipAdd = True
                        name = i.get('name', '')
                        if not name:
                            name = basename(path)
                        if name == path:
                            delete_imports.append(
                                ('%sdelete: %s' % (indent, name), i))
                        else:
                            delete_imports.append(
                                ('%sdelete: %s ( %s )' % (indent, name, path),
                                 i))

                if not skipAdd:
                    s = '%s%s' % (indent, path)
                    m = {
                        'path': path,
                        'add': True,
                    }

                    nm = paths[path]
                    if nm and nm != path and not path.endswith('/%s' % nm):
                        s = '%s (%s)' % (s, nm)
                        if gs.setting('use_named_imports') is True:
                            m['name'] = nm

                    add_imports.append((s, m))

            for i in sorted(delete_imports):
                self.add_item(i[0], toggle_import, (view, i[1]))
            if len(delete_imports) > 0:
                self.add_item(' ', self.show_palette, 'imports')
            for i in sorted(add_imports):
                self.add_item(i[0], toggle_import, (view, i[1]))

            self.do_show_panel()
コード例 #51
0
def fix_shell_cmd(shell, cmd):
	if not gs.is_a(cmd, []):
		cmd = [cmd]

	if shell:
		sh = gs.setting('shell')
		cmd_str = ' '.join(cmd)
		cmd_map = {'CMD': cmd_str}
		if sh:
			shell = False
			cmd = []
			for v in sh:
				if v:
					cmd.append(string.Template(v).safe_substitute(cmd_map))
		else:
			cmd = [cmd_str]

	return (shell, [gs.astr(v) for v in cmd])
コード例 #52
0
    def run(self, edit, rkey, output, hourglass_repl=''):
        view = self.view
        output = '\t%s' % gs.ustr(output).strip().replace('\r', '').replace(
            '\n', '\n\t')
        regions = view.get_regions(rkey)
        if regions:
            line = view.line(regions[0].begin())
            lsrc = view.substr(line).replace(HOURGLASS,
                                             (hourglass_repl or '| done'))
            view.replace(edit, line, lsrc)
            r = line
            if output.strip():
                line = view.line(regions[0].begin())
                view.insert(edit, line.end(), '\n%s' % output)
                r = view.get_regions(rkey)[0]
        else:
            n = view.size()
            view.insert(edit, n, '\n%s' % output)
            r = sublime.Region(n, view.size())

        if gs.setting('9o_show_end') is True:
            view.show(r.end())
        else:
            view.show(r.begin())
コード例 #53
0
ファイル: gsev.py プロジェクト: eticzon/GoSublime
def do_set_gohtml_syntax(view):
    fn = view.file_name()
    xl = gs.setting('gohtml_extensions', [])
    if xl and fn and fn.lower().endswith(tuple(xl)):
        view.set_syntax_file(gs.tm_path('gohtml'))
コード例 #54
0
def _send():
    while True:
        try:
            try:
                method, arg, cb = gs.mg9_send_q.get()

                proc = gs.attr(PROC_ATTR_NAME)
                if not proc or proc.poll() is not None:
                    killSrv()

                    if _inst_state() != "busy":
                        maybe_install()

                    while _inst_state() == "busy":
                        time.sleep(0.100)

                    mg_bin = _margo_bin()
                    cmd = [
                        mg_bin,
                        '-oom',
                        gs.setting('margo_oom', 0),
                        '-poll',
                        30,
                        '-tag',
                        TAG,
                    ]

                    c = sh.Command(cmd)
                    c.stderr = gs.LOGFILE
                    c.env = {
                        'GOGC': 10,
                        'XDG_CONFIG_HOME': gs.home_path(),
                    }

                    pr = c.proc()
                    if pr.ok:
                        proc = pr.p
                        err = ''
                    else:
                        proc = None
                        err = 'Exception: %s' % pr.exc

                    if err or not proc or proc.poll() is not None:
                        killSrv()
                        _call(cb, {}, 'Abort. Cannot start MarGo: %s' % err)

                        continue

                    gs.set_attr(PROC_ATTR_NAME, proc)
                    gsq.launch(DOMAIN, lambda: _read_stdout(proc))

                req = Request(f=cb, method=method)
                gs.set_attr(REQUEST_PREFIX + req.token, req)

                header, err = gs.json_encode(req.header())
                if err:
                    _cb_err(cb, 'Failed to construct ipc header: %s' % err)
                    continue

                body, err = gs.json_encode(arg)
                if err:
                    _cb_err(cb, 'Failed to construct ipc body: %s' % err)
                    continue

                ev.debug(DOMAIN, 'margo request: %s ' % header)

                ln = '%s %s\n' % (header, body)

                try:
                    if gs.PY3K:
                        proc.stdin.write(bytes(ln, 'UTF-8'))
                    else:
                        proc.stdin.write(ln)

                except Exception as ex:
                    _cb_err(cb, 'Cannot talk to MarGo: %s' % err)
                    killSrv()
                    gs.println(gs.traceback())

            except Exception:
                killSrv()
                gs.println(gs.traceback())
        except Exception:
            gs.println(gs.traceback())
            break
コード例 #55
0
def complete(fn, src, pos):
    builtins = (gs.setting('autocomplete_builtins') is True
                or gs.setting('complete_builtins') is True)
    res, err = bcall('gocode_complete', _complete_opts(fn, src, pos, builtins))
    res = gs.dval(res.get('Candidates'), [])
    return res, err