rikukissa
11/20/2013 - 1:47 PM

gistfile1.py

# -*- 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)