Sublime Forum

What is the easiest way to clear the view?

#1

Lets say I have a bunch of text written in the editor, and the plugin in knows which view this is. What is the best way to empty the document? Do you select all and then clear?

Do you use these methods:

Methods Return Value Description
begin() int Returns the minimum of a and b.
end() int Returns the maximum of a and b.
erase(edit, region) None Erases the contents of the region from the buffer.

Well I’m not to clear on what Regions are so if you would enlighten me I’d appreciate it : )

1 Like

#2

Searching the default key-bindings to find the equivalent of Ctrl-A and Delete:

some_view.run_command("select_all") some_view.run_command("right_delete")
When working with the ST-API it is easy to forget that often the simplest way is just to run a command.

To do this with the API:

some_view.erase(edit, sublime.Region(0, some_view.size())

FYI The content of a view can be considered the region (0, view.size()). This does not correspond directly to the number of (single) character-positions as the Tab character, which might cover e.g. four-space, can be regarded as a single character. Internally, it is a little more detailed than this suggests, because ST is able to extract from a region the line (row) and column positions. It must, therefore, (I’m guessing!) maintain an internal map of how different regions correspond to different *areas *of the view.

RegionSets are far less useful (than Regions) as we cannot arbitrarily create these. The most significant RegionSet is sel(), which we can clear and add-to, etc… However, we can store Regions in a list which, effectively, can then behave like a RegionSet.

2 Likes

#3

Thank you for your help again : ) I’m still writing the plugin and will be able to test once I finish the modifications

1 Like

#4

In addition, you can also replace the text in a view without creating/adding two steps into the undo stack, i.e, the Ctrl+Z feature by creating a new text command:

import sublime_plugin

class ReplaceTextInViewWithSingleUndoStackCommand(sublime_plugin.TextCommand):
	def run(self, edit, new_text):
		view = self.view
		view.erase( edit, sublime.Region( 0, view.size() ) )
		view.insert( edit, 0, new_text )

# Then, you can call it later with:
view.run_command( 
        "replace_text_in_view_with_single_undo_stack", 
        { "new_text", "You new cool text to add..." } 
)

Related to:
https://www.sublimetext.com/docs/3/api_reference.html#sublime.View


0 Likes