Created
November 23, 2022 04:29
-
-
Save DavesCodeMusings/f0bae9d18775346a8cfbf9349e52c705 to your computer and use it in GitHub Desktop.
Python class to implement a gap buffer for accepting user input with editing features.
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
| class GapBuffer: | |
| def __init__(self, size, prefill=None): | |
| self._buffer = bytearray(size) | |
| self._gap_start = 0 # first element of gap | |
| self._gap_end = len(self._buffer) # first element after gap | |
| if prefill != None: | |
| prefill_end = len(prefill) if (len(prefill) <= size) else size | |
| self._buffer[0:prefill_end] = prefill[0:prefill_end] | |
| self._gap_start = len(prefill) | |
| def __len__(self): | |
| return len(self._buffer) - (self._gap_end - self._gap_start) | |
| def __repr__(self): | |
| contiguous_buffer = self._buffer[0:self._gap_start] + self._buffer[self._gap_end:len(self._buffer)] | |
| return contiguous_buffer | |
| def __str__(self): | |
| return self.__repr__().decode('utf-8') | |
| @property | |
| def is_full(self): | |
| return True if (self._gap_start >= len(self._buffer)) else False | |
| def insert(self, c): | |
| if self.is_full == True: | |
| return None | |
| self._buffer[self._gap_start] = ord(c) | |
| if (self._gap_start < self._gap_end): | |
| self._gap_start = self._gap_start + 1 | |
| return self._gap_start | |
| def delete(self): | |
| if (self._gap_start > 0): | |
| self._gap_start -= 1 | |
| return self._gap_start | |
| def back(self): | |
| """ | |
| Move insertion point one character closer to buffer's end. | |
| """ | |
| if self._gap_start > 0: | |
| self._gap_start -= 1 | |
| self._gap_end -= 1 | |
| self._buffer[self._gap_end] = self._buffer[self._gap_start] | |
| return self._gap_start | |
| def forward(self): | |
| """ | |
| Move insertion point one character closer to buffer's beginning. | |
| """ | |
| if self._gap_end < len(self._buffer): | |
| self._buffer[self._gap_start] = self._buffer[self._gap_end] | |
| self._gap_start += 1 | |
| self._gap_end += 1 | |
| return self._gap_start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment