diff --git a/pysrt/srtfile.py b/pysrt/srtfile.py index e3d79b5..b2cbffe 100644 --- a/pysrt/srtfile.py +++ b/pysrt/srtfile.py @@ -178,11 +178,11 @@ def read(self, source_file, error_handling=ERROR_PASS): opened with `codecs.open()` or an array of unicode. """ self.eol = self._guess_eol(source_file) - self.extend(self.stream(source_file, error_handling=error_handling)) + self.extend(self.stream(source_file, error_handling=error_handling, parent=self)) return self @classmethod - def stream(cls, source_file, error_handling=ERROR_PASS): + def stream(cls, source_file, error_handling=ERROR_PASS, parent=None): """ stream(source_file, [error_handling]) @@ -209,7 +209,7 @@ def stream(cls, source_file, error_handling=ERROR_PASS): string_buffer = [] if source and all(source): try: - yield SubRipItem.from_lines(source) + yield SubRipItem.from_lines(source, parent) except Error as error: error.args += (''.join(source), ) cls._handle_error(error, error_handling, index) diff --git a/pysrt/srtitem.py b/pysrt/srtitem.py index 5597905..34f2a00 100644 --- a/pysrt/srtitem.py +++ b/pysrt/srtitem.py @@ -22,7 +22,7 @@ class SubRipItem(ComparableMixin): ITEM_PATTERN = str('%s\n%s --> %s%s\n%s\n') TIMESTAMP_SEPARATOR = '-->' - def __init__(self, index=0, start=None, end=None, text='', position=''): + def __init__(self, index=0, start=None, end=None, text='', position='', parent=None): try: self.index = int(index) except (TypeError, ValueError): # try to cast as int, but it's not mandatory @@ -32,6 +32,23 @@ def __init__(self, index=0, start=None, end=None, text='', position=''): self.end = SubRipTime.coerce(end or 0) self.position = str(position) self.text = str(text) + self.parent = parent + + @property + def previous(self): + index = self.parent.index(self) - 1 + if index >= 0: + return self.parent[index] + else: + return None + + @property + def next(self): + index = self.parent.index(self) + 1 + if index < len(self.parent): + return self.parent[index] + else: + return None @property def duration(self): @@ -74,11 +91,11 @@ def shift(self, *args, **kwargs): self.end.shift(*args, **kwargs) @classmethod - def from_string(cls, source): - return cls.from_lines(source.splitlines(True)) + def from_string(cls, source, parent=None): + return cls.from_lines(source.splitlines(True), parent=parent) @classmethod - def from_lines(cls, lines): + def from_lines(cls, lines, parent=None): if len(lines) < 2: raise InvalidItem() lines = [l.rstrip() for l in lines] @@ -87,7 +104,7 @@ def from_lines(cls, lines): index = lines.pop(0) start, end, position = cls.split_timestamps(lines[0]) body = '\n'.join(lines[1:]) - return cls(index, start, end, body, position) + return cls(index, start, end, body, position, parent) @classmethod def split_timestamps(cls, line):