Search code examples
sublimetext3sublime-text-plugin

Writing an autocomplete plugin in Sublime Text


Within my company we have an XML-based notation. Among other features, it is possible to define references from one XML document into another. I would like to enable autocompletion in Sublime so that whenever I am adding a reference, the possible files (i.e. XML files within the same project) and link points (i.e. symbols within that file) get offered as recommendations.

So far, I have found a lot of plugins that enable autocomplete for, say, HTML, PHP or LaTeX. However, I have the feeling the code base is too complex for a somewhat simple task. Is there, for instance, some vanilla function that generates completions based on an arbitrary array received as parameter? I would create the logic to determine what is a symbol and derive said array, but the whole process seems somewhat cumbersome to me.

(As a note: I can program in Python and have fiddled with other Sublime features, such as snippets, but these packages seem to be much more complex than it feels necessary.)


Solution

  • The base to create the completions entry is not to complicated. You now need to fill the array with the correct values (this could be done via a project setting or parsing other files).

    import sublime
    import sublime_plugin
    
    
    # Your array, which contains the completions
    arr = ["foo", "bar", "baz"]
    
    
    class MyCompletionsListener(sublime_plugin.EventListener):
        def on_query_completions(self, view, prefix, locations):
            loc = locations[0]
    
            # limit you completions scope
            if not view.score_selector(loc, "text"):
                return
    
            completions = [(v + "\tYour Description", v) for v in arr]
    
            return completions
    

    OP's note: The answer works as advertised. However, the integration is so seamless that I thought for a while that something was missing. If the Python script above is on the right folder, all of the completions returned by the completions array will be suggested (depending on Sublime settings, it might be necessary to trigger the completions menu with Ctrl+Space). Also worth noting:

    • The completions may be None, in which case they just don't add any completion option, or an array of 2-tuples, where the first element is the description (which will be shown in the drop-down menu and trigger the completion) and the second is the value (i.e. the text that will be input if the completion is selected).
    • The score_selector method can be used to determine if the cursor position is within a given scope.