Sublime Forum

Highlight/change background color of selected text

#1

I was wondering if there was a way to select a line of text and then change the background color as if it were highlighted. Basically I am going through a list and want to highlight the items I have completed. TIA!

0 Likes

#2

This should get you started. Assign command “add_highlight” in your key bindings. Then you can use toggle_bookmark and clear_bookmarks to remove the highlighting.

The code below will highlight the selected text with the syntax coloring for scope “comment”. You can change the color - by changing the third argument to add_regions. Look at the API Reference for add_regions: “The scope is used to source a color to draw the regions in, it should be the name of a scope, such as “comment” or “string”.”

[code]import sublime, sublime_plugin

class AddHighlightCommand(sublime_plugin.TextCommand):
def run(self, edit):
HighlightRegions = self.view.get_regions(“bookmarks”)
HighlightRegions.append(self.view.sel()[0])
self.view.add_regions(“bookmarks”, HighlightRegions, “string”, “dot”, sublime.PERSISTENT)
[/code]

0 Likes

#3

I created a new plugin using the following

import sublime, sublime_plugin

class AddHighlightCommand(sublime_plugin.TextCommand):
   def run(self, edit):
      HighlightRegions = self.view.get_regions("bookmarks")
      HighlightRegions.append(self.view.sel()[0])
      add_regions("bookmarks", HighlightRegions, "string", "dot", sublime.PERSISTENT)

and then made the following key bindings

	{ "keys": "ctrl+f7"], "command": "toggle_bookmark" },
	{ "keys": "alt+f7"], "command": "clear_bookmark" }

and it just puts a “>” next to the selected line. What am I doing wrong? Thanks!

0 Likes

#4
  1. toggle_bookmark will not highlight, which is why you are making your own custom command. Did you add the keybinding for add_highlight? To find the command name - take the class name - remove “Command” and convert CamelCase to snake_case (AddHighlightCommand becomes add_highlight).
    { “keys”: “f7”], “command”: “add_highlight” },

  2. When you save the plugin and when you run the command- open the console (usually ctrl+`) to see if it is giving any errors.

  3. You could actually have a singular key biding for toggle_highlight. You can use the custom toggle bookmark command I had written earlier - class ToggleBookmarkWholelineCommand here - then remove sublime.HIDDEN so that it will highlight. It will ALSO have an icon in the gutter which you can choose a “>” or a “dot” or a “circle” by changing the fourth argument of add_regions. Look at the arguments for add_regions in the API link posted earlier.
    So:
    sublime.active_window().active_view().add_regions(“bookmarks”, newBookmarks, “bookmarks”, “bookmark”, sublime.HIDDEN | sublime.PERSISTENT)
    should become:
    sublime.active_window().active_view().add_regions(“bookmarks”, newBookmarks, “bookmarks”, “bookmark”, sublime.PERSISTENT)

0 Likes