kasperhj
kasperhj

Reputation: 10482

How do I get the current caret position?

I have written a simple ST2 plugin that should just insert a timestamp at the current caret position. However, I am unable to find out how to get the current position.

I have

def run(self, edit):
    timestamp = "%s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
    pos = ???
    self.view.insert(edit, pos, timestamp)

What should pos be?

Upvotes: 12

Views: 4164

Answers (1)

Riccardo Marotti
Riccardo Marotti

Reputation: 20348

Try with

pos = self.view.sel()[0].begin()

This gets the start point of the current selection (if nothing is selected, start and end of selection are the current cursor position).

If you want this to work with multiple selection, you have to iterate on all selections returned by self.view.sel():

for pos in self.view.sel():
    self.view.insert(edit, pos.begin(), timestamp)

Upvotes: 23

Related Questions