示例#1
0
    def on_load(self, view):
        use_corona_sdk_completion = _corona_utils.GetSetting(
            "corona_sdk_completion", True)

        if use_corona_sdk_completion and self.is_lua_file(view):
            use_periods_in_completion = _corona_utils.GetSetting(
                "corona_sdk_complete_periods", True)

            # Completion behavior is improved if periods are included in the completion process
            if use_periods_in_completion:
                # If "auto_complete_triggers" for periods is not set for this buffer, set it
                auto_complete_triggers = view.settings().get(
                    "auto_complete_triggers")
                self.periods_set[view.file_name()] = False
                for act in auto_complete_triggers:
                    if "source.lua.corona" in act["selector"] and "." in act[
                            "characters"]:
                        self.periods_set[view.file_name()] = True
                        break
                if not self.periods_set.get(view.file_name(), False):
                    auto_complete_triggers.append({
                        "selector": "source.lua.corona",
                        "characters": "."
                    })
                    view.settings().set("auto_complete_triggers",
                                        auto_complete_triggers)
                    self.periods_set[view.file_name()] = True
        _corona_utils.debug(
            "on_load view: ", view.file_name(), "periods_set"
            if self.periods_set.get(view.file_name(), False) else "not set")
  def run(self, edit, **args):

    if 'name' in args:
      trigger = args['name']
    else:
      trigger = args['file']

    if self._comps is None:
      completions.CoronaCompletions.initialize()
      self._comps = completions.CoronaCompletions._completions

    # print("CoronaSnippetCommand:")
    # print(str(self._comps))
    # print(str(len(self._comps['completions'])) + " completions available")

    # print("trigger: " + trigger)
    if trigger.endswith(".sublime-snippet"):
      # The command wants names in the form: "Packages/User/Snippets/foo.sublime-snippet" so we
      # need to remove everything in the path before "Packages" and convert backslashes to slashes
      # (TODO: note that this wont work for a user called "Packages")
      trigger = re.sub(r'.*Packages', "Packages", trigger, 1)
      trigger = trigger.replace('\\', '/')
      _corona_utils.debug("modified trigger: " + trigger)
      self.view.run_command("insert_snippet", {"name": trigger})
    else:
      # Find a completion keyed by the contents of the snippet file
      with open(trigger, "r") as fd:
        lookup = fd.read().strip()

      key = [key for key, item in enumerate(self._comps['completions']) if item['trigger'].lower().startswith(lookup.lower())]
      if key is not None and len(key) != 0:
        self.view.run_command("insert_snippet", {"contents": self._comps['completions'][key[0]]['contents']})
      else:
        self.view.run_command('insert', {'characters': lookup})
 def on_close(self, view):
   _corona_utils.debug("on_close view: ", view.file_name(), "periods_set" if self.periods_set.get(view.file_name(), False) else "not set" )
   if view.file_name() is not None and self.periods_set.get(view.file_name(), False):
     auto_complete_triggers = view.settings().get("auto_complete_triggers")
     if { "selector": "source.lua.corona", "characters": "." } in auto_complete_triggers:
       auto_complete_triggers.remove({ "selector": "source.lua.corona", "characters": "." })
       self.periods_set[view.file_name()] = False
示例#4
0
 def on_post_save(self, view):
     if self.is_lua_file(view):
         auto_build = _corona_utils.GetSetting("corona_sdk_auto_build",
                                               False)
         if auto_build:
             _corona_utils.debug("Corona Editor: auto build triggered")
             view.window().run_command("build")
 def __init__(self):
   _corona_utils.debug("CoronaLabs: __init__")
   global CoronaCompletions
   CoronaCompletions = self
   # Use fuzzy completions (essentially search for the characters in the target even if separated)
   self._use_fuzzy_completion = _corona_utils.GetSetting("corona_sdk_use_fuzzy_completion", True)
   # Remove whitespace in completions to match some coding styles
   self._strip_white_space = _corona_utils.GetSetting("corona_sdk_completions_strip_white_space", False)
  def find_completions(self, view, prefix):
    self.load_completions(_corona_utils.GetSetting("corona_sdk_use_docset", "public"))

    completion_target = self.current_word(view)

    # Because we adjust the prefix to make completions with periods in them work better we may need to
    # trim the part before the period from the returned string (or it will appear to be doubled)
    completion_adjustment = "" if "." not in completion_target else completion_target.partition('.')[0] + '.'

    # _corona_utils.debug('prefix: ', prefix, 'completion_target: ', completion_target, "; completion_adjustment: ", completion_adjustment, "; corona_sdk_complete_periods: ", _corona_utils.GetSetting("corona_sdk_complete_periods", True) )

    self.setupFuzzyMatch(completion_target)

    # Sample:
    #   { "trigger": "audio.stopWithDelay()", "contents": "audio.stopWithDelay( ${1:duration}, ${2:[, options ]} )"},
    #   "audio.totalChannels ",

    # This is horrible on a variety of levels but is brought upon us by the fact that
    # ST completion files contain an array that is a mixture of strings and dicts
    comps = []
    for c in self._completions['completions']:
      trigger = ""
      contents = ""
      if isinstance(c, dict):
        if self.fuzzyMatchString(c['trigger'], self._use_fuzzy_completion):
          trigger = c['trigger']
          contents = c['contents']
      elif is_string_instance(c):
        if self.fuzzyMatchString(c, self._use_fuzzy_completion):
          _corona_utils.debug("String match: ", c)
          trigger = c
          contents = c

      if trigger is not "":
        if self._strip_white_space and contents is not "":
           contents = self._findWhiteSpace.sub("\\1", contents)
        # If we do the completion adjustment on completions that aren't functions
        # ST somehow erases the text before the period from the document leaving
        # just the piece after it (it makes no sense).  This fixes that but will
        # almost certainly have to be changed when ST's behavior changes.
        if "(" in contents:
          comps.append((trigger, contents.replace(completion_adjustment, '')))
        else:
          comps.append((trigger, contents))

    # _corona_utils.debug("extract_completions: ", view.extract_completions(completion_target))

    # Add textual completions from the document
    for c in view.extract_completions(completion_target):
      comps.append((c, c))

    # Reorganize into a list
    comps = list(set(comps))
    comps.sort()

    # _corona_utils.debug("comps: ", comps)

    return comps
示例#7
0
 def __init__(self):
     _corona_utils.debug("CoronaLabs: __init__")
     global CoronaCompletions
     CoronaCompletions = self
     # Use fuzzy completions (essentially search for the characters in the target even if separated)
     self._use_fuzzy_completion = _corona_utils.GetSetting(
         "corona_sdk_use_fuzzy_completion", True)
     # Remove whitespace in completions to match some coding styles
     self._strip_white_space = _corona_utils.GetSetting(
         "corona_sdk_completions_strip_white_space", False)
示例#8
0
    def on_post_save(self, view):
        if self.is_lua_file(view):
            auto_build = _corona_utils.GetSetting("corona_sdk_auto_build",
                                                  default=False)
            if auto_build:
                _corona_utils.debug("Corona Editor: auto build triggered")
                view.window().run_command("build")

        if view.file_name().lower().endswith(
                ".lua") and _corona_utils.GetSetting(
                    "corona_sdk_default_new_file_to_corona_lua", default=True):
            view.set_syntax_file(
                "Packages/CoronaSDK-SublimeText/CoronaSDKLua.tmLanguage")
def debug(s):
  global debugFP
  try:
    if not debugFP and _corona_utils.GetSetting("corona_sdk_debug", False):
      if not os.path.isdir(_corona_utils.PACKAGE_USER_DIR):
        os.makedirs(_corona_utils.PACKAGE_USER_DIR)
      debugFP = open(os.path.normpath(os.path.join(_corona_utils.PACKAGE_USER_DIR, "debug.log")), "w", 1)
  except:
    pass

  # <CoronaDebuggerThread(Thread-5, started 4583960576)>
  thread_id = re.sub(r'.*\(([^,]*),.*', r'\1', str(threading.current_thread()))
  log_line = str(datetime.datetime.now()) + " (" + str(thread_id) + "): " + str(s)
  if debugFP:
    debugFP.write(log_line + "\n")
  _corona_utils.debug(log_line)
示例#10
0
 def on_close(self, view):
     _corona_utils.debug(
         "on_close view: ", view.file_name(), "periods_set"
         if self.periods_set.get(view.file_name(), False) else "not set")
     if view.file_name() is not None and self.periods_set.get(
             view.file_name(), False):
         auto_complete_triggers = view.settings().get(
             "auto_complete_triggers")
         if {
                 "selector": "source.lua.corona",
                 "characters": "."
         } in auto_complete_triggers:
             auto_complete_triggers.remove({
                 "selector": "source.lua.corona",
                 "characters": "."
             })
             self.periods_set[view.file_name()] = False
def debug(s):
  global debugFP
  global corona_sdk_debug
  try:
    if not debugFP and corona_sdk_debug:
      if not os.path.isdir(_corona_utils.PACKAGE_USER_DIR):
        os.makedirs(_corona_utils.PACKAGE_USER_DIR)
      debugFP = open(os.path.normpath(os.path.join(_corona_utils.PACKAGE_USER_DIR, "debug.log")), "w", 1)
  except:
    pass

  # <CoronaDebuggerThread(Thread-5, started 4583960576)>
  thread_id = re.sub(r'.*\(([^,]*),.*', r'\1', str(threading.current_thread()))
  log_line = str(datetime.datetime.now()) + " (" + str(thread_id) + "): " + str(s)
  if debugFP:
    debugFP.write(log_line + "\n")
  _corona_utils.debug(log_line)
  def on_query_completions(self, view, prefix, locations):
    use_corona_sdk_completion = _corona_utils.GetSetting("corona_sdk_completion", True)

    if self._first_time and use_corona_sdk_completion:
      if not self.is_lua_file(view) and view.file_name().lower().endswith(".lua"):
        msg = "Corona Editor: syntax is not set to 'Corona SDK Lua' so completion is inactive"
        sublime.status_message(msg)
        print(msg)
        self._first_time = False

    _corona_utils.debug("on_query_completions: ",  "use_corona_sdk_completion: ", use_corona_sdk_completion, "source.lua.corona - entity: ", view.match_selector(locations[0], "source.lua.corona - entity"))
    if use_corona_sdk_completion and view.match_selector(locations[0], "source.lua.corona - entity"):
      comps = self.find_completions(view, prefix)
      flags = 0  # sublime.INHIBIT_EXPLICIT_COMPLETIONS | sublime.INHIBIT_WORD_COMPLETIONS
      return (comps, flags)
    else:
      return []
  def on_load(self, view):
    use_corona_sdk_completion = _corona_utils.GetSetting("corona_sdk_completion", True)

    if use_corona_sdk_completion and self.is_lua_file(view):
      use_periods_in_completion = _corona_utils.GetSetting("corona_sdk_complete_periods", True)

      # Completion behavior is improved if periods are included in the completion process
      if use_periods_in_completion:
        # If "auto_complete_triggers" for periods is not set for this buffer, set it
        auto_complete_triggers = view.settings().get("auto_complete_triggers")
        self.periods_set[view.file_name()] = False
        for act in auto_complete_triggers:
          if "source.lua.corona" in act["selector"] and "." in act["characters"]:
            self.periods_set[view.file_name()] = True
            break
        if not self.periods_set.get(view.file_name(), False):
          auto_complete_triggers.append({ "selector": "source.lua.corona", "characters": "." })
          view.settings().set("auto_complete_triggers", auto_complete_triggers)
          self.periods_set[view.file_name()] = True
    _corona_utils.debug("on_load view: ", view.file_name(), "periods_set" if self.periods_set.get(view.file_name(), False) else "not set")
示例#14
0
    def run(self, edit, **args):

        if 'name' in args:
            trigger = args['name']
        else:
            trigger = args['file']

        if self._comps is None:
            completions.CoronaCompletions.initialize()
            self._comps = completions.CoronaCompletions._completions

        # print("CoronaSnippetCommand:")
        # print(str(self._comps))
        # print(str(len(self._comps['completions'])) + " completions available")

        # print("trigger: " + trigger)
        if trigger.endswith(".sublime-snippet"):
            # The command wants names in the form: "Packages/User/Snippets/foo.sublime-snippet" so we
            # need to remove everything in the path before "Packages" and convert backslashes to slashes
            # (TODO: note that this wont work for a user called "Packages")
            trigger = re.sub(r'.*Packages', "Packages", trigger, 1)
            trigger = trigger.replace('\\', '/')
            _corona_utils.debug("modified trigger: " + trigger)
            self.view.run_command("insert_snippet", {"name": trigger})
        else:
            # Find a completion keyed by the contents of the snippet file
            with open(trigger, "r") as fd:
                lookup = fd.read().strip()

            key = [
                key for key, item in enumerate(self._comps['completions'])
                if item['trigger'].lower().startswith(lookup.lower())
            ]
            if key is not None and len(key) != 0:
                self.view.run_command("insert_snippet", {
                    "contents":
                    self._comps['completions'][key[0]]['contents']
                })
            else:
                self.view.run_command('insert', {'characters': lookup})
示例#15
0
    def on_query_completions(self, view, prefix, locations):
        use_corona_sdk_completion = _corona_utils.GetSetting(
            "corona_sdk_completion", True)

        if self._first_time and use_corona_sdk_completion:
            if not self.is_lua_file(view) and view.file_name().lower(
            ).endswith(".lua"):
                msg = "Corona Editor: syntax is not set to 'Corona Lua' so completion is inactive"
                sublime.status_message(msg)
                print(msg)
                self._first_time = False

        _corona_utils.debug(
            "on_query_completions: ", "use_corona_sdk_completion: ",
            use_corona_sdk_completion, "source.lua.corona - entity: ",
            view.match_selector(locations[0], "source.lua.corona - entity"))
        if use_corona_sdk_completion and view.match_selector(
                locations[0], "source.lua.corona - entity"):
            comps = self.find_completions(view, prefix)
            flags = 0  # sublime.INHIBIT_EXPLICIT_COMPLETIONS | sublime.INHIBIT_WORD_COMPLETIONS
            return (comps, flags)
        else:
            return []
示例#16
0
    def find_completions(self, view, prefix):
        self.load_completions(
            _corona_utils.GetSetting("corona_sdk_use_docset",
                                     default="public"))
        strip_white_space = _corona_utils.GetSetting(
            "corona_sdk_completions_strip_white_space", default=False)
        use_fuzzy_completion = _corona_utils.GetSetting(
            "corona_sdk_use_fuzzy_completion", default=True)

        completion_target = self.current_word(view)

        # Because we adjust the prefix to make completions with periods in them work better we may need to
        # trim the part before the period from the returned string (or it will appear to be doubled)
        completion_adjustment = "" if "." not in completion_target else completion_target.partition(
            '.')[0] + '.'

        # _corona_utils.debug('prefix: ', prefix, 'completion_target: ', completion_target, "; completion_adjustment: ", completion_adjustment, "; corona_sdk_complete_periods: ", _corona_utils.GetSetting("corona_sdk_complete_periods", True) )
        self.setupFuzzyMatch(completion_target)

        # Sample:
        #   { "trigger": "audio.stopWithDelay()", "contents": "audio.stopWithDelay( ${1:duration}, ${2:[, options ]} )"},
        #   "audio.totalChannels ",

        # This is horrible on a variety of levels but is brought upon us by the fact that
        # ST completion files contain an array that is a mixture of strings and dicts
        comps = []

        # check if text in current line to cursor contains require statement
        # if so attempt to fill completions with lua formatted file paths
        textToCursor = _sublime_utils.getTextToCursor(view)
        completingRequireStatement = self._findRequire.search(textToCursor)
        inString = self.inString(textToCursor)
        if completingRequireStatement or inString:
            extensions = [".lua"]
            if not completingRequireStatement:
                extensions = _corona_utils.GetSetting(
                    "corona_sdk_autocomplete_extensions", default=[])
            followSymlinks = _corona_utils.GetSetting(
                "corona_sdk_follow_symlinks", default=False)
            pathSuggestions = _lua_paths.getFilesAndPaths(
                view,
                extensions=extensions,
                followlinks=followSymlinks,
                converttoluapaths=completingRequireStatement)
            for namePath in pathSuggestions:
                name = namePath[0]
                luaPath = namePath[1]
                if self.fuzzyMatchString(
                        name, use_fuzzy_completion) or self.fuzzyMatchString(
                            luaPath, use_fuzzy_completion):
                    comps.append((luaPath, luaPath))

        # Add textual completions from the document
        for c in view.extract_completions(completion_target):
            comps.append((c, c))

        # don't add Corona API completions if editing a require statement or more generally a string
        # the regex will correctly match multiline strings, but to detect them we need to search more of the document
        if completingRequireStatement or inString:
            return list(set(comps))

        for c in self._completions['completions']:
            trigger = ""
            contents = ""
            if isinstance(c, dict):
                if self.fuzzyMatchString(c['trigger'], use_fuzzy_completion):
                    trigger = c['trigger']
                    contents = c['contents']
            elif is_string_instance(c):
                if self.fuzzyMatchString(c, use_fuzzy_completion):
                    _corona_utils.debug("String match: ", c)
                    trigger = c
                    contents = c
            if trigger is not "":
                if strip_white_space and contents is not "":
                    contents = self._findWhiteSpace.sub("\\1", contents)
                # If we do the completion adjustment on completions that aren't functions
                # ST somehow erases the text before the period from the document leaving
                # just the piece after it (it makes no sense).  This fixes that but will
                # almost certainly have to be changed when ST's behavior changes.
                if "(" in contents:
                    comps.append(
                        (trigger, contents.replace(completion_adjustment, '')))
                else:
                    comps.append((trigger, contents))

        # _corona_utils.debug("extract_completions: ", view.extract_completions(completion_target))

        # Remove duplicates
        comps = list(set(comps))

        # _corona_utils.debug("comps: ", comps)

        return comps
 def on_post_save(self, view):
   if self.is_lua_file(view):
     auto_build = _corona_utils.GetSetting("corona_sdk_auto_build", False)
     if auto_build:
       _corona_utils.debug("Corona Editor: auto build triggered")
       view.window().run_command("build")
 def __init__(self, *args, **kw):
   _corona_utils.debug("CoronaLabsCollector: __init__")
   super(CoronaLabsCollector, self).__init__(*args, **kw)
   self.periods_set = {}
示例#19
0
 def __init__(self):
     _corona_utils.debug("CoronaLabs: __init__")
     global CoronaCompletions
     CoronaCompletions = self
示例#20
0
    def find_completions(self, view, prefix):
        self.load_completions(
            _corona_utils.GetSetting("corona_sdk_use_docset", "public"))

        completion_target = self.current_word(view)

        # Because we adjust the prefix to make completions with periods in them work better we may need to
        # trim the part before the period from the returned string (or it will appear to be doubled)
        completion_adjustment = "" if "." not in completion_target else completion_target.partition(
            '.')[0] + '.'

        # _corona_utils.debug('prefix: ', prefix, 'completion_target: ', completion_target, "; completion_adjustment: ", completion_adjustment, "; corona_sdk_complete_periods: ", _corona_utils.GetSetting("corona_sdk_complete_periods", True) )

        self.setupFuzzyMatch(completion_target)

        # Sample:
        #   { "trigger": "audio.stopWithDelay()", "contents": "audio.stopWithDelay( ${1:duration}, ${2:[, options ]} )"},
        #   "audio.totalChannels ",

        # This is horrible on a variety of levels but is brought upon us by the fact that
        # ST completion files contain an array that is a mixture of strings and dicts
        comps = []
        for c in self._completions['completions']:
            trigger = ""
            contents = ""
            if isinstance(c, dict):
                if self.fuzzyMatchString(c['trigger'],
                                         self._use_fuzzy_completion):
                    trigger = c['trigger']
                    contents = c['contents']
            elif is_string_instance(c):
                if self.fuzzyMatchString(c, self._use_fuzzy_completion):
                    _corona_utils.debug("String match: ", c)
                    trigger = c
                    contents = c

            if trigger is not "":
                if self._strip_white_space and contents is not "":
                    contents = self._findWhiteSpace.sub("\\1", contents)
                # If we do the completion adjustment on completions that aren't functions
                # ST somehow erases the text before the period from the document leaving
                # just the piece after it (it makes no sense).  This fixes that but will
                # almost certainly have to be changed when ST's behavior changes.
                if "(" in contents:
                    comps.append(
                        (trigger, contents.replace(completion_adjustment, '')))
                else:
                    comps.append((trigger, contents))

        # _corona_utils.debug("extract_completions: ", view.extract_completions(completion_target))

        # Add textual completions from the document
        for c in view.extract_completions(completion_target):
            comps.append((c, c))

        # Reorganize into a list
        comps = list(set(comps))
        comps.sort()

        # _corona_utils.debug("comps: ", comps)

        return comps
示例#21
0
 def __init__(self, *args, **kw):
     _corona_utils.debug("CoronaLabsCollector: __init__")
     super(CoronaLabsCollector, self).__init__(*args, **kw)
     self.periods_set = {}