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