]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_2_0.py
Just do the best we can here.
[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 find_end_of_inset(lines, i):
32     " Find end of inset, where lines[i] is included."
33     return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
34
35
36 def add_to_preamble(document, text):
37     """ Add text to the preamble if it is not already there.
38     Only the first line is checked!"""
39
40     if find_token(document.preamble, text[0], 0) != -1:
41         return
42
43     document.preamble.extend(text)
44
45
46 def insert_to_preamble(index, document, text):
47     """ Insert text to the preamble at a given line"""
48
49     document.preamble.insert(index, text)
50
51
52 def read_unicodesymbols():
53     " Read the unicodesymbols list of unicode characters and corresponding commands."
54     pathname = os.path.abspath(os.path.dirname(sys.argv[0]))
55     fp = open(os.path.join(pathname.strip('lyx2lyx'), 'unicodesymbols'))
56     spec_chars = []
57     # Two backslashes, followed by some non-word character, and then a character
58     # in brackets. The idea is to check for constructs like: \"{u}, which is how
59     # they are written in the unicodesymbols file; but they can also be written
60     # as: \"u or even \" u.
61     r = re.compile(r'\\\\(\W)\{(\w)\}')
62     for line in fp.readlines():
63         if line[0] != '#' and line.strip() != "":
64             line=line.replace(' "',' ') # remove all quotation marks with spaces before
65             line=line.replace('" ',' ') # remove all quotation marks with spaces after
66             line=line.replace(r'\"','"') # replace \" by " (for characters with diaeresis)
67             try:
68                 [ucs4,command,dead] = line.split(None,2)
69                 if command[0:1] != "\\":
70                     continue
71                 spec_chars.append([command, unichr(eval(ucs4))])
72             except:
73                 continue
74             m = r.match(command)
75             if m != None:
76                 command = "\\\\"
77                 # If the character is a double-quote, then we need to escape it, too,
78                 # since it is done that way in the LyX file.
79                 if m.group(1) == "\"":
80                     command += "\\"
81                 commandbl = command
82                 command += m.group(1) + m.group(2)
83                 commandbl += m.group(1) + ' ' + m.group(2)
84                 spec_chars.append([command, unichr(eval(ucs4))])
85                 spec_chars.append([commandbl, unichr(eval(ucs4))])
86     fp.close()
87     return spec_chars
88
89
90 unicode_reps = read_unicodesymbols()
91
92
93 # DO NOT USE THIS ROUTINE ANY MORE. Better yet, replace the uses that
94 # have been made of it with uses of put_cmd_in_ert.
95 def old_put_cmd_in_ert(string):
96     for rep in unicode_reps:
97         string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
98     string = string.replace('\\', "\\backslash\n")
99     string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
100       + string + "\n\\end_layout\n\\end_inset"
101     return string
102
103
104 # This routine wraps some content in an ERT inset. It returns a 
105 # LIST of strings. This is how lyx2lyx works: with a list of strings, 
106 # each representing a line of a LyX file. Embedded newlines confuse
107 # lyx2lyx very much.
108 # For this same reason, we expect as input a LIST of strings, not
109 # something with embedded newlines. That said, if any of your strings
110 # do have embedded newlines, the string will eventually get split on
111 # them and you'll get a list back.
112 #
113 # A call to this routine will often go something like this:
114 #   i = find_token('\\begin_inset FunkyInset', ...)
115 #   ...
116 #   j = find_end_of_inset(document.body, i)
117 #   content = ...extract content from insets
118 #   ert = put_cmd_in_ert(content)
119 #   document.body[i:j] = ert
120 # Now, before we continue, we need to reset i appropriately. Normally,
121 # this would be: 
122 #   i += len(ert)
123 # That puts us right after the ERT we just inserted.
124 def put_cmd_in_ert(strlist):
125     ret = ["\\begin_inset ERT", "status collapsed", "\\begin_layout Plain Layout\n"]
126     # Despite the warnings just given, it will be faster for us to work
127     # with a single string internally. That way, we only go through the
128     # unicode_reps loop once.
129     s = "\n".join(strlist)
130     for rep in unicode_reps:
131         s = s.replace(rep[1], rep[0].replace('\\\\', '\\'))
132     s = s.replace('\\', "\\backslash\n")
133     ret += s.splitlines()
134     ret += ["\\end_layout", "\\end_inset"]
135     return ret
136
137             
138 def lyx2latex(document, lines):
139     'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
140     # clean up multiline stuff
141     content = ""
142     ert_end = 0
143
144     for curline in range(len(lines)):
145       line = lines[curline]
146       if line.startswith("\\begin_inset ERT"):
147           # We don't want to replace things inside ERT, so figure out
148           # where the end of the inset is.
149           ert_end = find_end_of_inset(lines, curline + 1)
150           continue
151       elif line.startswith("\\begin_inset Formula"):
152           line = line[20:]
153       elif line.startswith("\\begin_inset Quotes"):
154           # For now, we do a very basic reversion. Someone who understands
155           # quotes is welcome to fix it up.
156           qtype = line[20:].strip()
157           # lang = qtype[0]
158           side = qtype[1]
159           dbls = qtype[2]
160           if side == "l":
161               if dbls == "d":
162                   line = "``"
163               else:
164                   line = "`"
165           else:
166               if dbls == "d":
167                   line = "''"
168               else:
169                   line = "'"
170       elif line.isspace() or \
171             line.startswith("\\begin_layout") or \
172             line.startswith("\\end_layout") or \
173             line.startswith("\\begin_inset") or \
174             line.startswith("\\end_inset") or \
175             line.startswith("\\lang") or \
176             line.strip() == "status collapsed" or \
177             line.strip() == "status open":
178           #skip all that stuff
179           continue
180
181       # this needs to be added to the preamble because of cases like
182       # \textmu, \textbackslash, etc.
183       add_to_preamble(document, ['% added by lyx2lyx for converted index entries',
184                                  '\\@ifundefined{textmu}',
185                                  ' {\\usepackage{textcomp}}{}'])
186       # a lossless reversion is not possible
187       # try at least to handle some common insets and settings
188       if ert_end >= curline:
189           line = line.replace(r'\backslash', r'\\')
190       else:
191           line = line.replace('&', '\\&{}')
192           line = line.replace('#', '\\#{}')
193           line = line.replace('^', '\\^{}')
194           line = line.replace('%', '\\%{}')
195           line = line.replace('_', '\\_{}')
196           line = line.replace('$', '\\${}')
197
198           # Do the LyX text --> LaTeX conversion
199           for rep in unicode_reps:
200             line = line.replace(rep[1], rep[0] + "{}")
201           line = line.replace(r'\backslash', r'\textbackslash{}')
202           line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
203           line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
204           line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
205           line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
206           line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
207           line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
208           line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
209           line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
210           line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
211       content += line
212     return content
213
214
215 def latex_length(string):
216     'Convert lengths to their LaTeX representation.'
217     i = 0
218     percent = False
219     # the string has the form
220     # ValueUnit+ValueUnit-ValueUnit or
221     # ValueUnit+-ValueUnit
222     # the + and - (glue lengths) are optional
223     # the + always precedes the -
224
225     # Convert relative lengths to LaTeX units
226     units = {"text%":"\\textwidth", "col%":"\\columnwidth",
227              "page%":"\\pagewidth", "line%":"\\linewidth",
228              "theight%":"\\textheight", "pheight%":"\\pageheight"}
229     for unit in units.keys():
230         i = string.find(unit)
231         if i != -1:
232             percent = True
233             minus = string.rfind("-", 1, i)
234             plus = string.rfind("+", 0, i)
235             latex_unit = units[unit]
236             if plus == -1 and minus == -1:
237                 value = string[:i]
238                 value = str(float(value)/100)
239                 end = string[i + len(unit):]
240                 string = value + latex_unit + end
241             if plus > minus:
242                 value = string[plus+1:i]
243                 value = str(float(value)/100)
244                 begin = string[:plus+1]
245                 end = string[i+len(unit):]
246                 string = begin + value + latex_unit + end
247             if plus < minus:
248                 value = string[minus+1:i]
249                 value = str(float(value)/100)
250                 begin = string[:minus+1]
251                 string = begin + value + latex_unit
252
253     # replace + and -, but only if the - is not the first character
254     string = string[0] + string[1:].replace("+", " plus ").replace("-", " minus ")
255     # handle the case where "+-1mm" was used, because LaTeX only understands
256     # "plus 1mm minus 1mm"
257     if string.find("plus  minus"):
258         lastvaluepos = string.rfind(" ")
259         lastvalue = string[lastvaluepos:]
260         string = string.replace("  ", lastvalue + " ")
261     if percent ==  False:
262         return "False," + string
263     else:
264         return "True," + string
265         
266
267 ####################################################################
268
269
270 def revert_swiss(document):
271     " Set language german-ch to ngerman "
272     i = 0
273     if document.language == "german-ch":
274         document.language = "ngerman"
275         i = find_token(document.header, "\\language", 0)
276         if i != -1:
277             document.header[i] = "\\language ngerman"
278     j = 0
279     while True:
280         j = find_token(document.body, "\\lang german-ch", j)
281         if j == -1:
282             return
283         document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
284         j = j + 1
285
286
287 def revert_tabularvalign(document):
288    " Revert the tabular valign option "
289    i = 0
290    while True:
291        i = find_token(document.body, "\\begin_inset Tabular", i)
292        if i == -1:
293            return
294        j = find_token(document.body, "</cell>", i)
295        if j == -1:
296            document.warning("Malformed LyX document: Could not find end of tabular cell.")
297            i = j
298            continue
299        # don't set a box for longtables, only delete tabularvalignment
300        # the alignment is 2 lines below \\begin_inset Tabular
301        p = document.body[i+2].find("islongtable")
302        if p > -1:
303            q = document.body[i+2].find("tabularvalignment")
304            if q > -1:
305                document.body[i+2] = document.body[i+2][:q-1]
306                document.body[i+2] = document.body[i+2] + '>'
307            i = i + 1
308
309        # when no longtable
310        if p == -1:
311          tabularvalignment = 'c'
312          # which valignment is specified?
313          m = document.body[i+2].find('tabularvalignment="top"')
314          if m > -1:
315              tabularvalignment = 't'
316          m = document.body[i+2].find('tabularvalignment="bottom"')
317          if m > -1:
318              tabularvalignment = 'b'
319          # delete tabularvalignment
320          q = document.body[i+2].find("tabularvalignment")
321          if q > -1:
322              document.body[i+2] = document.body[i+2][:q-1]
323              document.body[i+2] = document.body[i+2] + '>'
324
325          # don't add a box when centered
326          if tabularvalignment == 'c':
327              i = j
328              continue
329          subst = ['\\end_layout', '\\end_inset']
330          document.body[j:j] = subst # just inserts those lines
331          subst = ['\\begin_inset Box Frameless',
332              'position "' + tabularvalignment +'"',
333              'hor_pos "c"',
334              'has_inner_box 1',
335              'inner_pos "c"',
336              'use_parbox 0',
337              # we don't know the width, assume 50%
338              'width "50col%"',
339              'special "none"',
340              'height "1in"',
341              'height_special "totalheight"',
342              'status open',
343              '',
344              '\\begin_layout Plain Layout']
345          document.body[i:i] = subst # this just inserts the array at i
346          i += len(subst) + 2 # adjust i to save a few cycles
347
348
349 def revert_phantom(document):
350     " Reverts phantom to ERT "
351     i = 0
352     j = 0
353     while True:
354       i = find_token(document.body, "\\begin_inset Phantom Phantom", i)
355       if i == -1:
356           return
357       substi = document.body[i].replace('\\begin_inset Phantom Phantom', \
358                 '\\begin_inset ERT\nstatus collapsed\n\n' \
359                 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
360                 'phantom{\n\\end_layout\n\n\\end_inset\n')
361       substi = substi.split('\n')
362       document.body[i : i+4] = substi
363       i += len(substi)
364       j = find_token(document.body, "\\end_layout", i)
365       if j == -1:
366           document.warning("Malformed LyX document: Could not find end of Phantom inset.")
367           return
368       substj = document.body[j].replace('\\end_layout', \
369                 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
370                 '\\begin_layout Plain Layout\n\n' \
371                 '}\n\\end_layout\n\n\\end_inset\n')
372       substj = substj.split('\n')
373       document.body[j : j+4] = substj
374       i += len(substj)
375
376
377 def revert_hphantom(document):
378     " Reverts hphantom to ERT "
379     i = 0
380     j = 0
381     while True:
382       i = find_token(document.body, "\\begin_inset Phantom HPhantom", i)
383       if i == -1:
384           return
385       substi = document.body[i].replace('\\begin_inset Phantom HPhantom', \
386                 '\\begin_inset ERT\nstatus collapsed\n\n' \
387                 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
388                 'hphantom{\n\\end_layout\n\n\\end_inset\n')
389       substi = substi.split('\n')
390       document.body[i : i+4] = substi
391       i += len(substi)
392       j = find_token(document.body, "\\end_layout", i)
393       if j == -1:
394           document.warning("Malformed LyX document: Could not find end of HPhantom inset.")
395           return
396       substj = document.body[j].replace('\\end_layout', \
397                 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
398                 '\\begin_layout Plain Layout\n\n' \
399                 '}\n\\end_layout\n\n\\end_inset\n')
400       substj = substj.split('\n')
401       document.body[j : j+4] = substj
402       i += len(substj)
403
404
405 def revert_vphantom(document):
406     " Reverts vphantom to ERT "
407     i = 0
408     j = 0
409     while True:
410       i = find_token(document.body, "\\begin_inset Phantom VPhantom", i)
411       if i == -1:
412           return
413       substi = document.body[i].replace('\\begin_inset Phantom VPhantom', \
414                 '\\begin_inset ERT\nstatus collapsed\n\n' \
415                 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
416                 'vphantom{\n\\end_layout\n\n\\end_inset\n')
417       substi = substi.split('\n')
418       document.body[i : i+4] = substi
419       i += len(substi)
420       j = find_token(document.body, "\\end_layout", i)
421       if j == -1:
422           document.warning("Malformed LyX document: Could not find end of VPhantom inset.")
423           return
424       substj = document.body[j].replace('\\end_layout', \
425                 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
426                 '\\begin_layout Plain Layout\n\n' \
427                 '}\n\\end_layout\n\n\\end_inset\n')
428       substj = substj.split('\n')
429       document.body[j : j+4] = substj
430       i += len(substj)
431
432
433 def revert_xetex(document):
434     " Reverts documents that use XeTeX "
435     i = find_token(document.header, '\\use_xetex', 0)
436     if i == -1:
437         document.warning("Malformed LyX document: Missing \\use_xetex.")
438         return
439     if get_value(document.header, "\\use_xetex", i) == 'false':
440         del document.header[i]
441         return
442     del document.header[i]
443     # 1.) set doc encoding to utf8-plain
444     i = find_token(document.header, "\\inputencoding", 0)
445     if i == -1:
446         document.warning("Malformed LyX document: Missing \\inputencoding.")
447     document.header[i] = "\\inputencoding utf8-plain"
448     # 2.) check font settings
449     l = find_token(document.header, "\\font_roman", 0)
450     if l == -1:
451         document.warning("Malformed LyX document: Missing \\font_roman.")
452     line = document.header[l]
453     l = re.compile(r'\\font_roman (.*)$')
454     m = l.match(line)
455     roman = m.group(1)
456     l = find_token(document.header, "\\font_sans", 0)
457     if l == -1:
458         document.warning("Malformed LyX document: Missing \\font_sans.")
459     line = document.header[l]
460     l = re.compile(r'\\font_sans (.*)$')
461     m = l.match(line)
462     sans = m.group(1)
463     l = find_token(document.header, "\\font_typewriter", 0)
464     if l == -1:
465         document.warning("Malformed LyX document: Missing \\font_typewriter.")
466     line = document.header[l]
467     l = re.compile(r'\\font_typewriter (.*)$')
468     m = l.match(line)
469     typewriter = m.group(1)
470     osf = get_value(document.header, '\\font_osf', 0) == "true"
471     sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
472     tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
473     # 3.) set preamble stuff
474     pretext = '%% This document must be processed with xelatex!\n'
475     pretext += '\\usepackage{fontspec}\n'
476     if roman != "default":
477         pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
478     if sans != "default":
479         pretext += '\\setsansfont['
480         if sf_scale != 100:
481             pretext += 'Scale=' + str(sf_scale / 100) + ','
482         pretext += 'Mapping=tex-text]{' + sans + '}\n'
483     if typewriter != "default":
484         pretext += '\\setmonofont'
485         if tt_scale != 100:
486             pretext += '[Scale=' + str(tt_scale / 100) + ']'
487         pretext += '{' + typewriter + '}\n'
488     if osf:
489         pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
490     pretext += '\usepackage{xunicode}\n'
491     pretext += '\usepackage{xltxtra}\n'
492     insert_to_preamble(0, document, pretext)
493     # 4.) reset font settings
494     i = find_token(document.header, "\\font_roman", 0)
495     if i == -1:
496         document.warning("Malformed LyX document: Missing \\font_roman.")
497     document.header[i] = "\\font_roman default"
498     i = find_token(document.header, "\\font_sans", 0)
499     if i == -1:
500         document.warning("Malformed LyX document: Missing \\font_sans.")
501     document.header[i] = "\\font_sans default"
502     i = find_token(document.header, "\\font_typewriter", 0)
503     if i == -1:
504         document.warning("Malformed LyX document: Missing \\font_typewriter.")
505     document.header[i] = "\\font_typewriter default"
506     i = find_token(document.header, "\\font_osf", 0)
507     if i == -1:
508         document.warning("Malformed LyX document: Missing \\font_osf.")
509     document.header[i] = "\\font_osf false"
510     i = find_token(document.header, "\\font_sc", 0)
511     if i == -1:
512         document.warning("Malformed LyX document: Missing \\font_sc.")
513     document.header[i] = "\\font_sc false"
514     i = find_token(document.header, "\\font_sf_scale", 0)
515     if i == -1:
516         document.warning("Malformed LyX document: Missing \\font_sf_scale.")
517     document.header[i] = "\\font_sf_scale 100"
518     i = find_token(document.header, "\\font_tt_scale", 0)
519     if i == -1:
520         document.warning("Malformed LyX document: Missing \\font_tt_scale.")
521     document.header[i] = "\\font_tt_scale 100"
522
523
524 def revert_outputformat(document):
525     " Remove default output format param "
526     i = find_token(document.header, '\\default_output_format', 0)
527     if i == -1:
528         document.warning("Malformed LyX document: Missing \\default_output_format.")
529         return
530     del document.header[i]
531
532
533 def revert_backgroundcolor(document):
534     " Reverts background color to preamble code "
535     i = 0
536     colorcode = ""
537     while True:
538       i = find_token(document.header, "\\backgroundcolor", i)
539       if i == -1:
540           return
541       colorcode = get_value(document.header, '\\backgroundcolor', 0)
542       del document.header[i]
543       # don't clutter the preamble if backgroundcolor is not set
544       if colorcode == "#ffffff":
545           continue
546       # the color code is in the form #rrggbb where every character denotes a hex number
547       # convert the string to an int
548       red = string.atoi(colorcode[1:3],16)
549       # we want the output "0.5" for the value "127" therefore add here
550       if red != 0:
551           red = red + 1
552       redout = float(red) / 256
553       green = string.atoi(colorcode[3:5],16)
554       if green != 0:
555           green = green + 1
556       greenout = float(green) / 256
557       blue = string.atoi(colorcode[5:7],16)
558       if blue != 0:
559           blue = blue + 1
560       blueout = float(blue) / 256
561       # write the preamble
562       insert_to_preamble(0, document,
563                            '% Commands inserted by lyx2lyx to set the background color\n'
564                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
565                            + '\\definecolor{page_backgroundcolor}{rgb}{'
566                            + str(redout) + ', ' + str(greenout)
567                            + ', ' + str(blueout) + '}\n'
568                            + '\\pagecolor{page_backgroundcolor}\n')
569
570
571 def revert_splitindex(document):
572     " Reverts splitindex-aware documents "
573     i = find_token(document.header, '\\use_indices', 0)
574     if i == -1:
575         document.warning("Malformed LyX document: Missing \\use_indices.")
576         return
577     indices = get_value(document.header, "\\use_indices", i)
578     preamble = ""
579     if indices == "true":
580          preamble += "\\usepackage{splitidx}\n"
581     del document.header[i]
582     i = 0
583     while True:
584         i = find_token(document.header, "\\index", i)
585         if i == -1:
586             break
587         k = find_token(document.header, "\\end_index", i)
588         if k == -1:
589             document.warning("Malformed LyX document: Missing \\end_index.")
590             return
591         line = document.header[i]
592         l = re.compile(r'\\index (.*)$')
593         m = l.match(line)
594         iname = m.group(1)
595         ishortcut = get_value(document.header, '\\shortcut', i, k)
596         if ishortcut != "" and indices == "true":
597             preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
598         del document.header[i:k+1]
599         i = 0
600     if preamble != "":
601         insert_to_preamble(0, document, preamble)
602     i = 0
603     while True:
604         i = find_token(document.body, "\\begin_inset Index", i)
605         if i == -1:
606             break
607         line = document.body[i]
608         l = re.compile(r'\\begin_inset Index (.*)$')
609         m = l.match(line)
610         itype = m.group(1)
611         if itype == "idx" or indices == "false":
612             document.body[i] = "\\begin_inset Index"
613         else:
614             k = find_end_of_inset(document.body, i)
615             if k == -1:
616                  return
617             content = lyx2latex(document, document.body[i:k])
618             # escape quotes
619             content = content.replace('"', r'\"')
620             subst = [old_put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")]
621             document.body[i:k+1] = subst
622         i = i + 1
623     i = 0
624     while True:
625         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
626         if i == -1:
627             return
628         k = find_end_of_inset(document.body, i)
629         ptype = get_value(document.body, 'type', i, k).strip('"')
630         if ptype == "idx":
631             j = find_token(document.body, "type", i, k)
632             del document.body[j]
633         elif indices == "false":
634             del document.body[i:k+1]
635         else:
636             subst = [old_put_cmd_in_ert("\\printindex[" + ptype + "]{}")]
637             document.body[i:k+1] = subst
638         i = i + 1
639
640
641 def convert_splitindex(document):
642     " Converts index and printindex insets to splitindex-aware format "
643     i = 0
644     while True:
645         i = find_token(document.body, "\\begin_inset Index", i)
646         if i == -1:
647             break
648         document.body[i] = document.body[i].replace("\\begin_inset Index",
649             "\\begin_inset Index idx")
650         i = i + 1
651     i = 0
652     while True:
653         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
654         if i == -1:
655             return
656         if document.body[i + 1].find('LatexCommand printindex') == -1:
657             document.warning("Malformed LyX document: Incomplete printindex inset.")
658             return
659         subst = ["LatexCommand printindex", 
660             "type \"idx\""]
661         document.body[i + 1:i + 2] = subst
662         i = i + 1
663
664
665 def revert_subindex(document):
666     " Reverts \\printsubindex CommandInset types "
667     i = find_token(document.header, '\\use_indices', 0)
668     if i == -1:
669         document.warning("Malformed LyX document: Missing \\use_indices.")
670         return
671     indices = get_value(document.header, "\\use_indices", i)
672     i = 0
673     while True:
674         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
675         if i == -1:
676             return
677         k = find_end_of_inset(document.body, i)
678         ctype = get_value(document.body, 'LatexCommand', i, k)
679         if ctype != "printsubindex":
680             i = i + 1
681             continue
682         ptype = get_value(document.body, 'type', i, k).strip('"')
683         if indices == "false":
684             del document.body[i:k+1]
685         else:
686             subst = [old_put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")]
687             document.body[i:k+1] = subst
688         i = i + 1
689
690
691 def revert_printindexall(document):
692     " Reverts \\print[sub]index* CommandInset types "
693     i = find_token(document.header, '\\use_indices', 0)
694     if i == -1:
695         document.warning("Malformed LyX document: Missing \\use_indices.")
696         return
697     indices = get_value(document.header, "\\use_indices", i)
698     i = 0
699     while True:
700         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
701         if i == -1:
702             return
703         k = find_end_of_inset(document.body, i)
704         ctype = get_value(document.body, 'LatexCommand', i, k)
705         if ctype != "printindex*" and ctype != "printsubindex*":
706             i = i + 1
707             continue
708         if indices == "false":
709             del document.body[i:k+1]
710         else:
711             subst = [old_put_cmd_in_ert("\\" + ctype + "{}")]
712             document.body[i:k+1] = subst
713         i = i + 1
714
715
716 def revert_strikeout(document):
717     " Reverts \\strikeout character style "
718     while True:
719         i = find_token(document.body, '\\strikeout', 0)
720         if i == -1:
721             return
722         del document.body[i]
723
724
725 def revert_uulinewave(document):
726     " Reverts \\uuline, and \\uwave character styles "
727     while True:
728         i = find_token(document.body, '\\uuline', 0)
729         if i == -1:
730             break
731         del document.body[i]
732     while True:
733         i = find_token(document.body, '\\uwave', 0)
734         if i == -1:
735             return
736         del document.body[i]
737
738
739 def revert_ulinelatex(document):
740     " Reverts \\uline character style "
741     i = find_token(document.body, '\\bar under', 0)
742     if i == -1:
743         return
744     insert_to_preamble(0, document,
745             '% Commands inserted by lyx2lyx for proper underlining\n'
746             + '\\PassOptionsToPackage{normalem}{ulem}\n'
747             + '\\usepackage{ulem}\n'
748             + '\\let\\cite@rig\\cite\n'
749             + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
750             + '  \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
751             + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
752
753
754 def revert_custom_processors(document):
755     " Remove bibtex_command and index_command params "
756     i = find_token(document.header, '\\bibtex_command', 0)
757     if i == -1:
758         document.warning("Malformed LyX document: Missing \\bibtex_command.")
759         return
760     del document.header[i]
761     i = find_token(document.header, '\\index_command', 0)
762     if i == -1:
763         document.warning("Malformed LyX document: Missing \\index_command.")
764         return
765     del document.header[i]
766
767
768 def convert_nomencl_width(document):
769     " Add set_width param to nomencl_print "
770     i = 0
771     while True:
772       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
773       if i == -1:
774         break
775       document.body.insert(i + 2, "set_width \"none\"")
776       i = i + 1
777
778
779 def revert_nomencl_width(document):
780     " Remove set_width param from nomencl_print "
781     i = 0
782     while True:
783       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
784       if i == -1:
785         break
786       j = find_end_of_inset(document.body, i)
787       l = find_token(document.body, "set_width", i, j)
788       if l == -1:
789             document.warning("Can't find set_width option for nomencl_print!")
790             i = j
791             continue
792       del document.body[l]
793       i = i + 1
794
795
796 def revert_nomencl_cwidth(document):
797     " Remove width param from nomencl_print "
798     i = 0
799     while True:
800       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
801       if i == -1:
802         break
803       j = find_end_of_inset(document.body, i)
804       l = find_token(document.body, "width", i, j)
805       if l == -1:
806             #Can't find width option for nomencl_print
807             i = j
808             continue
809       width = get_value(document.body, "width", i, j).strip('"')
810       del document.body[l]
811       add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
812       add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
813       i = i + 1
814
815
816 def revert_applemac(document):
817     " Revert applemac encoding to auto "
818     i = 0
819     if document.encoding == "applemac":
820         document.encoding = "auto"
821         i = find_token(document.header, "\\encoding", 0)
822         if i != -1:
823             document.header[i] = "\\encoding auto"
824
825
826 def revert_longtable_align(document):
827     " Remove longtable alignment setting "
828     i = 0
829     j = 0
830     while True:
831       i = find_token(document.body, "\\begin_inset Tabular", i)
832       if i == -1:
833           break
834       # the alignment is 2 lines below \\begin_inset Tabular
835       j = document.body[i+2].find("longtabularalignment")
836       if j == -1:
837           break
838       document.body[i+2] = document.body[i+2][:j-1]
839       document.body[i+2] = document.body[i+2] + '>'
840       i = i + 1
841
842
843 def revert_branch_filename(document):
844     " Remove \\filename_suffix parameter from branches "
845     i = 0
846     while True:
847         i = find_token(document.header, "\\filename_suffix", i)
848         if i == -1:
849             return
850         del document.header[i]
851
852
853 def revert_paragraph_indentation(document):
854     " Revert custom paragraph indentation to preamble code "
855     i = 0
856     while True:
857       i = find_token(document.header, "\\paragraph_indentation", i)
858       if i == -1:
859           break
860       # only remove the preamble line if default
861       # otherwise also write the value to the preamble
862       length = get_value(document.header, "\\paragraph_indentation", i)
863       if length == "default":
864           del document.header[i]
865           break
866       else:
867           # handle percent lengths
868           # latex_length returns "bool,length"
869           length = latex_length(length).split(",")[1]
870           add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
871           add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
872           del document.header[i]
873       i = i + 1
874
875
876 def revert_percent_skip_lengths(document):
877     " Revert relative lengths for paragraph skip separation to preamble code "
878     i = 0
879     while True:
880       i = find_token(document.header, "\\defskip", i)
881       if i == -1:
882           break
883       length = get_value(document.header, "\\defskip", i)
884       # only revert when a custom length was set and when
885       # it used a percent length
886       if length not in ('smallskip', 'medskip', 'bigskip'):
887           # handle percent lengths
888           length = latex_length(length)
889           # latex_length returns "bool,length"
890           percent = length.split(",")[0]
891           length = length.split(",")[1]
892           if percent == "True":
893               add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
894               add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
895               # set defskip to medskip as default
896               document.header[i] = "\\defskip medskip"
897       i = i + 1
898
899
900 def revert_percent_vspace_lengths(document):
901     " Revert relative VSpace lengths to ERT "
902     i = 0
903     while True:
904       i = find_token(document.body, "\\begin_inset VSpace", i)
905       if i == -1:
906           break
907       # only revert if a custom length was set and if
908       # it used a percent length
909       line = document.body[i]
910       r = re.compile(r'\\begin_inset VSpace (.*)$')
911       m = r.match(line)
912       length = m.group(1)
913       if length not in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
914           # check if the space has a star (protected space)
915           protected = (document.body[i].rfind("*") != -1)
916           if protected:
917               length = length.rstrip('*')
918           # handle percent lengths
919           length = latex_length(length)
920           # latex_length returns "bool,length"
921           percent = length.split(",")[0]
922           length = length.split(",")[1]
923           # revert the VSpace inset to ERT
924           if percent == "True":
925               if protected:
926                   subst = [old_put_cmd_in_ert("\\vspace*{" + length + "}")]
927               else:
928                   subst = [old_put_cmd_in_ert("\\vspace{" + length + "}")]
929               document.body[i:i+2] = subst
930       i = i + 1
931
932
933 def revert_percent_hspace_lengths(document):
934     " Revert relative HSpace lengths to ERT "
935     i = 0
936     while True:
937       i = find_token(document.body, "\\begin_inset space \\hspace", i)
938       if i == -1:
939           break
940       protected = (document.body[i].find("\\hspace*{}") != -1)
941       # only revert if a custom length was set and if
942       # it used a percent length
943       length = get_value(document.body, '\\length', i+1)
944       if length == '':
945           document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
946           return
947       # handle percent lengths
948       length = latex_length(length)
949       # latex_length returns "bool,length"
950       percent = length.split(",")[0]
951       length = length.split(",")[1]
952       # revert the HSpace inset to ERT
953       if percent == "True":
954           if protected:
955               subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
956           else:
957               subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
958           document.body[i:i+3] = subst
959       i = i + 2
960
961
962 def revert_hspace_glue_lengths(document):
963     " Revert HSpace glue lengths to ERT "
964     i = 0
965     while True:
966       i = find_token(document.body, "\\begin_inset space \\hspace", i)
967       if i == -1:
968           break
969       protected = (document.body[i].find("\\hspace*{}") != -1)
970       length = get_value(document.body, '\\length', i+1)
971       if length == '':
972           document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
973           return
974       # only revert if the length contains a plus or minus at pos != 0
975       glue  = re.compile(r'.+[\+-]')
976       if glue.search(length):
977           # handle percent lengths
978           # latex_length returns "bool,length"
979           length = latex_length(length).split(",")[1]
980           # revert the HSpace inset to ERT
981           if protected:
982               subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
983           else:
984               subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
985           document.body[i:i+3] = subst
986       i = i + 2
987
988 def convert_author_id(document):
989     " Add the author_id to the \\author definition and make sure 0 is not used"
990     i = 0
991     j = 1
992     while True:
993         i = find_token(document.header, "\\author", i)
994         if i == -1:
995             break
996         
997         r = re.compile(r'(\\author) (\".*\")\s?(.*)$')
998         m = r.match(document.header[i])
999         if m != None:
1000             name = m.group(2)
1001             
1002             email = ''
1003             if m.lastindex == 3:
1004                 email = m.group(3)
1005             document.header[i] = "\\author %i %s %s" % (j, name, email)
1006         j = j + 1
1007         i = i + 1
1008         
1009     k = 0
1010     while True:
1011         k = find_token(document.body, "\\change_", k)
1012         if k == -1:
1013             break
1014
1015         change = document.body[k].split(' ');
1016         if len(change) == 3:
1017             type = change[0]
1018             author_id = int(change[1])
1019             time = change[2]
1020             document.body[k] = "%s %i %s" % (type, author_id + 1, time)
1021         k = k + 1
1022
1023 def revert_author_id(document):
1024     " Remove the author_id from the \\author definition "
1025     i = 0
1026     j = 0
1027     idmap = dict()
1028     while True:
1029         i = find_token(document.header, "\\author", i)
1030         if i == -1:
1031             break
1032         
1033         r = re.compile(r'(\\author) (\d+) (\".*\")\s?(.*)$')
1034         m = r.match(document.header[i])
1035         if m != None:
1036             author_id = int(m.group(2))
1037             idmap[author_id] = j
1038             name = m.group(3)
1039             
1040             email = ''
1041             if m.lastindex == 4:
1042                 email = m.group(4)
1043             document.header[i] = "\\author %s %s" % (name, email)
1044         i = i + 1
1045         j = j + 1
1046
1047     k = 0
1048     while True:
1049         k = find_token(document.body, "\\change_", k)
1050         if k == -1:
1051             break
1052
1053         change = document.body[k].split(' ');
1054         if len(change) == 3:
1055             type = change[0]
1056             author_id = int(change[1])
1057             time = change[2]
1058             document.body[k] = "%s %i %s" % (type, idmap[author_id], time)
1059         k = k + 1
1060
1061
1062 def revert_suppress_date(document):
1063     " Revert suppressing of default document date to preamble code "
1064     i = 0
1065     while True:
1066       i = find_token(document.header, "\\suppress_date", i)
1067       if i == -1:
1068           break
1069       # remove the preamble line and write to the preamble
1070       # when suppress_date was true
1071       date = get_value(document.header, "\\suppress_date", i)
1072       if date == "true":
1073           add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1074           add_to_preamble(document, ["\\date{}"])
1075       del document.header[i]
1076       i = i + 1
1077
1078
1079 def revert_mhchem(document):
1080     "Revert mhchem loading to preamble code"
1081     i = 0
1082     j = 0
1083     k = 0
1084     i = find_token(document.header, "\\use_mhchem 1", 0)
1085     if i != -1:
1086         mhchem = "auto"
1087     else:
1088         i = find_token(document.header, "\\use_mhchem 2", 0)
1089         if i != -1:
1090             mhchem = "on"
1091     if mhchem == "auto":
1092         j = find_token(document.body, "\\cf{", 0)
1093         if j != -1:
1094             mhchem = "on"
1095         else:
1096             j = find_token(document.body, "\\ce{", 0)
1097             if j != -1:
1098                 mhchem = "on"
1099     if mhchem == "on":
1100         add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1101         add_to_preamble(document, ["\\PassOptionsToPackage{version=3}{mhchem}"])
1102         add_to_preamble(document, ["\\usepackage{mhchem}"])
1103     k = find_token(document.header, "\\use_mhchem", 0)
1104     if k == -1:
1105         document.warning("Malformed LyX document: Could not find mhchem setting.")
1106         return
1107     del document.header[k]
1108
1109
1110 def revert_fontenc(document):
1111     " Remove fontencoding param "
1112     i = find_token(document.header, '\\fontencoding', 0)
1113     if i == -1:
1114         document.warning("Malformed LyX document: Missing \\fontencoding.")
1115         return
1116     del document.header[i]
1117
1118
1119 def merge_gbrief(document):
1120     " Merge g-brief-en and g-brief-de to one class "
1121
1122     if document.textclass != "g-brief-de":
1123         if document.textclass == "g-brief-en":
1124             document.textclass = "g-brief"
1125             document.set_textclass()
1126         return
1127
1128     obsoletedby = { "Brieftext":       "Letter",
1129                     "Unterschrift":    "Signature",
1130                     "Strasse":         "Street",
1131                     "Zusatz":          "Addition",
1132                     "Ort":             "Town",
1133                     "Land":            "State",
1134                     "RetourAdresse":   "ReturnAddress",
1135                     "MeinZeichen":     "MyRef",
1136                     "IhrZeichen":      "YourRef",
1137                     "IhrSchreiben":    "YourMail",
1138                     "Telefon":         "Phone",
1139                     "BLZ":             "BankCode",
1140                     "Konto":           "BankAccount",
1141                     "Postvermerk":     "PostalComment",
1142                     "Adresse":         "Address",
1143                     "Datum":           "Date",
1144                     "Betreff":         "Reference",
1145                     "Anrede":          "Opening",
1146                     "Anlagen":         "Encl.",
1147                     "Verteiler":       "cc",
1148                     "Gruss":           "Closing"}
1149     i = 0
1150     while 1:
1151         i = find_token(document.body, "\\begin_layout", i)
1152         if i == -1:
1153             break
1154
1155         layout = document.body[i][14:]
1156         if layout in obsoletedby:
1157             document.body[i] = "\\begin_layout " + obsoletedby[layout]
1158
1159         i += 1
1160         
1161     document.textclass = "g-brief"
1162     document.set_textclass()
1163
1164
1165 def revert_gbrief(document):
1166     " Revert g-brief to g-brief-en "
1167     if document.textclass == "g-brief":
1168         document.textclass = "g-brief-en"
1169         document.set_textclass()
1170
1171
1172 def revert_html_options(document):
1173     " Remove html options "
1174     i = find_token(document.header, '\\html_use_mathml', 0)
1175     if i != -1:
1176         del document.header[i]
1177     i = find_token(document.header, '\\html_be_strict', 0)
1178     if i != -1:
1179         del document.header[i]
1180
1181
1182 def revert_includeonly(document):
1183     i = 0
1184     while True:
1185         i = find_token(document.header, "\\begin_includeonly", i)
1186         if i == -1:
1187             return
1188         j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
1189         if j == -1:
1190             # this should not happen
1191             break
1192         document.header[i : j + 1] = []
1193
1194
1195 def revert_includeall(document):
1196     " Remove maintain_unincluded_children param "
1197     i = find_token(document.header, '\\maintain_unincluded_children', 0)
1198     if i != -1:
1199         del document.header[i]
1200
1201
1202 def revert_multirow(document):
1203     " Revert multirow cells in tables "
1204     i = 0
1205     multirow = False
1206     while True:
1207       # cell type 3 is multirow begin cell
1208       i = find_token(document.body, '<cell multirow="3"', i)
1209       if i == -1:
1210           break
1211       # a multirow cell was found
1212       multirow = True
1213       # remove the multirow tag, set the valignment to top
1214       # and remove the bottom line
1215       document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
1216       document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1217       document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
1218       # write ERT to create the multirow cell
1219       # use 2 rows and 2cm as default with because the multirow span
1220       # and the column width is only hardly accessible
1221       subst = [old_put_cmd_in_ert("\\multirow{2}{2cm}{")]
1222       document.body[i + 4:i + 4] = subst
1223       i = find_token(document.body, "</cell>", i)
1224       if i == -1:
1225            document.warning("Malformed LyX document: Could not find end of tabular cell.")
1226            break
1227       subst = [old_put_cmd_in_ert("}")]
1228       document.body[i - 3:i - 3] = subst
1229       # cell type 4 is multirow part cell
1230       i = find_token(document.body, '<cell multirow="4"', i)
1231       if i == -1:
1232           break
1233       # remove the multirow tag, set the valignment to top
1234       # and remove the top line
1235       document.body[i] = document.body[i].replace(' multirow="4" ', ' ')
1236       document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1237       document.body[i] = document.body[i].replace(' topline="true" ', ' ')
1238       i = i + 1
1239     if multirow == True:
1240         add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1241         add_to_preamble(document, ["\\usepackage{multirow}"])
1242
1243
1244 def convert_math_output(document):
1245     " Convert \html_use_mathml to \html_math_output "
1246     i = find_token(document.header, "\\html_use_mathml", 0)
1247     if i == -1:
1248         return
1249     rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1250     m = rgx.match(document.header[i])
1251     if rgx:
1252         newval = "0" # MathML
1253         val = m.group(1)
1254         if val != "true":
1255             newval = "2" # Images
1256         document.header[i] = "\\html_math_output " + newval
1257
1258
1259 def revert_math_output(document):
1260     " Revert \html_math_output to \html_use_mathml "
1261     i = find_token(document.header, "\\html_math_output", 0)
1262     if i == -1:
1263         return
1264     rgx = re.compile(r'\\html_math_output\s+(\d)')
1265     m = rgx.match(document.header[i])
1266     newval = "true"
1267     if rgx:
1268         val = m.group(1)
1269         if val == "1" or val == "2":
1270             newval = "false"
1271     else:
1272         document.warning("Unable to match " + document.header[i])
1273     document.header[i] = "\\html_use_mathml " + newval
1274                 
1275
1276
1277 def revert_inset_preview(document):
1278     " Dissolves the preview inset "
1279     i = 0
1280     j = 0
1281     k = 0
1282     while True:
1283       i = find_token(document.body, "\\begin_inset Preview", i)
1284       if i == -1:
1285           return
1286       j = find_end_of_inset(document.body, i)
1287       if j == -1:
1288           document.warning("Malformed LyX document: Could not find end of Preview inset.")
1289           return
1290       #If the layout is Standard we need to remove it, otherwise there
1291       #will be paragraph breaks that shouldn't be there.
1292       k = find_token(document.body, "\\begin_layout Standard", i)
1293       if k == i+2:
1294           del document.body[i : i+3]
1295           del document.body[j-5 : j-2]
1296           i -= 6
1297       else:
1298           del document.body[i]
1299           del document.body[j-1]
1300           i -= 2
1301                 
1302
1303 def revert_equalspacing_xymatrix(document):
1304     " Revert a Formula with xymatrix@! to an ERT inset "
1305     i = 0
1306     j = 0
1307     has_preamble = False
1308     has_equal_spacing = False
1309     while True:
1310       found = -1
1311       i = find_token(document.body, "\\begin_inset Formula", i)
1312       if i == -1:
1313           break
1314       j = find_end_of_inset(document.body, i)
1315       if j == -1:
1316           document.warning("Malformed LyX document: Could not find end of Formula inset.")
1317           break
1318           
1319       for curline in range(i,j):
1320           found = document.body[curline].find("\\xymatrix@!")
1321           if found != -1:
1322               break
1323  
1324       if found != -1:
1325           has_equal_spacing = True
1326           content = [document.body[i][21:]]
1327           content += document.body[i+1:j]
1328           subst = put_cmd_in_ert(content)
1329           document.body[i:j+1] = subst
1330           i += len(subst)
1331       else:
1332           for curline in range(i,j):
1333               l = document.body[curline].find("\\xymatrix")
1334               if l != -1:
1335                   has_preamble = True;
1336                   break;
1337           i = j + 1
1338     if has_equal_spacing and not has_preamble:
1339         add_to_preamble(document, ['\\usepackage[all]{xy}'])
1340
1341
1342 def revert_notefontcolor(document):
1343     " Reverts greyed-out note font color to preamble code "
1344     i = 0
1345     colorcode = ""
1346     while True:
1347       i = find_token(document.header, "\\notefontcolor", i)
1348       if i == -1:
1349           return
1350       colorcode = get_value(document.header, '\\notefontcolor', 0)
1351       del document.header[i]
1352       # the color code is in the form #rrggbb where every character denotes a hex number
1353       # convert the string to an int
1354       red = string.atoi(colorcode[1:3],16)
1355       # we want the output "0.5" for the value "127" therefore increment here
1356       if red != 0:
1357           red = red + 1
1358       redout = float(red) / 256
1359       green = string.atoi(colorcode[3:5],16)
1360       if green != 0:
1361           green = green + 1
1362       greenout = float(green) / 256
1363       blue = string.atoi(colorcode[5:7],16)
1364       if blue != 0:
1365           blue = blue + 1
1366       blueout = float(blue) / 256
1367       # write the preamble
1368       insert_to_preamble(0, document,
1369                            '% Commands inserted by lyx2lyx to set the font color\n'
1370                            '% for greyed-out notes\n'
1371                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1372                            + '\\definecolor{note_fontcolor}{rgb}{'
1373                            + str(redout) + ', ' + str(greenout)
1374                            + ', ' + str(blueout) + '}\n'
1375                            + '\\renewenvironment{lyxgreyedout}\n'
1376                            + ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}\n')
1377
1378
1379 def revert_turkmen(document):
1380     "Set language Turkmen to English" 
1381     i = 0 
1382     if document.language == "turkmen": 
1383         document.language = "english" 
1384         i = find_token(document.header, "\\language", 0) 
1385         if i != -1: 
1386             document.header[i] = "\\language english" 
1387     j = 0 
1388     while True: 
1389         j = find_token(document.body, "\\lang turkmen", j) 
1390         if j == -1: 
1391             return 
1392         document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english") 
1393         j = j + 1 
1394
1395
1396 def revert_fontcolor(document):
1397     " Reverts font color to preamble code "
1398     i = 0
1399     colorcode = ""
1400     while True:
1401       i = find_token(document.header, "\\fontcolor", i)
1402       if i == -1:
1403           return
1404       colorcode = get_value(document.header, '\\fontcolor', 0)
1405       del document.header[i]
1406       # don't clutter the preamble if backgroundcolor is not set
1407       if colorcode == "#000000":
1408           continue
1409       # the color code is in the form #rrggbb where every character denotes a hex number
1410       # convert the string to an int
1411       red = string.atoi(colorcode[1:3],16)
1412       # we want the output "0.5" for the value "127" therefore add here
1413       if red != 0:
1414           red = red + 1
1415       redout = float(red) / 256
1416       green = string.atoi(colorcode[3:5],16)
1417       if green != 0:
1418           green = green + 1
1419       greenout = float(green) / 256
1420       blue = string.atoi(colorcode[5:7],16)
1421       if blue != 0:
1422           blue = blue + 1
1423       blueout = float(blue) / 256
1424       # write the preamble
1425       insert_to_preamble(0, document,
1426                            '% Commands inserted by lyx2lyx to set the font color\n'
1427                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1428                            + '\\definecolor{document_fontcolor}{rgb}{'
1429                            + str(redout) + ', ' + str(greenout)
1430                            + ', ' + str(blueout) + '}\n'
1431                            + '\\color{document_fontcolor}\n')
1432
1433
1434 def revert_shadedboxcolor(document):
1435     " Reverts shaded box color to preamble code "
1436     i = 0
1437     colorcode = ""
1438     while True:
1439       i = find_token(document.header, "\\boxbgcolor", i)
1440       if i == -1:
1441           return
1442       colorcode = get_value(document.header, '\\boxbgcolor', 0)
1443       del document.header[i]
1444       # the color code is in the form #rrggbb where every character denotes a hex number
1445       # convert the string to an int
1446       red = string.atoi(colorcode[1:3],16)
1447       # we want the output "0.5" for the value "127" therefore increment here
1448       if red != 0:
1449           red = red + 1
1450       redout = float(red) / 256
1451       green = string.atoi(colorcode[3:5],16)
1452       if green != 0:
1453           green = green + 1
1454       greenout = float(green) / 256
1455       blue = string.atoi(colorcode[5:7],16)
1456       if blue != 0:
1457           blue = blue + 1
1458       blueout = float(blue) / 256
1459       # write the preamble
1460       insert_to_preamble(0, document,
1461                            '% Commands inserted by lyx2lyx to set the color\n'
1462                            '% of boxes with shaded background\n'
1463                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1464                            + '\\definecolor{shadecolor}{rgb}{'
1465                            + str(redout) + ', ' + str(greenout)
1466                            + ', ' + str(blueout) + '}\n')
1467
1468
1469 def revert_lyx_version(document):
1470     " Reverts LyX Version information from Inset Info "
1471     version = "LyX version"
1472     try:
1473         import lyx2lyx_version
1474         version = lyx2lyx_version.version
1475     except:
1476             pass
1477         
1478     i = 0
1479     while 1:
1480         i = find_token(document.body, '\\begin_inset Info', i)
1481         if i == -1:
1482             return
1483         j = find_end_of_inset(document.body, i + 1)
1484         if j == -1:
1485             # should not happen
1486             document.warning("Malformed LyX document: Could not find end of Info inset.")
1487         # We expect:
1488         # \begin_inset Info
1489         # type  "lyxinfo"
1490         # arg   "version"
1491         # \end_inset
1492         # but we shall try to be forgiving.
1493         arg = typ = ""
1494         for k in range(i, j):
1495             if document.body[k].startswith("arg"):
1496                 arg = document.body[k][3:].strip().strip('"')
1497             if document.body[k].startswith("type"):
1498                 typ = document.body[k][4:].strip().strip('"')
1499         if arg != "version" or typ != "lyxinfo":
1500             i = j+1
1501             continue
1502
1503         # We do not actually know the version of LyX used to produce the document.
1504         # But we can use our version, since we are reverting.
1505         s = [version]
1506         # Now we want to check if the line after "\end_inset" is empty. It normally
1507         # is, so we want to remove it, too.
1508         lastline = j+1
1509         if document.body[j+1].strip() == "":
1510             lastline = j+2
1511         document.body[i: lastline] = s
1512         i = i+1
1513
1514
1515 ##
1516 # Conversion hub
1517 #
1518
1519 supported_versions = ["2.0.0","2.0"]
1520 convert = [[346, []],
1521            [347, []],
1522            [348, []],
1523            [349, []],
1524            [350, []],
1525            [351, []],
1526            [352, [convert_splitindex]],
1527            [353, []],
1528            [354, []],
1529            [355, []],
1530            [356, []],
1531            [357, []],
1532            [358, []],
1533            [359, [convert_nomencl_width]],
1534            [360, []],
1535            [361, []],
1536            [362, []],
1537            [363, []],
1538            [364, []],
1539            [365, []],
1540            [366, []],
1541            [367, []],
1542            [368, []],
1543            [369, [convert_author_id]],
1544            [370, []],
1545            [371, []],
1546            [372, []],
1547            [373, [merge_gbrief]],
1548            [374, []],
1549            [375, []],
1550            [376, []],
1551            [377, []],
1552            [378, []],
1553            [379, [convert_math_output]],
1554            [380, []],
1555            [381, []],
1556            [382, []],
1557            [383, []],
1558            [384, []],
1559            [385, []],
1560            [386, []]
1561           ]
1562
1563 revert =  [[385, [revert_lyx_version]],
1564            [384, [revert_shadedboxcolor]],
1565            [383, [revert_fontcolor]],
1566            [382, [revert_turkmen]],
1567            [381, [revert_notefontcolor]],
1568            [380, [revert_equalspacing_xymatrix]],
1569            [379, [revert_inset_preview]],
1570            [378, [revert_math_output]],
1571            [377, []],
1572            [376, [revert_multirow]],
1573            [375, [revert_includeall]],
1574            [374, [revert_includeonly]],
1575            [373, [revert_html_options]],
1576            [372, [revert_gbrief]],
1577            [371, [revert_fontenc]],
1578            [370, [revert_mhchem]],
1579            [369, [revert_suppress_date]],
1580            [368, [revert_author_id]],
1581            [367, [revert_hspace_glue_lengths]],
1582            [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
1583            [365, [revert_percent_skip_lengths]],
1584            [364, [revert_paragraph_indentation]],
1585            [363, [revert_branch_filename]],
1586            [362, [revert_longtable_align]],
1587            [361, [revert_applemac]],
1588            [360, []],
1589            [359, [revert_nomencl_cwidth]],
1590            [358, [revert_nomencl_width]],
1591            [357, [revert_custom_processors]],
1592            [356, [revert_ulinelatex]],
1593            [355, [revert_uulinewave]],
1594            [354, [revert_strikeout]],
1595            [353, [revert_printindexall]],
1596            [352, [revert_subindex]],
1597            [351, [revert_splitindex]],
1598            [350, [revert_backgroundcolor]],
1599            [349, [revert_outputformat]],
1600            [348, [revert_xetex]],
1601            [347, [revert_phantom, revert_hphantom, revert_vphantom]],
1602            [346, [revert_tabularvalign]],
1603            [345, [revert_swiss]]
1604           ]
1605
1606
1607 if __name__ == "__main__":
1608     pass