Sublime Forum

Erasing Phantom by Region not working

#1

So I am running a phantom example, as I am new to sublime plugin. I tried to erase the phantom by phantom.region, but it is not working, any ideas?

def open_test(self, edit):
		# v = self.view
		# test_view = v.window().new_file()
		# v.window().set_view_index(test_view, 1, 1)
		# phantoms = []
		# phantoms.append(sublime.Phantom(sublime.Region(0), "100", sublime.LAYOUT_INLINE))
		# self.phantom_set.update(phantoms)
		phantoms = []
		if self.view.size() < 2**20:
			candidates = self.view.find_all('=>')
			for r in candidates:
				line_region = self.view.line(r.a)
				line = self.view.substr(line_region)
				idx = r.a - line_region.a
				if idx != -1:
					val = len(line[0:idx].strip())
					op_pt = line_region.a + idx
					phantoms.append(sublime.Phantom(sublime.Region(op_pt + 2),"test_test_test",sublime.LAYOUT_INLINE))
		self.phantom_set.update(phantoms)
		for phantom in phantoms:
			self.view.erase(edit, phantom.region)
0 Likes

#2

That’s because View.erase is an API method that changes the underlying buffer associated with the view. In simpler words, it changes the file on disk. That’s why when you use any of View.replace, View.erase or View.insert, the file modifies & you see that white dot in the tab (characteristic of unsaved files).

Now phantoms are something special. It allows you to introduce something (can be plain text or some bits of HTML) into the buffer without any modifications to the file. Your file doesn’t change on disk even after a phantom is introduced.(that’s why it’s such a powerful feature).

In your present code however, you are trying to erase a phantom in the wrong way. View.erase is for something that is “physically” (for want of a better word) present in the file. Phantoms are not physically present. The correct method is to use View.erase_phantoms if you know the key or View.erase_phantom_by_id if you know the pid (phantom id).

Other than that, the example you are referring to comes from this post :- Dev Build 3118
You can refer that post for more details.

Here are some other endpoints related to phantoms (missed by the documentation) :

1. View.add_phantom(key, region, content, layout, on_navigate = None)
2. View.erase_phantoms(key)
3. View.erase_phantom_by_id(pid)
4. View.query_phantom(pid)
5. View.query_phantoms(pid)
0 Likes