Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bofm
Last active March 3, 2017 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bofm/a378dd4525352ac0e67431861a96a65d to your computer and use it in GitHub Desktop.
Save bofm/a378dd4525352ac0e67431861a96a65d to your computer and use it in GitHub Desktop.
Sublime Text captute edits
# Source:
# https://forum.sublimetext.com/t/retrieving-inserted-and-deleted-text/18697/24
import sublime
import sublime_plugin
def get_cursors(view):
# can't use `view.sel()[:]` because it gives an error `TypeError: an integer is required`
return [cursor for cursor in view.sel()]
class RecordSessionListener(sublime_plugin.EventListener):
prev_cursors = {}
def on_new_async(self, view):
self.record_cursor_pos(view)
def on_activated_async(self, view):
self.record_cursor_pos(view)
def record_cursor_pos(self, view):
cursors = []
for cursor in get_cursors(view):
if cursor.empty() and cursor.begin() > 0: # if the cursor is empty and isn't at the start of the document
# record the previous character for backspace purposes
cursors.append((cursor, view.substr(cursor.begin() - 1)))
else:
cursors.append((cursor, view.substr(cursor))) # record the text inside the cursor
self.prev_cursors[view.id()] = cursors
def on_selection_modified(self, view):
self.record_cursor_pos(view)
def on_insert(self, view, cursor_begin, cursor_end, text):
self.log('insert', 'from', view.rowcol(cursor_begin),
'to', view.rowcol(cursor_end), '"' + text + '"')
def on_delete(self, view, cursor_begin, cursor_end, text):
self.log('delete', 'from', view.rowcol(cursor_begin), 'to', cursor_end, '"' + text + '"')
def log(self, *values):
print(type(self).__name__, *values)
def on_modified(self, view):
sel = view.sel()
offset = 0
print('current:', list(sel))
print('previous:', self.prev_cursors[view.id()])
for index, cursor in enumerate(sel):
prev_cursor, prev_text = self.prev_cursors[view.id()][index]
prev_cursor = sublime.Region(prev_cursor.begin() + offset, prev_cursor.end() + offset)
if not prev_cursor.empty() or cursor.begin() < prev_cursor.begin():
self.on_delete(view, prev_cursor.begin(), prev_cursor.end(), prev_text)
if cursor.begin() > prev_cursor.begin():
region = prev_cursor.cover(cursor)
self.on_insert(view, region.begin(), region.end(), view.substr(region))
offset += cursor.begin() - prev_cursor.begin()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment