]> rtime.felk.cvut.cz Git - opencv.git/blob - opencv/doc/latex2sphinx/latex.py
00c9f525e558d8a018dc2a7cf64d3d7dbb226488
[opencv.git] / opencv / doc / latex2sphinx / latex.py
1 import sys
2 from latexparser import latexparser, TexCmd
3 import distutils.dep_util
4 import os
5 import cPickle as pickle
6 import pyparsing as pp
7 import StringIO
8 from qfile import QOpen
9 from string import Template
10
11 # useful things for pyparsing
12 def returnList(x):
13     def listify(s, loc, toks):
14         return [toks]
15     x.setParseAction(listify)
16     return x
17 def returnTuple(x):
18     def listify(s, loc, toks):
19         return [tuple(toks)]
20     x.setParseAction(listify)
21     return x
22 def CommaList(word):
23     return returnList(pp.Optional(word + pp.ZeroOrMore(pp.Suppress(',') + word)))
24 def sl(s):
25     return pp.Suppress(pp.Literal(s))
26
27 import pythonapi
28
29 python_api = pythonapi.reader("../../interfaces/python/api")
30
31
32 class SphinxWriter:
33     def __init__(self, filename, language, abspath):
34         assert language in ['py', 'c', 'cpp']
35         self.language = language
36
37         self.abspath = abspath
38         os.path.abspath(os.path.dirname(filename))
39
40         self.f_index = QOpen(os.path.join(self.language, filename), 'wt')
41         self.f = self.f_index
42         self.f_chapter = None
43         self.f_section = None
44         self.indent = 0
45         self.state = None
46         self.envstack = []
47         self.tags = {}
48         self.errors = open('errors.%s' % language, 'wt')
49         self.unhandled_commands = set()
50         self.freshline = True
51         self.function_props = {}
52         self.covered = set()        # covered functions, used for error report
53         self.description = ""
54
55     def write(self, s):
56         self.freshline = len(s) > 0 and (s[-1] == '\n')
57         self.f.write(s.replace('\n', '\n' + self.indent * "    "))
58
59     def appendspace(self):
60         """ append a space to the output - if we're not at the start of a line """
61         if not self.freshline:
62             self.write(' ')
63
64     def doplain(self, s):
65         if (len(s) > 1) and (s[0] == '$' and s[-1] == '$') and self.state != 'math':
66             s = ":math:`%s`" % s[1:-1].strip()
67         elif self.state != 'math':
68             s.replace('\\_', '_')
69         if len(s) > 0 and s[-1] == '\n':
70             s = s[:-1]
71         if self.state == 'fpreamble':
72             self.description += s
73         else:
74             self.write(s)
75
76     def docmd(self, c):
77         if self.state == 'math':
78             if c.cmd != ']':
79                 self.default_cmd(c)
80             else:
81                 self.indent -= 1
82                 self.state = None
83                 self.write('\n\n')
84         else:
85             if c.cmd == '\n':
86                 self.write('\\\n')
87             else:
88                 if c.cmd == '[':
89                     meth = self.cmd_gomath
90                 else:
91                     cname = "cmd_" + c.cmd
92                     meth = getattr(self, cname, self.unrecognized_cmd)
93                 meth(c)
94
95     def cmd_gomath(self, c):
96         self.state = 'math'
97         print >>self, "\n\n.. math::"
98         self.indent += 1
99         print >>self
100
101     def cmd_chapter(self, c):
102         filename = str(c.params[0]).lower().replace(' ', '_').replace('/','_')
103         self.f_index.write("    %s\n" % filename)
104         self.f_chapter = QOpen(os.path.join(self.language, filename + '.rst'), 'wt')
105         self.f_section = None
106         self.f = self.f_chapter
107         self.indent = 0
108         title = str(c.params[0])
109         print >>self, '*' * len(title)
110         print >>self, title
111         print >>self, '*' * len(title)
112         print >>self
113         self.chapter_intoc = False
114
115     def cmd_section(self, c):
116         filename = str(c.params[0]).lower().replace(' ', '_').replace('/','_')
117         if not self.chapter_intoc:
118             self.chapter_intoc = True
119             print >>self.f_chapter
120             print >>self.f_chapter, '.. toctree::'
121             print >>self.f_chapter, '    :maxdepth: 2'
122             print >>self.f_chapter
123         self.f_chapter.write("    %s\n" % filename)
124         self.f_section = QOpen(os.path.join(self.language, filename + '.rst'), 'wt')
125         self.f = self.f_section
126         self.indent = 0
127         title = self.render(c.params[0].str)
128         print >>self, title
129         print >>self, '=' * len(title)
130         print >>self
131         print >>self, '.. highlight:: %s' % {'c': 'c', 'cpp': 'cpp', 'py': 'python'}[self.language]
132         print >>self
133
134     def cmd_subsection(self, c):
135         print >>self
136         nm = str(c.params[0])
137         print >>self, nm
138         print >>self, '-' * len(nm)
139         print >>self
140         self.function_props = {}
141         self.covered.add(nm)
142
143     def cmd_includegraphics(self, c):
144         filename = os.path.join('..', '..', str(c.params[0]))
145         print >>self, "\n\n.. image:: %s\n\n" % filename
146
147     def cmd_cvCppCross(self, c):
148         self.write(":func:`%s`" % str(c.params[0]))
149
150     def cmd_cvCPyCross(self, c):
151         self.write(":ref:`%s`" % str(c.params[0]))
152
153     def cmd_cross(self, c):
154         self.write(":ref:`%s`" % str(c.params[0]))
155
156     def cmd_cvCross(self, c):
157         self.write(":ref:`%s`" % str(c.params[0]))
158
159     def cmd_cvclass(self, c):
160         self.indent = 0
161         self.state = None
162         nm = self.render(list(c.params[0].str))
163         print >>self, "\n.. index:: %s\n" % nm
164         print >>self, ".. _%s:\n" % nm
165         print >>self, nm
166         print >>self, '-' * len(nm)
167         print >>self
168         if self.language == 'py':
169             print >>self, ".. class:: " + nm + "\n"
170         else:
171             print >>self, ".. ctype:: " + nm + "\n"
172         print >>self
173         self.addtag(nm, c)
174         self.state = 'class'
175
176     def addtag(self, nm, c):
177         if nm == "":
178             self.report_error(c, "empty name")
179         self.tags[nm] = "%s\t%s\t%d" % (nm, os.path.join(os.getcwd(), c.filename), c.lineno)
180
181     def cmd_cvfunc(self, c):
182         self.cmd_cvCPyFunc(c)
183
184     def cmd_cvCPyFunc(self, c):
185         self.indent = 0
186         nm = self.render(c.params[0].str)
187         print >>self, "\n.. index:: %s\n" % nm
188         print >>self, ".. _%s:\n" % nm
189         print >>self, nm
190         print >>self, '-' * len(nm)
191         print >>self
192         self.state = 'fpreamble'
193         if self.description != "":
194             self.report_error(c, "overflow - preceding cvfunc (starting %s) not terminated?" % repr(self.description[:30]))
195         self.description = ""
196         self.addtag(nm, c)
197
198         self.function_props = {'name' : nm}
199         self.covered.add(nm)
200
201     def cmd_cvCppFunc(self, c):
202         self.indent = 0
203         nm = self.render(c.params[0].str)
204         print >>self, "\n.. index:: %s\n" % nm
205         if 0:
206             print >>self, "\n.. _%s:\n" % nm
207         print >>self
208         print >>self, 'cv::%s' % nm
209         print >>self, '-' * (4+len(nm))
210         print >>self
211         self.state = 'fpreamble'
212         if self.description != "":
213             self.report_error(c, "overflow - preceding cvfunc (starting %s) not terminated?" % repr(self.description[:30]))
214         self.description = ""
215         self.addtag(nm, c)
216
217         self.function_props = {'name' : nm}
218         self.covered.add(nm)
219
220     def cmd_cvdefC(self, c):
221         if self.language != 'c':
222             return
223         s = str(c.params[0]).replace('\\_', '_')
224         s = s.replace('\\par', '')
225         s = s.replace('\n', ' ')
226         s = s.replace(';', '')
227         self.indent = 0
228         for proto in s.split('\\newline'):
229             if proto.strip() != "":
230                 print >>self, "\n\n.. cfunction:: " + proto.strip() + "\n"
231         # print >>self, "=", repr(c.params[0].str)
232         print >>self, '    ' + self.description
233         self.description = ""
234         print >>self
235         self.state = None
236         self.function_props['defpy'] = s
237
238     def cmd_cvdefCpp(self, c):
239         if self.language != 'cpp':
240             return
241         s = str(c.params[0]).replace('\\_', '_')
242         s = s.replace('\\par', '')
243         s = s.replace('\n', ' ')
244         s = s.replace(';', '')
245         self.indent = 0
246         for proto in s.split('\\newline'):
247             if proto.strip() != "":
248                 print >>self, "\n\n.. cfunction:: " + proto.strip() + "\n"
249         # print >>self, "=", repr(c.params[0].str)
250         if self.description != "":
251             print >>self, '    ' + self.description
252         else:
253             self.report_error(c, 'empty description')
254         self.description = ""
255         print >>self
256         self.state = None
257         self.function_props['defpy'] = s
258
259     def cmd_cvdefPy(self, c):
260         if self.language != 'py':
261             return
262         s = str(c.params[0]).replace('\\_', '_')
263         self.indent = 0
264         print >>self, ".. function:: " + s + "\n"
265         # print >>self, "=", repr(c.params[0].str)
266         print >>self, '    ' + self.description
267         print >>self
268         self.description = ""
269         self.state = None
270         self.function_props['defpy'] = s
271
272         pp.ParserElement.setDefaultWhitespaceChars(" \n\t")
273
274         ident = pp.Word(pp.alphanums + "_.+-")
275         ident_or_tuple = ident | (sl('(') + CommaList(ident) + sl(')'))
276         initializer = ident_or_tuple
277         arg = returnList(ident + pp.Optional(sl('=') + initializer))
278
279         decl = ident + sl('(') + CommaList(arg) + sl(')') + sl("->") + ident_or_tuple + pp.StringEnd()
280
281         try:
282             l = decl.parseString(s)
283             if str(l[0]) != self.function_props['name']:
284                 self.report_error(c, 'Decl "%s" does not match function name "%s"' % (str(l[0]), self.function_props['name']))
285             self.function_props['signature'] = l
286             if l[0] in python_api:
287                 (ins, outs) = python_api[l[0]]
288                 ins = [a for a in ins if not 'O' in a.flags]
289                 if outs != None:
290                     outs = outs.split(',')
291                 if len(ins) != len(l[1]):
292                     self.report_error(c, "function %s documented arity %d, code arity %d" % (l[0], len(l[1]), len(ins)))
293                 if outs == None:
294                     if l[2] != 'None':
295                         self.report_error(c, "function %s documented None, but code has %s" % (l[0], l[2]))
296                 else:
297                     if isinstance(l[2], str):
298                         doc_outs = [l[2]]
299                     else:
300                         doc_outs = l[2]
301                     if len(outs) != len(doc_outs):
302                         self.report_error(c, "function %s output documented tuple %d, code %d" % (l[0], len(outs), len(doc_outs)))
303             else:
304                 # self.report_error(c, "function %s documented but not found in code" % l[0])
305                 pass
306         except pp.ParseException, pe:
307             self.report_error(c, str(pe))
308             print s
309             print pe
310
311     def report_error(self, c, msg):
312         print >>self.errors, "%s:%d: [%s] Error %s" % (c.filename, c.lineno, self.language, msg)
313
314     def cmd_begin(self, c):
315         if len(c.params) == 0:
316             self.report_error(c, "Malformed begin")
317             return
318         self.write('\n')
319         s = str(c.params[0])
320         self.envstack.append((s, (c.filename, c.lineno)))
321         if s == 'description':
322             if self.language == 'py' and 'name' in self.function_props and not 'defpy' in self.function_props:
323                 self.report_error(c, "No cvdefPy for function %s" % self.function_props['name'])
324             self.indent += 1
325         elif s == 'lstlisting':
326             # Set indent to zero while collecting code; so later write will not double-indent
327             self.saved_f = self.f
328             self.saved_indent = self.indent
329             self.f = StringIO.StringIO()
330             self.indent = 0
331         elif s in ['itemize', 'enumerate']:
332             self.indent += 1
333         elif s == 'tabular':
334             self.f = StringIO.StringIO()
335         else:
336             self.default_cmd(c)
337
338     def cmd_item(self, c):
339         if len(self.ee()) == 0:
340             self.report_error(c, "item without environment")
341             return
342         self.indent -= 1
343         markup = {'itemize' : '*', 'enumerate' : '#.', 'description' : '*'}[self.ee()[-1]]
344         if len(c.args) > 0:
345             markup += " " + self.render([c.args[0].str])
346         if len(c.params) > 0:
347             markup += " " + self.render(c.params[0].str)
348         self.write("\n\n" + markup)
349         self.indent += 1
350
351     def cmd_end(self, c):
352         if len(c.params) != 1:
353             self.report_error(c, "Malformed end")
354             return
355         if len(self.envstack) == 0:
356             self.report_error(c, "end with no env")
357             return
358         self.write('\n')
359         s = str(c.params[0])
360         if self.envstack == []:
361             print "Cannot pop at", (c.filename, c.lineno)
362         if self.envstack[-1][0] != s:
363             self.report_error(c, "end{%s} does not match current stack %s" % (s, repr(self.envstack)))
364         self.envstack.pop()
365         if s == 'description':
366             self.indent -= 1
367             if self.indent == 0:
368                 self.function_props['done'] = True
369         elif s in ['itemize', 'enumerate']:
370             self.indent -= 1
371         elif s == 'tabular':
372             tabletxt = self.f.getvalue()
373             self.f = self.f_section
374             self.f.write(self.handle_table(tabletxt))
375         elif s == 'lstlisting':
376             listing = self.f.getvalue()
377
378             self.f = self.saved_f
379             self.indent = self.saved_indent
380             print >>self
381             if self.language == 'py':
382                 ckeys = ['#define', 'void', '#include', ';\n']
383                 found = [repr(k) for k in ckeys if k in listing]
384                 if len(found) > 0:
385                     self.report_error(c, 'listing is probably C, found %s' % ",".join(found))
386             if (self.language == 'py') and ('>>>' in listing):
387                 print >>self, "\n.. doctest::\n"
388             else:
389                 print >>self, "\n::\n"
390             self.indent += 1
391             print >>self
392             self.write(listing)
393             self.indent -= 1
394             print >>self
395             print >>self
396             print >>self, ".."      # otherwise a following :param: gets treated as more listing
397         elif s == 'document':
398             pass
399         else:
400             self.default_cmd(c)
401         
402     def cmd_label(self, c):
403         pass
404
405     def cmd_lstinputlisting(self, c):
406         s = str(c.params[0])
407         print >>self.f, ".. include:: %s" % os.path.normpath(os.path.join(self.abspath, s))
408         print >>self.f, "    :literal:"
409         print >>self.f
410
411     # Conditionals
412     def cmd_cvC(self, c):
413         self.do_conditional(['c'], c)
414     def cmd_cvCpp(self, c):
415         self.do_conditional(['cpp'], c)
416     def cmd_cvPy(self, c):
417         self.do_conditional(['py'], c)
418     def cmd_cvCPy(self, c):
419         self.do_conditional(['c', 'py'], c)
420     def do_conditional(self, langs, c):
421         if self.language in langs:
422             self.doL(c.params[0].str, False)
423
424     def render(self, L):
425         """ return L rendered as a string """
426         save = self.f
427         self.f = StringIO.StringIO()
428         for x in L:
429             if isinstance(x, TexCmd):
430                 self.docmd(x)
431             else:
432                 self.doplain(x)
433         r = self.f.getvalue()
434         self.f = save
435         return r
436
437     def cmd_cvarg(self, c):
438         if len(c.params) != 2:
439             self.report_error(c, "Malformed cvarg")
440             return
441         e = self.ee()
442         if self.state == 'class':
443             nm = self.render(c.params[0].str)
444             if '->' in nm:
445                 print >>self, "\n\n.. method:: %s\n\n" % nm
446             else:
447                 print >>self, "\n\n.. attribute:: %s\n\n" % nm
448             self.indent += 1
449             print >>self
450             self.doL(c.params[1].str, False)
451             self.indent -= 1
452             print >>self
453             return
454         is_func_arg = (e == ['description']) and (not 'done' in self.function_props)
455         if is_func_arg:
456             nm = self.render(c.params[0].str)
457             print >>self, '\n:param %s: ' % nm,
458             type = None         # Try to figure out the argument type
459             # For now, multiple args get a pass
460             if (self.language == 'py') and ('signature' in self.function_props) and (not ',' in nm):
461                 sig = self.function_props['signature']
462                 argnames = [a[0] for a in sig[1]]
463                 if isinstance(sig[2], str):
464                     resnames = [sig[2]]
465                 else:
466                     resnames = list(sig[2])
467                 if not nm in argnames + resnames:
468                     self.report_error(c, "Argument %s is not mentioned in signature (%s) (%s)" % (nm, ", ".join(argnames), ", ".join(resnames)))
469
470                 api = python_api.get(self.function_props['name'], None)
471                 if api:
472                     (ins, outs) = api
473                     adict = dict([(a.nm, a) for a in ins])
474                     arg = adict.get(nm, None)
475                     if arg:
476                         type = arg.ty
477                     else:
478                         self.report_error(c, 'cannot find arg %s in code' % nm)
479         elif len(e) > 0 and e[-1] == 'description':
480             print >>self, '\n* **%s** ' % self.render(c.params[0].str),
481         else:
482             self.report_error(c, "unexpected env (%s) for cvarg" % ",".join(e))
483         self.indent += 1
484         self.doL(c.params[1].str, False)
485         self.indent -= 1
486         print >>self
487         if is_func_arg and type:
488             type = type.replace('*', '')
489             translate = {
490                 "ints" : "sequence of int",
491                 "floats" : "sequence of int",
492                 "IplImages" : "sequence of :class:`IplImage`",
493                 "double" : "float",
494                 "int" : "int",
495                 "float" : "float",
496                 "char" : "str",
497                 "cvarrseq" : ":class:`CvArr` or :class:`CvSeq`",
498                 "CvPoint2D32fs" : "sequence of (float, float)",
499                 "pts_npts_contours" : "list of lists of (x,y) pairs",
500                 "CvSeqOfCvSURFPoint" : ":class:`CvSeq` of :class:`CvSURFPoint`",
501                 "CvSeqOfCvSURFDescriptor" : ":class:`CvSeq` of list of float",
502                 "cvpoint2d32f_count" : "int",
503                 "ranges" : "list of tuples of ints",
504             }
505             print >>self, "\n:type %s: %s" % (nm, translate.get(type, ':class:`%s`' % type))
506
507     def cmd_genc(self, c): pass 
508     def cmd_genpy(self, c): pass 
509     def cmd_author(self, c): pass 
510     def cmd_date(self, c): pass
511     def cmd_def(self, c): pass
512     def cmd_documentclass(self, c): pass
513     def cmd_maketitle(self, c): pass
514     def cmd_newcommand(self, c): pass
515     def cmd_newline(self, c): pass
516     def cmd_setcounter(self, c): pass
517     def cmd_tableofcontents(self, c): pass
518     def cmd_targetlang(self, c): pass
519     def cmd_usepackage(self, c): pass
520     def cmd_title(self, c): pass
521     def cmd_par(self, c): pass
522     def cmd_hline(self, c):
523         print >>self, "\\hline"
524
525     def cmd_cite(self, c):
526         self.write("[%s]_" % str(c.params[0]))
527
528     def cmd_href(self, c):
529         if len(c.params) == 2:
530             self.write("`%s <%s>`_" % (str(c.params[1]), self.render(c.params[0].str)))
531         else:
532             self.report_error(c, "href should have two params")
533
534     def cmd_url(self, c):
535         self.write(str(c.params[0]))
536
537     def cmd_emph(self, c):
538         self.write("*" + self.render(c.params[0].str) + "*")
539
540     def cmd_textit(self, c):
541         self.write("*" + self.render(c.params[0].str) + "*")
542
543     def cmd_textbf(self, c):
544         self.write("**" + self.render(c.params[0].str) + "**")
545
546     def cmd_texttt(self, c):
547         self.write("``" + self.render(c.params[0].str) + "``")
548
549     def default_cmd(self, c):
550         if self.f == self.f_section:
551             self.write(repr(c))
552
553     def unrecognized_cmd(self, c):
554         # if writing the index or chapter heading, anything goes
555         if not self.f in [self.f_index, self.f_chapter]:
556             self.write(c.cmd)
557             if (not 'lstlisting' in self.ee()) and (not c.cmd in "#{}%&*\\_"):
558                 if not c.cmd in self.unhandled_commands:
559                     self.report_error(c, 'unhandled command %s' % c.cmd)
560                     self.unhandled_commands.add(c.cmd)
561
562     def doL(self, L, newlines = True):
563         for x in L:
564             pos0 = self.f.tell()
565             if isinstance(x, TexCmd):
566                 self.docmd(x)
567             else:
568                 if 'lstlisting' in self.ee() or not newlines:
569                     self.doplain(x)
570                 else:
571                     self.doplain(x.lstrip())
572             pos1 = self.f.tell()
573             if pos0 != pos1:
574                 if self.state in ['math'] or not newlines:
575                     self.appendspace()
576                 else:
577                     if not 'lstlisting' in self.ee():
578                         self.write('\n')
579
580     def handle_table(self, s):
581         oneline = s.replace('\n', ' ').strip()
582         rows = [r.strip() for r in oneline.split('\\hline')]
583         tab = []
584         for r in rows:
585             if r != "":
586                 cols = [c.strip() for c in r.split('&')]
587                 tab.append(cols)
588         widths = [max([len(r[i]) for r in tab]) for i in range(len(tab[0]))]
589
590         st = ""         # Sphinx table
591
592         if 0:
593             sep = "+" + "+".join(["-" * w for w in widths]) + "+"
594             st += sep + '\n'
595             for r in tab:
596                 st += "|" + "|".join([c.center(w) for (c, w) in zip(r, widths)]) + "|" + '\n'
597                 st += sep + '\n'
598
599         st = '.. table::\n\n'
600         sep = "  ".join(["=" * w for w in widths])
601         st += '    ' + sep + '\n'
602         for y,r in enumerate(tab):
603             st += '    ' + "  ".join([c.ljust(w) for (c, w) in zip(r, widths)]) + '\n'
604             if y == 0:
605                 st += '    ' + sep + '\n'
606         st += '    ' + sep + '\n'
607         return st
608
609     def ee(self):
610         """ Return tags of the envstack.  envstack[0] is 'document', so skip it """
611         return [n for (n,_) in self.envstack[1:]]
612
613     def get_tags(self):
614         return self.tags
615
616     def close(self):
617
618         if self.envstack != []:
619             print >>self.errors, "Error envstack not empty at end of doc: " + repr(self.envstack)
620         print >>self.errors, "Unrecognized commands:"
621         for c in sorted(self.unhandled_commands):
622             print >>self.errors, "\n    " + c
623         print >>self.errors
624         if self.language == 'py':
625             print >>self.errors, "The following functions are undocumented"
626             for f in sorted(set(python_api) - self.covered):
627                 print >>self.errors, '    ', f
628
629         print >>self.f_index, "    bibliography"
630         print >>self.f_index, """
631
632 Indices and tables
633 ==================
634
635 * :ref:`genindex`
636 * :ref:`search`
637 """
638
639 # Quick and dirty bibtex parser
640
641 def parseBib(filename, language):
642     pp.ParserElement.setDefaultWhitespaceChars(" \n\t")
643     entry = returnList(pp.Word('@', pp.alphanums) + sl('{') +
644         pp.Word(pp.alphanums + "_") + sl(',') +
645         CommaList(returnTuple(pp.Word(pp.alphanums) + sl('=') + pp.QuotedString('{', endQuoteChar = '}'))) +
646         pp.Suppress(pp.Optional(',')) +
647         sl('}'))
648     r = (pp.ZeroOrMore(entry) | pp.Suppress('#' + pp.ZeroOrMore(pp.CharsNotIn('\n'))) + pp.StringEnd()).parseFile(filename)
649
650     bibliography = QOpen(os.path.join(language, "bibliography.rst"), 'wt')
651     print >>bibliography, "Bibliography"
652     print >>bibliography, "============"
653     print >>bibliography
654
655     for _,e in sorted([(str(x[1]), x) for x in r]):
656         (etype, tag, attrs) = str(e[0][1:]), str(e[1]), dict([(str(a), str(b)) for (a,b) in e[2]])
657         
658         representations = {
659             'article' :         '$author, "$title". $journal $volume $number, pp $pages ($year)',
660             'inproceedings' :   '$author "$title", $booktitle, $year',
661             'misc' :            '$author "$title", $year',
662             'techreport' :      '$author "$title", $edition, $edition ($year)',
663         }
664         if etype in representations:
665             if 0:
666                 print >>bibliography, tag
667                 print >>bibliography, "^" * len(tag)
668                 print >>bibliography
669
670             print >>bibliography, ".. [%s] %s" % (tag, Template(representations[etype]).safe_substitute(attrs))
671             print >>bibliography
672     bibliography.close()
673
674 if 1:
675     fulldoc = latexparser(sys.argv[1])
676
677     abspath = os.path.abspath(os.path.dirname(sys.argv[1]))
678
679     raw = open('raw.full', 'w')
680     for x in fulldoc:
681         print >>raw, repr(x)
682     raw.close()
683
684     # Filter on target language
685     def preprocess_conditionals(fd, conditionals):
686         r = []
687         ifstack = []
688         for x in fd:
689             if isinstance(x, TexCmd):
690                 ll = x.cmd.rstrip()
691                 loc = (x.filename, x.lineno)
692                 if ll.startswith("if"):
693                     # print " " * len(ifstack), '{', loc
694                     ifstack.append((conditionals.get(ll[2:], False), loc))
695                 elif ll.startswith("else"):
696                     ifstack[-1] = (not ifstack[-1][0], ifstack[-1][1])
697                 elif ll.startswith("fi"):
698                     ifstack.pop()
699                     # print " " * len(ifstack), '}', loc
700                 elif not False in [p for (p,_) in ifstack]:
701                     r.append(x)
702             else:
703                 if not False in [p for (p,_) in ifstack]:
704                     r.append(x)
705         if ifstack != []:
706             print "unterminated if", ifstack
707             sys.exit(0)
708         return r
709
710     tags = {}
711     for language in sys.argv[2:]:
712         doc = preprocess_conditionals(fulldoc, {
713                                               'C' : language=='c',
714                                               'Python' : language=='py',
715                                               'Py' : language=='py',
716                                               'CPy' : (language=='py' or language == 'c'),
717                                               'Cpp' : language=='cpp',
718                                               'plastex' : True})
719
720         raw = open('raw.%s' % language, 'w')
721         for x in doc:
722             print >>raw, repr(x)
723         raw.close()
724         sr = SphinxWriter('index.rst', language, abspath)
725         print >>sr, """
726 OpenCV |version| %s Reference
727 =================================
728
729 The OpenCV Wiki is here: http://opencv.willowgarage.com/
730
731 Contents:
732
733 .. toctree::
734     :maxdepth: 2
735
736 """ % {'c': 'C', 'cpp': 'C++', 'py': 'Python'}[language]
737         sr.doL(doc)
738         sr.close()
739         parseBib('../opencv.bib', language)
740         tags.update(sr.get_tags())
741     open('TAGS', 'w').write("\n".join(sorted(tags.values())) + "\n")
742