2 # -*- coding: utf-8 -*-
4 # Copyright 2006 Zuza Software Foundation
6 # This file is part of translate.
8 # translate is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # translate is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with translate; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 """Supports a hybrid Unicode string that can also have a list of alternate strings in the strings attribute"""
24 from translate
.misc
import autoencode
26 class multistring(autoencode
.autoencode
):
27 def __new__(newtype
, string
=u
"", encoding
=None, errors
=None):
28 if isinstance(string
, list):
30 raise ValueError("multistring must contain at least one string")
31 mainstring
= string
[0]
32 newstring
= multistring
.__new
__(newtype
, string
[0], encoding
, errors
)
33 newstring
.strings
= [newstring
] + [autoencode
.autoencode
.__new
__(autoencode
.autoencode
, altstring
, encoding
, errors
) for altstring
in string
[1:]]
35 newstring
= autoencode
.autoencode
.__new
__(newtype
, string
, encoding
, errors
)
36 newstring
.strings
= [newstring
]
39 def __init__(self
, *args
, **kwargs
):
40 super(multistring
, self
).__init
__(*args
, **kwargs
)
41 if not hasattr(self
, "strings"):
44 def __cmp__(self
, otherstring
):
45 if isinstance(otherstring
, multistring
):
46 parentcompare
= cmp(autoencode
.autoencode(self
), otherstring
)
50 return cmp(self
.strings
[1:], otherstring
.strings
[1:])
51 elif isinstance(otherstring
, autoencode
.autoencode
):
52 return cmp(autoencode
.autoencode(self
), otherstring
)
53 elif isinstance(otherstring
, unicode):
54 return cmp(unicode(self
), otherstring
)
55 elif isinstance(otherstring
, str):
56 return cmp(str(self
), otherstring
)
58 return cmp(type(self
), type(otherstring
))
60 def __ne__(self
, otherstring
):
61 return self
.__cmp
__(otherstring
) != 0
63 def __eq__(self
, otherstring
):
64 return self
.__cmp
__(otherstring
) == 0
67 parts
= [autoencode
.autoencode
.__repr
__(self
)] + [repr(a
) for a
in self
.strings
[1:]]
68 return "multistring([" + ",".join(parts
) + "])"
70 def replace(self
, old
, new
, count
=None):
72 newstr
= multistring(super(multistring
, self
).replace(old
, new
), self
.encoding
)
74 newstr
= multistring(super(multistring
, self
).replace(old
, new
, count
), self
.encoding
)
75 for s
in self
.strings
[1:]:
77 newstr
.strings
.append(s
.replace(old
, new
))
79 newstr
.strings
.append(s
.replace(old
, new
, count
))