Skip to content

Instantly share code, notes, and snippets.

@rikukissa
Last active December 28, 2015 21:19
Show Gist options
  • Save rikukissa/7563448 to your computer and use it in GitHub Desktop.
Save rikukissa/7563448 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import sublime, sublime_plugin, json, codecs
class I18nCommand(sublime_plugin.TextCommand):
settings = sublime.load_settings('i18nHelper')
last_path = settings.get('default_path', '')
last_key = settings.get('default_chain', '')
def run(self, edit):
if len(self.view.sel()) is 0:
return
self.edit = edit
self.selection_points = self.view.sel()
self.selection = self.view.substr(self.selection_points[0])
if len(self.selection) is 0:
return
self.view.window().show_input_panel("Select localization file", self.last_path, self.fetch_localization_file, None, None)
def fetch_localization_file(self, path):
self.last_path = path
self.settings.set('default_path', path)
self.complete_path = self.view.window().folders()[0] + '/' + path
with codecs.open(self.complete_path, 'r', encoding='utf-8') as content_file:
content = content_file.read()
self.localization = json.loads(content)
self.get_key()
def get_key(self):
self.view.window().show_input_panel("Insert corresponding key", self.last_key, self.find_key, None, None)
def find_key(self, chain):
self.last_key = chain
self.settings.set('default_chain', chain)
current_point = self.localization
keys = chain.split('.')
for i, key in enumerate(keys):
if key in current_point:
current_point = current_point[key]
else:
if i + 1 is len(keys): # last key
current_point[key] = self.selection
break
current_point[key] = {}
current_point = current_point[key]
json_output = json.dumps(self.localization, indent=2, separators=(',', ': '), ensure_ascii=False)
with codecs.open(self.complete_path, 'w', encoding='utf-8') as localization_file:
localization_file.write(json_output)
self.replace(chain)
def replace(self, key):
sublime.save_settings('i18nHelper')
for sel in self.selection_points:
self.view.replace(self.edit, sel, u"{{ \"%s\" | translate }}" % key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment