Sublime Forum

Extend selection

#1

Hello. I’m trying to do something fairly straight-forward. If there is nothing selected in the view, I want to insert a couple of words at the cursor position, but then extend the selection to include these new words.

The following code works in a round-about way, by creating a Region of a known size and adding it to sel(). If I don’t specify the size (13) then the text is added but not selected :angry:.

How can I extend the current cursor/ selection to include my new text (without specifying a length for my region) please? Andy.

[code]def run(self, edit):
sels = self.view.sel() # sels: RegionSet
for a_sel in sels:
# handle multi-select
pass
if len(sels) != 1: # cancel if multi-select
return
the_region = sels[0]

if the_region.empty():	# that is, begin() == end()
	# print 'nothing selected'
	self.view.sel().clear()
	my_edit = self.view.begin_edit()
	new_region = sublime.Region(the_region.begin(), the_region.end()+13)
	self.view.insert(my_edit, new_region.begin(), ' after cursor')
	self.view.sel().add(new_region)
	self.view.end_edit(my_edit)
	print '#' + self.view.substr(new_region) + '#'
	return[/code]
0 Likes

#2

Well, no worries. I’m reasonably happy with the following solution. It effectively does this:
remembers the cursor position
inserts text (which moves the cursor)
adds the region (from the previous cursor position to the end of the line) to the selection.

[code] the_region = sels[0]

if the_region.empty():		# begin() == end()
	self.view.insert(edit, the_region.end(), ' after cursor')
	self.view.sel().add(sublime.Region(the_region.begin(), 
		self.view.line(the_region).end()))
	return[/code]

I still think it should be possible to insert text in such a way that the selection automatically includes/adds the new text(?). Andy.

0 Likes

#3

You can do this via the insert_snippet command, and setting the “contents” argument to something like ${0:Hello, World}.

You can either make a key binding for this command directly, or call it from a plugin via view.run_command

0 Likes

#4

[quote=“jps”]You can do this via the insert_snippet command, and setting the “contents” argument to something like ${0:Hello, World}.

You can either make a key binding for this command directly, or call it from a plugin via view.run_command[/quote]

Hello jps and thank you for this suggestion. I suppose I could also run commands to select the next two words, or to the end of the line.

However, I’m studying the API at the moment, so I want to work with sel() and regions currently. Andy.

0 Likes