1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 """
22 Contains the C{parse} function that parses normal strings into StringElem-
23 based "rich" string element trees.
24 """
25
26 from translate.storage.placeables import base, StringElem
27
28 -def parse(tree, parse_funcs):
29 """Parse placeables from the given string or sub-tree by using the
30 parsing functions provided.
31
32 The output of this function is B{heavily} dependent on the order of the
33 parsing functions. This is because of the algorithm used.
34
35 An over-simplification of the algorithm: the leaves in the C{StringElem}
36 tree are expanded to the output of the first parsing function in
37 C{parse_funcs}. The next level of recursion is then started on the new
38 set of leaves with the used parsing function removed from
39 C{parse_funcs}.
40
41 @type tree: unicode|StringElem
42 @param tree: The string or string element sub-tree to parse.
43 @type parse_funcs: A list of parsing functions. It must take exactly
44 one argument (a C{unicode} string to parse) and return a list of
45 C{StringElem}s which, together, form the original string. If nothing
46 could be parsed, it should return C{None}."""
47 if isinstance(tree, unicode):
48 tree = StringElem(tree)
49 if not parse_funcs:
50 return tree
51
52 parse_func = parse_funcs[0]
53
54 for leaf in tree.flatten():
55
56
57 if not leaf.istranslatable:
58 continue
59
60 unileaf = unicode(leaf)
61 if not unileaf:
62 continue
63
64 subleaves = parse_func(unileaf)
65 if subleaves is not None:
66 if len(subleaves) == 1 and type(leaf) is type(subleaves[0]) and leaf == subleaves[0]:
67 pass
68 elif isinstance(leaf, unicode):
69 parent = tree.get_parent_elem(leaf)
70 if parent is not None:
71 if len(parent.sub) == 1:
72 parent.sub = subleaves
73 leaf = parent
74 else:
75 leafindex = parent.sub.index(leaf)
76 parent.sub[leafindex] = StringElem(subleaves)
77 leaf = parent.sub[leafindex]
78 else:
79 leaf.sub = subleaves
80
81 parse(leaf, parse_funcs[1:])
82
83 if isinstance(leaf, StringElem):
84 leaf.prune()
85 return tree
86