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