Skip to content

Instantly share code, notes, and snippets.

@trevordixon
Created February 1, 2016 17:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trevordixon/6a795a13c4776a26102b to your computer and use it in GitHub Desktop.
Save trevordixon/6a795a13c4776a26102b to your computer and use it in GitHub Desktop.
Sublime command that replaces repeated lines with a single instance prefixed with a count (much like uniq -c).
import sublime, sublime_plugin
class CountConsecutiveDuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit):
# end and start mark the beginning and end of the current region to replace,
# working backwards.
start = end = self.view.size()
# Preserve trailing newline if last line is empty.
if self.view.line(end).empty():
start = end = end - 1
prevText = None
count = 0
# Once start hits -1, we've reached the beginning and are done.
while start > -1:
line = self.view.line(start - 1)
text = self.view.substr(line)
# Start a new section.
if prevText is None:
prevText = text
start = line.begin()
count += 1
# End of section reached; replace text.
elif text != prevText or start == 0:
replaceRegion = sublime.Region(start, end)
self.view.replace(edit, replaceRegion, str(count) + ' ' + prevText)
start = end = start - 1
prevText = None
count = 0
# Another occurrence. Expand replacement region and increment count.
elif text == prevText:
count += 1
start = line.begin()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment