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