Source code

Download source archive ↓

src/pypdf/pagerange.py

1"""
2Representation and utils for ranges of PDF file pages.
3
4Copyright (c) 2014, Steve Witham <switham_github@mac-guyver.com>.
5All rights reserved. This software is available under a BSD license;
6see https://github.com/py-pdf/pypdf/blob/main/LICENSE
7"""
8
9import re
10from typing import Any, Union
11
12from .errors import ParseError
13
14_INT_RE = r"(0|-?[1-9]\d*)"  # A decimal int, don't allow "-0".
15PAGE_RANGE_RE = f"^({_INT_RE}|({_INT_RE}?(:{_INT_RE}?(:{_INT_RE}?)?)))$"
16# groups:         12     34     5 6     7 8
17
18
19class PageRange:
20    """
21    A slice-like representation of a range of page indices.
22
23    For example, page numbers, only starting at zero.
24
25    The syntax is like what you would put between brackets [ ].
26    The slice is one of the few Python types that can't be subclassed,
27    but this class converts to and from slices, and allows similar use.
28
29      -  PageRange(str) parses a string representing a page range.
30      -  PageRange(slice) directly "imports" a slice.
31      -  to_slice() gives the equivalent slice.
32      -  str() and repr() allow printing.
33      -  indices(n) is like slice.indices(n).
34    """
35
36    def __init__(self, arg: Union[slice, "PageRange", str]) -> None:
37        """
38        Initialize with either a slice -- giving the equivalent page range,
39        or a PageRange object -- making a copy,
40        or a string like
41            "int", "[int]:[int]" or "[int]:[int]:[int]",
42            where the brackets indicate optional ints.
43        Remember, page indices start with zero.
44        Page range expression examples:
45
46            :     all pages.                   -1    last page.
47            22    just the 23rd page.          :-1   all but the last page.
48            0:3   the first three pages.       -2    second-to-last page.
49            :3    the first three pages.       -2:   last two pages.
50            5:    from the sixth page onward.  -3:-1 third & second to last.
51        The third, "stride" or "step" number is also recognized.
52            ::2       0 2 4 ... to the end.    3:0:-1    3 2 1 but not 0.
53            1:10:2    1 3 5 7 9                2::-1     2 1 0.
54            ::-1      all pages in reverse order.
55        Note the difference between this notation and arguments to slice():
56            slice(3) means the first three pages;
57            PageRange("3") means the range of only the fourth page.
58            However PageRange(slice(3)) means the first three pages.
59        """
60        if isinstance(arg, slice):
61            if arg.step == 0:
62                raise ParseError(arg)
63            self._slice = arg
64            return
65
66        if isinstance(arg, PageRange):
67            self._slice = arg.to_slice()
68            return
69
70        m = isinstance(arg, str) and re.match(PAGE_RANGE_RE, arg)
71        if not m:
72            raise ParseError(arg)
73        if m.group(2):
74            # Special case: just an int means a range of one page.
75            start = int(m.group(2))
76            stop = start + 1 if start != -1 else None
77            self._slice = slice(start, stop)
78        else:
79            bounds = [int(g) if g else None for g in m.group(4, 6, 8)]
80            step = bounds[2]
81            if step == 0:
82                # A zero stride cannot select anything; slice() accepts it here
83                # but raises as soon as the range is applied.
84                raise ParseError(arg)
85            self._slice = slice(*bounds)
86
87    @staticmethod
88    def valid(input: Any) -> bool:
89        """
90        True if input is a valid initializer for a PageRange.
91
92        Args:
93            input: A possible PageRange string, slice, or PageRange object.
94
95        Returns:
96            True, if the ``input`` is a valid PageRange.
97
98        """
99        if isinstance(input, PageRange):
100            return True
101        if not isinstance(input, (str, slice)):
102            return False
103        try:
104            PageRange(input)
105        except ParseError:
106            return False
107        return True
108
109    def to_slice(self) -> slice:
110        """Return the slice equivalent of this page range."""
111        return self._slice
112
113    def __str__(self) -> str:
114        """A string like "1:2:3"."""
115        s = self._slice
116        indices: tuple[int, int] | tuple[int, int, int]
117        if s.step is None:
118            # A lone "-1" parses as the last page, which is slice(-1, None),
119            # so slice(-1, 0) cannot be written that way.
120            if s.start is not None and s.stop == s.start + 1 and s.start != -1:
121                return str(s.start)
122
123            indices = s.start, s.stop
124        else:
125            indices = s.start, s.stop, s.step
126        return ":".join("" if i is None else str(i) for i in indices)
127
128    def __repr__(self) -> str:
129        """A string like "PageRange('1:2:3')"."""
130        return "PageRange(" + repr(str(self)) + ")"
131
132    def indices(self, n: int) -> tuple[int, int, int]:
133        """
134        Assuming a sequence of length n, calculate the start and stop indices,
135        and the stride length of the PageRange.
136
137        See help(slice.indices).
138
139        Args:
140            n:  the length of the list of pages to choose from.
141
142        Returns:
143            Arguments for range().
144
145        """
146        return self._slice.indices(n)
147
148    def __eq__(self, other: object) -> bool:
149        if not isinstance(other, PageRange):
150            return False
151        return self._slice == other._slice
152
153    def __hash__(self) -> int:
154        return hash((self.__class__, (self._slice.start, self._slice.stop, self._slice.step)))
155
156    def __add__(self, other: "PageRange") -> "PageRange":
157        if not isinstance(other, PageRange):
158            raise TypeError(f"Can't add PageRange and {type(other)}")
159        if self._slice.step is not None or other._slice.step is not None:
160            raise ValueError("Can't add PageRange with stride")
161        a = self._slice.start, self._slice.stop
162        b = other._slice.start, other._slice.stop
163
164        # None start means "beginning" (-inf for ordering); None stop means "end" (+inf).
165        def _start_key(v: int | None) -> float:
166            return float("-inf") if v is None else v
167
168        def _stop_key(v: int | None) -> float:
169            return float("inf") if v is None else v
170
171        if _start_key(a[0]) > _start_key(b[0]):
172            a, b = b, a
173
174        # Now `a` has the smaller (or equal) start.
175        if _start_key(b[0]) > _stop_key(a[1]):
176            # There is a gap between a and b.
177            raise ValueError("Can't add PageRanges with gap")
178        stop = b[1] if _stop_key(b[1]) > _stop_key(a[1]) else a[1]
179        return PageRange(slice(a[0], stop))
180
181
182PAGE_RANGE_ALL = PageRange(":")  # The range of all pages.
183
184
185def parse_filename_page_ranges(
186    args: list[str | PageRange | None]
187) -> list[tuple[str, PageRange]]:
188    """
189    Given a list of filenames and page ranges, return a list of (filename, page_range) pairs.
190
191    Args:
192        args: A list where the first element is a filename. The other elements are
193            filenames, page-range expressions, slice objects, or PageRange objects.
194            A filename not followed by a page range indicates all pages of the file.
195
196    Returns:
197        A list of (filename, page_range) pairs.
198
199    """
200    pairs: list[tuple[str, PageRange]] = []
201    pdf_filename: str | None = None
202    did_page_range = False
203    for arg in [*args, None]:
204        if PageRange.valid(arg):
205            if not pdf_filename:
206                raise ValueError(
207                    "The first argument must be a filename, not a page range."
208                )
209
210            assert arg is not None
211            pairs.append((pdf_filename, PageRange(arg)))
212            did_page_range = True
213        else:
214            # New filename or end of list - use the complete previous file?
215            if pdf_filename and not did_page_range:
216                pairs.append((pdf_filename, PAGE_RANGE_ALL))
217
218            assert not isinstance(arg, PageRange), arg
219            pdf_filename = arg
220            did_page_range = False
221    return pairs
222
223
224PageRangeSpec = str | PageRange | tuple[int, int] | tuple[int, int, int] | list[int]