Sublime Forum

What's Wrong with My Command?

#1

Following is my command in a plugin that is banded to ctrl+’(not ctrl+`). It does not work exactly. It is expected to add the 3-quote mark to the beginning side and end of the selected region(s). However, in fact, the open quote-mark lies on right place, but the close dose not, it inserts to the last-third of the region. Why? How?

class AddQuoteCommand(PyBasicCommand): # a simple command that appends 3-quote mark to the two sides of selected region(s) def run(self, edit): for sel in self.view.sel(): b, e = sel.begin(), sel.end() self.view.insert(edit, b, "'''") self.view.insert(edit, e, "'''")

system: winxp
version: 3.3083

ps: There are so many posts unrelated to sublime :frowning:

0 Likes

#2

This is a logic bug on your part. When you insert at (b), it inserts 3 chars and moves the selection end location, but (e) still points to the old location, so you insert too early. My advice is to work backwards and insert the end of the last selection first and work all the way back. This is because when you insert at the end, it does not change your beginning position, but when you insert at the beginning, you move the positions of all selections points that come after that insert.

0 Likes

#3

:exclamation:Thanks

0 Likes

#4

As an addition to this, usually you would think that you needed to iterate on the selection regions in reverse as well, but this is actually not true. The selections do get updated internally, but the sublime.Region instance that you received from the for loop already does not.

Basically, for each iteration in your loop, sel is assigned the actual current selection because it is a dynamic lookup, but once the object is assigned, it’s static. For that reason, it’s also highly unencouraged to modify the selection while iterating over it. The workaround for that is to copy the entire selection (by passing it to the list constructor, i.e. list(self.view.sel()) and then iterate on that list in reverse.

You probably don’t need to know this (right now), but maybe it will come in hand later or for others reading this.

0 Likes