Created
October 22, 2024 12:42
-
-
Save zezic/a9937bc097f3bff1fc7413e2cf74fbbc to your computer and use it in GitHub Desktop.
Highlight Last Word Diff for Sublime Text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sublime | |
import sublime_plugin | |
import re | |
class HighlightLastWordDiffCommand(sublime_plugin.TextCommand): | |
def run(self, edit): | |
# Get all lines in the document | |
view = self.view | |
lines = view.lines(sublime.Region(0, view.size())) | |
# Keep track of last word from the previous line | |
last_word_prev = None | |
# Clear existing regions to reset highlights | |
view.erase_regions("last_word_diff_highlight") | |
regions_to_highlight = [] | |
for i in range(1, len(lines) - 1): | |
# Extract text from previous, current, and next line regions | |
line_prev = view.substr(lines[i - 1]).strip() | |
line_curr = view.substr(lines[i]).strip() | |
line_next = view.substr(lines[i + 1]).strip() | |
# Get the last words of current and previous lines | |
last_word_curr = line_curr.split()[-1] | |
last_word_prev = line_prev.split()[-1] | |
# Compare last words | |
if last_word_curr != last_word_prev: | |
# Find the region of the last word in the current line | |
last_word_region = self.get_last_word_region(view, lines[i], last_word_curr) | |
if last_word_region: | |
regions_to_highlight.append(last_word_region) | |
# Apply highlights to the view | |
if regions_to_highlight: | |
view.add_regions("last_word_diff_highlight", regions_to_highlight, "region.redish", "", sublime.DRAW_NO_OUTLINE) | |
def get_last_word_region(self, view, line_region, last_word): | |
""" Returns the region of the last word in the given line. """ | |
line_text = view.substr(line_region) | |
last_word_match = re.search(rf'(\b{re.escape(last_word)}\b)$', line_text) | |
if last_word_match: | |
# Find the region of the last word within the line | |
start = line_region.begin() + last_word_match.start(1) | |
end = line_region.begin() + last_word_match.end(1) | |
return sublime.Region(start, end) | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment