I'm trying to create a Sublime Text plugin (using python) that reverses the order of words in a selected string. I've got the main functionality working but now my problem is that every symbol at the end of a word (periods, commas, question marks etc) stays where it is, and my goal is to get everything reversed properly so the symbols should move to the start of the word.
def run(self, edit):
selections = self.view.sel()
# Loop through multiple text selections
for location in selections:
# Grab selection
sentence = self.view.substr(location)
# Break the string into an array of words
words = sentence.split()
# The greasy fix
for individual in words:
if individual.endswith('.'):
words[words.index(individual)] = "."+individual[:-1]
# Join the array items together in reverse order
sentence_rev = " ".join(reversed(words))
# Replace the current string with the new reversed string
self.view.replace(edit, location, sentence_rev)
# The quick brown fox, jumped over the lazy dog.
# .dog lazy the over jumped ,fox brown quick The
I've been able to loop through each word and use the endswith() method for a quick fix but this will not find multiple symbols (without a long list of if statements) or account for multiple symbols and move them all.
I've been playing around with regex but still haven't got a solution that works, and I've been looking for a way to change the index of the symbol but still nothing...
If I can give any more details please let me know.
Thanks!