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
29 -def parse(tree, parse_funcs):
30 """Parse placeables from the given string or sub-tree by using the
31 parsing functions provided.
32
33 The output of this function is B{heavily} dependent on the order of the
34 parsing functions. This is because of the algorithm used.
35
36 An over-simplification of the algorithm: the leaves in the C{StringElem}
37 tree are expanded to the output of the first parsing function in
38 C{parse_funcs}. The next level of recursion is then started on the new
39 set of leaves with the used parsing function removed from
40 C{parse_funcs}.
41
42 @type tree: unicode|StringElem
43 @param tree: The string or string element sub-tree to parse.
44 @type parse_funcs: A list of parsing functions. It must take exactly
45 one argument (a C{unicode} string to parse) and return a list of
46 C{StringElem}s which, together, form the original string. If nothing
47 could be parsed, it should return C{None}."""
48 if isinstance(tree, unicode):
49 tree = StringElem(tree)
50 if not parse_funcs:
51 return tree
52
53 parse_func = parse_funcs[0]
54
55 for leaf in tree.flatten():
56
57
58 if not leaf.istranslatable:
59 continue
60
61 unileaf = unicode(leaf)
62 if not unileaf:
63 continue
64
65 subleaves = parse_func(unileaf)
66 if subleaves is not None:
67 if len(subleaves) == 1 and type(leaf) is type(subleaves[0]) and leaf == subleaves[0]:
68 pass
69 elif isinstance(leaf, unicode):
70 parent = tree.get_parent_elem(leaf)
71 if parent is not None:
72 if len(parent.sub) == 1:
73 parent.sub = subleaves
74 leaf = parent
75 else:
76 leafindex = parent.sub.index(leaf)
77 parent.sub[leafindex] = StringElem(subleaves)
78 leaf = parent.sub[leafindex]
79 else:
80 leaf.sub = subleaves
81
82 parse(leaf, parse_funcs[1:])
83
84 if isinstance(leaf, StringElem):
85 leaf.prune()
86 return tree
87