Debian Codegraph @

pypy/tool/rest/rst.py

raw symbols SCIP
1
2 """ reStructuredText generation tools
3
4 provides an api to build a tree from nodes, which can be converted to
5 ReStructuredText on demand
6
7 note that not all of ReST is supported, a usable subset is offered, but
8 certain features aren't supported, and also certain details (like how links
9 are generated, or how escaping is done) can not be controlled
10 """
11
12 from __future__ import generators
13
14 import py
15
16 def escape(txt):
17 """escape ReST markup"""
18 if not isinstance(txt, str) and not isinstance(txt, unicode):
19 txt = str(txt)
20 # XXX this takes a very naive approach to escaping, but it seems to be
21 # sufficient...
22 for c in '\\*`|:_':
23 txt = txt.replace(c, '\\%s' % (c,))
24 return txt
25
26 class RestError(Exception):
27 """ raised on containment errors (wrong parent) """
28
29 class AbstractMetaclass(type):
30 def __new__(cls, *args):
31 obj = super(AbstractMetaclass, cls).__new__(cls, *args)
32 parent_cls = obj.parentclass
33 if parent_cls is None:
34 return obj
35 if not isinstance(parent_cls, list):
36 class_list = [parent_cls]
37 else:
38 class_list = parent_cls
39 if obj.allow_nesting:
40 class_list.append(obj)
41
42 for _class in class_list:
43 if not _class.allowed_child:
44 _class.allowed_child = {obj:True}
45 else:
46 _class.allowed_child[obj] = True
47 return obj
48
49 class AbstractNode(object):
50 """ Base class implementing rest generation
51 """
52 sep = ''
53 __metaclass__ = AbstractMetaclass
54 parentclass = None # this exists to allow parent to know what
55 # children can exist
56 allow_nesting = False
57 allowed_child = {}
58 defaults = {}
59
60 _reg_whitespace = py.std.re.compile('\s+')
61
62 def __init__(self, *args, **kwargs):
63 self.parent = None
64 self.children = []
65 for child in args:
66 self._add(child)
67 for arg in kwargs:
68 setattr(self, arg, kwargs[arg])
69
70 def join(self, *children):
71 """ add child nodes
72
73 returns a reference to self
74 """
75 for child in children:
76 self._add(child)
77 return self
78
79 def add(self, child):
80 """ adds a child node
81
82 returns a reference to the child
83 """
84 self._add(child)
85 return child
86
87 def _add(self, child):
88 if child.__class__ not in self.allowed_child:
89 raise RestError("%r cannot be child of %r" % \
90 (child.__class__, self.__class__))
91 self.children.append(child)
92 child.parent = self
93
94 def __getitem__(self, item):
95 return self.children[item]
96
97 def __setitem__(self, item, value):
98 self.children[item] = value
99
100 def text(self):
101 """ return a ReST string representation of the node """
102 return self.sep.join([child.text() for child in self.children])
103
104 def wordlist(self):
105 """ return a list of ReST strings for this node and its children """
106 return [self.text()]
107
108 class Rest(AbstractNode):
109 """ Root node of a document """
110
111 sep = "\n\n"
112 def __init__(self, *args, **kwargs):
113 AbstractNode.__init__(self, *args, **kwargs)
114 self.links = {}
115
116 def render_links(self, check=False):
117 """render the link attachments of the document"""
118 assert not check, "Link checking not implemented"
119 if not self.links:
120 return ""
121 link_texts = []
122 # XXX this could check for duplicates and remove them...
123 for link, target in self.links.iteritems():
124 link_texts.append(".. _%s: %s" % (escape(link), target))
125 return "\n" + "\n".join(link_texts) + "\n\n"
126
127 def text(self):
128 outcome = []
129 if (isinstance(self.children[0], Transition) or
130 isinstance(self.children[-1], Transition)):
131 raise ValueError('document must not begin or end with a '
132 'transition')
133 for child in self.children:
134 outcome.append(child.text())
135
136 # always a trailing newline
137 text = self.sep.join([i for i in outcome if i]) + "\n"
138 return text + self.render_links()
139
140 class Transition(AbstractNode):
141 """ a horizontal line """
142 parentclass = Rest
143
144 def __init__(self, char='-', width=80, *args, **kwargs):
145 self.char = char
146 self.width = width
147 super(Transition, self).__init__(*args, **kwargs)
148
149 def text(self):
150 return (self.width - 1) * self.char
151
152 class Paragraph(AbstractNode):
153 """ simple paragraph """
154
155 parentclass = Rest
156 sep = " "
157 indent = ""
158 width = 80
159
160 def __init__(self, *args, **kwargs):
161 # make shortcut
162 args = list(args)
163 for num, arg in py.builtin.enumerate(args):
164 if isinstance(arg, str):
165 args[num] = Text(arg)
166 super(Paragraph, self).__init__(*args, **kwargs)
167
168 def text(self):
169 texts = []
170 for child in self.children:
171 texts += child.wordlist()
172
173 buf = []
174 outcome = []
175 lgt = len(self.indent)
176
177 def grab(buf):
178 outcome.append(self.indent + self.sep.join(buf))
179
180 texts.reverse()
181 while texts:
182 next = texts[-1]
183 if not next:
184 texts.pop()
185 continue
186 if lgt + len(self.sep) + len(next) <= self.width or not buf:
187 buf.append(next)
188 lgt += len(next) + len(self.sep)
189 texts.pop()
190 else:
191 grab(buf)
192 lgt = len(self.indent)
193 buf = []
194 grab(buf)
195 return "\n".join(outcome)
196
197 class SubParagraph(Paragraph):
198 """ indented sub paragraph """
199
200 indent = " "
201
202 class Title(Paragraph):
203 """ title element """
204
205 parentclass = Rest
206 belowchar = "="
207 abovechar = ""
208
209 def text(self):
210 txt = self._get_text()
211 lines = []
212 if self.abovechar:
213 lines.append(self.abovechar * len(txt))
214 lines.append(txt)
215 if self.belowchar:
216 lines.append(self.belowchar * len(txt))
217 return "\n".join(lines)
218
219 def _get_text(self):
220 txt = []
221 for node in self.children:
222 txt += node.wordlist()
223 return ' '.join(txt)
224
225 class AbstractText(AbstractNode):
226 parentclass = [Paragraph, Title]
227 start = ""
228 end = ""
229 def __init__(self, _text):
230 self._text = _text
231
232 def text(self):
233 text = self.escape(self._text)
234 return self.start + text + self.end
235
236 def escape(self, text):
237 if not isinstance(text, str) and not isinstance(text, unicode):
238 text = str(text)
239 if self.start:
240 text = text.replace(self.start, '\\%s' % (self.start,))
241 if self.end and self.end != self.start:
242 text = text.replace(self.end, '\\%s' % (self.end,))
243 return text
244
245 class Text(AbstractText):
246 def wordlist(self):
247 text = escape(self._text)
248 return self._reg_whitespace.split(text)
249
250 class LiteralBlock(AbstractText):
251 parentclass = Rest
252 start = '::\n\n'
253
254 def text(self):
255 if not self._text.strip():
256 return ''
257 text = self.escape(self._text).split('\n')
258 for i, line in py.builtin.enumerate(text):
259 if line.strip():
260 text[i] = ' %s' % (line,)
261 return self.start + '\n'.join(text)
262
263 class Em(AbstractText):
264 start = "*"
265 end = "*"
266
267 class Strong(AbstractText):
268 start = "**"
269 end = "**"
270
271 class Quote(AbstractText):
272 start = '``'
273 end = '``'
274
275 class Anchor(AbstractText):
276 start = '_`'
277 end = '`'
278
279 class Footnote(AbstractText):
280 def __init__(self, note, symbol=False):
281 raise NotImplementedError('XXX')
282
283 class Citation(AbstractText):
284 def __init__(self, text, cite):
285 raise NotImplementedError('XXX')
286
287 class ListItem(Paragraph):
288 allow_nesting = True
289 item_chars = '*+-'
290
291 def text(self):
292 idepth = self.get_indent_depth()
293 indent = self.indent + (idepth + 1) * ' '
294 txt = '\n\n'.join(self.render_children(indent))
295 ret = []
296 item_char = self.item_chars[idepth]
297 ret += [indent[len(item_char)+1:], item_char, ' ', txt[len(indent):]]
298 return ''.join(ret)
299
300 def render_children(self, indent):
301 txt = []
302 buffer = []
303 def render_buffer(fro, to):
304 if not fro:
305 return
306 p = Paragraph(indent=indent, *fro)
307 p.parent = self.parent
308 to.append(p.text())
309 for child in self.children:
310 if isinstance(child, AbstractText):
311 buffer.append(child)
312 else:
313 if buffer:
314 render_buffer(buffer, txt)
315 buffer = []
316 txt.append(child.text())
317
318 render_buffer(buffer, txt)
319 return txt
320
321 def get_indent_depth(self):
322 depth = 0
323 current = self
324 while (current.parent is not None and
325 isinstance(current.parent, ListItem)):
326 depth += 1
327 current = current.parent
328 return depth
329
330 class OrderedListItem(ListItem):
331 item_chars = ["#."] * 5
332
333 class DListItem(ListItem):
334 item_chars = None
335 def __init__(self, term, definition, *args, **kwargs):
336 self.term = term
337 super(DListItem, self).__init__(definition, *args, **kwargs)
338
339 def text(self):
340 idepth = self.get_indent_depth()
341 indent = self.indent + (idepth + 1) * ' '
342 txt = '\n\n'.join(self.render_children(indent))
343 ret = []
344 ret += [indent[2:], self.term, '\n', txt]
345 return ''.join(ret)
346
347 class Link(AbstractText):
348 start = '`'
349 end = '`_'
350
351 def __init__(self, _text, target):
352 self._text = _text
353 self.target = target
354 self.rest = None
355
356 def text(self):
357 if self.rest is None:
358 self.rest = self.find_rest()
359 if self.rest.links.get(self._text, self.target) != self.target:
360 raise ValueError('link name %r already in use for a different '
361 'target' % (self.target,))
362 self.rest.links[self._text] = self.target
363 return AbstractText.text(self)
364
365 def find_rest(self):
366 # XXX little overkill, but who cares...
367 next = self
368 while next.parent is not None:
369 next = next.parent
370 return next
371
372 class InternalLink(AbstractText):
373 start = '`'
374 end = '`_'
375
376 class LinkTarget(Paragraph):
377 def __init__(self, name, target):
378 self.name = name
379 self.target = target
380
381 def text(self):
382 return ".. _%s: %s\n" % (self.name, self.target)
383
384 class Substitution(AbstractText):
385 def __init__(self, text, **kwargs):
386 raise NotImplementedError('XXX')
387
388 class Directive(Paragraph):
389 indent = ' '
390 def __init__(self, name, *args, **options):
391 self.name = name
392 self.content = args
393 super(Directive, self).__init__()
394 self.options = options
395
396 def text(self):
397 # XXX not very pretty...
398 txt = '.. %s::' % (self.name,)
399 options = '\n'.join([' :%s: %s' % (k, v) for (k, v) in
400 self.options.iteritems()])
401 if options:
402 txt += '\n%s' % (options,)
403
404 if self.content:
405 txt += '\n'
406 for item in self.content:
407 txt += '\n ' + item
408
409 return txt
410