Debian Codegraph @

docs/_static/info.py

raw symbols SCIP
1 # Copyright (C) 2016 Sebastian Wiesner and Flycheck contributors
2
3 # This file is not part of GNU Emacs.
4
5 # This program is free software: you can redistribute it and/or modify it under
6 # the terms of the GNU General Public License as published by the Free Software
7 # Foundation, either version 3 of the License, or (at your option) any later
8 # version.
9
10 # This program is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 # details.
14
15 # You should have received a copy of the GNU General Public License along with
16 # this program. If not, see <http://www.gnu.org/licenses/>.
17
18 import re
19 from string import Template
20
21 import requests
22 from docutils import nodes
23 from sphinx.roles import XRefRole
24 from sphinx.util import ws_re, logging
25
26 logger = logging.getLogger(__name__)
27
28 # Regular expression object to parse the contents of an Info reference
29 # role.
30 INFO_RE = re.compile(r'\A\((?P<manual>[^)]+)\)(?P<node>.+)\Z')
31
32
33 class InfoNodeXRefRole(XRefRole):
34 """A role to reference a node in an Info manual."""
35
36 innernodeclass = nodes.emphasis
37
38 def process_link(self, env, refnode, has_explicit_title, title, target):
39 """Process the link created by this role.
40
41 Swap node and manual name, to more closely match the look of references
42 in Texinfo.
43
44 """
45 # Normalize whitespace in info node targets
46 target = ws_re.sub(' ', target)
47 refnode['has_explicit_title'] = has_explicit_title
48 if not has_explicit_title:
49 match = INFO_RE.match(target)
50 if match:
51 # Swap title and node to create a title like info does
52 title = '{0}({1})'.format(match.group('node'),
53 match.group('manual'))
54 return title, target
55
56
57 def node_encode(char):
58 if char.isalnum():
59 return char
60 elif char == ' ':
61 return '-'
62 else:
63 return '_00{:02x}'.format(ord(char))
64
65
66 def expand_node_name(node):
67 """Expand ``node`` for use in HTML.
68
69 ``node`` is the name of a node as string.
70
71 Return a pair ``(filename, anchor)``, where ``filename`` is the base-name
72 of the corresponding file, sans extension, and ``anchor`` the HTML anchor.
73
74 See
75 http://www.gnu.org/software/texinfo/manual/texinfo/html_node/HTML-Xref-Node-Name-Expansion.html.
76
77 """
78 if node == 'Top':
79 return ('index', 'Top')
80 else:
81 normalized = ws_re.sub(' ', node.strip())
82 encoded = ''.join(node_encode(c) for c in normalized)
83 prefix = 'g_t' if not node[0].isalpha() else ''
84 return (encoded, prefix + encoded)
85
86
87 class HTMLXRefDB(object):
88 """Cross-reference database for Info manuals."""
89
90 #: URL of the htmlxref database of GNU Texinfo
91 XREF_URL = 'http://ftpmirror.gnu.org/texinfo/htmlxref.cnf'
92
93 #: Regular expression to parse entries from an xref DB
94 XREF_RE = re.compile(r"""
95 ^\s*
96 (?:
97 (?P<comment>[#].*) |
98 (?P<substname>\w+)\s*=\s*(?P<substurl>\S+) |
99 (?P<manname>\w+)\s*(?P<mantype>node|mono)\s*(?P<manurl>\S+)
100 )
101 \s*$""", re.VERBOSE)
102
103 @classmethod
104 def parse(cls, htmlxref):
105 substitutions = {}
106 manuals = {}
107 for line in htmlxref.splitlines():
108 match = cls.XREF_RE.match(line)
109 if match:
110 if match.group('substname'):
111 url = Template(match.group('substurl')).substitute(
112 substitutions)
113 substitutions[match.group('substname')] = url
114 elif (match.group('manname')
115 and match.group('mantype') == 'node'):
116 url = Template(match.group('manurl')).substitute(
117 substitutions)
118 manuals[match.group('manname')] = url
119 return cls(manuals)
120
121 def __init__(self, entries):
122 """Initialize the HTMLXrefDB object with the provided entries."""
123 self.entries = entries
124
125 def resolve(self, manual, node):
126 manual_url = self.entries.get(manual)
127 if not manual_url:
128 return None
129 else:
130 filename, anchor = expand_node_name(node)
131 return manual_url + filename + '.html#' + anchor
132
133
134 def update_htmlxref(app):
135 if not isinstance(getattr(app.env, 'info_htmlxref', None), HTMLXRefDB):
136 logger.info('fetching Texinfo htmlxref database from {0}... '.format(
137 HTMLXRefDB.XREF_URL))
138 try:
139 app.env.info_htmlxref = HTMLXRefDB.parse(
140 requests.get(HTMLXRefDB.XREF_URL).text)
141 except requests.exceptions.ConnectionError:
142 app.warn('Failed to load xref DB. '
143 'Info references will not be resolved')
144 app.env.info_htmlxref = None
145
146
147 def resolve_info_references(app, _env, refnode, contnode):
148 """Resolve Info references.
149
150 Process all :class:`~sphinx.addnodes.pending_xref` nodes whose ``reftype``
151 is ``infonode``.
152
153 Replace the pending reference with a :class:`~docutils.nodes.reference`
154 node, which references the corresponding web URL, as stored in the database
155 referred to by :data:`HTMLXREF_URL`.
156
157 """
158 if refnode['reftype'] != 'infonode':
159 return None
160
161 target = ws_re.sub(' ', refnode['reftarget'])
162 match = INFO_RE.match(target)
163 if not match:
164 app.env.warn(refnode.source, 'Invalid info target: {0}'.format(target),
165 refnode.line)
166 return contnode
167
168 manual = match.group('manual')
169 node = match.group('node')
170
171 xrefdb = app.env.info_htmlxref
172 if xrefdb:
173 uri = xrefdb.resolve(manual, node)
174 if not uri:
175 message = 'Cannot resolve info manual {0}'.format(manual)
176 app.env.warn(refnode.source, message, refnode.line)
177 return contnode
178 else:
179 reference = nodes.reference('', '', internal=False,
180 refuri=uri, reftitle=target)
181 reference += contnode
182 return reference
183 else:
184 # Without an xref DB we're unable to resolve any info references
185 return None
186
187
188 def setup(app):
189 app.add_role('infonode', InfoNodeXRefRole())
190 app.connect(str('builder-inited'), update_htmlxref)
191 app.connect(str('missing-reference'), resolve_info_references)
192 return {'version': '0.1', 'parallel_read_safe': True}