Sublime Forum

How to enumerate bookmarks?

#1

From within the API, how can I enumerate all the bookmarks that are present in the current view, without changing the current regions?

(I know I can call select_all_bookmarks but this would alter my set of regions and thus potentially cause the view to jump around, even if I restore the regions later.)

Relatedly, is there a way to remove a bookmark without calling toggle_bookmark? The latter requires setting up the current region to equals the targeted bookmark, as far I know.

0 Likes

#2

The API call view.get_regions() gives you a list of all regions associated with a particular region key, and the region key for bookmarks is bookmarks.

for region in self.view.get_regions("bookmarks"):
    line = self.view.line(region)
    print(self.view.substr(line))

This snippet of code finds all of the bookmark regions, expands them out full lines (via self.view.line()) and then prints them to the console. Bookmark regions capture the state of the selections in the buffer at the time you toggle the bookmark; this means that the bookmark region will be somewhere inside of the line the cursor is on, might be empty if no text was selected (here empty means that the begin and end value are the same), there may be multiples on the same line, etc.

This operation doesn’t disrupt anything to do with the bookmark regions, selections or anything else, unless whatever you do with the information that the bookmarks provide causes that to happen.

In order to do this via the API, you would use view.get_regions() as above, modify the list of regions (either adding in new ones or removing old ones) and then use view.add_regions() to reset the set of regions that are associated with that key:

regions = self.view.get_regions("bookmarks")
self.view.add_regions("bookmarks", regions[1:], "text", "bookmark")

This snippet removes the first bookmark from the list and then puts the remainder back, which has the effect of removing the first one. The "text" says that the bookmark icon in the gutter should be rendered the same as the text color in use in the current theme, and the "bookmark" tells the call what icon to use in the gutter.

The only thing this changes is the regions that are considered bookmarks.

2 Likes

#3

Sorry for the late reply. It’s what I needed. (Nb: view.set_regions should be view.add_regions, as corrected later.)

0 Likes