Created
January 20, 2009 02:37
-
-
Save gcr/49289 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def insert(self, user, pos, text, state): | |
""" | |
Inserts text into the document at pos | |
""" | |
# MANY THANKS TO Infinote for help with these transformations: | |
# http://gobby.0x539.de/trac/wiki/Infinote/Protocol | |
# First, reach back in time and see what we should do | |
# Think of this like a "git rebase"- we want to rebase | |
# the NEW changes on top of the changes the person | |
# didn't know about so they don't have to worry about it. | |
# This has the side-effect of sending events with slightly different | |
# parameters than what you requested. | |
# For every event in our history after our state: | |
for e in self.history[state:]: | |
if (e['operation'] == "insert"): | |
# We gotta account for stuff that was inserted before our | |
# latest characters | |
if (e['pos'] <= pos): | |
# The old stuff should push our new stuff forward. | |
# Add the text length to the position | |
pos += len(e['text']) | |
elif (e['operation'] == "delete"): | |
# Deleted text should be accounted for | |
if (pos >= e['end']): | |
# Our new inserted text should be shifted to the left | |
pos -= (e['end'] - e['begin']) | |
elif (pos >= e['begin']): | |
# Right between what they deleted. Ha ha. | |
# Our inserted text should be placed right at the | |
# beginning of where they deleted | |
pos = e['begin'] | |
# BY THIS POINT: Our changes should be applicable to the new | |
# version of the document. Silly client for not knowing better... | |
# Then, take our new "pos" and help it along | |
self.content = self.content[:pos] + text + self.content[pos:] | |
# And send the event to everyone | |
self.send_event({ | |
"type": "insert", | |
"user": user.get_state(), | |
"text": text, | |
"pos": pos, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment