]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_2_0.py
lyx_2_0.py: coding style fixes
[lyx.git] / lib / lyx2lyx / lyx_2_0.py
1 # -*- coding: utf-8 -*-
2 # This file is part of lyx2lyx
3 # -*- coding: utf-8 -*-
4 # Copyright (C) 2008 José Matos  <jamatos@lyx.org>
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 """ Convert files to the file format generated by lyx 2.0"""
21
22 import re, string
23 import unicodedata
24 import sys, os
25
26 from parser_tools import find_token, find_end_of, find_tokens, get_value, get_value_string
27
28 ####################################################################
29 # Private helper functions
30
31 def remove_option(document, m, option):
32     l = document.body[m].find(option)
33     if l != -1:
34         val = document.body[m][l:].split('"')[1]
35         document.body[m] = document.body[m][:l - 1] + document.body[m][l+len(option + '="' + val + '"'):]
36     return l
37
38 def find_end_of_inset(lines, i):
39     " Find end of inset, where lines[i] is included."
40     return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
41
42
43 def add_to_preamble(document, text):
44     """ Add text to the preamble if it is not already there.
45     Only the first line is checked!"""
46
47     if find_token(document.preamble, text[0], 0) != -1:
48         return
49
50     document.preamble.extend(text)
51
52
53 def insert_to_preamble(index, document, text):
54     """ Insert text to the preamble at a given line"""
55
56     document.preamble.insert(index, text)
57
58
59 def read_unicodesymbols():
60     " Read the unicodesymbols list of unicode characters and corresponding commands."
61     pathname = os.path.abspath(os.path.dirname(sys.argv[0]))
62     fp = open(os.path.join(pathname.strip('lyx2lyx'), 'unicodesymbols'))
63     spec_chars = []
64     # Two backslashes, followed by some non-word character, and then a character
65     # in brackets. The idea is to check for constructs like: \"{u}, which is how
66     # they are written in the unicodesymbols file; but they can also be written
67     # as: \"u or even \" u.
68     r = re.compile(r'\\\\(\W)\{(\w)\}')
69     for line in fp.readlines():
70         if line[0] != '#' and line.strip() != "":
71             line=line.replace(' "',' ') # remove all quotation marks with spaces before
72             line=line.replace('" ',' ') # remove all quotation marks with spaces after
73             line=line.replace(r'\"','"') # replace \" by " (for characters with diaeresis)
74             try:
75                 [ucs4,command,dead] = line.split(None,2)
76                 if command[0:1] != "\\":
77                     continue
78                 spec_chars.append([command, unichr(eval(ucs4))])
79             except:
80                 continue
81             m = r.match(command)
82             if m != None:
83                 command = "\\\\"
84                 # If the character is a double-quote, then we need to escape it, too,
85                 # since it is done that way in the LyX file.
86                 if m.group(1) == "\"":
87                     command += "\\"
88                 commandbl = command
89                 command += m.group(1) + m.group(2)
90                 commandbl += m.group(1) + ' ' + m.group(2)
91                 spec_chars.append([command, unichr(eval(ucs4))])
92                 spec_chars.append([commandbl, unichr(eval(ucs4))])
93     fp.close()
94     return spec_chars
95
96
97 unicode_reps = read_unicodesymbols()
98
99
100 # DO NOT USE THIS ROUTINE ANY MORE. Better yet, replace the uses that
101 # have been made of it with uses of put_cmd_in_ert.
102 def old_put_cmd_in_ert(string):
103     for rep in unicode_reps:
104         string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
105     string = string.replace('\\', "\\backslash\n")
106     string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
107       + string + "\n\\end_layout\n\\end_inset"
108     return string
109
110
111 # This routine wraps some content in an ERT inset. 
112 #
113 # NOTE: The function accepts either a single string or a LIST of strings as
114 # argument. But it returns a LIST of strings, split on \n, so that it does 
115 # not have embedded newlines.
116
117 # This is how lyx2lyx represents a LyX document: as a list of strings, 
118 # each representing a line of a LyX file. Embedded newlines confuse 
119 # lyx2lyx very much.
120 #
121 # A call to this routine will often go something like this:
122 #   i = find_token('\\begin_inset FunkyInset', ...)
123 #   ...
124 #   j = find_end_of_inset(document.body, i)
125 #   content = ...extract content from insets
126 #   # that could be as simple as: 
127 #   # content = lyx2latex(document[i:j + 1])
128 #   ert = put_cmd_in_ert(content)
129 #   document.body[i:j] = ert
130 # Now, before we continue, we need to reset i appropriately. Normally,
131 # this would be: 
132 #   i += len(ert)
133 # That puts us right after the ERT we just inserted.
134 #
135 def put_cmd_in_ert(arg):
136     ret = ["\\begin_inset ERT", "status collapsed", "\\begin_layout Plain Layout", ""]
137     # Despite the warnings just given, it will be faster for us to work
138     # with a single string internally. That way, we only go through the
139     # unicode_reps loop once.
140     if type(arg) is list:
141       s = "\n".join(arg)
142     else:
143       s = arg
144     for rep in unicode_reps:
145       s = s.replace(rep[1], rep[0].replace('\\\\', '\\'))
146     s = s.replace('\\', "\\backslash\n")
147     ret += s.splitlines()
148     ret += ["\\end_layout", "\\end_inset"]
149     return ret
150
151             
152 def lyx2latex(document, lines):
153     'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
154     # clean up multiline stuff
155     content = ""
156     ert_end = 0
157     note_end = 0
158
159     for curline in range(len(lines)):
160       line = lines[curline]
161       if line.startswith("\\begin_inset ERT"):
162           # We don't want to replace things inside ERT, so figure out
163           # where the end of the inset is.
164           ert_end = find_end_of_inset(lines, curline + 1)
165           continue
166       elif line.startswith("\\begin_inset Formula"):
167           line = line[20:]
168       elif line.startswith("\\begin_inset Quotes"):
169           # For now, we do a very basic reversion. Someone who understands
170           # quotes is welcome to fix it up.
171           qtype = line[20:].strip()
172           # lang = qtype[0]
173           side = qtype[1]
174           dbls = qtype[2]
175           if side == "l":
176               if dbls == "d":
177                   line = "``"
178               else:
179                   line = "`"
180           else:
181               if dbls == "d":
182                   line = "''"
183               else:
184                   line = "'"
185       elif line.startswith("\\begin_inset Note Note"):
186           # We want to skip LyX notes, so remember where the inset ends
187           note_end = find_end_of_inset(lines, curline + 1)
188           continue
189       elif line.isspace() or \
190             line.startswith("\\begin_layout") or \
191             line.startswith("\\end_layout") or \
192             line.startswith("\\begin_inset") or \
193             line.startswith("\\end_inset") or \
194             line.startswith("\\lang") or \
195             line.strip() == "status collapsed" or \
196             line.strip() == "status open":
197           #skip all that stuff
198           continue
199
200       # Skip LyX notes
201       if note_end >= curline:
202           continue
203
204       # this needs to be added to the preamble because of cases like
205       # \textmu, \textbackslash, etc.
206       add_to_preamble(document, ['% added by lyx2lyx for converted index entries',
207                                  '\\@ifundefined{textmu}',
208                                  ' {\\usepackage{textcomp}}{}'])
209       # a lossless reversion is not possible
210       # try at least to handle some common insets and settings
211       if ert_end >= curline:
212           line = line.replace(r'\backslash', r'\\')
213       else:
214           line = line.replace('&', '\\&{}')
215           line = line.replace('#', '\\#{}')
216           line = line.replace('^', '\\^{}')
217           line = line.replace('%', '\\%{}')
218           line = line.replace('_', '\\_{}')
219           line = line.replace('$', '\\${}')
220
221           # Do the LyX text --> LaTeX conversion
222           for rep in unicode_reps:
223             line = line.replace(rep[1], rep[0] + "{}")
224           line = line.replace(r'\backslash', r'\textbackslash{}')
225           line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
226           line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
227           line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
228           line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
229           line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
230           line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
231           line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
232           line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
233           line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
234       content += line
235     return content
236
237
238 def latex_length(string):
239     'Convert lengths to their LaTeX representation.'
240     i = 0
241     percent = False
242     # the string has the form
243     # ValueUnit+ValueUnit-ValueUnit or
244     # ValueUnit+-ValueUnit
245     # the + and - (glue lengths) are optional
246     # the + always precedes the -
247
248     # Convert relative lengths to LaTeX units
249     units = {"text%":"\\textwidth", "col%":"\\columnwidth",
250              "page%":"\\paperwidth", "line%":"\\linewidth",
251              "theight%":"\\textheight", "pheight%":"\\paperheight"}
252     for unit in units.keys():
253         i = string.find(unit)
254         if i != -1:
255             percent = True
256             minus = string.rfind("-", 1, i)
257             plus = string.rfind("+", 0, i)
258             latex_unit = units[unit]
259             if plus == -1 and minus == -1:
260                 value = string[:i]
261                 value = str(float(value)/100)
262                 end = string[i + len(unit):]
263                 string = value + latex_unit + end
264             if plus > minus:
265                 value = string[plus + 1:i]
266                 value = str(float(value)/100)
267                 begin = string[:plus + 1]
268                 end = string[i+len(unit):]
269                 string = begin + value + latex_unit + end
270             if plus < minus:
271                 value = string[minus + 1:i]
272                 value = str(float(value)/100)
273                 begin = string[:minus + 1]
274                 string = begin + value + latex_unit
275
276     # replace + and -, but only if the - is not the first character
277     string = string[0] + string[1:].replace("+", " plus ").replace("-", " minus ")
278     # handle the case where "+-1mm" was used, because LaTeX only understands
279     # "plus 1mm minus 1mm"
280     if string.find("plus  minus"):
281         lastvaluepos = string.rfind(" ")
282         lastvalue = string[lastvaluepos:]
283         string = string.replace("  ", lastvalue + " ")
284     if percent ==  False:
285         return "False," + string
286     else:
287         return "True," + string
288
289
290 def revert_flex_inset(document, name, LaTeXname, position):
291   " Convert flex insets to TeX code "
292   i = position
293   while True:
294     i = find_token(document.body, '\\begin_inset Flex ' + name, i)
295     if i == -1:
296       return
297     z = find_end_of_inset(document.body, i)
298     if z == -1:
299       document.warning("Malformed LyX document: Can't find end of Flex " + name + " inset.")
300       return
301     # remove the \end_inset
302     document.body[z - 2:z + 1] = put_cmd_in_ert("}")
303     # we need to reset character layouts if necessary
304     j = find_token(document.body, '\\emph on', i)
305     k = find_token(document.body, '\\noun on', i)
306     l = find_token(document.body, '\\series', i)
307     m = find_token(document.body, '\\family', i)
308     n = find_token(document.body, '\\shape', i)
309     o = find_token(document.body, '\\color', i)
310     p = find_token(document.body, '\\size', i)
311     q = find_token(document.body, '\\bar under', i)
312     r = find_token(document.body, '\\uuline on', i)
313     s = find_token(document.body, '\\uwave on', i)
314     t = find_token(document.body, '\\strikeout on', i)
315     if j != -1 and j < z:
316       document.body.insert(z - 2, "\\emph default")
317     if k != -1 and k < z:
318       document.body.insert(z - 2, "\\noun default")
319     if l != -1 and l < z:
320       document.body.insert(z - 2, "\\series default")
321     if m != -1 and m < z:
322       document.body.insert(z - 2, "\\family default")
323     if n != -1 and n < z:
324       document.body.insert(z - 2, "\\shape default")
325     if o != -1 and o < z:
326       document.body.insert(z - 2, "\\color inherit")
327     if p != -1 and p < z:
328       document.body.insert(z - 2, "\\size default")
329     if q != -1 and q < z:
330       document.body.insert(z - 2, "\\bar default")
331     if r != -1 and r < z:
332       document.body.insert(z - 2, "\\uuline default")
333     if s != -1 and s < z:
334       document.body.insert(z - 2, "\\uwave default")
335     if t != -1 and t < z:
336       document.body.insert(z - 2, "\\strikeout default")
337     document.body[i:i + 4] = put_cmd_in_ert(LaTeXname + "{")
338     i += 1
339
340
341 def revert_charstyles(document, name, LaTeXname, changed):
342   " Reverts character styles to TeX code "
343   i = 0
344   while True:
345     i = find_token(document.body, name + ' on', i)
346     if i == -1:
347       return changed
348     j = find_token(document.body, name + ' default', i)
349     k = find_token(document.body, name + ' on', i + 1)
350     # if there is no default set, the style ends with the layout
351     # assure hereby that we found the correct layout end
352     if j != -1 and (j < k or k == -1):
353       document.body[j:j + 1] = put_cmd_in_ert("}")
354     else:
355       j = find_token(document.body, '\\end_layout', i)
356       document.body[j:j] = put_cmd_in_ert("}")
357     document.body[i:i + 1] = put_cmd_in_ert(LaTeXname + "{")
358     changed = True
359     i += 1
360
361
362 def revert_layout_command(document, name, LaTeXname, position):
363   " Reverts a command from a layout to TeX code "
364   i = position
365   while True:
366     i = find_token(document.body, '\\begin_layout ' + name, i)
367     if i == -1:
368       return
369     k = -1
370     # find the next layout
371     j = i + 1
372     while k == -1:
373       j = find_token(document.body, '\\begin_layout', j)
374       l = len(document.body)
375       # if nothing was found it was the last layout of the document
376       if j == -1:
377         document.body[l - 4:l - 4] = put_cmd_in_ert("}")
378         k = 0
379       # exclude plain layout because this can be TeX code or another inset
380       elif document.body[j] != '\\begin_layout Plain Layout':
381         document.body[j - 2:j - 2] = put_cmd_in_ert("}")
382         k = 0
383       else:
384         j += 1
385     document.body[i] = '\\begin_layout Standard'
386     document.body[i + 1:i + 1] = put_cmd_in_ert(LaTeXname + "{")
387     i += 1
388
389
390 ####################################################################
391
392
393 def revert_swiss(document):
394     " Set language german-ch to ngerman "
395     i = 0
396     if document.language == "german-ch":
397         document.language = "ngerman"
398         i = find_token(document.header, "\\language", 0)
399         if i != -1:
400             document.header[i] = "\\language ngerman"
401     j = 0
402     while True:
403         j = find_token(document.body, "\\lang german-ch", j)
404         if j == -1:
405             return
406         document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
407         j = j + 1
408
409
410 def revert_tabularvalign(document):
411    " Revert the tabular valign option "
412    i = 0
413    while True:
414        i = find_token(document.body, "\\begin_inset Tabular", i)
415        if i == -1:
416            return
417        j = find_token(document.body, "</cell>", i)
418        if j == -1:
419            document.warning("Malformed LyX document: Could not find end of tabular cell.")
420            i = j
421            continue
422        # don't set a box for longtables, only delete tabularvalignment
423        # the alignment is 2 lines below \\begin_inset Tabular
424        p = document.body[i + 2].find("islongtable")
425        if p > -1:
426            q = document.body[i + 2].find("tabularvalignment")
427            if q > -1:
428                document.body[i + 2] = document.body[i + 2][:q - 1]
429                document.body[i + 2] = document.body[i + 2] + '>'
430            i = i + 1
431
432        # when no longtable
433        if p == -1:
434          tabularvalignment = 'c'
435          # which valignment is specified?
436          m = document.body[i + 2].find('tabularvalignment="top"')
437          if m > -1:
438              tabularvalignment = 't'
439          m = document.body[ i+ 2].find('tabularvalignment="bottom"')
440          if m > -1:
441              tabularvalignment = 'b'
442          # delete tabularvalignment
443          q = document.body[i + 2].find("tabularvalignment")
444          if q > -1:
445              document.body[i + 2] = document.body[i + 2][:q - 1]
446              document.body[i + 2] = document.body[i + 2] + '>'
447
448          # don't add a box when centered
449          if tabularvalignment == 'c':
450              i = j
451              continue
452          subst = ['\\end_layout', '\\end_inset']
453          document.body[j:j] = subst # just inserts those lines
454          subst = ['\\begin_inset Box Frameless',
455              'position "' + tabularvalignment +'"',
456              'hor_pos "c"',
457              'has_inner_box 1',
458              'inner_pos "c"',
459              'use_parbox 0',
460              # we don't know the width, assume 50%
461              'width "50col%"',
462              'special "none"',
463              'height "1in"',
464              'height_special "totalheight"',
465              'status open',
466              '',
467              '\\begin_layout Plain Layout']
468          document.body[i:i] = subst # this just inserts the array at i
469          i += len(subst) + 2 # adjust i to save a few cycles
470
471
472 def revert_phantom(document):
473     " Reverts phantom to ERT "
474     i = 0
475     j = 0
476     while True:
477       i = find_token(document.body, "\\begin_inset Phantom Phantom", i)
478       if i == -1:
479           return
480       substi = document.body[i].replace('\\begin_inset Phantom Phantom', \
481                 '\\begin_inset ERT\nstatus collapsed\n\n' \
482                 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
483                 'phantom{\n\\end_layout\n\n\\end_inset\n')
484       substi = substi.split('\n')
485       document.body[i:i + 4] = substi
486       i += len(substi)
487       j = find_token(document.body, "\\end_layout", i)
488       if j == -1:
489           document.warning("Malformed LyX document: Could not find end of Phantom inset.")
490           return
491       substj = document.body[j].replace('\\end_layout', \
492                 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
493                 '\\begin_layout Plain Layout\n\n' \
494                 '}\n\\end_layout\n\n\\end_inset\n')
495       substj = substj.split('\n')
496       document.body[j:j + 4] = substj
497       i += len(substj)
498
499
500 def revert_hphantom(document):
501     " Reverts hphantom to ERT "
502     i = 0
503     j = 0
504     while True:
505       i = find_token(document.body, "\\begin_inset Phantom HPhantom", i)
506       if i == -1:
507           return
508       substi = document.body[i].replace('\\begin_inset Phantom HPhantom', \
509                 '\\begin_inset ERT\nstatus collapsed\n\n' \
510                 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
511                 'hphantom{\n\\end_layout\n\n\\end_inset\n')
512       substi = substi.split('\n')
513       document.body[i:i + 4] = substi
514       i += len(substi)
515       j = find_token(document.body, "\\end_layout", i)
516       if j == -1:
517           document.warning("Malformed LyX document: Could not find end of HPhantom inset.")
518           return
519       substj = document.body[j].replace('\\end_layout', \
520                 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
521                 '\\begin_layout Plain Layout\n\n' \
522                 '}\n\\end_layout\n\n\\end_inset\n')
523       substj = substj.split('\n')
524       document.body[j:j + 4] = substj
525       i += len(substj)
526
527
528 def revert_vphantom(document):
529     " Reverts vphantom to ERT "
530     i = 0
531     j = 0
532     while True:
533       i = find_token(document.body, "\\begin_inset Phantom VPhantom", i)
534       if i == -1:
535           return
536       substi = document.body[i].replace('\\begin_inset Phantom VPhantom', \
537                 '\\begin_inset ERT\nstatus collapsed\n\n' \
538                 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
539                 'vphantom{\n\\end_layout\n\n\\end_inset\n')
540       substi = substi.split('\n')
541       document.body[i:i + 4] = substi
542       i += len(substi)
543       j = find_token(document.body, "\\end_layout", i)
544       if j == -1:
545           document.warning("Malformed LyX document: Could not find end of VPhantom inset.")
546           return
547       substj = document.body[j].replace('\\end_layout', \
548                 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
549                 '\\begin_layout Plain Layout\n\n' \
550                 '}\n\\end_layout\n\n\\end_inset\n')
551       substj = substj.split('\n')
552       document.body[j:j + 4] = substj
553       i += len(substj)
554
555
556 def revert_xetex(document):
557     " Reverts documents that use XeTeX "
558     i = find_token(document.header, '\\use_xetex', 0)
559     if i == -1:
560         document.warning("Malformed LyX document: Missing \\use_xetex.")
561         return
562     if get_value(document.header, "\\use_xetex", i) == 'false':
563         del document.header[i]
564         return
565     del document.header[i]
566     # 1.) set doc encoding to utf8-plain
567     i = find_token(document.header, "\\inputencoding", 0)
568     if i == -1:
569         document.warning("Malformed LyX document: Missing \\inputencoding.")
570     document.header[i] = "\\inputencoding utf8-plain"
571     # 2.) check font settings
572     l = find_token(document.header, "\\font_roman", 0)
573     if l == -1:
574         document.warning("Malformed LyX document: Missing \\font_roman.")
575     line = document.header[l]
576     l = re.compile(r'\\font_roman (.*)$')
577     m = l.match(line)
578     roman = m.group(1)
579     l = find_token(document.header, "\\font_sans", 0)
580     if l == -1:
581         document.warning("Malformed LyX document: Missing \\font_sans.")
582     line = document.header[l]
583     l = re.compile(r'\\font_sans (.*)$')
584     m = l.match(line)
585     sans = m.group(1)
586     l = find_token(document.header, "\\font_typewriter", 0)
587     if l == -1:
588         document.warning("Malformed LyX document: Missing \\font_typewriter.")
589     line = document.header[l]
590     l = re.compile(r'\\font_typewriter (.*)$')
591     m = l.match(line)
592     typewriter = m.group(1)
593     osf = get_value(document.header, '\\font_osf', 0) == "true"
594     sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
595     tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
596     # 3.) set preamble stuff
597     pretext = '%% This document must be processed with xelatex!\n'
598     pretext += '\\usepackage{fontspec}\n'
599     if roman != "default":
600         pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
601     if sans != "default":
602         pretext += '\\setsansfont['
603         if sf_scale != 100:
604             pretext += 'Scale=' + str(sf_scale / 100) + ','
605         pretext += 'Mapping=tex-text]{' + sans + '}\n'
606     if typewriter != "default":
607         pretext += '\\setmonofont'
608         if tt_scale != 100:
609             pretext += '[Scale=' + str(tt_scale / 100) + ']'
610         pretext += '{' + typewriter + '}\n'
611     if osf:
612         pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
613     pretext += '\usepackage{xunicode}\n'
614     pretext += '\usepackage{xltxtra}\n'
615     insert_to_preamble(0, document, pretext)
616     # 4.) reset font settings
617     i = find_token(document.header, "\\font_roman", 0)
618     if i == -1:
619         document.warning("Malformed LyX document: Missing \\font_roman.")
620     document.header[i] = "\\font_roman default"
621     i = find_token(document.header, "\\font_sans", 0)
622     if i == -1:
623         document.warning("Malformed LyX document: Missing \\font_sans.")
624     document.header[i] = "\\font_sans default"
625     i = find_token(document.header, "\\font_typewriter", 0)
626     if i == -1:
627         document.warning("Malformed LyX document: Missing \\font_typewriter.")
628     document.header[i] = "\\font_typewriter default"
629     i = find_token(document.header, "\\font_osf", 0)
630     if i == -1:
631         document.warning("Malformed LyX document: Missing \\font_osf.")
632     document.header[i] = "\\font_osf false"
633     i = find_token(document.header, "\\font_sc", 0)
634     if i == -1:
635         document.warning("Malformed LyX document: Missing \\font_sc.")
636     document.header[i] = "\\font_sc false"
637     i = find_token(document.header, "\\font_sf_scale", 0)
638     if i == -1:
639         document.warning("Malformed LyX document: Missing \\font_sf_scale.")
640     document.header[i] = "\\font_sf_scale 100"
641     i = find_token(document.header, "\\font_tt_scale", 0)
642     if i == -1:
643         document.warning("Malformed LyX document: Missing \\font_tt_scale.")
644     document.header[i] = "\\font_tt_scale 100"
645
646
647 def revert_outputformat(document):
648     " Remove default output format param "
649     i = find_token(document.header, '\\default_output_format', 0)
650     if i == -1:
651         document.warning("Malformed LyX document: Missing \\default_output_format.")
652         return
653     del document.header[i]
654
655
656 def revert_backgroundcolor(document):
657     " Reverts background color to preamble code "
658     i = 0
659     colorcode = ""
660     while True:
661       i = find_token(document.header, "\\backgroundcolor", i)
662       if i == -1:
663           return
664       colorcode = get_value(document.header, '\\backgroundcolor', 0)
665       del document.header[i]
666       # don't clutter the preamble if backgroundcolor is not set
667       if colorcode == "#ffffff":
668           continue
669       # the color code is in the form #rrggbb where every character denotes a hex number
670       # convert the string to an int
671       red = string.atoi(colorcode[1:3],16)
672       # we want the output "0.5" for the value "127" therefore add here
673       if red != 0:
674           red = red + 1
675       redout = float(red) / 256
676       green = string.atoi(colorcode[3:5],16)
677       if green != 0:
678           green = green + 1
679       greenout = float(green) / 256
680       blue = string.atoi(colorcode[5:7],16)
681       if blue != 0:
682           blue = blue + 1
683       blueout = float(blue) / 256
684       # write the preamble
685       insert_to_preamble(0, document,
686                            '% Commands inserted by lyx2lyx to set the background color\n'
687                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
688                            + '\\definecolor{page_backgroundcolor}{rgb}{'
689                            + str(redout) + ', ' + str(greenout)
690                            + ', ' + str(blueout) + '}\n'
691                            + '\\pagecolor{page_backgroundcolor}\n')
692
693
694 def revert_splitindex(document):
695     " Reverts splitindex-aware documents "
696     i = find_token(document.header, '\\use_indices', 0)
697     if i == -1:
698         document.warning("Malformed LyX document: Missing \\use_indices.")
699         return
700     indices = get_value(document.header, "\\use_indices", i)
701     preamble = ""
702     if indices == "true":
703          preamble += "\\usepackage{splitidx}\n"
704     del document.header[i]
705     i = 0
706     while True:
707         i = find_token(document.header, "\\index", i)
708         if i == -1:
709             break
710         k = find_token(document.header, "\\end_index", i)
711         if k == -1:
712             document.warning("Malformed LyX document: Missing \\end_index.")
713             return
714         line = document.header[i]
715         l = re.compile(r'\\index (.*)$')
716         m = l.match(line)
717         iname = m.group(1)
718         ishortcut = get_value(document.header, '\\shortcut', i, k)
719         if ishortcut != "" and indices == "true":
720             preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
721         del document.header[i:k + 1]
722         i = 0
723     if preamble != "":
724         insert_to_preamble(0, document, preamble)
725     i = 0
726     while True:
727         i = find_token(document.body, "\\begin_inset Index", i)
728         if i == -1:
729             break
730         line = document.body[i]
731         l = re.compile(r'\\begin_inset Index (.*)$')
732         m = l.match(line)
733         itype = m.group(1)
734         if itype == "idx" or indices == "false":
735             document.body[i] = "\\begin_inset Index"
736         else:
737             k = find_end_of_inset(document.body, i)
738             if k == -1:
739                  return
740             content = lyx2latex(document, document.body[i:k])
741             # escape quotes
742             content = content.replace('"', r'\"')
743             subst = [old_put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")]
744             document.body[i:k + 1] = subst
745         i = i + 1
746     i = 0
747     while True:
748         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
749         if i == -1:
750             return
751         k = find_end_of_inset(document.body, i)
752         ptype = get_value(document.body, 'type', i, k).strip('"')
753         if ptype == "idx":
754             j = find_token(document.body, "type", i, k)
755             del document.body[j]
756         elif indices == "false":
757             del document.body[i:k + 1]
758         else:
759             subst = [old_put_cmd_in_ert("\\printindex[" + ptype + "]{}")]
760             document.body[i:k + 1] = subst
761         i = i + 1
762
763
764 def convert_splitindex(document):
765     " Converts index and printindex insets to splitindex-aware format "
766     i = 0
767     while True:
768         i = find_token(document.body, "\\begin_inset Index", i)
769         if i == -1:
770             break
771         document.body[i] = document.body[i].replace("\\begin_inset Index",
772             "\\begin_inset Index idx")
773         i = i + 1
774     i = 0
775     while True:
776         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
777         if i == -1:
778             return
779         if document.body[i + 1].find('LatexCommand printindex') == -1:
780             document.warning("Malformed LyX document: Incomplete printindex inset.")
781             return
782         subst = ["LatexCommand printindex", 
783             "type \"idx\""]
784         document.body[i + 1:i + 2] = subst
785         i = i + 1
786
787
788 def revert_subindex(document):
789     " Reverts \\printsubindex CommandInset types "
790     i = find_token(document.header, '\\use_indices', 0)
791     if i == -1:
792         document.warning("Malformed LyX document: Missing \\use_indices.")
793         return
794     indices = get_value(document.header, "\\use_indices", i)
795     i = 0
796     while True:
797         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
798         if i == -1:
799             return
800         k = find_end_of_inset(document.body, i)
801         ctype = get_value(document.body, 'LatexCommand', i, k)
802         if ctype != "printsubindex":
803             i = i + 1
804             continue
805         ptype = get_value(document.body, 'type', i, k).strip('"')
806         if indices == "false":
807             del document.body[i:k + 1]
808         else:
809             subst = [old_put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")]
810             document.body[i:k + 1] = subst
811         i = i + 1
812
813
814 def revert_printindexall(document):
815     " Reverts \\print[sub]index* CommandInset types "
816     i = find_token(document.header, '\\use_indices', 0)
817     if i == -1:
818         document.warning("Malformed LyX document: Missing \\use_indices.")
819         return
820     indices = get_value(document.header, "\\use_indices", i)
821     i = 0
822     while True:
823         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
824         if i == -1:
825             return
826         k = find_end_of_inset(document.body, i)
827         ctype = get_value(document.body, 'LatexCommand', i, k)
828         if ctype != "printindex*" and ctype != "printsubindex*":
829             i = i + 1
830             continue
831         if indices == "false":
832             del document.body[i:k + 1]
833         else:
834             subst = [old_put_cmd_in_ert("\\" + ctype + "{}")]
835             document.body[i:k + 1] = subst
836         i = i + 1
837
838
839 def revert_strikeout(document):
840   " Reverts \\strikeout character style "
841   changed = False
842   changed = revert_charstyles(document, "\\uuline", "\\uuline", changed)
843   changed = revert_charstyles(document, "\\uwave", "\\uwave", changed)
844   changed = revert_charstyles(document, "\\strikeout", "\\sout", changed)
845   if changed == True:
846     insert_to_preamble(0, document,
847         '% Commands inserted by lyx2lyx for proper underlining\n'
848         + '\\PassOptionsToPackage{normalem}{ulem}\n'
849         + '\\usepackage{ulem}\n')
850
851
852 def revert_ulinelatex(document):
853     " Reverts \\uline character style "
854     i = find_token(document.body, '\\bar under', 0)
855     if i == -1:
856         return
857     insert_to_preamble(0, document,
858             '% Commands inserted by lyx2lyx for proper underlining\n'
859             + '\\PassOptionsToPackage{normalem}{ulem}\n'
860             + '\\usepackage{ulem}\n'
861             + '\\let\\cite@rig\\cite\n'
862             + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
863             + '  \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
864             + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
865
866
867 def revert_custom_processors(document):
868     " Remove bibtex_command and index_command params "
869     i = find_token(document.header, '\\bibtex_command', 0)
870     if i == -1:
871         document.warning("Malformed LyX document: Missing \\bibtex_command.")
872         return
873     del document.header[i]
874     i = find_token(document.header, '\\index_command', 0)
875     if i == -1:
876         document.warning("Malformed LyX document: Missing \\index_command.")
877         return
878     del document.header[i]
879
880
881 def convert_nomencl_width(document):
882     " Add set_width param to nomencl_print "
883     i = 0
884     while True:
885       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
886       if i == -1:
887         break
888       document.body.insert(i + 2, "set_width \"none\"")
889       i = i + 1
890
891
892 def revert_nomencl_width(document):
893     " Remove set_width param from nomencl_print "
894     i = 0
895     while True:
896       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
897       if i == -1:
898         break
899       j = find_end_of_inset(document.body, i)
900       l = find_token(document.body, "set_width", i, j)
901       if l == -1:
902             document.warning("Can't find set_width option for nomencl_print!")
903             i = j
904             continue
905       del document.body[l]
906       i = i + 1
907
908
909 def revert_nomencl_cwidth(document):
910     " Remove width param from nomencl_print "
911     i = 0
912     while True:
913       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
914       if i == -1:
915         break
916       j = find_end_of_inset(document.body, i)
917       l = find_token(document.body, "width", i, j)
918       if l == -1:
919             #Can't find width option for nomencl_print
920             i = j
921             continue
922       width = get_value(document.body, "width", i, j).strip('"')
923       del document.body[l]
924       add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
925       add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
926       i = i + 1
927
928
929 def revert_applemac(document):
930     " Revert applemac encoding to auto "
931     i = 0
932     if document.encoding == "applemac":
933         document.encoding = "auto"
934         i = find_token(document.header, "\\encoding", 0)
935         if i != -1:
936             document.header[i] = "\\encoding auto"
937
938
939 def revert_longtable_align(document):
940     " Remove longtable alignment setting "
941     i = 0
942     j = 0
943     while True:
944       i = find_token(document.body, "\\begin_inset Tabular", i)
945       if i == -1:
946           break
947       # the alignment is 2 lines below \\begin_inset Tabular
948       j = document.body[i + 2].find("longtabularalignment")
949       if j == -1:
950           break
951       document.body[i + 2] = document.body[i + 2][:j - 1]
952       document.body[i + 2] = document.body[i + 2] + '>'
953       i = i + 1
954
955
956 def revert_branch_filename(document):
957     " Remove \\filename_suffix parameter from branches "
958     i = 0
959     while True:
960         i = find_token(document.header, "\\filename_suffix", i)
961         if i == -1:
962             return
963         del document.header[i]
964
965
966 def revert_paragraph_indentation(document):
967     " Revert custom paragraph indentation to preamble code "
968     i = 0
969     while True:
970       i = find_token(document.header, "\\paragraph_indentation", i)
971       if i == -1:
972           break
973       # only remove the preamble line if default
974       # otherwise also write the value to the preamble
975       length = get_value(document.header, "\\paragraph_indentation", i)
976       if length == "default":
977           del document.header[i]
978           break
979       else:
980           # handle percent lengths
981           # latex_length returns "bool,length"
982           length = latex_length(length).split(",")[1]
983           add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
984           add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
985           del document.header[i]
986       i = i + 1
987
988
989 def revert_percent_skip_lengths(document):
990     " Revert relative lengths for paragraph skip separation to preamble code "
991     i = 0
992     while True:
993       i = find_token(document.header, "\\defskip", i)
994       if i == -1:
995           break
996       length = get_value(document.header, "\\defskip", i)
997       # only revert when a custom length was set and when
998       # it used a percent length
999       if length not in ('smallskip', 'medskip', 'bigskip'):
1000           # handle percent lengths
1001           length = latex_length(length)
1002           # latex_length returns "bool,length"
1003           percent = length.split(",")[0]
1004           length = length.split(",")[1]
1005           if percent == "True":
1006               add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1007               add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
1008               # set defskip to medskip as default
1009               document.header[i] = "\\defskip medskip"
1010       i = i + 1
1011
1012
1013 def revert_percent_vspace_lengths(document):
1014     " Revert relative VSpace lengths to ERT "
1015     i = 0
1016     while True:
1017       i = find_token(document.body, "\\begin_inset VSpace", i)
1018       if i == -1:
1019           break
1020       # only revert if a custom length was set and if
1021       # it used a percent length
1022       line = document.body[i]
1023       r = re.compile(r'\\begin_inset VSpace (.*)$')
1024       m = r.match(line)
1025       length = m.group(1)
1026       if length not in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
1027           # check if the space has a star (protected space)
1028           protected = (document.body[i].rfind("*") != -1)
1029           if protected:
1030               length = length.rstrip('*')
1031           # handle percent lengths
1032           length = latex_length(length)
1033           # latex_length returns "bool,length"
1034           percent = length.split(",")[0]
1035           length = length.split(",")[1]
1036           # revert the VSpace inset to ERT
1037           if percent == "True":
1038               if protected:
1039                   subst = [old_put_cmd_in_ert("\\vspace*{" + length + "}")]
1040               else:
1041                   subst = [old_put_cmd_in_ert("\\vspace{" + length + "}")]
1042               document.body[i:i + 2] = subst
1043       i = i + 1
1044
1045
1046 def revert_percent_hspace_lengths(document):
1047     " Revert relative HSpace lengths to ERT "
1048     i = 0
1049     while True:
1050       i = find_token(document.body, "\\begin_inset space \\hspace", i)
1051       if i == -1:
1052           break
1053       protected = (document.body[i].find("\\hspace*{}") != -1)
1054       # only revert if a custom length was set and if
1055       # it used a percent length
1056       length = get_value(document.body, '\\length', i + 1)
1057       if length == '':
1058           document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1059           return
1060       # handle percent lengths
1061       length = latex_length(length)
1062       # latex_length returns "bool,length"
1063       percent = length.split(",")[0]
1064       length = length.split(",")[1]
1065       # revert the HSpace inset to ERT
1066       if percent == "True":
1067           if protected:
1068               subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1069           else:
1070               subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1071           document.body[i:i + 3] = subst
1072       i = i + 2
1073
1074
1075 def revert_hspace_glue_lengths(document):
1076     " Revert HSpace glue lengths to ERT "
1077     i = 0
1078     while True:
1079       i = find_token(document.body, "\\begin_inset space \\hspace", i)
1080       if i == -1:
1081           break
1082       protected = (document.body[i].find("\\hspace*{}") != -1)
1083       length = get_value(document.body, '\\length', i + 1)
1084       if length == '':
1085           document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1086           return
1087       # only revert if the length contains a plus or minus at pos != 0
1088       glue  = re.compile(r'.+[\+-]')
1089       if glue.search(length):
1090           # handle percent lengths
1091           # latex_length returns "bool,length"
1092           length = latex_length(length).split(",")[1]
1093           # revert the HSpace inset to ERT
1094           if protected:
1095               subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1096           else:
1097               subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1098           document.body[i:i + 3] = subst
1099       i = i + 2
1100
1101 def convert_author_id(document):
1102     " Add the author_id to the \\author definition and make sure 0 is not used"
1103     i = 0
1104     j = 1
1105     while True:
1106         i = find_token(document.header, "\\author", i)
1107         if i == -1:
1108             break
1109         
1110         r = re.compile(r'(\\author) (\".*\")\s?(.*)$')
1111         m = r.match(document.header[i])
1112         if m != None:
1113             name = m.group(2)
1114             
1115             email = ''
1116             if m.lastindex == 3:
1117                 email = m.group(3)
1118             document.header[i] = "\\author %i %s %s" % (j, name, email)
1119         j = j + 1
1120         i = i + 1
1121         
1122     k = 0
1123     while True:
1124         k = find_token(document.body, "\\change_", k)
1125         if k == -1:
1126             break
1127
1128         change = document.body[k].split(' ');
1129         if len(change) == 3:
1130             type = change[0]
1131             author_id = int(change[1])
1132             time = change[2]
1133             document.body[k] = "%s %i %s" % (type, author_id + 1, time)
1134         k = k + 1
1135
1136 def revert_author_id(document):
1137     " Remove the author_id from the \\author definition "
1138     i = 0
1139     j = 0
1140     idmap = dict()
1141     while True:
1142         i = find_token(document.header, "\\author", i)
1143         if i == -1:
1144             break
1145         
1146         r = re.compile(r'(\\author) (\d+) (\".*\")\s?(.*)$')
1147         m = r.match(document.header[i])
1148         if m != None:
1149             author_id = int(m.group(2))
1150             idmap[author_id] = j
1151             name = m.group(3)
1152             
1153             email = ''
1154             if m.lastindex == 4:
1155                 email = m.group(4)
1156             document.header[i] = "\\author %s %s" % (name, email)
1157         i = i + 1
1158         j = j + 1
1159
1160     k = 0
1161     while True:
1162         k = find_token(document.body, "\\change_", k)
1163         if k == -1:
1164             break
1165
1166         change = document.body[k].split(' ');
1167         if len(change) == 3:
1168             type = change[0]
1169             author_id = int(change[1])
1170             time = change[2]
1171             document.body[k] = "%s %i %s" % (type, idmap[author_id], time)
1172         k = k + 1
1173
1174
1175 def revert_suppress_date(document):
1176     " Revert suppressing of default document date to preamble code "
1177     i = 0
1178     while True:
1179       i = find_token(document.header, "\\suppress_date", i)
1180       if i == -1:
1181           break
1182       # remove the preamble line and write to the preamble
1183       # when suppress_date was true
1184       date = get_value(document.header, "\\suppress_date", i)
1185       if date == "true":
1186           add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1187           add_to_preamble(document, ["\\date{}"])
1188       del document.header[i]
1189       i = i + 1
1190
1191
1192 def revert_mhchem(document):
1193     "Revert mhchem loading to preamble code"
1194     i = 0
1195     j = 0
1196     k = 0
1197     mhchem = "off"
1198     i = find_token(document.header, "\\use_mhchem 1", 0)
1199     if i != -1:
1200         mhchem = "auto"
1201     else:
1202         i = find_token(document.header, "\\use_mhchem 2", 0)
1203         if i != -1:
1204             mhchem = "on"
1205     if mhchem == "auto":
1206         j = find_token(document.body, "\\cf{", 0)
1207         if j != -1:
1208             mhchem = "on"
1209         else:
1210             j = find_token(document.body, "\\ce{", 0)
1211             if j != -1:
1212                 mhchem = "on"
1213     if mhchem == "on":
1214         add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1215         add_to_preamble(document, ["\\PassOptionsToPackage{version=3}{mhchem}"])
1216         add_to_preamble(document, ["\\usepackage{mhchem}"])
1217     k = find_token(document.header, "\\use_mhchem", 0)
1218     if k == -1:
1219         document.warning("Malformed LyX document: Could not find mhchem setting.")
1220         return
1221     del document.header[k]
1222
1223
1224 def revert_fontenc(document):
1225     " Remove fontencoding param "
1226     i = find_token(document.header, '\\fontencoding', 0)
1227     if i == -1:
1228         document.warning("Malformed LyX document: Missing \\fontencoding.")
1229         return
1230     del document.header[i]
1231
1232
1233 def merge_gbrief(document):
1234     " Merge g-brief-en and g-brief-de to one class "
1235
1236     if document.textclass != "g-brief-de":
1237         if document.textclass == "g-brief-en":
1238             document.textclass = "g-brief"
1239             document.set_textclass()
1240         return
1241
1242     obsoletedby = { "Brieftext":       "Letter",
1243                     "Unterschrift":    "Signature",
1244                     "Strasse":         "Street",
1245                     "Zusatz":          "Addition",
1246                     "Ort":             "Town",
1247                     "Land":            "State",
1248                     "RetourAdresse":   "ReturnAddress",
1249                     "MeinZeichen":     "MyRef",
1250                     "IhrZeichen":      "YourRef",
1251                     "IhrSchreiben":    "YourMail",
1252                     "Telefon":         "Phone",
1253                     "BLZ":             "BankCode",
1254                     "Konto":           "BankAccount",
1255                     "Postvermerk":     "PostalComment",
1256                     "Adresse":         "Address",
1257                     "Datum":           "Date",
1258                     "Betreff":         "Reference",
1259                     "Anrede":          "Opening",
1260                     "Anlagen":         "Encl.",
1261                     "Verteiler":       "cc",
1262                     "Gruss":           "Closing"}
1263     i = 0
1264     while 1:
1265         i = find_token(document.body, "\\begin_layout", i)
1266         if i == -1:
1267             break
1268
1269         layout = document.body[i][14:]
1270         if layout in obsoletedby:
1271             document.body[i] = "\\begin_layout " + obsoletedby[layout]
1272
1273         i += 1
1274         
1275     document.textclass = "g-brief"
1276     document.set_textclass()
1277
1278
1279 def revert_gbrief(document):
1280     " Revert g-brief to g-brief-en "
1281     if document.textclass == "g-brief":
1282         document.textclass = "g-brief-en"
1283         document.set_textclass()
1284
1285
1286 def revert_html_options(document):
1287     " Remove html options "
1288     i = find_token(document.header, '\\html_use_mathml', 0)
1289     if i != -1:
1290         del document.header[i]
1291     i = find_token(document.header, '\\html_be_strict', 0)
1292     if i != -1:
1293         del document.header[i]
1294
1295
1296 def revert_includeonly(document):
1297     i = 0
1298     while True:
1299         i = find_token(document.header, "\\begin_includeonly", i)
1300         if i == -1:
1301             return
1302         j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
1303         if j == -1:
1304             # this should not happen
1305             break
1306         document.header[i : j + 1] = []
1307
1308
1309 def revert_includeall(document):
1310     " Remove maintain_unincluded_children param "
1311     i = find_token(document.header, '\\maintain_unincluded_children', 0)
1312     if i != -1:
1313         del document.header[i]
1314
1315
1316 def revert_multirow(document):
1317     " Revert multirow cells in tables "
1318     i = 0
1319     multirow = False
1320     while True:
1321       # cell type 3 is multirow begin cell
1322       i = find_token(document.body, '<cell multirow="3"', i)
1323       if i == -1:
1324           break
1325       # a multirow cell was found
1326       multirow = True
1327       # remove the multirow tag, set the valignment to top
1328       # and remove the bottom line
1329       document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
1330       document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1331       document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
1332       # write ERT to create the multirow cell
1333       # use 2 rows and 2cm as default with because the multirow span
1334       # and the column width is only hardly accessible
1335       subst = [old_put_cmd_in_ert("\\multirow{2}{2cm}{")]
1336       document.body[i + 4:i + 4] = subst
1337       i = find_token(document.body, "</cell>", i)
1338       if i == -1:
1339            document.warning("Malformed LyX document: Could not find end of tabular cell.")
1340            break
1341       subst = [old_put_cmd_in_ert("}")]
1342       document.body[i - 3:i - 3] = subst
1343       # cell type 4 is multirow part cell
1344       i = find_token(document.body, '<cell multirow="4"', i)
1345       if i == -1:
1346           break
1347       # remove the multirow tag, set the valignment to top
1348       # and remove the top line
1349       document.body[i] = document.body[i].replace(' multirow="4" ', ' ')
1350       document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1351       document.body[i] = document.body[i].replace(' topline="true" ', ' ')
1352       i = i + 1
1353     if multirow == True:
1354         add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1355         add_to_preamble(document, ["\\usepackage{multirow}"])
1356
1357
1358 def convert_math_output(document):
1359     " Convert \html_use_mathml to \html_math_output "
1360     i = find_token(document.header, "\\html_use_mathml", 0)
1361     if i == -1:
1362         return
1363     rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1364     m = rgx.match(document.header[i])
1365     if rgx:
1366         newval = "0" # MathML
1367         val = m.group(1)
1368         if val != "true":
1369             newval = "2" # Images
1370         document.header[i] = "\\html_math_output " + newval
1371
1372
1373 def revert_math_output(document):
1374     " Revert \html_math_output to \html_use_mathml "
1375     i = find_token(document.header, "\\html_math_output", 0)
1376     if i == -1:
1377         return
1378     rgx = re.compile(r'\\html_math_output\s+(\d)')
1379     m = rgx.match(document.header[i])
1380     newval = "true"
1381     if rgx:
1382         val = m.group(1)
1383         if val == "1" or val == "2":
1384             newval = "false"
1385     else:
1386         document.warning("Unable to match " + document.header[i])
1387     document.header[i] = "\\html_use_mathml " + newval
1388                 
1389
1390
1391 def revert_inset_preview(document):
1392     " Dissolves the preview inset "
1393     i = 0
1394     j = 0
1395     k = 0
1396     while True:
1397       i = find_token(document.body, "\\begin_inset Preview", i)
1398       if i == -1:
1399           return
1400       j = find_end_of_inset(document.body, i)
1401       if j == -1:
1402           document.warning("Malformed LyX document: Could not find end of Preview inset.")
1403           return
1404       #If the layout is Standard we need to remove it, otherwise there
1405       #will be paragraph breaks that shouldn't be there.
1406       k = find_token(document.body, "\\begin_layout Standard", i)
1407       if k == i + 2:
1408           del document.body[i:i + 3]
1409           del document.body[j - 5:j - 2]
1410           i -= 6
1411       else:
1412           del document.body[i]
1413           del document.body[j - 1]
1414           i -= 2
1415                 
1416
1417 def revert_equalspacing_xymatrix(document):
1418     " Revert a Formula with xymatrix@! to an ERT inset "
1419     i = 0
1420     j = 0
1421     has_preamble = False
1422     has_equal_spacing = False
1423     while True:
1424       found = -1
1425       i = find_token(document.body, "\\begin_inset Formula", i)
1426       if i == -1:
1427           break
1428       j = find_end_of_inset(document.body, i)
1429       if j == -1:
1430           document.warning("Malformed LyX document: Could not find end of Formula inset.")
1431           break
1432           
1433       for curline in range(i,j):
1434           found = document.body[curline].find("\\xymatrix@!")
1435           if found != -1:
1436               break
1437  
1438       if found != -1:
1439           has_equal_spacing = True
1440           content = [document.body[i][21:]]
1441           content += document.body[i + 1:j]
1442           subst = put_cmd_in_ert(content)
1443           document.body[i:j + 1] = subst
1444           i += len(subst)
1445       else:
1446           for curline in range(i,j):
1447               l = document.body[curline].find("\\xymatrix")
1448               if l != -1:
1449                   has_preamble = True;
1450                   break;
1451           i = j + 1
1452     if has_equal_spacing and not has_preamble:
1453         add_to_preamble(document, ['\\usepackage[all]{xy}'])
1454
1455
1456 def revert_notefontcolor(document):
1457     " Reverts greyed-out note font color to preamble code "
1458     i = 0
1459     colorcode = ""
1460     while True:
1461       i = find_token(document.header, "\\notefontcolor", i)
1462       if i == -1:
1463           return
1464       colorcode = get_value(document.header, '\\notefontcolor', 0)
1465       del document.header[i]
1466       # the color code is in the form #rrggbb where every character denotes a hex number
1467       # convert the string to an int
1468       red = string.atoi(colorcode[1:3],16)
1469       # we want the output "0.5" for the value "127" therefore increment here
1470       if red != 0:
1471           red = red + 1
1472       redout = float(red) / 256
1473       green = string.atoi(colorcode[3:5],16)
1474       if green != 0:
1475           green = green + 1
1476       greenout = float(green) / 256
1477       blue = string.atoi(colorcode[5:7],16)
1478       if blue != 0:
1479           blue = blue + 1
1480       blueout = float(blue) / 256
1481       # write the preamble
1482       insert_to_preamble(0, document,
1483                            '% Commands inserted by lyx2lyx to set the font color\n'
1484                            '% for greyed-out notes\n'
1485                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1486                            + '\\definecolor{note_fontcolor}{rgb}{'
1487                            + str(redout) + ', ' + str(greenout)
1488                            + ', ' + str(blueout) + '}\n'
1489                            + '\\renewenvironment{lyxgreyedout}\n'
1490                            + ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}\n')
1491
1492
1493 def revert_turkmen(document):
1494     "Set language Turkmen to English" 
1495     i = 0 
1496     if document.language == "turkmen": 
1497         document.language = "english" 
1498         i = find_token(document.header, "\\language", 0) 
1499         if i != -1: 
1500             document.header[i] = "\\language english" 
1501     j = 0 
1502     while True: 
1503         j = find_token(document.body, "\\lang turkmen", j) 
1504         if j == -1: 
1505             return 
1506         document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english") 
1507         j = j + 1 
1508
1509
1510 def revert_fontcolor(document):
1511     " Reverts font color to preamble code "
1512     i = 0
1513     colorcode = ""
1514     while True:
1515       i = find_token(document.header, "\\fontcolor", i)
1516       if i == -1:
1517           return
1518       colorcode = get_value(document.header, '\\fontcolor', 0)
1519       del document.header[i]
1520       # don't clutter the preamble if backgroundcolor is not set
1521       if colorcode == "#000000":
1522           continue
1523       # the color code is in the form #rrggbb where every character denotes a hex number
1524       # convert the string to an int
1525       red = string.atoi(colorcode[1:3],16)
1526       # we want the output "0.5" for the value "127" therefore add here
1527       if red != 0:
1528           red = red + 1
1529       redout = float(red) / 256
1530       green = string.atoi(colorcode[3:5],16)
1531       if green != 0:
1532           green = green + 1
1533       greenout = float(green) / 256
1534       blue = string.atoi(colorcode[5:7],16)
1535       if blue != 0:
1536           blue = blue + 1
1537       blueout = float(blue) / 256
1538       # write the preamble
1539       insert_to_preamble(0, document,
1540                            '% Commands inserted by lyx2lyx to set the font color\n'
1541                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1542                            + '\\definecolor{document_fontcolor}{rgb}{'
1543                            + str(redout) + ', ' + str(greenout)
1544                            + ', ' + str(blueout) + '}\n'
1545                            + '\\color{document_fontcolor}\n')
1546
1547
1548 def revert_shadedboxcolor(document):
1549     " Reverts shaded box color to preamble code "
1550     i = 0
1551     colorcode = ""
1552     while True:
1553       i = find_token(document.header, "\\boxbgcolor", i)
1554       if i == -1:
1555           return
1556       colorcode = get_value(document.header, '\\boxbgcolor', 0)
1557       del document.header[i]
1558       # the color code is in the form #rrggbb where every character denotes a hex number
1559       # convert the string to an int
1560       red = string.atoi(colorcode[1:3],16)
1561       # we want the output "0.5" for the value "127" therefore increment here
1562       if red != 0:
1563           red = red + 1
1564       redout = float(red) / 256
1565       green = string.atoi(colorcode[3:5],16)
1566       if green != 0:
1567           green = green + 1
1568       greenout = float(green) / 256
1569       blue = string.atoi(colorcode[5:7],16)
1570       if blue != 0:
1571           blue = blue + 1
1572       blueout = float(blue) / 256
1573       # write the preamble
1574       insert_to_preamble(0, document,
1575                            '% Commands inserted by lyx2lyx to set the color\n'
1576                            '% of boxes with shaded background\n'
1577                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1578                            + '\\definecolor{shadecolor}{rgb}{'
1579                            + str(redout) + ', ' + str(greenout)
1580                            + ', ' + str(blueout) + '}\n')
1581
1582
1583 def revert_lyx_version(document):
1584     " Reverts LyX Version information from Inset Info "
1585     version = "LyX version"
1586     try:
1587         import lyx2lyx_version
1588         version = lyx2lyx_version.version
1589     except:
1590         pass
1591
1592     i = 0
1593     while 1:
1594         i = find_token(document.body, '\\begin_inset Info', i)
1595         if i == -1:
1596             return
1597         j = find_end_of_inset(document.body, i + 1)
1598         if j == -1:
1599             # should not happen
1600             document.warning("Malformed LyX document: Could not find end of Info inset.")
1601         # We expect:
1602         # \begin_inset Info
1603         # type  "lyxinfo"
1604         # arg   "version"
1605         # \end_inset
1606         # but we shall try to be forgiving.
1607         arg = typ = ""
1608         for k in range(i, j):
1609             if document.body[k].startswith("arg"):
1610                 arg = document.body[k][3:].strip().strip('"')
1611             if document.body[k].startswith("type"):
1612                 typ = document.body[k][4:].strip().strip('"')
1613         if arg != "version" or typ != "lyxinfo":
1614             i = j + 1
1615             continue
1616
1617         # We do not actually know the version of LyX used to produce the document.
1618         # But we can use our version, since we are reverting.
1619         s = [version]
1620         # Now we want to check if the line after "\end_inset" is empty. It normally
1621         # is, so we want to remove it, too.
1622         lastline = j + 1
1623         if document.body[j + 1].strip() == "":
1624             lastline = j + 2
1625         document.body[i: lastline] = s
1626         i = i + 1
1627
1628
1629 def revert_math_scale(document):
1630   " Remove math scaling and LaTeX options "
1631   i = find_token(document.header, '\\html_math_img_scale', 0)
1632   if i != -1:
1633     del document.header[i]
1634   i = find_token(document.header, '\\html_latex_start', 0)
1635   if i != -1:
1636     del document.header[i]
1637   i = find_token(document.header, '\\html_latex_end', 0)
1638   if i != -1:
1639     del document.header[i]
1640
1641
1642 def revert_pagesizes(document):
1643   i = 0
1644   " Revert page sizes to default "
1645   i = find_token(document.header, '\\papersize', 0)
1646   if i != -1:
1647     size = document.header[i][11:]
1648     if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1649     or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1650     or size == "b2paper" or size == "b6paper" or size == "b0j" \
1651     or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1652     or size == "b5j" or size == "b6j":
1653       del document.header[i]
1654
1655
1656 def convert_html_quotes(document):
1657   " Remove quotes around html_latex_start and html_latex_end "
1658
1659   i = find_token(document.header, '\\html_latex_start', 0)
1660   if i != -1:
1661     line = document.header[i]
1662     l = re.compile(r'\\html_latex_start\s+"(.*)"')
1663     m = l.match(line)
1664     if m != None:
1665       document.header[i] = "\\html_latex_start " + m.group(1)
1666       
1667   i = find_token(document.header, '\\html_latex_end', 0)
1668   if i != -1:
1669     line = document.header[i]
1670     l = re.compile(r'\\html_latex_end\s+"(.*)"')
1671     m = l.match(line)
1672     if m != None:
1673       document.header[i] = "\\html_latex_end " + m.group(1)
1674       
1675
1676 def revert_html_quotes(document):
1677   " Remove quotes around html_latex_start and html_latex_end "
1678   
1679   i = find_token(document.header, '\\html_latex_start', 0)
1680   if i != -1:
1681     line = document.header[i]
1682     l = re.compile(r'\\html_latex_start\s+(.*)')
1683     m = l.match(line)
1684     document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1685       
1686   i = find_token(document.header, '\\html_latex_end', 0)
1687   if i != -1:
1688     line = document.header[i]
1689     l = re.compile(r'\\html_latex_end\s+(.*)')
1690     m = l.match(line)
1691     document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1692
1693
1694 def revert_output_sync(document):
1695   " Remove forward search options "
1696   i = find_token(document.header, '\\output_sync_macro', 0)
1697   if i != -1:
1698     del document.header[i]
1699   i = find_token(document.header, '\\output_sync', 0)
1700   if i != -1:
1701     del document.header[i]
1702
1703
1704 def convert_beamer_args(document):
1705   " Convert ERT arguments in Beamer to InsetArguments "
1706
1707   if document.textclass != "beamer" and document.textclass != "article-beamer":
1708     return
1709   
1710   layouts = ("Block", "ExampleBlock", "AlertBlock")
1711   for layout in layouts:
1712     blay = 0
1713     while True:
1714       blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1715       if blay == -1:
1716         break
1717       elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1718       if elay == -1:
1719         document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1720         blay += 1
1721         continue
1722       bert = find_token(document.body, '\\begin_inset ERT', blay)
1723       if bert == -1:
1724         document.warning("Malformed Beamer LyX document: Can't find argument of " + layout + " layout.")
1725         blay = elay + 1
1726         continue
1727       eert = find_end_of_inset(document.body, bert)
1728       if eert == -1:
1729         document.warning("Malformed LyX document: Can't find end of ERT.")
1730         blay = elay + 1
1731         continue
1732       
1733       # So the ERT inset begins at line k and goes to line l. We now wrap it in 
1734       # an argument inset.
1735       # Do the end first, so as not to mess up the variables.
1736       document.body[eert + 1:eert + 1] = ['', '\\end_layout', '', '\\end_inset', '']
1737       document.body[bert:bert] = ['\\begin_inset OptArg', 'status open', '', 
1738           '\\begin_layout Plain Layout']
1739       blay = elay + 9
1740
1741
1742 def revert_beamer_args(document):
1743   " Revert Beamer arguments to ERT "
1744   
1745   if document.textclass != "beamer" and document.textclass != "article-beamer":
1746     return
1747     
1748   layouts = ("Block", "ExampleBlock", "AlertBlock")
1749   for layout in layouts:
1750     blay = 0
1751     while True:
1752       blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1753       if blay == -1:
1754         break
1755       elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1756       if elay == -1:
1757         document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1758         blay += 1
1759         continue
1760       bopt = find_token(document.body, '\\begin_inset OptArg', blay)
1761       if bopt == -1:
1762         # it is legal not to have one of these
1763         blay = elay + 1
1764         continue
1765       eopt = find_end_of_inset(document.body, bopt)
1766       if eopt == -1:
1767         document.warning("Malformed LyX document: Can't find end of argument.")
1768         blay = elay + 1
1769         continue
1770       bplay = find_token(document.body, '\\begin_layout Plain Layout', blay)
1771       if bplay == -1:
1772         document.warning("Malformed LyX document: Can't find plain layout.")
1773         blay = elay + 1
1774         continue
1775       eplay = find_end_of(document.body, bplay, '\\begin_layout', '\\end_layout')
1776       if eplay == -1:
1777         document.warning("Malformed LyX document: Can't find end of plain layout.")
1778         blay = elay + 1
1779         continue
1780       # So the content of the argument inset goes from bplay + 1 to eplay - 1
1781       bcont = bplay + 1
1782       if bcont >= eplay:
1783         # Hmm.
1784         document.warning(str(bcont) + " " + str(eplay))
1785         blay = blay + 1
1786         continue
1787       # we convert the content of the argument into pure LaTeX...
1788       content = lyx2latex(document, document.body[bcont:eplay])
1789       strlist = put_cmd_in_ert(["{" + content + "}"])
1790       
1791       # now replace the optional argument with the ERT
1792       document.body[bopt:eopt + 1] = strlist
1793       blay = blay + 1
1794
1795
1796 def revert_align_decimal(document):
1797   l = 0
1798   while True:
1799     l = document.body[l].find('alignment=decimal')
1800     if l == -1:
1801         break
1802     remove_option(document, l, 'decimal_point')
1803     document.body[l].replace('decimal', 'center')
1804
1805
1806 def convert_optarg(document):
1807   " Convert \\begin_inset OptArg to \\begin_inset Argument "
1808   i = 0
1809   while 1:
1810     i = find_token(document.body, '\\begin_inset OptArg', i)
1811     if i == -1:
1812       return
1813     document.body[i] = "\\begin_inset Argument"
1814     i += 1
1815
1816
1817 def revert_argument(document):
1818   " Convert \\begin_inset Argument to \\begin_inset OptArg "
1819   i = 0
1820   while 1:
1821     i = find_token(document.body, '\\begin_inset Argument', i)
1822     if i == -1:
1823       return
1824     document.body[i] = "\\begin_inset OptArg"
1825     i += 1
1826
1827
1828 def revert_makebox(document):
1829   " Convert \\makebox to TeX code "
1830   i = 0
1831   while 1:
1832     # only revert frameless boxes without an inner box
1833     i = find_token(document.body, '\\begin_inset Box Frameless', i)
1834     if i == -1:
1835       return
1836     z = find_end_of_inset(document.body, i)
1837     if z == -1:
1838       document.warning("Malformed LyX document: Can't find end of box inset.")
1839       return
1840     j = find_token(document.body, 'use_makebox 1', i)
1841     # assure we found the makebox of the current box
1842     if j > z or j == -1:
1843       return
1844     y = find_token(document.body, "\\begin_layout", i)
1845     if y > z or y == -1:
1846       document.warning("Malformed LyX document: Can't find layout in box.")
1847       return
1848     # remove the \end_layout \end_inset pair
1849     document.body[z - 2:z + 1] = put_cmd_in_ert("}")
1850     # determine the alignment
1851     k = find_token(document.body, 'hor_pos', j - 4)
1852     align = document.body[k][9]
1853     # determine the width
1854     l = find_token(document.body, 'width "', j + 1)
1855     length = document.body[l][7:]
1856     # remove trailing '"'
1857     length = length[:-1]
1858     # latex_length returns "bool,length"
1859     length = latex_length(length).split(",")[1]
1860     subst = "\\makebox[" + length + "][" \
1861       + align + "]{"
1862     document.body[i:y + 1] = put_cmd_in_ert(subst)
1863     i += 1
1864
1865
1866 def revert_IEEEtran(document):
1867   " Convert IEEEtran layouts and styles to TeX code "
1868   if document.textclass != "IEEEtran":
1869     return
1870
1871   revert_flex_inset(document, "IEEE membership", "\\IEEEmembership", 0)
1872   revert_flex_inset(document, "Lowercase", "\\MakeLowercase", 0)
1873
1874   layouts = ("Special Paper Notice", "After Title Text", "Publication ID",
1875              "Page headings", "Biography without photo")
1876
1877   latexcmd = {"Special Paper Notice": "\\IEEEspecialpapernotice",
1878               "After Title Text":     "\\IEEEaftertitletext",
1879               "Publication ID":       "\\IEEEpubid"}
1880
1881   obsoletedby = {"Page headings":            "MarkBoth",
1882                  "Biography without photo":  "BiographyNoPhoto"}
1883
1884   for layout in layouts:
1885     i = 0
1886     while True:
1887         i = find_token(document.body, '\\begin_layout ' + layout, i)
1888         if i == -1:
1889           break
1890         j = find_end_of(document.body, i, '\\begin_layout', '\\end_layout')
1891         if j == -1:
1892           document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1893           i += 1
1894           continue
1895         if layout in obsoletedby:
1896           document.body[i] = "\\begin_layout " + obsoletedby[layout]
1897           i = j
1898         else:
1899           content = lyx2latex(document, document.body[i:j + 1])
1900           add_to_preamble(document, [latexcmd[layout] + "{" + content + "}"])
1901           del document.body[i:j + 1]
1902
1903
1904 ##
1905 # Conversion hub
1906 #
1907
1908 supported_versions = ["2.0.0","2.0"]
1909 convert = [[346, []],
1910            [347, []],
1911            [348, []],
1912            [349, []],
1913            [350, []],
1914            [351, []],
1915            [352, [convert_splitindex]],
1916            [353, []],
1917            [354, []],
1918            [355, []],
1919            [356, []],
1920            [357, []],
1921            [358, []],
1922            [359, [convert_nomencl_width]],
1923            [360, []],
1924            [361, []],
1925            [362, []],
1926            [363, []],
1927            [364, []],
1928            [365, []],
1929            [366, []],
1930            [367, []],
1931            [368, []],
1932            [369, [convert_author_id]],
1933            [370, []],
1934            [371, []],
1935            [372, []],
1936            [373, [merge_gbrief]],
1937            [374, []],
1938            [375, []],
1939            [376, []],
1940            [377, []],
1941            [378, []],
1942            [379, [convert_math_output]],
1943            [380, []],
1944            [381, []],
1945            [382, []],
1946            [383, []],
1947            [384, []],
1948            [385, []],
1949            [386, []],
1950            [387, []],
1951            [388, []],
1952            [389, [convert_html_quotes]],
1953            [390, []],
1954            [391, []],
1955            [392, [convert_beamer_args]],
1956            [393, [convert_optarg]],
1957            [394, []]
1958           ]
1959
1960 revert =  [[393, [revert_makebox]],
1961            [392, [revert_argument]],
1962            [391, [revert_beamer_args]],
1963            [390, [revert_align_decimal, revert_IEEEtran]],
1964            [389, [revert_output_sync]],
1965            [388, [revert_html_quotes]],
1966            [387, [revert_pagesizes]],
1967            [386, [revert_math_scale]],
1968            [385, [revert_lyx_version]],
1969            [384, [revert_shadedboxcolor]],
1970            [383, [revert_fontcolor]],
1971            [382, [revert_turkmen]],
1972            [381, [revert_notefontcolor]],
1973            [380, [revert_equalspacing_xymatrix]],
1974            [379, [revert_inset_preview]],
1975            [378, [revert_math_output]],
1976            [377, []],
1977            [376, [revert_multirow]],
1978            [375, [revert_includeall]],
1979            [374, [revert_includeonly]],
1980            [373, [revert_html_options]],
1981            [372, [revert_gbrief]],
1982            [371, [revert_fontenc]],
1983            [370, [revert_mhchem]],
1984            [369, [revert_suppress_date]],
1985            [368, [revert_author_id]],
1986            [367, [revert_hspace_glue_lengths]],
1987            [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
1988            [365, [revert_percent_skip_lengths]],
1989            [364, [revert_paragraph_indentation]],
1990            [363, [revert_branch_filename]],
1991            [362, [revert_longtable_align]],
1992            [361, [revert_applemac]],
1993            [360, []],
1994            [359, [revert_nomencl_cwidth]],
1995            [358, [revert_nomencl_width]],
1996            [357, [revert_custom_processors]],
1997            [356, [revert_ulinelatex]],
1998            [355, []],
1999            [354, [revert_strikeout]],
2000            [353, [revert_printindexall]],
2001            [352, [revert_subindex]],
2002            [351, [revert_splitindex]],
2003            [350, [revert_backgroundcolor]],
2004            [349, [revert_outputformat]],
2005            [348, [revert_xetex]],
2006            [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2007            [346, [revert_tabularvalign]],
2008            [345, [revert_swiss]]
2009           ]
2010
2011
2012 if __name__ == "__main__":
2013     pass