Search code examples
pythonsublimetext2sublimetextsublime-text-plugin

Get the word under cursor with Sublime


Let's say we have this text in Sublime Text, and that we have the cursor over f:

hello blabla.foo youhou

I'd like to find a command to get blabla.foo, i.e.

  • search the previous whitespace () occurence before cursor
  • search the next whitespace occurence after cursor
  • get the string between these two occurences

It seems that view.word(...) doesn't work:

import sublime, sublime_plugin

class MyCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        for region in self.view.sel():
            print self.view.substr(self.view.word(region))

because the returned word is foo. How to get the full word instead (i.e. blabla.foo)?


Solution

  • This is because the . (full stop) is recognized as word separator. In your Sublime settings you can remove the . (full stop) from the list of word separators:

    Default: "word_separators": "./\\()\"'-:,.;<>~!@#$%^&*|+=[]{}``~?",
    Change to: "word_separators": "/\\()\"'-:,.;<>~!@#$%^&*|+=[]{``~?",

    After that change view.word(...) should return blabla.foo.