I don’t know that I’m any particular judge of things being properly pythonic (I often check SO to see if I’m contravening any defined idioms, for example) or Sublime-y, for that matter. What I would do and what’s a good idea may or may not jive at any given point. 
If you only intend to take the first selection instead of all of them, it’s possibly cleaner to flip the order of extracting the words and checking how many so that you only trigger on a single selection and generate an error right away. Then w
is always just a single string and you don’t need to subscript it:
if not len(self.view.sel()) == 1:
sublime.error_message("Must select exactly one region.")
return
w = self.view.substr(self.view.sel()[0])
Note however that as defined in your post, this will trigger even if there is no outwardly visible selection, which may not be what you want.
There is one sublime.Region
in view.sel()
for every caret that is in the buffer (which can be none at all, in which case the list is empty). The Region
tells you where it starts and ends as character offsets in the buffer, and also tells you the size()
in characters that the region spans.
Regular carets with no selection have a begin()
and end()
that are the same character, which makes the size()
report 0, which causes view.substr()
to always return an empty string.
This is missing a return
, so it will warn you that the command isn’t an expected one, but it will try to run it anyway. Sublime silently ignores attempts to run commands that don’t exist, so that’s not really any big deal though.
One last thing would be that technically it’s not just white space that separates things into words, punctuation does as well. The word_separators
setting contains the characters that Sublime considers word separators for various commands, so you could consult that and see if any of the characters in it appear in the extracted word.
An example of something like that might be the following:
# Get the list of word separators
sepchars = self.view.settings().get("word_separators", "")
# If w contains white space or a separator, it's more than one word.
for c in sepchars + " \t\n":
if c in w:
print("this is more than one word")
return