Answers a copy of self with a sliced string or with a single indexed character. We can't just slice the concatenated string, as there may be overlapping runs and styles. Note that the styles are copied within slice range. No cascading style values are taken from previ
(self, given)
| 637 | textSize = property(_get_textSize) |
| 638 | |
| 639 | def __getitem__(self, given): |
| 640 | """Answers a copy of self with a sliced string or with a single indexed |
| 641 | character. We can't just slice the concatenated string, as there may be |
| 642 | overlapping runs and styles. |
| 643 | Note that the styles are copied within slice range. No cascading |
| 644 | style values are taken from previous runs. |
| 645 | |
| 646 | >>> from pagebot.contexts import getContext |
| 647 | >>> from pagebot.toolbox.units import pt |
| 648 | >>> context = getContext() |
| 649 | >>> style1 = dict(fontSize=pt(12)) |
| 650 | >>> style2 = dict(fontSize=pt(18)) |
| 651 | >>> style3 = dict(fontSize=pt(24)) |
| 652 | >>> bs = context.newString('ABCD', style1) |
| 653 | >>> bs += context.newString('EFGH', style2) # Adding needs context |
| 654 | >>> bs += context.newString('IJKL', style3) |
| 655 | >>> bs # Show concatinated string, spanning the 2 styles |
| 656 | $ABCDEFGHIJ...$ |
| 657 | >>> bs[3], bs[3].runs # Take indexed character from the first run |
| 658 | ($D$, [<BabelRun "D">]) |
| 659 | >>> bs[7], bs[7].runs # Spanning into the second run |
| 660 | ($H$, [<BabelRun "H">]) |
| 661 | >>> bs[2:], bs[2:].runs |
| 662 | ($CDEFGHIJKL$, [<BabelRun "CD">, <BabelRun "EFGH">, <BabelRun "IJKL">]) |
| 663 | >>> bs[:5], bs[:5].runs |
| 664 | ($ABCDE$, [<BabelRun "ABCD">, <BabelRun "E">]) |
| 665 | >>> bs[2:9], bs[2:9].runs |
| 666 | ($CDEFGHI$, [<BabelRun "CD">, <BabelRun "EFGH">, <BabelRun "I">]) |
| 667 | >>> bs[2:-5], bs[2:-5].runs |
| 668 | ($CDEFG$, [<BabelRun "CD">, <BabelRun "EFG">]) |
| 669 | >>> bs[-6:-2], bs[-6:-2].runs |
| 670 | ($GHIJ$, [<BabelRun "GH">, <BabelRun "IJ">]) |
| 671 | >>> bs.context = getContext() # Reset to other context |
| 672 | >>> bs[3], bs[3].runs |
| 673 | ($D$, [<BabelRun "D">]) |
| 674 | """ |
| 675 | if isinstance(given, slice): |
| 676 | start = given.start or 0 |
| 677 | if start < 0: |
| 678 | start += len(self) |
| 679 | stop = given.stop or len(self)+1 |
| 680 | if stop < 0: |
| 681 | stop += len(self) |
| 682 | slicedBs = self.__class__(context=self.context) # Context can be None |
| 683 | i = 0 |
| 684 | for run in self.runs: |
| 685 | style = copy(run.style) |
| 686 | l = len(run) |
| 687 | if i + l < start: |
| 688 | i += len(run) |
| 689 | continue # Not yet there |
| 690 | if i < start: |
| 691 | if i+l < stop: |
| 692 | slicedBs.add(run.s[start-i:], style) |
| 693 | i += len(run) |
| 694 | continue |
| 695 | slicedBs.add(run.s[start-i:stop-i], style) |
| 696 | i += len(run) |
nothing calls this directly
no test coverage detected