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