blob: 56c46268bab3a33337d927ae63980a133034ffb9 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
from parsimonious.grammar import Grammar
from .. import document_matchers, documents
def read_document_matcher(string):
root_node = _grammar.parse(string)
return read_document_matcher_node(root_node)
def read_document_matcher_node(root_node):
element_node = root_node.children[0]
if element_node.expr_name == "paragraph":
return _read_paragraph_node(element_node)
elif element_node.expr_name == "run":
return _read_run_node(element_node)
elif element_node.expr_name == "underline":
return document_matchers.underline
def _read_paragraph_node(paragraph_node):
style_id = _read_style_id_node(paragraph_node.children[1])
style_name = _read_style_name_node(paragraph_node.children[2])
numbering = _read_list_node(paragraph_node.children[3])
return document_matchers.paragraph(style_id=style_id, style_name=style_name, numbering=numbering)
def _read_run_node(run_node):
style_id = _read_style_id_node(run_node.children[1])
style_name = _read_style_name_node(run_node.children[2])
return document_matchers.run(style_id=style_id, style_name=style_name)
def _read_style_id_node(style_id_node):
if style_id_node.children:
return style_id_node.children[0].children[1].text
else:
return None
def _read_style_name_node(style_name_node):
if style_name_node.children:
return style_name_node.children[0].children[1].text
else:
return None
def _read_list_node(list_node):
if list_node.children:
return documents.numbering_level(
int(list_node.children[0].children[3].text) - 1,
is_ordered=list_node.children[0].children[1].text == "ordered-list",
)
else:
return None
grammar_text = r"""
document_matcher = paragraph / run / underline
underline = "u"
paragraph = "p" style_id? style_name_specifier? list?
run = "r" style_id? style_name_specifier?
style_id = "." style_identifier
style_identifier = ~"[A-Z0-9]*"i
style_name_specifier = "[style-name='" style_name "']"
style_name = ~"[^']+"
list = ":" list_type "(" ~"[0-9]+" ")"
list_type = "ordered-list" / "unordered-list"
"""
_grammar = Grammar(grammar_text)
|