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