Sublime Forum

Region.end() not really the end?

#1

Hello there,

I’ve been using Sublime Text for a few days now, and figured I would mess around with the plugin system. I decided to write a plugin that would wrap the selected strings in a html tag. However, I came across a little issue when using the code below:

view.insert(region.begin(),openTag)
view.insert(region.end(),closeTag)

The code would consistently place the closing tag 3 characters before the end of the selected region, meaning if I selected “cheese” and run the plugin, the code would generate “

che

ese” instead of the desired “

cheese

”.

Now I managed to fix this by just adding three to the region.end(), but this isn’t the ideal solution. Does anybody know what is causing this, or is it just a quirk of Sublime Text?

I’ve put the full code listing below.

class TagWrapCommand(sublimeplugin.TextCommand):
	def run(self, view, args):
		openTag = "<p>"
		closeTag = "</p>"
		for region in view.sel():
			view.insert(region.begin(),openTag)
			view.insert(region.end(),closeTag)
0 Likes

#2

Fret not, I’ve figured it out.

Put simply, region doesn’t change when you add text to the line, so region.end() is still in the same place as it was before I added “

” before it, which is three characters long, hence the three character shift.

A quick solution would be to simply add the end tag first, although a variable could be used to keep track of the amount of characters, and move the end accordingly; essentially making a sort of dynamic region.

0 Likes