| 673 | |
| 674 | |
| 675 | class NavigableString(str, PageElement): |
| 676 | |
| 677 | PREFIX = '' |
| 678 | SUFFIX = '' |
| 679 | |
| 680 | def __new__(cls, value): |
| 681 | """Create a new NavigableString. |
| 682 | |
| 683 | When unpickling a NavigableString, this method is called with |
| 684 | the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be |
| 685 | passed in to the superclass's __new__ or the superclass won't know |
| 686 | how to handle non-ASCII characters. |
| 687 | """ |
| 688 | if isinstance(value, str): |
| 689 | u = str.__new__(cls, value) |
| 690 | else: |
| 691 | u = str.__new__(cls, value, DEFAULT_OUTPUT_ENCODING) |
| 692 | u.setup() |
| 693 | return u |
| 694 | |
| 695 | def __copy__(self): |
| 696 | """A copy of a NavigableString has the same contents and class |
| 697 | as the original, but it is not connected to the parse tree. |
| 698 | """ |
| 699 | return type(self)(self) |
| 700 | |
| 701 | def __getnewargs__(self): |
| 702 | return (str(self),) |
| 703 | |
| 704 | def __getattr__(self, attr): |
| 705 | """text.string gives you text. This is for backwards |
| 706 | compatibility for Navigable*String, but for CData* it lets you |
| 707 | get the string without the CData wrapper.""" |
| 708 | if attr == 'string': |
| 709 | return self |
| 710 | else: |
| 711 | raise AttributeError( |
| 712 | "'%s' object has no attribute '%s'" % ( |
| 713 | self.__class__.__name__, attr)) |
| 714 | |
| 715 | def output_ready(self, formatter="minimal"): |
| 716 | output = self.format_string(self, formatter) |
| 717 | return self.PREFIX + output + self.SUFFIX |
| 718 | |
| 719 | @property |
| 720 | def name(self): |
| 721 | return None |
| 722 | |
| 723 | @name.setter |
| 724 | def name(self, name): |
| 725 | raise AttributeError("A NavigableString cannot be given a name.") |
| 726 | |
| 727 | class PreformattedString(NavigableString): |
| 728 | """A NavigableString not subject to the normal formatting rules. |