Skip to content

Instantly share code, notes, and snippets.

@eliquious
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliquious/c44158262fa7e421e7d6 to your computer and use it in GitHub Desktop.
Save eliquious/c44158262fa7e421e7d6 to your computer and use it in GitHub Desktop.
Basic Golang Sublime Support
{
"shell_cmd": "go build $file_path/*go",
"file_regex": "^(.*):([0-9]*):",
"selector": "source.go",
"env": {
"GOPATH": "$HOME/.go"
}
}
import sublime, sublime_plugin
import subprocess
import os.path
import re
import tempfile
class GoImportsCommand(sublime_plugin.TextCommand):
def run(self, edit):
print('goimports')
p = subprocess.Popen(["goimports"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# p.stdin.write(bytes(self.view.substr(sublime.Region(0, self.view.size())), 'utf-8'))
data = bytes(self.view.substr(sublime.Region(0, self.view.size())), 'utf-8')
out, err = p.communicate(data)
if len(out) > 0:
print('goimports: replacing output')
# replace buffer contents
self.view.replace(edit, sublime.Region(0, self.view.size()), out.decode("utf-8"))
else:
print('goimports: No output to replace')
class GoBuildCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.window().run_command("build")
# d = tempfile.gettempdir()
# filename = os.path.join(d, 'go_subl_build')
# # run goimports
# # env={'GOPATH': '$HOME/.go', 'GOROOT': '/usr/local/Cellar/go/1.3.1/libexec'}
# p = subprocess.Popen(["go", "build", "-o=" + filename, os.path.dirname(self.view.file_name()) + '/*go'],
# shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# out, err = p.communicate()
# data = out.decode('utf-8')
# if len(data) > 0:
# # create output window
# output = self.view.window().get_output_panel('go_build')
# output.insert(edit, 0, out.decode('utf-8'))
# # self.view.window().show_panel('go_build')
# self.view.window().run_command("show_panel", {"panel": "output." + 'go_build'})
# else:
# self.view.window().run_command("hide_panel", {"cancel": True})
class EventDump(sublime_plugin.EventListener):
def on_pre_save(self, view):
# filter by file extension
if not 'go' in os.path.splitext(view.file_name())[1]:
return
# run goimports on save
view.run_command('go_imports')
def on_post_save(self, view):
# filter by file extension
if not 'go' in os.path.splitext(view.file_name())[1]:
return
view.run_command('go_build')
# view.run_command('show_panel', {"panel": "output.exec"})
# view.run_command('build')
# print(view.file_name(), "just got saved")
def on_query_completions(self, view, prefix, locations):
# filter by file extension
if not 'go' in os.path.splitext(view.file_name())[1]:
return
# pos = view.sel()[0].begin()
pos = locations[0]
# run goimports
p = subprocess.Popen(["gocode", "autocomplete", str(pos)], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# p.stdin.write(bytes(self.view.substr(sublime.Region(0, self.view.size())), 'utf-8'))
data = bytes(view.substr(sublime.Region(0, view.size())), 'utf-8')
out, err = p.communicate(data)
lines = out.decode('utf-8').split('\n')
completions = []
if len(lines) > 1:
for line in lines:
comp = self.content(line)
if comp is not None:
completions.append(comp)
# return completions
return completions
else:
return None
def content(self, line):
if line.strip().startswith('func'):
return self.function(line)
elif line.strip().startswith('const'):
return self.const(line)
elif line.strip().startswith('type'):
return self.type_(line)
elif line.strip().startswith('var'):
return self.var(line)
else:
print(line)
return None
def var(self, line):
trigger = line + '\tfield'
var = re.search('\s+var\s(\w+)', line)
if var is not None:
return (trigger, var.group(1))
return (trigger, line)
def type_(self, line):
trigger = line + '\t'
if 'interface' in line:
trigger += 'interface'
elif 'struct' in line:
trigger += 'struct'
t = re.search('\s+type\s(\w+)', line)
if t is not None:
return (trigger, t.group(1))
return (trigger, line)
def const(self, line):
trigger = line + '\tconstant'
const = re.search('\s+const\s(\w+)', line)
if const is not None:
return (trigger, const.group(1))
return (trigger, line)
def function(self, line):
trigger = line + '\tfunc'
# remove keyword func
line = re.sub("\s+func\s", "", line)
# find arg list
o = line.find('(')
c = line.find(')')
matches = line[o+1:c].split(', ')
print(matches)
# found args
if len(matches) > 0 and matches[0]:
# get arg offsets
args = []
for m in matches:
a = line.find(m)
z = a + len(m)
args.append((a, z, m))
index = 1
offset = 0
contents = ''
while offset < len(line):
if len(args) > 0:
start, end, match = args.pop(0)
if offset < start:
contents += line[offset:start]
# write arg
match = re.sub('}', '\}', match)
contents += '${%s:%s}' % (index, match)
offset = end
index += 1
else:
contents += ')'
break
else:
fname = re.search('^(\w+)\(', line)
contents = fname.group(1) + '()'
return (trigger, contents)
Create directory in ST3 Packages: eg. gosub
Copy GIST file into new directory:
/Users/mfranks/Library/Application Support/Sublime Text 3/Packages/gosub/gosubl.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment