Skip to content

Instantly share code, notes, and snippets.

@alpancs
Last active October 7, 2019 02:46
Show Gist options
  • Save alpancs/9f6b589c84a873e2e62e7ca7b5b4ff0c to your computer and use it in GitHub Desktop.
Save alpancs/9f6b589c84a873e2e62e7ca7b5b4ff0c to your computer and use it in GitHub Desktop.
run goimports automatically when saving Go code
# put this file in $HOME/.config/sublime-text-3/Packages
from sublime import *
from sublime_plugin import *
from os import environ
from subprocess import Popen, PIPE
class AutoGoimports(ViewEventListener):
def on_pre_save(self):
self.view.run_command("goimports")
class GoimportsCommand(TextCommand):
# edit if necessary
goimports = '{HOME}/go/bin/goimports'.format(**environ)
gofmt = '/usr/local/go/bin/gofmt'
def run(self, edit):
if not self.view.settings().get('syntax').endswith("Go.sublime-syntax"): return
region = Region(0, self.view.size())
content = self.view.substr(region)
command = '{} | {} -s'.format(self.goimports, self.gofmt)
with Popen(command, shell=True, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) as p:
stdout, stderr = p.communicate(content, 2)
if stderr: error_message(stderr.replace('<standard input>:', '')[:400])
elif stdout != content: self.view.replace(edit, region, stdout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment