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