]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_2_0.py
OK, so that version of revert_inset_preview wasn't so good. Restore the
[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             if i == -1:
1211                break
1212             line = document.body[i]
1213             if line.find("\\ce{") != -1 or line.find("\\cf{") != 1:
1214               mhchem = "on"
1215               break
1216             i += 1
1217
1218     if mhchem == "on":
1219         pre = ["% lyx2lyx mhchem commands", 
1220           "\\PassOptionsToPackage{version=3}{mhchem}", 
1221           "\\usepackage{mhchem}"]
1222         add_to_preamble(document, pre) 
1223
1224
1225 def revert_fontenc(document):
1226     " Remove fontencoding param "
1227     i = find_token(document.header, '\\fontencoding', 0)
1228     if i == -1:
1229         document.warning("Malformed LyX document: Missing \\fontencoding.")
1230         return
1231     del document.header[i]
1232
1233
1234 def merge_gbrief(document):
1235     " Merge g-brief-en and g-brief-de to one class "
1236
1237     if document.textclass != "g-brief-de":
1238         if document.textclass == "g-brief-en":
1239             document.textclass = "g-brief"
1240             document.set_textclass()
1241         return
1242
1243     obsoletedby = { "Brieftext":       "Letter",
1244                     "Unterschrift":    "Signature",
1245                     "Strasse":         "Street",
1246                     "Zusatz":          "Addition",
1247                     "Ort":             "Town",
1248                     "Land":            "State",
1249                     "RetourAdresse":   "ReturnAddress",
1250                     "MeinZeichen":     "MyRef",
1251                     "IhrZeichen":      "YourRef",
1252                     "IhrSchreiben":    "YourMail",
1253                     "Telefon":         "Phone",
1254                     "BLZ":             "BankCode",
1255                     "Konto":           "BankAccount",
1256                     "Postvermerk":     "PostalComment",
1257                     "Adresse":         "Address",
1258                     "Datum":           "Date",
1259                     "Betreff":         "Reference",
1260                     "Anrede":          "Opening",
1261                     "Anlagen":         "Encl.",
1262                     "Verteiler":       "cc",
1263                     "Gruss":           "Closing"}
1264     i = 0
1265     while 1:
1266         i = find_token(document.body, "\\begin_layout", i)
1267         if i == -1:
1268             break
1269
1270         layout = document.body[i][14:]
1271         if layout in obsoletedby:
1272             document.body[i] = "\\begin_layout " + obsoletedby[layout]
1273
1274         i += 1
1275         
1276     document.textclass = "g-brief"
1277     document.set_textclass()
1278
1279
1280 def revert_gbrief(document):
1281     " Revert g-brief to g-brief-en "
1282     if document.textclass == "g-brief":
1283         document.textclass = "g-brief-en"
1284         document.set_textclass()
1285
1286
1287 def revert_html_options(document):
1288     " Remove html options "
1289     i = find_token(document.header, '\\html_use_mathml', 0)
1290     if i != -1:
1291         del document.header[i]
1292     i = find_token(document.header, '\\html_be_strict', 0)
1293     if i != -1:
1294         del document.header[i]
1295
1296
1297 def revert_includeonly(document):
1298     i = 0
1299     while True:
1300         i = find_token(document.header, "\\begin_includeonly", i)
1301         if i == -1:
1302             return
1303         j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
1304         if j == -1:
1305             document.warning("Unable to find end of includeonly section!!")
1306             break
1307         document.header[i : j + 1] = []
1308
1309
1310 def revert_includeall(document):
1311     " Remove maintain_unincluded_children param "
1312     i = find_token(document.header, '\\maintain_unincluded_children', 0)
1313     if i != -1:
1314         del document.header[i]
1315
1316
1317 def revert_multirow(document):
1318     " Revert multirow cells in tables to TeX-code"
1319     i = 0
1320     multirow = False
1321     while True:
1322       # cell type 3 is multirow begin cell
1323       i = find_token(document.body, '<cell multirow="3"', i)
1324       if i == -1:
1325           break
1326       # a multirow cell was found
1327       multirow = True
1328       # remove the multirow tag, set the valignment to top
1329       # and remove the bottom line
1330       # FIXME Are we sure these always have space around them?
1331       document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
1332       document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1333       document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
1334       # write ERT to create the multirow cell
1335       # use 2 rows and 2cm as default with because the multirow span
1336       # and the column width is only hardly accessible
1337       cend = find_token(document.body, "</cell>", i)
1338       if cend == -1:
1339           document.warning("Malformed LyX document: Could not find end of tabular cell.")
1340           i += 1
1341           continue
1342       blay = find_token(document.body, "\\begin_layout", i, cend)
1343       if blay == -1:
1344           document.warning("Can't find layout for cell!")
1345           i = j
1346           continue
1347       bend = find_end_of_layout(document.body, blay)
1348       if blay == -1:
1349           document.warning("Can't find end of layout for cell!")
1350           i = cend
1351           continue
1352
1353       # do the later one first, so as not to mess up the numbering
1354       # we are wrapping the whole cell in this ert
1355       # so before the end of the layout...
1356       document.body[bend:bend] = put_cmd_in_ert("}")
1357       # ...and after the beginning
1358       document.body[blay+1:blay+1] = put_cmd_in_ert("\\multirow{2}{2cm}{")
1359
1360       while True:
1361           # cell type 4 is multirow part cell
1362           k = find_token(document.body, '<cell multirow="4"', cend)
1363           if k == -1:
1364               break
1365           # remove the multirow tag, set the valignment to top
1366           # and remove the top line
1367           # FIXME Are we sure these always have space around them?
1368           document.body[k] = document.body[k].replace(' multirow="4" ', ' ')
1369           document.body[k] = document.body[k].replace('valignment="middle"', 'valignment="top"')
1370           document.body[k] = document.body[k].replace(' topline="true" ', ' ')
1371           k += 1
1372       # this will always be ok
1373       i = cend
1374
1375     if multirow == True:
1376         add_to_preamble(document, 
1377           ["% lyx2lyx multirow additions ", "\\usepackage{multirow}"])
1378
1379
1380 def convert_math_output(document):
1381     " Convert \html_use_mathml to \html_math_output "
1382     i = find_token(document.header, "\\html_use_mathml", 0)
1383     if i == -1:
1384         return
1385     rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1386     m = rgx.match(document.header[i])
1387     newval = "0" # MathML
1388     if m:
1389       val = m.group(1)
1390       if val != "true":
1391         newval = "2" # Images
1392     else:
1393       document.warning("Can't match " + document.header[i])
1394     document.header[i] = "\\html_math_output " + newval
1395
1396
1397 def revert_math_output(document):
1398     " Revert \html_math_output to \html_use_mathml "
1399     i = find_token(document.header, "\\html_math_output", 0)
1400     if i == -1:
1401         return
1402     rgx = re.compile(r'\\html_math_output\s+(\d)')
1403     m = rgx.match(document.header[i])
1404     newval = "true"
1405     if m:
1406         val = m.group(1)
1407         if val == "1" or val == "2":
1408             newval = "false"
1409     else:
1410         document.warning("Unable to match " + document.header[i])
1411     document.header[i] = "\\html_use_mathml " + newval
1412                 
1413
1414
1415 def revert_inset_preview(document):
1416     " Dissolves the preview inset "
1417     i = 0
1418     while True:
1419       i = find_token(document.body, "\\begin_inset Preview", i)
1420       if i == -1:
1421           return
1422       iend = find_end_of_inset(document.body, i)
1423       if iend == -1:
1424           document.warning("Malformed LyX document: Could not find end of Preview inset.")
1425           i += 1
1426           continue
1427       
1428       # This has several issues.
1429       # We need to do something about the layouts inside InsetPreview.
1430       # If we just leave the first one, then we have something like:
1431       # \begin_layout Standard
1432       # ...
1433       # \begin_layout Standard
1434       # and we get a "no \end_layout" error. So something has to be done.
1435       # Ideally, we would check if it is the same as the layout we are in.
1436       # If so, we just remove it; if not, we end the active one. But it is 
1437       # not easy to know what layout we are in, due to depth changes, etc,
1438       # and it is not clear to me how much work it is worth doing. In most
1439       # cases, the layout will probably be the same.
1440       # 
1441       # For the same reason, we have to remove the \end_layout tag at the
1442       # end of the last layout in the inset. Again, that will sometimes be
1443       # wrong, but it will usually be right. To know what to do, we would
1444       # again have to know what layout the inset is in.
1445       
1446       blay = find_token(document.body, "\\begin_layout", i, iend)
1447       if blay == -1:
1448           document.warning("Can't find layout for preview inset!")
1449           # always do the later one first...
1450           del document.body[iend]
1451           del document.body[i]
1452           # deletions mean we do not need to reset i
1453           continue
1454
1455       # This is where we would check what layout we are in.
1456       # The check for Standard is definitely wrong.
1457       # 
1458       # lay = document.body[blay].split(None, 1)[1]
1459       # if lay != oldlayout:
1460       #     # record a boolean to tell us what to do later....
1461       #     # better to do it later, since (a) it won't mess up
1462       #     # the numbering and (b) we only modify at the end.
1463         
1464       # we want to delete the last \\end_layout in this inset, too.
1465       # note that this may not be the \\end_layout that goes with blay!!
1466       bend = find_end_of_layout(document.body, blay)
1467       while True:
1468           tmp = find_token(document.body, "\\end_layout", bend + 1, iend)
1469           if tmp == -1:
1470               break
1471           bend = tmp
1472       if bend == blay:
1473           document.warning("Unable to find last layout in preview inset!")
1474           del document.body[iend]
1475           del document.body[i]
1476           # deletions mean we do not need to reset i
1477           continue
1478       # always do the later one first...
1479       del document.body[iend]
1480       del document.body[bend]
1481       del document.body[i:blay + 1]
1482       # we do not need to reset i
1483                 
1484
1485 def revert_equalspacing_xymatrix(document):
1486     " Revert a Formula with xymatrix@! to an ERT inset "
1487     i = 0
1488     has_preamble = False
1489     has_equal_spacing = False
1490
1491     while True:
1492       i = find_token(document.body, "\\begin_inset Formula", i)
1493       if i == -1:
1494           break
1495       j = find_end_of_inset(document.body, i)
1496       if j == -1:
1497           document.warning("Malformed LyX document: Could not find end of Formula inset.")
1498           i += 1
1499           continue
1500       
1501       for curline in range(i,j):
1502           found = document.body[curline].find("\\xymatrix@!")
1503           if found != -1:
1504               break
1505  
1506       if found != -1:
1507           has_equal_spacing = True
1508           content = [document.body[i][21:]]
1509           content += document.body[i + 1:j]
1510           subst = put_cmd_in_ert(content)
1511           document.body[i:j + 1] = subst
1512           i += len(subst) - (j - i) + 1
1513       else:
1514           for curline in range(i,j):
1515               l = document.body[curline].find("\\xymatrix")
1516               if l != -1:
1517                   has_preamble = True;
1518                   break;
1519           i = j + 1
1520   
1521     if has_equal_spacing and not has_preamble:
1522         add_to_preamble(document, ['% lyx2lyx xymatrix addition', '\\usepackage[all]{xy}'])
1523
1524
1525 def revert_notefontcolor(document):
1526     " Reverts greyed-out note font color to preamble code "
1527     i = 0
1528     colorcode = ""
1529     while True:
1530       i = find_token(document.header, "\\notefontcolor", i)
1531       if i == -1:
1532           return
1533       colorcode = get_value(document.header, '\\notefontcolor', 0)
1534       del document.header[i]
1535       # the color code is in the form #rrggbb where every character denotes a hex number
1536       # convert the string to an int
1537       red = string.atoi(colorcode[1:3],16)
1538       # we want the output "0.5" for the value "127" therefore increment here
1539       if red != 0:
1540           red = red + 1
1541       redout = float(red) / 256
1542       green = string.atoi(colorcode[3:5],16)
1543       if green != 0:
1544           green = green + 1
1545       greenout = float(green) / 256
1546       blue = string.atoi(colorcode[5:7],16)
1547       if blue != 0:
1548           blue = blue + 1
1549       blueout = float(blue) / 256
1550       # write the preamble
1551       insert_to_preamble(0, document,
1552                            '% Commands inserted by lyx2lyx to set the font color\n'
1553                            '% for greyed-out notes\n'
1554                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1555                            + '\\definecolor{note_fontcolor}{rgb}{'
1556                            + str(redout) + ', ' + str(greenout)
1557                            + ', ' + str(blueout) + '}\n'
1558                            + '\\renewenvironment{lyxgreyedout}\n'
1559                            + ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}\n')
1560
1561
1562 def revert_turkmen(document):
1563     "Set language Turkmen to English" 
1564     i = 0 
1565     if document.language == "turkmen": 
1566         document.language = "english" 
1567         i = find_token(document.header, "\\language", 0) 
1568         if i != -1: 
1569             document.header[i] = "\\language english" 
1570     j = 0 
1571     while True: 
1572         j = find_token(document.body, "\\lang turkmen", j) 
1573         if j == -1: 
1574             return 
1575         document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english") 
1576         j = j + 1 
1577
1578
1579 def revert_fontcolor(document):
1580     " Reverts font color to preamble code "
1581     i = 0
1582     colorcode = ""
1583     while True:
1584       i = find_token(document.header, "\\fontcolor", i)
1585       if i == -1:
1586           return
1587       colorcode = get_value(document.header, '\\fontcolor', 0)
1588       del document.header[i]
1589       # don't clutter the preamble if backgroundcolor is not set
1590       if colorcode == "#000000":
1591           continue
1592       # the color code is in the form #rrggbb where every character denotes a hex number
1593       # convert the string to an int
1594       red = string.atoi(colorcode[1:3],16)
1595       # we want the output "0.5" for the value "127" therefore add here
1596       if red != 0:
1597           red = red + 1
1598       redout = float(red) / 256
1599       green = string.atoi(colorcode[3:5],16)
1600       if green != 0:
1601           green = green + 1
1602       greenout = float(green) / 256
1603       blue = string.atoi(colorcode[5:7],16)
1604       if blue != 0:
1605           blue = blue + 1
1606       blueout = float(blue) / 256
1607       # write the preamble
1608       insert_to_preamble(0, document,
1609                            '% Commands inserted by lyx2lyx to set the font color\n'
1610                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1611                            + '\\definecolor{document_fontcolor}{rgb}{'
1612                            + str(redout) + ', ' + str(greenout)
1613                            + ', ' + str(blueout) + '}\n'
1614                            + '\\color{document_fontcolor}\n')
1615
1616 def revert_shadedboxcolor(document):
1617     " Reverts shaded box color to preamble code "
1618     i = 0
1619     colorcode = ""
1620     while True:
1621       i = find_token(document.header, "\\boxbgcolor", i)
1622       if i == -1:
1623           return
1624       colorcode = get_value(document.header, '\\boxbgcolor', 0)
1625       del document.header[i]
1626       # the color code is in the form #rrggbb where every character denotes a hex number
1627       # convert the string to an int
1628       red = string.atoi(colorcode[1:3],16)
1629       # we want the output "0.5" for the value "127" therefore increment here
1630       if red != 0:
1631           red = red + 1
1632       redout = float(red) / 256
1633       green = string.atoi(colorcode[3:5],16)
1634       if green != 0:
1635           green = green + 1
1636       greenout = float(green) / 256
1637       blue = string.atoi(colorcode[5:7],16)
1638       if blue != 0:
1639           blue = blue + 1
1640       blueout = float(blue) / 256
1641       # write the preamble
1642       insert_to_preamble(0, document,
1643                            '% Commands inserted by lyx2lyx to set the color\n'
1644                            '% of boxes with shaded background\n'
1645                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1646                            + '\\definecolor{shadecolor}{rgb}{'
1647                            + str(redout) + ', ' + str(greenout)
1648                            + ', ' + str(blueout) + '}\n')
1649
1650
1651 def revert_lyx_version(document):
1652     " Reverts LyX Version information from Inset Info "
1653     version = "LyX version"
1654     try:
1655         import lyx2lyx_version
1656         version = lyx2lyx_version.version
1657     except:
1658         pass
1659
1660     i = 0
1661     while 1:
1662         i = find_token(document.body, '\\begin_inset Info', i)
1663         if i == -1:
1664             return
1665         j = find_end_of_inset(document.body, i + 1)
1666         if j == -1:
1667             # should not happen
1668             document.warning("Malformed LyX document: Could not find end of Info inset.")
1669         # We expect:
1670         # \begin_inset Info
1671         # type  "lyxinfo"
1672         # arg   "version"
1673         # \end_inset
1674         # but we shall try to be forgiving.
1675         arg = typ = ""
1676         for k in range(i, j):
1677             if document.body[k].startswith("arg"):
1678                 arg = document.body[k][3:].strip().strip('"')
1679             if document.body[k].startswith("type"):
1680                 typ = document.body[k][4:].strip().strip('"')
1681         if arg != "version" or typ != "lyxinfo":
1682             i = j + 1
1683             continue
1684
1685         # We do not actually know the version of LyX used to produce the document.
1686         # But we can use our version, since we are reverting.
1687         s = [version]
1688         # Now we want to check if the line after "\end_inset" is empty. It normally
1689         # is, so we want to remove it, too.
1690         lastline = j + 1
1691         if document.body[j + 1].strip() == "":
1692             lastline = j + 2
1693         document.body[i: lastline] = s
1694         i = i + 1
1695
1696
1697 def revert_math_scale(document):
1698   " Remove math scaling and LaTeX options "
1699   i = find_token(document.header, '\\html_math_img_scale', 0)
1700   if i != -1:
1701     del document.header[i]
1702   i = find_token(document.header, '\\html_latex_start', 0)
1703   if i != -1:
1704     del document.header[i]
1705   i = find_token(document.header, '\\html_latex_end', 0)
1706   if i != -1:
1707     del document.header[i]
1708
1709
1710 def revert_pagesizes(document):
1711   i = 0
1712   " Revert page sizes to default "
1713   i = find_token(document.header, '\\papersize', 0)
1714   if i != -1:
1715     size = document.header[i][11:]
1716     if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1717     or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1718     or size == "b2paper" or size == "b6paper" or size == "b0j" \
1719     or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1720     or size == "b5j" or size == "b6j":
1721       del document.header[i]
1722
1723
1724 def revert_DIN_C_pagesizes(document):
1725   i = 0
1726   " Revert DIN C page sizes to default "
1727   i = find_token(document.header, '\\papersize', 0)
1728   if i != -1:
1729     size = document.header[i][11:]
1730     if size == "c0paper" or size == "c1paper" or size == "c2paper" \
1731     or size == "c3paper" or size == "c4paper" or size == "c5paper" \
1732     or size == "c6paper":
1733       del document.header[i]
1734
1735
1736 def convert_html_quotes(document):
1737   " Remove quotes around html_latex_start and html_latex_end "
1738
1739   i = find_token(document.header, '\\html_latex_start', 0)
1740   if i != -1:
1741     line = document.header[i]
1742     l = re.compile(r'\\html_latex_start\s+"(.*)"')
1743     m = l.match(line)
1744     if m != None:
1745       document.header[i] = "\\html_latex_start " + m.group(1)
1746       
1747   i = find_token(document.header, '\\html_latex_end', 0)
1748   if i != -1:
1749     line = document.header[i]
1750     l = re.compile(r'\\html_latex_end\s+"(.*)"')
1751     m = l.match(line)
1752     if m != None:
1753       document.header[i] = "\\html_latex_end " + m.group(1)
1754       
1755
1756 def revert_html_quotes(document):
1757   " Remove quotes around html_latex_start and html_latex_end "
1758   
1759   i = find_token(document.header, '\\html_latex_start', 0)
1760   if i != -1:
1761     line = document.header[i]
1762     l = re.compile(r'\\html_latex_start\s+(.*)')
1763     m = l.match(line)
1764     document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1765       
1766   i = find_token(document.header, '\\html_latex_end', 0)
1767   if i != -1:
1768     line = document.header[i]
1769     l = re.compile(r'\\html_latex_end\s+(.*)')
1770     m = l.match(line)
1771     document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1772
1773
1774 def revert_output_sync(document):
1775   " Remove forward search options "
1776   i = find_token(document.header, '\\output_sync_macro', 0)
1777   if i != -1:
1778     del document.header[i]
1779   i = find_token(document.header, '\\output_sync', 0)
1780   if i != -1:
1781     del document.header[i]
1782
1783
1784 def convert_beamer_args(document):
1785   " Convert ERT arguments in Beamer to InsetArguments "
1786
1787   if document.textclass != "beamer" and document.textclass != "article-beamer":
1788     return
1789   
1790   layouts = ("Block", "ExampleBlock", "AlertBlock")
1791   for layout in layouts:
1792     blay = 0
1793     while True:
1794       blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1795       if blay == -1:
1796         break
1797       elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1798       if elay == -1:
1799         document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1800         blay += 1
1801         continue
1802       bert = find_token(document.body, '\\begin_inset ERT', blay)
1803       if bert == -1:
1804         document.warning("Malformed Beamer LyX document: Can't find argument of " + layout + " layout.")
1805         blay = elay + 1
1806         continue
1807       eert = find_end_of_inset(document.body, bert)
1808       if eert == -1:
1809         document.warning("Malformed LyX document: Can't find end of ERT.")
1810         blay = elay + 1
1811         continue
1812       
1813       # So the ERT inset begins at line k and goes to line l. We now wrap it in 
1814       # an argument inset.
1815       # Do the end first, so as not to mess up the variables.
1816       document.body[eert + 1:eert + 1] = ['', '\\end_layout', '', '\\end_inset', '']
1817       document.body[bert:bert] = ['\\begin_inset OptArg', 'status open', '', 
1818           '\\begin_layout Plain Layout']
1819       blay = elay + 9
1820
1821
1822 def revert_beamer_args(document):
1823   " Revert Beamer arguments to ERT "
1824   
1825   if document.textclass != "beamer" and document.textclass != "article-beamer":
1826     return
1827     
1828   layouts = ("Block", "ExampleBlock", "AlertBlock")
1829   for layout in layouts:
1830     blay = 0
1831     while True:
1832       blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1833       if blay == -1:
1834         break
1835       elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1836       if elay == -1:
1837         document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1838         blay += 1
1839         continue
1840       bopt = find_token(document.body, '\\begin_inset OptArg', blay)
1841       if bopt == -1:
1842         # it is legal not to have one of these
1843         blay = elay + 1
1844         continue
1845       eopt = find_end_of_inset(document.body, bopt)
1846       if eopt == -1:
1847         document.warning("Malformed LyX document: Can't find end of argument.")
1848         blay = elay + 1
1849         continue
1850       bplay = find_token(document.body, '\\begin_layout Plain Layout', blay)
1851       if bplay == -1:
1852         document.warning("Malformed LyX document: Can't find plain layout.")
1853         blay = elay + 1
1854         continue
1855       eplay = find_end_of(document.body, bplay, '\\begin_layout', '\\end_layout')
1856       if eplay == -1:
1857         document.warning("Malformed LyX document: Can't find end of plain layout.")
1858         blay = elay + 1
1859         continue
1860       # So the content of the argument inset goes from bplay + 1 to eplay - 1
1861       bcont = bplay + 1
1862       if bcont >= eplay:
1863         # Hmm.
1864         document.warning(str(bcont) + " " + str(eplay))
1865         blay = blay + 1
1866         continue
1867       # we convert the content of the argument into pure LaTeX...
1868       content = lyx2latex(document, document.body[bcont:eplay])
1869       strlist = put_cmd_in_ert(["{" + content + "}"])
1870       
1871       # now replace the optional argument with the ERT
1872       document.body[bopt:eopt + 1] = strlist
1873       blay = blay + 1
1874
1875
1876 def revert_align_decimal(document):
1877   l = 0
1878   while True:
1879     l = document.body[l].find('alignment=decimal')
1880     if l == -1:
1881         break
1882     remove_option(document, l, 'decimal_point')
1883     document.body[l].replace('decimal', 'center')
1884
1885
1886 def convert_optarg(document):
1887   " Convert \\begin_inset OptArg to \\begin_inset Argument "
1888   i = 0
1889   while 1:
1890     i = find_token(document.body, '\\begin_inset OptArg', i)
1891     if i == -1:
1892       return
1893     document.body[i] = "\\begin_inset Argument"
1894     i += 1
1895
1896
1897 def revert_argument(document):
1898   " Convert \\begin_inset Argument to \\begin_inset OptArg "
1899   i = 0
1900   while 1:
1901     i = find_token(document.body, '\\begin_inset Argument', i)
1902     if i == -1:
1903       return
1904     document.body[i] = "\\begin_inset OptArg"
1905     i += 1
1906
1907
1908 def revert_makebox(document):
1909   " Convert \\makebox to TeX code "
1910   i = 0
1911   while 1:
1912     # only revert frameless boxes without an inner box
1913     i = find_token(document.body, '\\begin_inset Box Frameless', i)
1914     if i == -1:
1915       # remove the option use_makebox
1916       revert_use_makebox(document)
1917       return
1918     z = find_end_of_inset(document.body, i)
1919     if z == -1:
1920       document.warning("Malformed LyX document: Can't find end of box inset.")
1921       return
1922     j = find_token(document.body, 'use_makebox 1', i)
1923     # assure we found the makebox of the current box
1924     if j < z and j != -1:
1925       y = find_token(document.body, "\\begin_layout", i)
1926       if y > z or y == -1:
1927         document.warning("Malformed LyX document: Can't find layout in box.")
1928         return
1929       # remove the \end_layout \end_inset pair
1930       document.body[z - 2:z + 1] = put_cmd_in_ert("}")
1931       # determine the alignment
1932       k = find_token(document.body, 'hor_pos', j - 4)
1933       align = document.body[k][9]
1934       # determine the width
1935       l = find_token(document.body, 'width "', j + 1)
1936       length = document.body[l][7:]
1937       # remove trailing '"'
1938       length = length[:-1]
1939       length = latex_length(length)[1]
1940       subst = "\\makebox[" + length + "][" \
1941         + align + "]{"
1942       document.body[i:y + 1] = put_cmd_in_ert(subst)
1943     i += 1
1944
1945
1946 def revert_use_makebox(document):
1947   " Deletes use_makebox option of boxes "
1948   h = 0
1949   while 1:
1950     # remove the option use_makebox
1951     h = find_token(document.body, 'use_makebox', 0)
1952     if h == -1:
1953       return
1954     del document.body[h]
1955     h += 1
1956
1957
1958 def convert_use_makebox(document):
1959   " Adds use_makebox option for boxes "
1960   i = 0
1961   while 1:
1962     # remove the option use_makebox
1963     i = find_token(document.body, '\\begin_inset Box', i)
1964     if i == -1:
1965       return
1966     k = find_token(document.body, 'use_parbox', i)
1967     if k == -1:
1968       document.warning("Malformed LyX document: Can't find use_parbox statement in box.")
1969       return
1970     document.body.insert(k + 1, "use_makebox 0")
1971     i = k + 1
1972
1973
1974 def revert_IEEEtran(document):
1975   " Convert IEEEtran layouts and styles to TeX code "
1976   if document.textclass != "IEEEtran":
1977     return
1978   revert_flex_inset(document, "IEEE membership", "\\IEEEmembership", 0)
1979   revert_flex_inset(document, "Lowercase", "\\MakeLowercase", 0)
1980   layouts = ("Special Paper Notice", "After Title Text", "Publication ID",
1981              "Page headings", "Biography without photo")
1982   latexcmd = {"Special Paper Notice": "\\IEEEspecialpapernotice",
1983               "After Title Text":     "\\IEEEaftertitletext",
1984               "Publication ID":       "\\IEEEpubid"}
1985   obsoletedby = {"Page headings":            "MarkBoth",
1986                  "Biography without photo":  "BiographyNoPhoto"}
1987   for layout in layouts:
1988     i = 0
1989     while True:
1990         i = find_token(document.body, '\\begin_layout ' + layout, i)
1991         if i == -1:
1992           break
1993         j = find_end_of(document.body, i, '\\begin_layout', '\\end_layout')
1994         if j == -1:
1995           document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1996           i += 1
1997           continue
1998         if layout in obsoletedby:
1999           document.body[i] = "\\begin_layout " + obsoletedby[layout]
2000           i = j
2001         else:
2002           content = lyx2latex(document, document.body[i:j + 1])
2003           add_to_preamble(document, [latexcmd[layout] + "{" + content + "}"])
2004           del document.body[i:j + 1]
2005
2006
2007 def convert_prettyref(document):
2008         " Converts prettyref references to neutral formatted refs "
2009         re_ref = re.compile("^\s*reference\s+\"(\w+):(\S+)\"")
2010         nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
2011
2012         i = 0
2013         while True:
2014                 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
2015                 if i == -1:
2016                         break
2017                 j = find_end_of_inset(document.body, i)
2018                 if j == -1:
2019                         document.warning("Malformed LyX document: No end of InsetRef!")
2020                         i += 1
2021                         continue
2022                 k = find_token(document.body, "LatexCommand prettyref", i)
2023                 if k != -1 and k < j:
2024                         document.body[k] = "LatexCommand formatted"
2025                 i = j + 1
2026         document.header.insert(-1, "\\use_refstyle 0")
2027                 
2028  
2029 def revert_refstyle(document):
2030         " Reverts neutral formatted refs to prettyref "
2031         re_ref = re.compile("^reference\s+\"(\w+):(\S+)\"")
2032         nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
2033
2034         i = 0
2035         while True:
2036                 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
2037                 if i == -1:
2038                         break
2039                 j = find_end_of_inset(document.body, i)
2040                 if j == -1:
2041                         document.warning("Malformed LyX document: No end of InsetRef")
2042                         i += 1
2043                         continue
2044                 k = find_token(document.body, "LatexCommand formatted", i)
2045                 if k != -1 and k < j:
2046                         document.body[k] = "LatexCommand prettyref"
2047                 i = j + 1
2048         i = find_token(document.header, "\\use_refstyle", 0)
2049         if i != -1:
2050                 document.header.pop(i)
2051  
2052
2053 def revert_nameref(document):
2054   " Convert namerefs to regular references "
2055   cmds = ["Nameref", "nameref"]
2056   foundone = False
2057   rx = re.compile(r'reference "(.*)"')
2058   for cmd in cmds:
2059     i = 0
2060     oldcmd = "LatexCommand " + cmd
2061     while 1:
2062       # It seems better to look for this, as most of the reference
2063       # insets won't be ones we care about.
2064       i = find_token(document.body, oldcmd, i)
2065       if i == -1:
2066         break
2067       cmdloc = i
2068       i += 1
2069       # Make sure it is actually in an inset!
2070       # We could just check document.lines[i-1], but that relies
2071       # upon something that might easily change.
2072       # We'll look back a few lines.
2073       stins = cmdloc - 10
2074       if stins < 0:
2075         stins = 0
2076       stins = find_token(document.body, "\\begin_inset CommandInset ref", stins)
2077       if stins == -1 or stins > cmdloc:
2078         continue
2079       endins = find_end_of_inset(document.body, stins)
2080       if endins == -1:
2081         document.warning("Can't find end of inset at line " + stins + "!!")
2082         continue
2083       if endins < cmdloc:
2084         continue
2085       refline = find_token(document.body, "reference", stins)
2086       if refline == -1 or refline > endins:
2087         document.warning("Can't find reference for inset at line " + stinst + "!!")
2088         continue
2089       m = rx.match(document.body[refline])
2090       if not m:
2091         document.warning("Can't match reference line: " + document.body[ref])
2092         continue
2093       foundone = True
2094       ref = m.group(1)
2095       newcontent = ['\\begin_inset ERT', 'status collapsed', '', \
2096         '\\begin_layout Plain Layout', '', '\\backslash', \
2097         cmd + '{' + ref + '}', '\\end_layout', '', '\\end_inset']
2098       document.body[stins:endins + 1] = newcontent
2099   if foundone:
2100     add_to_preamble(document, "\usepackage{nameref}")
2101
2102
2103 def remove_Nameref(document):
2104   " Convert Nameref commands to nameref commands "
2105   i = 0
2106   while 1:
2107     # It seems better to look for this, as most of the reference
2108     # insets won't be ones we care about.
2109     i = find_token(document.body, "LatexCommand Nameref" , i)
2110     if i == -1:
2111       break
2112     cmdloc = i
2113     i += 1
2114     
2115     # Make sure it is actually in an inset!
2116     # We could just check document.lines[i-1], but that relies
2117     # upon something that might easily change.
2118     # We'll look back a few lines.
2119     stins = cmdloc - 10
2120     if stins < 0:
2121       stins = 0
2122     stins = find_token(document.body, "\\begin_inset CommandInset ref", stins)
2123     if stins == -1 or stins > cmdloc:
2124       continue
2125     endins = find_end_of_inset(document.body, stins)
2126     if endins == -1:
2127       document.warning("Can't find end of inset at line " + stins + "!!")
2128       continue
2129     if endins < cmdloc:
2130       continue
2131     document.body[cmdloc] = "LatexCommand nameref"
2132
2133
2134 def revert_mathrsfs(document):
2135     " Load mathrsfs if \mathrsfs us use in the document "
2136     i = 0
2137     end = len(document.body) - 1
2138     while True:
2139       j = document.body[i].find("\\mathscr{")
2140       if j != -1:
2141         add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
2142         add_to_preamble(document, ["\\usepackage{mathrsfs}"])
2143         break
2144       if i == end:
2145         break
2146       i += 1
2147
2148
2149 def convert_flexnames(document):
2150     "Convert \\begin_inset Flex Custom:Style to \\begin_inset Flex Style and similarly for CharStyle and Element."
2151     
2152     i = 0
2153     rx = re.compile(r'^\\begin_inset Flex (?:Custom|CharStyle|Element):(.+)$')
2154     while True:
2155       i = find_token(document.body, "\\begin_inset Flex", i)
2156       if i == -1:
2157         return
2158       m = rx.match(document.body[i])
2159       if m:
2160         document.body[i] = "\\begin_inset Flex " + m.group(1)
2161       i += 1
2162
2163
2164 flex_insets = [
2165   ["Alert", "CharStyle:Alert"],
2166   ["Code", "CharStyle:Code"],
2167   ["Concepts", "CharStyle:Concepts"],
2168   ["E-Mail", "CharStyle:E-Mail"],
2169   ["Emph", "CharStyle:Emph"],
2170   ["Expression", "CharStyle:Expression"],
2171   ["Initial", "CharStyle:Initial"],
2172   ["Institute", "CharStyle:Institute"],
2173   ["Meaning", "CharStyle:Meaning"],
2174   ["Noun", "CharStyle:Noun"],
2175   ["Strong", "CharStyle:Strong"],
2176   ["Structure", "CharStyle:Structure"],
2177   ["ArticleMode", "Custom:ArticleMode"],
2178   ["Endnote", "Custom:Endnote"],
2179   ["Glosse", "Custom:Glosse"],
2180   ["PresentationMode", "Custom:PresentationMode"],
2181   ["Tri-Glosse", "Custom:Tri-Glosse"]
2182 ]
2183
2184 flex_elements = [
2185   ["Abbrev", "Element:Abbrev"],
2186   ["CCC-Code", "Element:CCC-Code"],
2187   ["Citation-number", "Element:Citation-number"],
2188   ["City", "Element:City"],
2189   ["Code", "Element:Code"],
2190   ["CODEN", "Element:CODEN"],
2191   ["Country", "Element:Country"],
2192   ["Day", "Element:Day"],
2193   ["Directory", "Element:Directory"],
2194   ["Dscr", "Element:Dscr"],
2195   ["Email", "Element:Email"],
2196   ["Emph", "Element:Emph"],
2197   ["Filename", "Element:Filename"],
2198   ["Firstname", "Element:Firstname"],
2199   ["Fname", "Element:Fname"],
2200   ["GuiButton", "Element:GuiButton"],
2201   ["GuiMenu", "Element:GuiMenu"],
2202   ["GuiMenuItem", "Element:GuiMenuItem"],
2203   ["ISSN", "Element:ISSN"],
2204   ["Issue-day", "Element:Issue-day"],
2205   ["Issue-months", "Element:Issue-months"],
2206   ["Issue-number", "Element:Issue-number"],
2207   ["KeyCap", "Element:KeyCap"],
2208   ["KeyCombo", "Element:KeyCombo"],
2209   ["Keyword", "Element:Keyword"],
2210   ["Literal", "Element:Literal"],
2211   ["MenuChoice", "Element:MenuChoice"],
2212   ["Month", "Element:Month"],
2213   ["Orgdiv", "Element:Orgdiv"],
2214   ["Orgname", "Element:Orgname"],
2215   ["Postcode", "Element:Postcode"],
2216   ["SS-Code", "Element:SS-Code"],
2217   ["SS-Title", "Element:SS-Title"],
2218   ["State", "Element:State"],
2219   ["Street", "Element:Street"],
2220   ["Surname", "Element:Surname"],
2221   ["Volume", "Element:Volume"],
2222   ["Year", "Element:Year"]
2223 ]
2224
2225
2226 def revert_flexnames(document):
2227   if document.backend == "latex":
2228     flexlist = flex_insets
2229   else:
2230     flexlist = flex_elements
2231   
2232   rx = re.compile(r'^\\begin_inset Flex\s+(.+)$')
2233   i = 0
2234   while True:
2235     i = find_token(document.body, "\\begin_inset Flex", i)
2236     if i == -1:
2237       return
2238     m = rx.match(document.body[i])
2239     if not m:
2240       document.warning("Illegal flex inset: " + document.body[i])
2241       i += 1
2242       continue
2243     
2244     style = m.group(1)
2245     for f in flexlist:
2246       if f[0] == style:
2247         document.body[i] = "\\begin_inset Flex " + f[1]
2248         break
2249
2250     i += 1
2251
2252
2253 def convert_mathdots(document):
2254     " Load mathdots automatically "
2255     while True:
2256       i = find_token(document.header, "\\use_esint" , 0)
2257       if i != -1:
2258         document.header.insert(i + 1, "\\use_mathdots 1")
2259       break
2260
2261
2262 def revert_mathdots(document):
2263     " Load mathdots if used in the document "
2264     i = 0
2265     ddots = re.compile(r'\\begin_inset Formula .*\\ddots', re.DOTALL)
2266     vdots = re.compile(r'\\begin_inset Formula .*\\vdots', re.DOTALL)
2267     iddots = re.compile(r'\\begin_inset Formula .*\\iddots', re.DOTALL)
2268     mathdots = find_token(document.header, "\\use_mathdots" , 0)
2269     no = find_token(document.header, "\\use_mathdots 0" , 0)
2270     auto = find_token(document.header, "\\use_mathdots 1" , 0)
2271     yes = find_token(document.header, "\\use_mathdots 2" , 0)
2272     if mathdots != -1:
2273       del document.header[mathdots]
2274     while True:
2275       i = find_token(document.body, '\\begin_inset Formula', i)
2276       if i == -1:
2277         return
2278       j = find_end_of_inset(document.body, i)
2279       if j == -1:
2280         document.warning("Malformed LyX document: Can't find end of Formula inset.")
2281         return 
2282       k = ddots.search("\n".join(document.body[i:j]))
2283       l = vdots.search("\n".join(document.body[i:j]))
2284       m = iddots.search("\n".join(document.body[i:j]))
2285       if (yes == -1) and ((no != -1) or (not k and not l and not m) or (auto != -1 and not m)):
2286         i += 1
2287         continue
2288       # use \@ifundefined to catch also the "auto" case
2289       add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
2290       add_to_preamble(document, ["\\@ifundefined{iddots}{\\usepackage{mathdots}}\n"])
2291       return
2292
2293
2294 def convert_rule(document):
2295     " Convert \\lyxline to CommandInset line "
2296     i = 0
2297     while True:
2298       i = find_token(document.body, "\\lyxline" , i)
2299       if i == -1:
2300         return
2301         
2302       j = find_token(document.body, "\\color" , i - 2)
2303       if j == i - 2:
2304         color = document.body[j] + '\n'
2305       else:
2306         color = ''
2307       k = find_token(document.body, "\\begin_layout Standard" , i - 4)
2308       # we need to handle the case that \lyxline is in a separate paragraph and that it is colored
2309       # the result is then an extra empty paragraph which we get by adding an empty ERT inset
2310       if k == i - 4 and j == i - 2 and document.body[i - 1] == '':
2311         layout = '\\begin_inset ERT\nstatus collapsed\n\n\\begin_layout Plain Layout\n\n\n\\end_layout\n\n\\end_inset\n' \
2312           + '\\end_layout\n\n' \
2313           + '\\begin_layout Standard\n'
2314       elif k == i - 2 and document.body[i - 1] == '':
2315         layout = ''
2316       else:
2317         layout = '\\end_layout\n\n' \
2318           + '\\begin_layout Standard\n'
2319       l = find_token(document.body, "\\begin_layout Standard" , i + 4)
2320       if l == i + 4 and document.body[i + 1] == '':
2321         layout2 = ''
2322       else:
2323         layout2 = '\\end_layout\n' \
2324           + '\n\\begin_layout Standard\n'
2325       subst = layout \
2326         + '\\noindent\n\n' \
2327         + color \
2328         + '\\begin_inset CommandInset line\n' \
2329         + 'LatexCommand rule\n' \
2330         + 'offset "0.5ex"\n' \
2331         + 'width "100line%"\n' \
2332         + 'height "1pt"\n' \
2333         + '\n\\end_inset\n\n\n' \
2334         + layout2
2335       document.body[i] = subst
2336       i += 1
2337
2338
2339 def revert_rule(document):
2340     " Revert line insets to Tex code "
2341     i = 0
2342     while 1:
2343       i = find_token(document.body, "\\begin_inset CommandInset line" , i)
2344       if i == -1:
2345         return
2346       # find end of inset
2347       j = find_token(document.body, "\\end_inset" , i)
2348       # assure we found the end_inset of the current inset
2349       if j > i + 6 or j == -1:
2350         document.warning("Malformed LyX document: Can't find end of line inset.")
2351         return
2352       # determine the optional offset
2353       k = find_token(document.body, 'offset', i, j)
2354       if k != -1:
2355         offset = document.body[k][8:-1]
2356       else:
2357         offset = ""
2358       # determine the width
2359       l = find_token(document.body, 'width', i, j)
2360       if l != -1:
2361         width = document.body[l][7:-1]
2362       else:
2363         width = "100col%"
2364       # determine the height
2365       m = find_token(document.body, 'height', i, j)
2366       if m != -1:
2367         height = document.body[m][8:-1]
2368       else:
2369         height = "1pt"
2370       # output the \rule command
2371       if offset:
2372         subst = "\\rule[" + offset + "]{" + width + "}{" + height + "}"
2373       else:
2374         subst = "\\rule{" + width + "}{" + height + "}"
2375       document.body[i:j + 1] = put_cmd_in_ert(subst)
2376       i += 1
2377
2378
2379 def revert_diagram(document):
2380   " Add the feyn package if \\Diagram is used in math "
2381   i = 0
2382   re_diagram = re.compile(r'\\begin_inset Formula .*\\Diagram', re.DOTALL)
2383   while True:
2384     i = find_token(document.body, '\\begin_inset Formula', i)
2385     if i == -1:
2386       return
2387     j = find_end_of_inset(document.body, i)
2388     if j == -1:
2389         document.warning("Malformed LyX document: Can't find end of Formula inset.")
2390         return 
2391     m = re_diagram.search("\n".join(document.body[i:j]))
2392     if not m:
2393       i += 1
2394       continue
2395     add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
2396     add_to_preamble(document, "\\usepackage{feyn}")
2397     # only need to do it once!
2398     return
2399
2400
2401 def convert_bibtex_clearpage(document):
2402   " insert a clear(double)page bibliographystyle if bibtotoc option is used "
2403
2404   i = find_token(document.header, '\\papersides', 0)
2405   if i == -1:
2406     document.warning("Malformed LyX document: Can't find papersides definition.")
2407     return
2408   sides = int(document.header[i][12])
2409
2410   j = 0
2411   while True:
2412     j = find_token(document.body, "\\begin_inset CommandInset bibtex", j)
2413     if j == -1:
2414       return
2415
2416     k = find_end_of_inset(document.body, j)
2417     if k == -1:
2418       document.warning("Can't find end of Bibliography inset at line " + str(j))
2419       j += 1
2420       continue
2421
2422     # only act if there is the option "bibtotoc"
2423     m = find_token(document.body, 'options', j, k)
2424     if m == -1:
2425       document.warning("Can't find options for bibliography inset at line " + str(j))
2426       j = k
2427       continue
2428     
2429     optline = document.body[m]
2430     idx = optline.find("bibtotoc")
2431     if idx == -1:
2432       j = k
2433       continue
2434     
2435     # so we want to insert a new page right before the paragraph that
2436     # this bibliography thing is in. we'll look for it backwards.
2437     lay = j - 1
2438     while lay >= 0:
2439       if document.body[lay].startswith("\\begin_layout"):
2440         break
2441       lay -= 1
2442
2443     if lay < 0:
2444       document.warning("Can't find layout containing bibliography inset at line " + str(j))
2445       j = k
2446       continue
2447
2448     subst1 = '\\begin_layout Standard\n' \
2449       + '\\begin_inset Newpage clearpage\n' \
2450       + '\\end_inset\n\n\n' \
2451       + '\\end_layout\n'
2452     subst2 = '\\begin_layout Standard\n' \
2453       + '\\begin_inset Newpage cleardoublepage\n' \
2454       + '\\end_inset\n\n\n' \
2455       + '\\end_layout\n'
2456     if sides == 1:
2457       document.body.insert(lay, subst1)
2458       document.warning(subst1)
2459     else:
2460       document.body.insert(lay, subst2)
2461       document.warning(subst2)
2462
2463     j = k
2464
2465
2466 ##
2467 # Conversion hub
2468 #
2469
2470 supported_versions = ["2.0.0","2.0"]
2471 convert = [[346, []],
2472            [347, []],
2473            [348, []],
2474            [349, []],
2475            [350, []],
2476            [351, []],
2477            [352, [convert_splitindex]],
2478            [353, []],
2479            [354, []],
2480            [355, []],
2481            [356, []],
2482            [357, []],
2483            [358, []],
2484            [359, [convert_nomencl_width]],
2485            [360, []],
2486            [361, []],
2487            [362, []],
2488            [363, []],
2489            [364, []],
2490            [365, []],
2491            [366, []],
2492            [367, []],
2493            [368, []],
2494            [369, [convert_author_id]],
2495            [370, []],
2496            [371, []],
2497            [372, []],
2498            [373, [merge_gbrief]],
2499            [374, []],
2500            [375, []],
2501            [376, []],
2502            [377, []],
2503            [378, []],
2504            [379, [convert_math_output]],
2505            [380, []],
2506            [381, []],
2507            [382, []],
2508            [383, []],
2509            [384, []],
2510            [385, []],
2511            [386, []],
2512            [387, []],
2513            [388, []],
2514            [389, [convert_html_quotes]],
2515            [390, []],
2516            [391, []],
2517            [392, []],
2518            [393, [convert_optarg]],
2519            [394, [convert_use_makebox]],
2520            [395, []],
2521            [396, []],
2522            [397, [remove_Nameref]],
2523            [398, []],
2524            [399, [convert_mathdots]],
2525            [400, [convert_rule]],
2526            [401, []],
2527            [402, [convert_bibtex_clearpage]],
2528            [403, [convert_flexnames]],
2529            [404, [convert_prettyref]]
2530 ]
2531
2532 revert =  [[403, [revert_refstyle]],
2533            [402, [revert_flexnames]],
2534            [401, []],
2535            [400, [revert_diagram]],
2536            [399, [revert_rule]],
2537            [398, [revert_mathdots]],
2538            [397, [revert_mathrsfs]],
2539            [396, []],
2540            [395, [revert_nameref]],
2541            [394, [revert_DIN_C_pagesizes]],
2542            [393, [revert_makebox]],
2543            [392, [revert_argument]],
2544            [391, [revert_beamer_args]],
2545            [390, [revert_align_decimal, revert_IEEEtran]],
2546            [389, [revert_output_sync]],
2547            [388, [revert_html_quotes]],
2548            [387, [revert_pagesizes]],
2549            [386, [revert_math_scale]],
2550            [385, [revert_lyx_version]],
2551            [384, [revert_shadedboxcolor]],
2552            [383, [revert_fontcolor]],
2553            [382, [revert_turkmen]],
2554            [381, [revert_notefontcolor]],
2555            [380, [revert_equalspacing_xymatrix]],
2556            [379, [revert_inset_preview]],
2557            [378, [revert_math_output]],
2558            [377, []],
2559            [376, [revert_multirow]],
2560            [375, [revert_includeall]],
2561            [374, [revert_includeonly]],
2562            [373, [revert_html_options]],
2563            [372, [revert_gbrief]],
2564            [371, [revert_fontenc]],
2565            [370, [revert_mhchem]],
2566            [369, [revert_suppress_date]],
2567            [368, [revert_author_id]],
2568            [367, [revert_hspace_glue_lengths]],
2569            [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
2570            [365, [revert_percent_skip_lengths]],
2571            [364, [revert_paragraph_indentation]],
2572            [363, [revert_branch_filename]],
2573            [362, [revert_longtable_align]],
2574            [361, [revert_applemac]],
2575            [360, []],
2576            [359, [revert_nomencl_cwidth]],
2577            [358, [revert_nomencl_width]],
2578            [357, [revert_custom_processors]],
2579            [356, [revert_ulinelatex]],
2580            [355, []],
2581            [354, [revert_strikeout]],
2582            [353, [revert_printindexall]],
2583            [352, [revert_subindex]],
2584            [351, [revert_splitindex]],
2585            [350, [revert_backgroundcolor]],
2586            [349, [revert_outputformat]],
2587            [348, [revert_xetex]],
2588            [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2589            [346, [revert_tabularvalign]],
2590            [345, [revert_swiss]]
2591           ]
2592
2593
2594 if __name__ == "__main__":
2595     pass