]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_2_0.py
lyx_2_0.py: add missing lxy2lyx routine after r34498
[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     mhchem = "off"
1085     i = find_token(document.header, "\\use_mhchem 1", 0)
1086     if i != -1:
1087         mhchem = "auto"
1088     else:
1089         i = find_token(document.header, "\\use_mhchem 2", 0)
1090         if i != -1:
1091             mhchem = "on"
1092     if mhchem == "auto":
1093         j = find_token(document.body, "\\cf{", 0)
1094         if j != -1:
1095             mhchem = "on"
1096         else:
1097             j = find_token(document.body, "\\ce{", 0)
1098             if j != -1:
1099                 mhchem = "on"
1100     if mhchem == "on":
1101         add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1102         add_to_preamble(document, ["\\PassOptionsToPackage{version=3}{mhchem}"])
1103         add_to_preamble(document, ["\\usepackage{mhchem}"])
1104     k = find_token(document.header, "\\use_mhchem", 0)
1105     if k == -1:
1106         document.warning("Malformed LyX document: Could not find mhchem setting.")
1107         return
1108     del document.header[k]
1109
1110
1111 def revert_fontenc(document):
1112     " Remove fontencoding param "
1113     i = find_token(document.header, '\\fontencoding', 0)
1114     if i == -1:
1115         document.warning("Malformed LyX document: Missing \\fontencoding.")
1116         return
1117     del document.header[i]
1118
1119
1120 def merge_gbrief(document):
1121     " Merge g-brief-en and g-brief-de to one class "
1122
1123     if document.textclass != "g-brief-de":
1124         if document.textclass == "g-brief-en":
1125             document.textclass = "g-brief"
1126             document.set_textclass()
1127         return
1128
1129     obsoletedby = { "Brieftext":       "Letter",
1130                     "Unterschrift":    "Signature",
1131                     "Strasse":         "Street",
1132                     "Zusatz":          "Addition",
1133                     "Ort":             "Town",
1134                     "Land":            "State",
1135                     "RetourAdresse":   "ReturnAddress",
1136                     "MeinZeichen":     "MyRef",
1137                     "IhrZeichen":      "YourRef",
1138                     "IhrSchreiben":    "YourMail",
1139                     "Telefon":         "Phone",
1140                     "BLZ":             "BankCode",
1141                     "Konto":           "BankAccount",
1142                     "Postvermerk":     "PostalComment",
1143                     "Adresse":         "Address",
1144                     "Datum":           "Date",
1145                     "Betreff":         "Reference",
1146                     "Anrede":          "Opening",
1147                     "Anlagen":         "Encl.",
1148                     "Verteiler":       "cc",
1149                     "Gruss":           "Closing"}
1150     i = 0
1151     while 1:
1152         i = find_token(document.body, "\\begin_layout", i)
1153         if i == -1:
1154             break
1155
1156         layout = document.body[i][14:]
1157         if layout in obsoletedby:
1158             document.body[i] = "\\begin_layout " + obsoletedby[layout]
1159
1160         i += 1
1161         
1162     document.textclass = "g-brief"
1163     document.set_textclass()
1164
1165
1166 def revert_gbrief(document):
1167     " Revert g-brief to g-brief-en "
1168     if document.textclass == "g-brief":
1169         document.textclass = "g-brief-en"
1170         document.set_textclass()
1171
1172
1173 def revert_html_options(document):
1174     " Remove html options "
1175     i = find_token(document.header, '\\html_use_mathml', 0)
1176     if i != -1:
1177         del document.header[i]
1178     i = find_token(document.header, '\\html_be_strict', 0)
1179     if i != -1:
1180         del document.header[i]
1181
1182
1183 def revert_includeonly(document):
1184     i = 0
1185     while True:
1186         i = find_token(document.header, "\\begin_includeonly", i)
1187         if i == -1:
1188             return
1189         j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
1190         if j == -1:
1191             # this should not happen
1192             break
1193         document.header[i : j + 1] = []
1194
1195
1196 def revert_includeall(document):
1197     " Remove maintain_unincluded_children param "
1198     i = find_token(document.header, '\\maintain_unincluded_children', 0)
1199     if i != -1:
1200         del document.header[i]
1201
1202
1203 def revert_multirow(document):
1204     " Revert multirow cells in tables "
1205     i = 0
1206     multirow = False
1207     while True:
1208       # cell type 3 is multirow begin cell
1209       i = find_token(document.body, '<cell multirow="3"', i)
1210       if i == -1:
1211           break
1212       # a multirow cell was found
1213       multirow = True
1214       # remove the multirow tag, set the valignment to top
1215       # and remove the bottom line
1216       document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
1217       document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1218       document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
1219       # write ERT to create the multirow cell
1220       # use 2 rows and 2cm as default with because the multirow span
1221       # and the column width is only hardly accessible
1222       subst = [old_put_cmd_in_ert("\\multirow{2}{2cm}{")]
1223       document.body[i + 4:i + 4] = subst
1224       i = find_token(document.body, "</cell>", i)
1225       if i == -1:
1226            document.warning("Malformed LyX document: Could not find end of tabular cell.")
1227            break
1228       subst = [old_put_cmd_in_ert("}")]
1229       document.body[i - 3:i - 3] = subst
1230       # cell type 4 is multirow part cell
1231       i = find_token(document.body, '<cell multirow="4"', i)
1232       if i == -1:
1233           break
1234       # remove the multirow tag, set the valignment to top
1235       # and remove the top line
1236       document.body[i] = document.body[i].replace(' multirow="4" ', ' ')
1237       document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1238       document.body[i] = document.body[i].replace(' topline="true" ', ' ')
1239       i = i + 1
1240     if multirow == True:
1241         add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1242         add_to_preamble(document, ["\\usepackage{multirow}"])
1243
1244
1245 def convert_math_output(document):
1246     " Convert \html_use_mathml to \html_math_output "
1247     i = find_token(document.header, "\\html_use_mathml", 0)
1248     if i == -1:
1249         return
1250     rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1251     m = rgx.match(document.header[i])
1252     if rgx:
1253         newval = "0" # MathML
1254         val = m.group(1)
1255         if val != "true":
1256             newval = "2" # Images
1257         document.header[i] = "\\html_math_output " + newval
1258
1259
1260 def revert_math_output(document):
1261     " Revert \html_math_output to \html_use_mathml "
1262     i = find_token(document.header, "\\html_math_output", 0)
1263     if i == -1:
1264         return
1265     rgx = re.compile(r'\\html_math_output\s+(\d)')
1266     m = rgx.match(document.header[i])
1267     newval = "true"
1268     if rgx:
1269         val = m.group(1)
1270         if val == "1" or val == "2":
1271             newval = "false"
1272     else:
1273         document.warning("Unable to match " + document.header[i])
1274     document.header[i] = "\\html_use_mathml " + newval
1275                 
1276
1277
1278 def revert_inset_preview(document):
1279     " Dissolves the preview inset "
1280     i = 0
1281     j = 0
1282     k = 0
1283     while True:
1284       i = find_token(document.body, "\\begin_inset Preview", i)
1285       if i == -1:
1286           return
1287       j = find_end_of_inset(document.body, i)
1288       if j == -1:
1289           document.warning("Malformed LyX document: Could not find end of Preview inset.")
1290           return
1291       #If the layout is Standard we need to remove it, otherwise there
1292       #will be paragraph breaks that shouldn't be there.
1293       k = find_token(document.body, "\\begin_layout Standard", i)
1294       if k == i+2:
1295           del document.body[i : i+3]
1296           del document.body[j-5 : j-2]
1297           i -= 6
1298       else:
1299           del document.body[i]
1300           del document.body[j-1]
1301           i -= 2
1302                 
1303
1304 def revert_equalspacing_xymatrix(document):
1305     " Revert a Formula with xymatrix@! to an ERT inset "
1306     i = 0
1307     j = 0
1308     has_preamble = False
1309     has_equal_spacing = False
1310     while True:
1311       found = -1
1312       i = find_token(document.body, "\\begin_inset Formula", i)
1313       if i == -1:
1314           break
1315       j = find_end_of_inset(document.body, i)
1316       if j == -1:
1317           document.warning("Malformed LyX document: Could not find end of Formula inset.")
1318           break
1319           
1320       for curline in range(i,j):
1321           found = document.body[curline].find("\\xymatrix@!")
1322           if found != -1:
1323               break
1324  
1325       if found != -1:
1326           has_equal_spacing = True
1327           content = [document.body[i][21:]]
1328           content += document.body[i+1:j]
1329           subst = put_cmd_in_ert(content)
1330           document.body[i:j+1] = subst
1331           i += len(subst)
1332       else:
1333           for curline in range(i,j):
1334               l = document.body[curline].find("\\xymatrix")
1335               if l != -1:
1336                   has_preamble = True;
1337                   break;
1338           i = j + 1
1339     if has_equal_spacing and not has_preamble:
1340         add_to_preamble(document, ['\\usepackage[all]{xy}'])
1341
1342
1343 def revert_notefontcolor(document):
1344     " Reverts greyed-out note font color to preamble code "
1345     i = 0
1346     colorcode = ""
1347     while True:
1348       i = find_token(document.header, "\\notefontcolor", i)
1349       if i == -1:
1350           return
1351       colorcode = get_value(document.header, '\\notefontcolor', 0)
1352       del document.header[i]
1353       # the color code is in the form #rrggbb where every character denotes a hex number
1354       # convert the string to an int
1355       red = string.atoi(colorcode[1:3],16)
1356       # we want the output "0.5" for the value "127" therefore increment here
1357       if red != 0:
1358           red = red + 1
1359       redout = float(red) / 256
1360       green = string.atoi(colorcode[3:5],16)
1361       if green != 0:
1362           green = green + 1
1363       greenout = float(green) / 256
1364       blue = string.atoi(colorcode[5:7],16)
1365       if blue != 0:
1366           blue = blue + 1
1367       blueout = float(blue) / 256
1368       # write the preamble
1369       insert_to_preamble(0, document,
1370                            '% Commands inserted by lyx2lyx to set the font color\n'
1371                            '% for greyed-out notes\n'
1372                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1373                            + '\\definecolor{note_fontcolor}{rgb}{'
1374                            + str(redout) + ', ' + str(greenout)
1375                            + ', ' + str(blueout) + '}\n'
1376                            + '\\renewenvironment{lyxgreyedout}\n'
1377                            + ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}\n')
1378
1379
1380 def revert_turkmen(document):
1381     "Set language Turkmen to English" 
1382     i = 0 
1383     if document.language == "turkmen": 
1384         document.language = "english" 
1385         i = find_token(document.header, "\\language", 0) 
1386         if i != -1: 
1387             document.header[i] = "\\language english" 
1388     j = 0 
1389     while True: 
1390         j = find_token(document.body, "\\lang turkmen", j) 
1391         if j == -1: 
1392             return 
1393         document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english") 
1394         j = j + 1 
1395
1396
1397 def revert_fontcolor(document):
1398     " Reverts font color to preamble code "
1399     i = 0
1400     colorcode = ""
1401     while True:
1402       i = find_token(document.header, "\\fontcolor", i)
1403       if i == -1:
1404           return
1405       colorcode = get_value(document.header, '\\fontcolor', 0)
1406       del document.header[i]
1407       # don't clutter the preamble if backgroundcolor is not set
1408       if colorcode == "#000000":
1409           continue
1410       # the color code is in the form #rrggbb where every character denotes a hex number
1411       # convert the string to an int
1412       red = string.atoi(colorcode[1:3],16)
1413       # we want the output "0.5" for the value "127" therefore add here
1414       if red != 0:
1415           red = red + 1
1416       redout = float(red) / 256
1417       green = string.atoi(colorcode[3:5],16)
1418       if green != 0:
1419           green = green + 1
1420       greenout = float(green) / 256
1421       blue = string.atoi(colorcode[5:7],16)
1422       if blue != 0:
1423           blue = blue + 1
1424       blueout = float(blue) / 256
1425       # write the preamble
1426       insert_to_preamble(0, document,
1427                            '% Commands inserted by lyx2lyx to set the font color\n'
1428                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1429                            + '\\definecolor{document_fontcolor}{rgb}{'
1430                            + str(redout) + ', ' + str(greenout)
1431                            + ', ' + str(blueout) + '}\n'
1432                            + '\\color{document_fontcolor}\n')
1433
1434
1435 def revert_shadedboxcolor(document):
1436     " Reverts shaded box color to preamble code "
1437     i = 0
1438     colorcode = ""
1439     while True:
1440       i = find_token(document.header, "\\boxbgcolor", i)
1441       if i == -1:
1442           return
1443       colorcode = get_value(document.header, '\\boxbgcolor', 0)
1444       del document.header[i]
1445       # the color code is in the form #rrggbb where every character denotes a hex number
1446       # convert the string to an int
1447       red = string.atoi(colorcode[1:3],16)
1448       # we want the output "0.5" for the value "127" therefore increment here
1449       if red != 0:
1450           red = red + 1
1451       redout = float(red) / 256
1452       green = string.atoi(colorcode[3:5],16)
1453       if green != 0:
1454           green = green + 1
1455       greenout = float(green) / 256
1456       blue = string.atoi(colorcode[5:7],16)
1457       if blue != 0:
1458           blue = blue + 1
1459       blueout = float(blue) / 256
1460       # write the preamble
1461       insert_to_preamble(0, document,
1462                            '% Commands inserted by lyx2lyx to set the color\n'
1463                            '% of boxes with shaded background\n'
1464                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1465                            + '\\definecolor{shadecolor}{rgb}{'
1466                            + str(redout) + ', ' + str(greenout)
1467                            + ', ' + str(blueout) + '}\n')
1468
1469
1470 def revert_lyx_version(document):
1471     " Reverts LyX Version information from Inset Info "
1472     version = "LyX version"
1473     try:
1474         import lyx2lyx_version
1475         version = lyx2lyx_version.version
1476     except:
1477             pass
1478         
1479     i = 0
1480     while 1:
1481         i = find_token(document.body, '\\begin_inset Info', i)
1482         if i == -1:
1483             return
1484         j = find_end_of_inset(document.body, i + 1)
1485         if j == -1:
1486             # should not happen
1487             document.warning("Malformed LyX document: Could not find end of Info inset.")
1488         # We expect:
1489         # \begin_inset Info
1490         # type  "lyxinfo"
1491         # arg   "version"
1492         # \end_inset
1493         # but we shall try to be forgiving.
1494         arg = typ = ""
1495         for k in range(i, j):
1496             if document.body[k].startswith("arg"):
1497                 arg = document.body[k][3:].strip().strip('"')
1498             if document.body[k].startswith("type"):
1499                 typ = document.body[k][4:].strip().strip('"')
1500         if arg != "version" or typ != "lyxinfo":
1501             i = j+1
1502             continue
1503
1504         # We do not actually know the version of LyX used to produce the document.
1505         # But we can use our version, since we are reverting.
1506         s = [version]
1507         # Now we want to check if the line after "\end_inset" is empty. It normally
1508         # is, so we want to remove it, too.
1509         lastline = j+1
1510         if document.body[j+1].strip() == "":
1511             lastline = j+2
1512         document.body[i: lastline] = s
1513         i = i+1
1514
1515
1516 def revert_math_scale(document):
1517   " Remove math scaling and LaTeX options "
1518   i = find_token(document.header, '\\html_math_img_scale', 0)
1519   if i != -1:
1520     del document.header[i]
1521   i = find_token(document.header, '\\html_latex_start', 0)
1522   if i != -1:
1523     del document.header[i]
1524   i = find_token(document.header, '\\html_latex_end', 0)
1525   if i != -1:
1526     del document.header[i]
1527
1528
1529 def revert_pagesizes(document):
1530   i = 0
1531   " Revert page sizes to default "
1532   i = find_token(document.header, '\\papersize', 0)
1533   if i != -1:
1534     size = document.header[i][11:]
1535     if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1536     or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1537     or size == "b2paper" or size == "b6paper" or size == "b0j" \
1538     or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1539     or size == "b5j" or size == "b6j":
1540       del document.header[i]
1541
1542
1543 def convert_html_quotes(document):
1544   " Remove quotes around html_latex_start and html_latex_end "
1545
1546   i = find_token(document.header, '\\html_latex_start', 0)
1547   if i != -1:
1548     line = document.header[i]
1549     l = re.compile(r'\\html_latex_start\s+"(.*)"')
1550     m = l.match(line)
1551     if m != None:
1552       document.header[i] = "\\html_latex_start " + m.group(1)
1553       
1554   i = find_token(document.header, '\\html_latex_end', 0)
1555   if i != -1:
1556     line = document.header[i]
1557     l = re.compile(r'\\html_latex_end\s+"(.*)"')
1558     m = l.match(line)
1559     if m != None:
1560       document.header[i] = "\\html_latex_end " + m.group(1)
1561       
1562
1563 def revert_html_quotes(document):
1564   " Remove quotes around html_latex_start and html_latex_end "
1565   
1566   i = find_token(document.header, '\\html_latex_start', 0)
1567   if i != -1:
1568     line = document.header[i]
1569     l = re.compile(r'\\html_latex_start\s+(.*)')
1570     m = l.match(line)
1571     document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1572       
1573   i = find_token(document.header, '\\html_latex_end', 0)
1574   if i != -1:
1575     line = document.header[i]
1576     l = re.compile(r'\\html_latex_end\s+(.*)')
1577     m = l.match(line)
1578     document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1579
1580
1581 def revert_output_sync(document):
1582   " Remove forward search options "
1583   i = find_token(document.header, '\\forward_search', 0)
1584   if i != -1:
1585     del document.header[i]
1586   i = find_token(document.header, '\\forward_macro', 0)
1587   if i != -1:
1588     del document.header[i]
1589   i = find_token(document.header, '\\output_sync', 0)
1590   if i != -1:
1591     del document.header[i]
1592
1593
1594 ##
1595 # Conversion hub
1596 #
1597
1598 supported_versions = ["2.0.0","2.0"]
1599 convert = [[346, []],
1600            [347, []],
1601            [348, []],
1602            [349, []],
1603            [350, []],
1604            [351, []],
1605            [352, [convert_splitindex]],
1606            [353, []],
1607            [354, []],
1608            [355, []],
1609            [356, []],
1610            [357, []],
1611            [358, []],
1612            [359, [convert_nomencl_width]],
1613            [360, []],
1614            [361, []],
1615            [362, []],
1616            [363, []],
1617            [364, []],
1618            [365, []],
1619            [366, []],
1620            [367, []],
1621            [368, []],
1622            [369, [convert_author_id]],
1623            [370, []],
1624            [371, []],
1625            [372, []],
1626            [373, [merge_gbrief]],
1627            [374, []],
1628            [375, []],
1629            [376, []],
1630            [377, []],
1631            [378, []],
1632            [379, [convert_math_output]],
1633            [380, []],
1634            [381, []],
1635            [382, []],
1636            [383, []],
1637            [384, []],
1638            [385, []],
1639            [386, []],
1640            [387, []],
1641            [388, []],
1642            [389, [convert_html_quotes]],
1643            [390, []]
1644                                         ]
1645
1646 revert =  [[389, [revert_output_sync]],
1647            [388, [revert_html_quotes]],
1648            [387, [revert_pagesizes]],
1649            [386, [revert_math_scale]],
1650            [385, [revert_lyx_version]],
1651            [384, [revert_shadedboxcolor]],
1652            [383, [revert_fontcolor]],
1653            [382, [revert_turkmen]],
1654            [381, [revert_notefontcolor]],
1655            [380, [revert_equalspacing_xymatrix]],
1656            [379, [revert_inset_preview]],
1657            [378, [revert_math_output]],
1658            [377, []],
1659            [376, [revert_multirow]],
1660            [375, [revert_includeall]],
1661            [374, [revert_includeonly]],
1662            [373, [revert_html_options]],
1663            [372, [revert_gbrief]],
1664            [371, [revert_fontenc]],
1665            [370, [revert_mhchem]],
1666            [369, [revert_suppress_date]],
1667            [368, [revert_author_id]],
1668            [367, [revert_hspace_glue_lengths]],
1669            [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
1670            [365, [revert_percent_skip_lengths]],
1671            [364, [revert_paragraph_indentation]],
1672            [363, [revert_branch_filename]],
1673            [362, [revert_longtable_align]],
1674            [361, [revert_applemac]],
1675            [360, []],
1676            [359, [revert_nomencl_cwidth]],
1677            [358, [revert_nomencl_width]],
1678            [357, [revert_custom_processors]],
1679            [356, [revert_ulinelatex]],
1680            [355, [revert_uulinewave]],
1681            [354, [revert_strikeout]],
1682            [353, [revert_printindexall]],
1683            [352, [revert_subindex]],
1684            [351, [revert_splitindex]],
1685            [350, [revert_backgroundcolor]],
1686            [349, [revert_outputformat]],
1687            [348, [revert_xetex]],
1688            [347, [revert_phantom, revert_hphantom, revert_vphantom]],
1689            [346, [revert_tabularvalign]],
1690            [345, [revert_swiss]]
1691           ]
1692
1693
1694 if __name__ == "__main__":
1695     pass