Skip to content

Instantly share code, notes, and snippets.

@apetrone
Last active August 29, 2015 14:04
Show Gist options
  • Save apetrone/6656680d04c59820e7a4 to your computer and use it in GitHub Desktop.
Save apetrone/6656680d04c59820e7a4 to your computer and use it in GitHub Desktop.
LiveJSON
# August 2014
# Adam Petrone
# This is a Sublime Text 2 plugin and was designed
# to allow live-editing of variables in my codebase
# for quicker iteration times.
# It communicates with CivetServer on the native C++ side
# and parses the incoming JSON.
import sublime, sublime_plugin
import json
import httplib
SERVER_HOST = "localhost:1983"
class PromptSetServerCommand(sublime_plugin.WindowCommand):
def run(self):
self.window.show_input_panel("Server:", "", self.on_done, None, None)
def on_done(self, value):
global SERVER_HOST
SERVER_HOST = value
class LiveJsonListener(sublime_plugin.EventListener):
def run(self, edit):
pass
def on_modified(self, view):
filename = view.file_name()
if filename and filename.endswith(".json"):
try:
view.erase_regions("error")
# get the buffer contents from the view
contents = view.substr(sublime.Region(0, view.size()))
# try to load it as json
data = json.loads(contents)
# if it loaded, we can send it
self.put_request(contents)
except:
# mark the region
region = [s for s in view.sel()]
view.add_regions("error", region, "invalid", "bookmark")
# ignore malformed json
pass
def put_request(self, data):
global SERVER_HOST
server_url = SERVER_HOST.split(":")
connection = httplib.HTTPConnection(server_url[0], server_url[1])
connection.request("PUT", "/json", data)
response = connection.getresponse()
if response.status != 204 and response.status != 200:
print("Request failed: (%i) %s" % (response.status, response.reason))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment