7
7
inventory = {}
8
8
9
9
10
- def ref_to_anchor (ref , text ):
10
+ def load_mock_inventory (items : "dict[str, str]" ):
11
+ for k , v in items .items ():
12
+ inventory [k ] = v
13
+
14
+
15
+ def ref_to_anchor (ref : str , text : "str | pf.ListContainer | None" ):
16
+ """Return a Link element based on ref in interlink format
17
+
18
+ Parameters
19
+ ----------
20
+ ref:
21
+ The interlink reference (e.g. "my_module.my_function").
22
+ text:
23
+ The text to be displayed for the link.
24
+
25
+ Examples
26
+ --------
27
+
28
+ >>> url = "https://example.org/functools.partial.html"
29
+ >>> load_mock_inventory({"functools.partial": {"full_uri": url, "name": "functools.partial"}})
30
+ >>> ref_to_anchor("functools.partial")
31
+ Link(Str(functools.partial); url='https://example.org/functools.partial.html')
32
+
33
+ >>> ref_to_anchor("~functools.partial")
34
+ Link(Str(partial); url='https://example.org/functools.partial.html')
35
+ """
11
36
# TODO: for now we just mutate el
12
37
is_shortened = ref .startswith ("~" )
13
38
@@ -28,11 +53,41 @@ def ref_to_anchor(ref, text):
28
53
else :
29
54
# when the element is an Link, content is a ListContainer, but it has to be
30
55
# *splatted back into Link?
31
- return pf .Link (* text , url = dst_url )
56
+ if isinstance (text , pf .ListContainer ):
57
+ return pf .Link (* text , url = dst_url )
58
+ elif isinstance (text , str ):
59
+ return pf .Link (pf .Str (text ), url = dst_url )
60
+ else :
61
+ raise TypeError (f"Unsupported type: { type (text )} " )
32
62
33
63
return pf .Link (name , url = dst_url )
34
64
35
65
66
+ def parse_rst_style_ref (full_text ):
67
+ """
68
+ Returns
69
+ -------
70
+ tuple
71
+ The parsed title (None if no title specified), and corresponding reference.
72
+ """
73
+
74
+ import re
75
+
76
+ pf .debug (full_text )
77
+
78
+ m = re .match (r"(?P<text>.+?)\<(?P<ref>[a-zA-Z\.\-: ]+)\>" , full_text )
79
+ if m is None :
80
+ # TODO: print a warning or something
81
+ return full_text , None
82
+
83
+ text , ref = m .groups ()
84
+
85
+ return ref , text
86
+
87
+
88
+ # Visitor ================================================================================
89
+
90
+
36
91
@dispatch
37
92
def visit (el , doc ):
38
93
return el
@@ -63,12 +118,14 @@ def visit(el: pf.Doc, doc):
63
118
64
119
65
120
@dispatch
66
- def visit (el : pf .Code , doc ):
67
- # TODO: also need to remove ref. Should handle in parent?
68
- left_el = el .prev
121
+ def visit (el : pf .Plain , doc ):
122
+ cont = el .content
123
+ if len (cont ) == 2 and cont [0 ] == pf .Str (":ref:" ) and isinstance (cont [1 ], pf .Code ):
124
+ _ , code = el .content
125
+
126
+ ref , title = parse_rst_style_ref (code .text )
69
127
70
- if left_el == pf .Str (":ref:" ):
71
- return ref_to_anchor (el .text , None )
128
+ return pf .Plain (ref_to_anchor (ref , title ))
72
129
73
130
return el
74
131
0 commit comments