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