]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_2_0.py
4af886bfa6c41daae6f8cef4f2cb7679beff8551
[lyx.git] / lib / lyx2lyx / lyx_2_0.py
1 # -*- coding: utf-8 -*-
2 # This file is part of lyx2lyx
3 # -*- coding: utf-8 -*-
4 # Copyright (C) 2010 The LyX team
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 """ Convert files to the file format generated by lyx 2.0"""
21
22 import re, string
23 import unicodedata
24 import sys, os
25
26 from parser_tools import find_token, find_end_of, find_tokens, get_value, get_value_string
27
28 ####################################################################
29 # Private helper functions
30
31 def remove_option(document, m, option):
32     l = document.body[m].find(option)
33     if l != -1:
34         val = document.body[m][l:].split('"')[1]
35         document.body[m] = document.body[m][:l - 1] + document.body[m][l+len(option + '="' + val + '"'):]
36     return l
37
38 def find_end_of_inset(lines, i):
39     " Find end of inset, where lines[i] is included."
40     return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
41
42
43 # Note that text can be either a list of lines or a single line.
44 def add_to_preamble(document, text):
45     """ Add text to the preamble if it is not already there.
46     Only the first line is checked!"""
47
48     if not type(text) is list:
49       # split on \n just in case
50       # it'll give us the one element list we want
51       # if there's no \n, too
52       text = text.split('\n')
53
54     if find_token(document.preamble, text[0], 0) != -1:
55         return
56
57     document.preamble.extend(text)
58
59
60 def insert_to_preamble(index, document, text):
61     """ Insert text to the preamble at a given line"""
62
63     document.preamble.insert(index, text)
64
65
66 def read_unicodesymbols():
67     " Read the unicodesymbols list of unicode characters and corresponding commands."
68     pathname = os.path.abspath(os.path.dirname(sys.argv[0]))
69     fp = open(os.path.join(pathname.strip('lyx2lyx'), 'unicodesymbols'))
70     spec_chars = []
71     # Two backslashes, followed by some non-word character, and then a character
72     # in brackets. The idea is to check for constructs like: \"{u}, which is how
73     # they are written in the unicodesymbols file; but they can also be written
74     # as: \"u or even \" u.
75     r = re.compile(r'\\\\(\W)\{(\w)\}')
76     for line in fp.readlines():
77         if line[0] != '#' and line.strip() != "":
78             line=line.replace(' "',' ') # remove all quotation marks with spaces before
79             line=line.replace('" ',' ') # remove all quotation marks with spaces after
80             line=line.replace(r'\"','"') # replace \" by " (for characters with diaeresis)
81             try:
82                 [ucs4,command,dead] = line.split(None,2)
83                 if command[0:1] != "\\":
84                     continue
85                 spec_chars.append([command, unichr(eval(ucs4))])
86             except:
87                 continue
88             m = r.match(command)
89             if m != None:
90                 command = "\\\\"
91                 # If the character is a double-quote, then we need to escape it, too,
92                 # since it is done that way in the LyX file.
93                 if m.group(1) == "\"":
94                     command += "\\"
95                 commandbl = command
96                 command += m.group(1) + m.group(2)
97                 commandbl += m.group(1) + ' ' + m.group(2)
98                 spec_chars.append([command, unichr(eval(ucs4))])
99                 spec_chars.append([commandbl, unichr(eval(ucs4))])
100     fp.close()
101     return spec_chars
102
103
104 unicode_reps = read_unicodesymbols()
105
106
107 # DO NOT USE THIS ROUTINE ANY MORE. Better yet, replace the uses that
108 # have been made of it with uses of put_cmd_in_ert.
109 def old_put_cmd_in_ert(string):
110     for rep in unicode_reps:
111         string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
112     string = string.replace('\\', "\\backslash\n")
113     string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
114       + string + "\n\\end_layout\n\\end_inset"
115     return string
116
117
118 # This routine wraps some content in an ERT inset. 
119 #
120 # NOTE: The function accepts either a single string or a LIST of strings as
121 # argument. But it returns a LIST of strings, split on \n, so that it does 
122 # not have embedded newlines.
123
124 # This is how lyx2lyx represents a LyX document: as a list of strings, 
125 # each representing a line of a LyX file. Embedded newlines confuse 
126 # lyx2lyx very much.
127 #
128 # A call to this routine will often go something like this:
129 #   i = find_token('\\begin_inset FunkyInset', ...)
130 #   ...
131 #   j = find_end_of_inset(document.body, i)
132 #   content = ...extract content from insets
133 #   # that could be as simple as: 
134 #   # content = lyx2latex(document[i:j + 1])
135 #   ert = put_cmd_in_ert(content)
136 #   document.body[i:j] = ert
137 # Now, before we continue, we need to reset i appropriately. Normally,
138 # this would be: 
139 #   i += len(ert)
140 # That puts us right after the ERT we just inserted.
141 #
142 def put_cmd_in_ert(arg):
143     ret = ["\\begin_inset ERT", "status collapsed", "\\begin_layout Plain Layout", ""]
144     # Despite the warnings just given, it will be faster for us to work
145     # with a single string internally. That way, we only go through the
146     # unicode_reps loop once.
147     if type(arg) is list:
148       s = "\n".join(arg)
149     else:
150       s = arg
151     for rep in unicode_reps:
152       s = s.replace(rep[1], rep[0].replace('\\\\', '\\'))
153     s = s.replace('\\', "\\backslash\n")
154     ret += s.splitlines()
155     ret += ["\\end_layout", "\\end_inset"]
156     return ret
157
158             
159 def lyx2latex(document, lines):
160     'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
161     # clean up multiline stuff
162     content = ""
163     ert_end = 0
164     note_end = 0
165     hspace = ""
166
167     for curline in range(len(lines)):
168       line = lines[curline]
169       if line.startswith("\\begin_inset Note Note"):
170           # We want to skip LyX notes, so remember where the inset ends
171           note_end = find_end_of_inset(lines, curline + 1)
172           continue
173       elif note_end >= curline:
174           # Skip LyX notes
175           continue
176       elif line.startswith("\\begin_inset ERT"):
177           # We don't want to replace things inside ERT, so figure out
178           # where the end of the inset is.
179           ert_end = find_end_of_inset(lines, curline + 1)
180           continue
181       elif line.startswith("\\begin_inset Formula"):
182           line = line[20:]
183       elif line.startswith("\\begin_inset Quotes"):
184           # For now, we do a very basic reversion. Someone who understands
185           # quotes is welcome to fix it up.
186           qtype = line[20:].strip()
187           # lang = qtype[0]
188           side = qtype[1]
189           dbls = qtype[2]
190           if side == "l":
191               if dbls == "d":
192                   line = "``"
193               else:
194                   line = "`"
195           else:
196               if dbls == "d":
197                   line = "''"
198               else:
199                   line = "'"
200       elif line.startswith("\\begin_inset space"):
201           line = line[18:].strip()
202           if line.startswith("\\hspace"):
203               # Account for both \hspace and \hspace*
204               hspace = line[:-2]
205               continue
206           elif line == "\\space{}":
207               line = "\\ "
208           elif line == "\\thinspace{}":
209               line = "\\,"
210       elif hspace != "":
211           # The LyX length is in line[8:], after the \length keyword
212           # latex_length returns "bool,length"
213           length = latex_length(line[8:]).split(",")[1]
214           line = hspace + "{" + length + "}"
215           hspace = ""
216       elif line.isspace() or \
217             line.startswith("\\begin_layout") or \
218             line.startswith("\\end_layout") or \
219             line.startswith("\\begin_inset") or \
220             line.startswith("\\end_inset") or \
221             line.startswith("\\lang") or \
222             line.strip() == "status collapsed" or \
223             line.strip() == "status open":
224           #skip all that stuff
225           continue
226
227       # this needs to be added to the preamble because of cases like
228       # \textmu, \textbackslash, etc.
229       add_to_preamble(document, ['% added by lyx2lyx for converted index entries',
230                                  '\\@ifundefined{textmu}',
231                                  ' {\\usepackage{textcomp}}{}'])
232       # a lossless reversion is not possible
233       # try at least to handle some common insets and settings
234       if ert_end >= curline:
235           line = line.replace(r'\backslash', '\\')
236       else:
237           # No need to add "{}" after single-nonletter macros
238           line = line.replace('&', '\\&')
239           line = line.replace('#', '\\#')
240           line = line.replace('^', '\\textasciicircum{}')
241           line = line.replace('%', '\\%')
242           line = line.replace('_', '\\_')
243           line = line.replace('$', '\\$')
244
245           # Do the LyX text --> LaTeX conversion
246           for rep in unicode_reps:
247             line = line.replace(rep[1], rep[0] + "{}")
248           line = line.replace(r'\backslash', r'\textbackslash{}')
249           line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
250           line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
251           line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
252           line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
253           line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
254           line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
255           line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
256           line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
257           line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
258       content += line
259     return content
260
261
262 def latex_length(string):
263     'Convert lengths to their LaTeX representation.'
264     i = 0
265     percent = False
266     # the string has the form
267     # ValueUnit+ValueUnit-ValueUnit or
268     # ValueUnit+-ValueUnit
269     # the + and - (glue lengths) are optional
270     # the + always precedes the -
271
272     # Convert relative lengths to LaTeX units
273     units = {"text%":"\\textwidth", "col%":"\\columnwidth",
274              "page%":"\\paperwidth", "line%":"\\linewidth",
275              "theight%":"\\textheight", "pheight%":"\\paperheight"}
276     for unit in units.keys():
277         i = string.find(unit)
278         if i != -1:
279             percent = True
280             minus = string.rfind("-", 1, i)
281             plus = string.rfind("+", 0, i)
282             latex_unit = units[unit]
283             if plus == -1 and minus == -1:
284                 value = string[:i]
285                 value = str(float(value)/100)
286                 end = string[i + len(unit):]
287                 string = value + latex_unit + end
288             if plus > minus:
289                 value = string[plus + 1:i]
290                 value = str(float(value)/100)
291                 begin = string[:plus + 1]
292                 end = string[i+len(unit):]
293                 string = begin + value + latex_unit + end
294             if plus < minus:
295                 value = string[minus + 1:i]
296                 value = str(float(value)/100)
297                 begin = string[:minus + 1]
298                 string = begin + value + latex_unit
299
300     # replace + and -, but only if the - is not the first character
301     string = string[0] + string[1:].replace("+", " plus ").replace("-", " minus ")
302     # handle the case where "+-1mm" was used, because LaTeX only understands
303     # "plus 1mm minus 1mm"
304     if string.find("plus  minus"):
305         lastvaluepos = string.rfind(" ")
306         lastvalue = string[lastvaluepos:]
307         string = string.replace("  ", lastvalue + " ")
308     if percent ==  False:
309         return "False," + string
310     else:
311         return "True," + string
312
313
314 def revert_flex_inset(document, name, LaTeXname, position):
315   " Convert flex insets to TeX code "
316   i = position
317   while True:
318     i = find_token(document.body, '\\begin_inset Flex ' + name, i)
319     if i == -1:
320       return
321     z = find_end_of_inset(document.body, i)
322     if z == -1:
323       document.warning("Malformed LyX document: Can't find end of Flex " + name + " inset.")
324       return
325     # remove the \end_inset
326     document.body[z - 2:z + 1] = put_cmd_in_ert("}")
327     # we need to reset character layouts if necessary
328     j = find_token(document.body, '\\emph on', i, z)
329     k = find_token(document.body, '\\noun on', i, z)
330     l = find_token(document.body, '\\series', i, z)
331     m = find_token(document.body, '\\family', i, z)
332     n = find_token(document.body, '\\shape', i, z)
333     o = find_token(document.body, '\\color', i, z)
334     p = find_token(document.body, '\\size', i, z)
335     q = find_token(document.body, '\\bar under', i, z)
336     r = find_token(document.body, '\\uuline on', i, z)
337     s = find_token(document.body, '\\uwave on', i, z)
338     t = find_token(document.body, '\\strikeout on', i, z)
339     if j != -1:
340       document.body.insert(z - 2, "\\emph default")
341     if k != -1:
342       document.body.insert(z - 2, "\\noun default")
343     if l != -1:
344       document.body.insert(z - 2, "\\series default")
345     if m != -1:
346       document.body.insert(z - 2, "\\family default")
347     if n != -1:
348       document.body.insert(z - 2, "\\shape default")
349     if o != -1:
350       document.body.insert(z - 2, "\\color inherit")
351     if p != -1:
352       document.body.insert(z - 2, "\\size default")
353     if q != -1:
354       document.body.insert(z - 2, "\\bar default")
355     if r != -1:
356       document.body.insert(z - 2, "\\uuline default")
357     if s != -1:
358       document.body.insert(z - 2, "\\uwave default")
359     if t != -1:
360       document.body.insert(z - 2, "\\strikeout default")
361     document.body[i:i + 4] = put_cmd_in_ert(LaTeXname + "{")
362     i += 1
363
364
365 def revert_font_attrs(document, name, LaTeXname):
366   " Reverts font changes to TeX code "
367   i = 0
368   changed = False
369   while True:
370     i = find_token(document.body, name + ' on', i)
371     if i == -1:
372       return changed
373     j = find_token(document.body, name + ' default', i)
374     k = find_token(document.body, name + ' on', i + 1)
375     # if there is no default set, the style ends with the layout
376     # assure hereby that we found the correct layout end
377     if j != -1 and (j < k or k == -1):
378       document.body[j:j + 1] = put_cmd_in_ert("}")
379     else:
380       j = find_token(document.body, '\\end_layout', i)
381       document.body[j:j] = put_cmd_in_ert("}")
382     document.body[i:i + 1] = put_cmd_in_ert(LaTeXname + "{")
383     changed = True
384     i += 1
385
386
387 def revert_layout_command(document, name, LaTeXname, position):
388   " Reverts a command from a layout to TeX code "
389   i = position
390   while True:
391     i = find_token(document.body, '\\begin_layout ' + name, i)
392     if i == -1:
393       return
394     k = -1
395     # find the next layout
396     j = i + 1
397     while k == -1:
398       j = find_token(document.body, '\\begin_layout', j)
399       l = len(document.body)
400       # if nothing was found it was the last layout of the document
401       if j == -1:
402         document.body[l - 4:l - 4] = put_cmd_in_ert("}")
403         k = 0
404       # exclude plain layout because this can be TeX code or another inset
405       elif document.body[j] != '\\begin_layout Plain Layout':
406         document.body[j - 2:j - 2] = put_cmd_in_ert("}")
407         k = 0
408       else:
409         j += 1
410     document.body[i] = '\\begin_layout Standard'
411     document.body[i + 1:i + 1] = put_cmd_in_ert(LaTeXname + "{")
412     i += 1
413
414
415 ###############################################################################
416 ###
417 ### Conversion and reversion routines
418 ###
419 ###############################################################################
420
421 def revert_swiss(document):
422     " Set language german-ch to ngerman "
423     i = 0
424     if document.language == "german-ch":
425         document.language = "ngerman"
426         i = find_token(document.header, "\\language", 0)
427         if i != -1:
428             document.header[i] = "\\language ngerman"
429     j = 0
430     while True:
431         j = find_token(document.body, "\\lang german-ch", j)
432         if j == -1:
433             return
434         document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
435         j = j + 1
436
437
438 def revert_tabularvalign(document):
439    " Revert the tabular valign option "
440    i = 0
441    while True:
442       i = find_token(document.body, "\\begin_inset Tabular", i)
443       if i == -1:
444           return
445       end = find_end_of_inset(document.body, i)
446       if end == -1:
447           document.warning("Can't find end of inset at line " + str(i))
448           i = j
449           continue
450       fline = find_token(document.body, "<features", i, end)
451       if fline == -1:
452           document.warning("Can't find features for inset at line " + str(i))
453           i = end
454           continue
455       p = document.body[fline].find("islongtable")
456       if p != -1:
457           q = document.body[fline].find("tabularvalignment")
458           if q != -1:
459               # FIXME
460               # This seems wrong: It removes everything after 
461               # tabularvalignment, too.
462               document.body[fline] = document.body[fline][:q - 1] + '>'
463           i = end
464           continue
465
466        # no longtable
467       tabularvalignment = 'c'
468       # which valignment is specified?
469       m = document.body[fline].find('tabularvalignment="top"')
470       if m != -1:
471           tabularvalignment = 't'
472       m = document.body[fline].find('tabularvalignment="bottom"')
473       if m != -1:
474           tabularvalignment = 'b'
475       # delete tabularvalignment
476       q = document.body[fline].find("tabularvalignment")
477       if q != -1:
478           # FIXME
479           # This seems wrong: It removes everything after 
480           # tabularvalignment, too.
481           document.body[fline] = document.body[fline][:q - 1] + '>'
482
483       # don't add a box when centered
484       if tabularvalignment == 'c':
485           i = end
486           continue
487       subst = ['\\end_layout', '\\end_inset']
488       document.body[end:end] = subst # just inserts those lines
489       subst = ['\\begin_inset Box Frameless',
490           'position "' + tabularvalignment +'"',
491           'hor_pos "c"',
492           'has_inner_box 1',
493           'inner_pos "c"',
494           'use_parbox 0',
495           # we don't know the width, assume 50%
496           'width "50col%"',
497           'special "none"',
498           'height "1in"',
499           'height_special "totalheight"',
500           'status open',
501           '',
502           '\\begin_layout Plain Layout']
503       document.body[i:i] = subst # this just inserts the array at i
504       i = end + len(subst) # adjust i to save a few cycles
505
506
507 def revert_phantom_types(document, ptype, cmd):
508     " Reverts phantom to ERT "
509     i = 0
510     while True:
511       i = find_token(document.body, "\\begin_inset Phantom " + ptype, i)
512       if i == -1:
513           return
514       end = find_end_of_inset(document.body, i)
515       if end == -1:
516           document.warning("Can't find end of inset at line " + str(i))
517           i += 1
518           continue
519       blay = find_token(document.body, "\\begin_layout Plain Layout", i, end)
520       if blay == -1:
521           document.warning("Can't find layout for inset at line " + str(i))
522           i = end
523           continue
524       bend = find_token(document.body, "\\end_layout", blay, end)
525       if bend == -1:
526           document.warning("Malformed LyX document: Could not find end of Phantom inset's layout.")
527           i = end
528           continue
529       substi = ["\\begin_inset ERT", "status collapsed", "",
530                 "\\begin_layout Plain Layout", "", "", "\\backslash", 
531                 cmd + "{", "\\end_layout", "", "\\end_inset"]
532       substj = ["\\size default", "", "\\begin_inset ERT", "status collapsed", "",
533                 "\\begin_layout Plain Layout", "", "}", "\\end_layout", "", "\\end_inset"]
534       # do the later one first so as not to mess up the numbering
535       document.body[bend:end + 1] = substj
536       document.body[i:blay + 1] = substi
537       i = end + len(substi) + len(substj) - (end - bend) - (blay - i) - 2
538
539
540 def revert_phantom(document):
541     revert_phantom_types(document, "Phantom", "phantom")
542     
543 def revert_hphantom(document):
544     revert_phantom_types(document, "HPhantom", "hphantom")
545
546 def revert_vphantom(document):
547     revert_phantom_types(document, "VPhantom", "vphantom")
548
549
550 def revert_xetex(document):
551     " Reverts documents that use XeTeX "
552     i = find_token(document.header, '\\use_xetex', 0)
553     if i == -1:
554         document.warning("Malformed LyX document: Missing \\use_xetex.")
555         return
556     if get_value(document.header, "\\use_xetex", i) == 'false':
557         del document.header[i]
558         return
559     del document.header[i]
560     # 1.) set doc encoding to utf8-plain
561     i = find_token(document.header, "\\inputencoding", 0)
562     if i == -1:
563         document.warning("Malformed LyX document: Missing \\inputencoding.")
564     document.header[i] = "\\inputencoding utf8-plain"
565     # 2.) check font settings
566     l = find_token(document.header, "\\font_roman", 0)
567     if l == -1:
568         document.warning("Malformed LyX document: Missing \\font_roman.")
569     line = document.header[l]
570     l = re.compile(r'\\font_roman (.*)$')
571     m = l.match(line)
572     roman = m.group(1)
573     l = find_token(document.header, "\\font_sans", 0)
574     if l == -1:
575         document.warning("Malformed LyX document: Missing \\font_sans.")
576     line = document.header[l]
577     l = re.compile(r'\\font_sans (.*)$')
578     m = l.match(line)
579     sans = m.group(1)
580     l = find_token(document.header, "\\font_typewriter", 0)
581     if l == -1:
582         document.warning("Malformed LyX document: Missing \\font_typewriter.")
583     line = document.header[l]
584     l = re.compile(r'\\font_typewriter (.*)$')
585     m = l.match(line)
586     typewriter = m.group(1)
587     osf = get_value(document.header, '\\font_osf', 0) == "true"
588     sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
589     tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
590     # 3.) set preamble stuff
591     pretext = '%% This document must be processed with xelatex!\n'
592     pretext += '\\usepackage{fontspec}\n'
593     if roman != "default":
594         pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
595     if sans != "default":
596         pretext += '\\setsansfont['
597         if sf_scale != 100:
598             pretext += 'Scale=' + str(sf_scale / 100) + ','
599         pretext += 'Mapping=tex-text]{' + sans + '}\n'
600     if typewriter != "default":
601         pretext += '\\setmonofont'
602         if tt_scale != 100:
603             pretext += '[Scale=' + str(tt_scale / 100) + ']'
604         pretext += '{' + typewriter + '}\n'
605     if osf:
606         pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
607     pretext += '\usepackage{xunicode}\n'
608     pretext += '\usepackage{xltxtra}\n'
609     insert_to_preamble(0, document, pretext)
610     # 4.) reset font settings
611     i = find_token(document.header, "\\font_roman", 0)
612     if i == -1:
613         document.warning("Malformed LyX document: Missing \\font_roman.")
614     document.header[i] = "\\font_roman default"
615     i = find_token(document.header, "\\font_sans", 0)
616     if i == -1:
617         document.warning("Malformed LyX document: Missing \\font_sans.")
618     document.header[i] = "\\font_sans default"
619     i = find_token(document.header, "\\font_typewriter", 0)
620     if i == -1:
621         document.warning("Malformed LyX document: Missing \\font_typewriter.")
622     document.header[i] = "\\font_typewriter default"
623     i = find_token(document.header, "\\font_osf", 0)
624     if i == -1:
625         document.warning("Malformed LyX document: Missing \\font_osf.")
626     document.header[i] = "\\font_osf false"
627     i = find_token(document.header, "\\font_sc", 0)
628     if i == -1:
629         document.warning("Malformed LyX document: Missing \\font_sc.")
630     document.header[i] = "\\font_sc false"
631     i = find_token(document.header, "\\font_sf_scale", 0)
632     if i == -1:
633         document.warning("Malformed LyX document: Missing \\font_sf_scale.")
634     document.header[i] = "\\font_sf_scale 100"
635     i = find_token(document.header, "\\font_tt_scale", 0)
636     if i == -1:
637         document.warning("Malformed LyX document: Missing \\font_tt_scale.")
638     document.header[i] = "\\font_tt_scale 100"
639
640
641 def revert_outputformat(document):
642     " Remove default output format param "
643     i = find_token(document.header, '\\default_output_format', 0)
644     if i == -1:
645         document.warning("Malformed LyX document: Missing \\default_output_format.")
646         return
647     del document.header[i]
648
649
650 def hex2ratio(s):
651     val = string.atoi(s, 16)
652     if val != 0:
653       val += 1
654     return str(val / 256.0)
655
656
657 def revert_backgroundcolor(document):
658     " Reverts background color to preamble code "
659     i = find_token(document.header, "\\backgroundcolor", 0)
660     if i == -1:
661         return
662     colorcode = get_value(document.header, '\\backgroundcolor', i)
663     del document.header[i]
664     # don't clutter the preamble if backgroundcolor is not set
665     if colorcode == "#ffffff":
666         return
667     red   = hex2ratio(colorcode[1:3])
668     green = hex2ratio(colorcode[3:5])
669     blue  = hex2ratio(colorcode[5:7])
670     insert_to_preamble(0, document,
671                           '% Commands inserted by lyx2lyx to set the background color\n'
672                           + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
673                           + '\\definecolor{page_backgroundcolor}{rgb}{'
674                           + red + ',' + green + ',' + blue + '}\n'
675                           + '\\pagecolor{page_backgroundcolor}\n')
676
677
678 def revert_splitindex(document):
679     " Reverts splitindex-aware documents "
680     i = find_token(document.header, '\\use_indices', 0)
681     if i == -1:
682         document.warning("Malformed LyX document: Missing \\use_indices.")
683         return
684     indices = get_value(document.header, "\\use_indices", i)
685     preamble = ""
686     useindices = (indices == "true")
687     if useindices:
688          preamble += "\\usepackage{splitidx}\n"
689     del document.header[i]
690     
691     # deal with index declarations in the preamble
692     i = 0
693     while True:
694         i = find_token(document.header, "\\index", i)
695         if i == -1:
696             break
697         k = find_token(document.header, "\\end_index", i)
698         if k == -1:
699             document.warning("Malformed LyX document: Missing \\end_index.")
700             return
701         if useindices:    
702           line = document.header[i]
703           l = re.compile(r'\\index (.*)$')
704           m = l.match(line)
705           iname = m.group(1)
706           ishortcut = get_value(document.header, '\\shortcut', i, k)
707           if ishortcut != "":
708               preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
709         del document.header[i:k + 1]
710     if preamble != "":
711         insert_to_preamble(0, document, preamble)
712         
713     # deal with index insets
714     # these need to have the argument removed
715     i = 0
716     while True:
717         i = find_token(document.body, "\\begin_inset Index", i)
718         if i == -1:
719             break
720         line = document.body[i]
721         l = re.compile(r'\\begin_inset Index (.*)$')
722         m = l.match(line)
723         itype = m.group(1)
724         if itype == "idx" or indices == "false":
725             document.body[i] = "\\begin_inset Index"
726         else:
727             k = find_end_of_inset(document.body, i)
728             if k == -1:
729                 document.warning("Can't find end of index inset!")
730                 i += 1
731                 continue
732             content = lyx2latex(document, document.body[i:k])
733             # escape quotes
734             content = content.replace('"', r'\"')
735             subst = put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")
736             document.body[i:k + 1] = subst
737         i = i + 1
738         
739     # deal with index_print insets
740     i = 0
741     while True:
742         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
743         if i == -1:
744             return
745         k = find_end_of_inset(document.body, i)
746         ptype = get_value(document.body, 'type', i, k).strip('"')
747         if ptype == "idx":
748             j = find_token(document.body, "type", i, k)
749             del document.body[j]
750         elif not useindices:
751             del document.body[i:k + 1]
752         else:
753             subst = put_cmd_in_ert("\\printindex[" + ptype + "]{}")
754             document.body[i:k + 1] = subst
755         i = i + 1
756
757
758 def convert_splitindex(document):
759     " Converts index and printindex insets to splitindex-aware format "
760     i = 0
761     while True:
762         i = find_token(document.body, "\\begin_inset Index", i)
763         if i == -1:
764             break
765         document.body[i] = document.body[i].replace("\\begin_inset Index",
766             "\\begin_inset Index idx")
767         i = i + 1
768     i = 0
769     while True:
770         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
771         if i == -1:
772             return
773         if document.body[i + 1].find('LatexCommand printindex') == -1:
774             document.warning("Malformed LyX document: Incomplete printindex inset.")
775             return
776         subst = ["LatexCommand printindex", 
777             "type \"idx\""]
778         document.body[i + 1:i + 2] = subst
779         i = i + 1
780
781
782 def revert_subindex(document):
783     " Reverts \\printsubindex CommandInset types "
784     i = find_token(document.header, '\\use_indices', 0)
785     if i == -1:
786         document.warning("Malformed LyX document: Missing \\use_indices.")
787         return
788     indices = get_value(document.header, "\\use_indices", i)
789     useindices = (indices == "true")
790     i = 0
791     while True:
792         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
793         if i == -1:
794             return
795         k = find_end_of_inset(document.body, i)
796         ctype = get_value(document.body, 'LatexCommand', i, k)
797         if ctype != "printsubindex":
798             i = k + 1
799             continue
800         ptype = get_value(document.body, 'type', i, k).strip('"')
801         if not useindices:
802             del document.body[i:k + 1]
803         else:
804             subst = put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")
805             document.body[i:k + 1] = subst
806         i = i + 1
807
808
809 def revert_printindexall(document):
810     " Reverts \\print[sub]index* CommandInset types "
811     i = find_token(document.header, '\\use_indices', 0)
812     if i == -1:
813         document.warning("Malformed LyX document: Missing \\use_indices.")
814         return
815     indices = get_value(document.header, "\\use_indices", i)
816     useindices = (indices == "true")
817     i = 0
818     while True:
819         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
820         if i == -1:
821             return
822         k = find_end_of_inset(document.body, i)
823         ctype = get_value(document.body, 'LatexCommand', i, k)
824         if ctype != "printindex*" and ctype != "printsubindex*":
825             i = k
826             continue
827         if not useindices:
828             del document.body[i:k + 1]
829         else:
830             subst = put_cmd_in_ert("\\" + ctype + "{}")
831             document.body[i:k + 1] = subst
832         i = i + 1
833
834
835 def revert_strikeout(document):
836   " Reverts \\strikeout font attribute "
837   changed = revert_font_attrs(document, "\\uuline", "\\uuline")
838   changed = revert_font_attrs(document, "\\uwave", "\\uwave") or changed
839   changed = revert_font_attrs(document, "\\strikeout", "\\sout")  or changed
840   if changed == True:
841     insert_to_preamble(0, document,
842         '% Commands inserted by lyx2lyx for proper underlining\n'
843         + '\\PassOptionsToPackage{normalem}{ulem}\n'
844         + '\\usepackage{ulem}\n')
845
846
847 def revert_ulinelatex(document):
848     " Reverts \\uline font attribute "
849     i = find_token(document.body, '\\bar under', 0)
850     if i == -1:
851         return
852     insert_to_preamble(0, document,
853             '% Commands inserted by lyx2lyx for proper underlining\n'
854             + '\\PassOptionsToPackage{normalem}{ulem}\n'
855             + '\\usepackage{ulem}\n'
856             + '\\let\\cite@rig\\cite\n'
857             + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
858             + '  \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
859             + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
860
861
862 def revert_custom_processors(document):
863     " Remove bibtex_command and index_command params "
864     i = find_token(document.header, '\\bibtex_command', 0)
865     if i == -1:
866         document.warning("Malformed LyX document: Missing \\bibtex_command.")
867     else:
868         del document.header[i]
869     i = find_token(document.header, '\\index_command', 0)
870     if i == -1:
871         document.warning("Malformed LyX document: Missing \\index_command.")
872     else:
873         del document.header[i]
874
875
876 def convert_nomencl_width(document):
877     " Add set_width param to nomencl_print "
878     i = 0
879     while True:
880       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
881       if i == -1:
882         break
883       document.body.insert(i + 2, "set_width \"none\"")
884       i = i + 1
885
886
887 def revert_nomencl_width(document):
888     " Remove set_width param from nomencl_print "
889     i = 0
890     while True:
891       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
892       if i == -1:
893         break
894       j = find_end_of_inset(document.body, i)
895       l = find_token(document.body, "set_width", i, j)
896       if l == -1:
897             document.warning("Can't find set_width option for nomencl_print!")
898             i = j
899             continue
900       del document.body[l]
901       i = i + 1
902
903
904 def revert_nomencl_cwidth(document):
905     " Remove width param from nomencl_print "
906     i = 0
907     while True:
908       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
909       if i == -1:
910         break
911       j = find_end_of_inset(document.body, i)
912       l = find_token(document.body, "width", i, j)
913       if l == -1:
914             #Can't find width option for nomencl_print
915             i = j
916             continue
917       width = get_value(document.body, "width", i, j).strip('"')
918       del document.body[l]
919       add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
920       add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
921       i = i + 1
922
923
924 def revert_applemac(document):
925     " Revert applemac encoding to auto "
926     i = 0
927     if document.encoding == "applemac":
928         document.encoding = "auto"
929         i = find_token(document.header, "\\encoding", 0)
930         if i != -1:
931             document.header[i] = "\\encoding auto"
932
933
934 def revert_longtable_align(document):
935     " Remove longtable alignment setting "
936     i = 0
937     j = 0
938     while True:
939       i = find_token(document.body, "\\begin_inset Tabular", i)
940       if i == -1:
941           break
942       # the alignment is 2 lines below \\begin_inset Tabular
943       j = document.body[i + 2].find("longtabularalignment")
944       if j == -1:
945           break
946       document.body[i + 2] = document.body[i + 2][:j - 1]
947       document.body[i + 2] = document.body[i + 2] + '>'
948       i = i + 1
949
950
951 def revert_branch_filename(document):
952     " Remove \\filename_suffix parameter from branches "
953     i = 0
954     while True:
955         i = find_token(document.header, "\\filename_suffix", i)
956         if i == -1:
957             return
958         del document.header[i]
959
960
961 def revert_paragraph_indentation(document):
962     " Revert custom paragraph indentation to preamble code "
963     i = 0
964     while True:
965       i = find_token(document.header, "\\paragraph_indentation", i)
966       if i == -1:
967           break
968       # only remove the preamble line if default
969       # otherwise also write the value to the preamble
970       length = get_value(document.header, "\\paragraph_indentation", i)
971       if length == "default":
972           del document.header[i]
973           break
974       else:
975           # handle percent lengths
976           # latex_length returns "bool,length"
977           length = latex_length(length).split(",")[1]
978           add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
979           add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
980           del document.header[i]
981       i = i + 1
982
983
984 def revert_percent_skip_lengths(document):
985     " Revert relative lengths for paragraph skip separation to preamble code "
986     i = 0
987     while True:
988       i = find_token(document.header, "\\defskip", i)
989       if i == -1:
990           break
991       length = get_value(document.header, "\\defskip", i)
992       # only revert when a custom length was set and when
993       # it used a percent length
994       if length not in ('smallskip', 'medskip', 'bigskip'):
995           # handle percent lengths
996           length = latex_length(length)
997           # latex_length returns "bool,length"
998           percent = length.split(",")[0]
999           length = length.split(",")[1]
1000           if percent == "True":
1001               add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1002               add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
1003               # set defskip to medskip as default
1004               document.header[i] = "\\defskip medskip"
1005       i = i + 1
1006
1007
1008 def revert_percent_vspace_lengths(document):
1009     " Revert relative VSpace lengths to ERT "
1010     i = 0
1011     while True:
1012       i = find_token(document.body, "\\begin_inset VSpace", i)
1013       if i == -1:
1014           break
1015       # only revert if a custom length was set and if
1016       # it used a percent length
1017       line = document.body[i]
1018       r = re.compile(r'\\begin_inset VSpace (.*)$')
1019       m = r.match(line)
1020       length = m.group(1)
1021       if length not in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
1022           # check if the space has a star (protected space)
1023           protected = (document.body[i].rfind("*") != -1)
1024           if protected:
1025               length = length.rstrip('*')
1026           # handle percent lengths
1027           length = latex_length(length)
1028           # latex_length returns "bool,length"
1029           percent = length.split(",")[0]
1030           length = length.split(",")[1]
1031           # revert the VSpace inset to ERT
1032           if percent == "True":
1033               if protected:
1034                   subst = [old_put_cmd_in_ert("\\vspace*{" + length + "}")]
1035               else:
1036                   subst = [old_put_cmd_in_ert("\\vspace{" + length + "}")]
1037               document.body[i:i + 2] = subst
1038       i = 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       protected = (document.body[i].find("\\hspace*{}") != -1)
1049       # only revert if a custom length was set and if
1050       # it used a percent length
1051       length = get_value(document.body, '\\length', i + 1)
1052       if length == '':
1053           document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1054           return
1055       # handle percent lengths
1056       length = latex_length(length)
1057       # latex_length returns "bool,length"
1058       percent = length.split(",")[0]
1059       length = length.split(",")[1]
1060       # revert the HSpace inset to ERT
1061       if percent == "True":
1062           if protected:
1063               subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1064           else:
1065               subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1066           document.body[i:i + 3] = subst
1067       i = i + 2
1068
1069
1070 def revert_hspace_glue_lengths(document):
1071     " Revert HSpace glue lengths to ERT "
1072     i = 0
1073     while True:
1074       i = find_token(document.body, "\\begin_inset space \\hspace", i)
1075       if i == -1:
1076           break
1077       protected = (document.body[i].find("\\hspace*{}") != -1)
1078       length = get_value(document.body, '\\length', i + 1)
1079       if length == '':
1080           document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1081           return
1082       # only revert if the length contains a plus or minus at pos != 0
1083       glue  = re.compile(r'.+[\+-]')
1084       if glue.search(length):
1085           # handle percent lengths
1086           # latex_length returns "bool,length"
1087           length = latex_length(length).split(",")[1]
1088           # revert the HSpace inset to ERT
1089           if protected:
1090               subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1091           else:
1092               subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1093           document.body[i:i + 3] = subst
1094       i = i + 2
1095
1096 def convert_author_id(document):
1097     " Add the author_id to the \\author definition and make sure 0 is not used"
1098     i = 0
1099     j = 1
1100     while True:
1101         i = find_token(document.header, "\\author", i)
1102         if i == -1:
1103             break
1104         
1105         r = re.compile(r'(\\author) (\".*\")\s?(.*)$')
1106         m = r.match(document.header[i])
1107         if m != None:
1108             name = m.group(2)
1109             
1110             email = ''
1111             if m.lastindex == 3:
1112                 email = m.group(3)
1113             document.header[i] = "\\author %i %s %s" % (j, name, email)
1114         j = j + 1
1115         i = i + 1
1116         
1117     k = 0
1118     while True:
1119         k = find_token(document.body, "\\change_", k)
1120         if k == -1:
1121             break
1122
1123         change = document.body[k].split(' ');
1124         if len(change) == 3:
1125             type = change[0]
1126             author_id = int(change[1])
1127             time = change[2]
1128             document.body[k] = "%s %i %s" % (type, author_id + 1, time)
1129         k = k + 1
1130
1131 def revert_author_id(document):
1132     " Remove the author_id from the \\author definition "
1133     i = 0
1134     j = 0
1135     idmap = dict()
1136     while True:
1137         i = find_token(document.header, "\\author", i)
1138         if i == -1:
1139             break
1140         
1141         r = re.compile(r'(\\author) (\d+) (\".*\")\s?(.*)$')
1142         m = r.match(document.header[i])
1143         if m != None:
1144             author_id = int(m.group(2))
1145             idmap[author_id] = j
1146             name = m.group(3)
1147             
1148             email = ''
1149             if m.lastindex == 4:
1150                 email = m.group(4)
1151             document.header[i] = "\\author %s %s" % (name, email)
1152         i = i + 1
1153         j = j + 1
1154
1155     k = 0
1156     while True:
1157         k = find_token(document.body, "\\change_", k)
1158         if k == -1:
1159             break
1160
1161         change = document.body[k].split(' ');
1162         if len(change) == 3:
1163             type = change[0]
1164             author_id = int(change[1])
1165             time = change[2]
1166             document.body[k] = "%s %i %s" % (type, idmap[author_id], time)
1167         k = k + 1
1168
1169
1170 def revert_suppress_date(document):
1171     " Revert suppressing of default document date to preamble code "
1172     i = 0
1173     while True:
1174       i = find_token(document.header, "\\suppress_date", i)
1175       if i == -1:
1176           break
1177       # remove the preamble line and write to the preamble
1178       # when suppress_date was true
1179       date = get_value(document.header, "\\suppress_date", i)
1180       if date == "true":
1181           add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1182           add_to_preamble(document, ["\\date{}"])
1183       del document.header[i]
1184       i = i + 1
1185
1186
1187 def revert_mhchem(document):
1188     "Revert mhchem loading to preamble code"
1189     i = 0
1190     j = 0
1191     k = 0
1192     mhchem = "off"
1193     i = find_token(document.header, "\\use_mhchem 1", 0)
1194     if i != -1:
1195         mhchem = "auto"
1196     else:
1197         i = find_token(document.header, "\\use_mhchem 2", 0)
1198         if i != -1:
1199             mhchem = "on"
1200     if mhchem == "auto":
1201         j = find_token(document.body, "\\cf{", 0)
1202         if j != -1:
1203             mhchem = "on"
1204         else:
1205             j = find_token(document.body, "\\ce{", 0)
1206             if j != -1:
1207                 mhchem = "on"
1208     if mhchem == "on":
1209         add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1210         add_to_preamble(document, ["\\PassOptionsToPackage{version=3}{mhchem}"])
1211         add_to_preamble(document, ["\\usepackage{mhchem}"])
1212     k = find_token(document.header, "\\use_mhchem", 0)
1213     if k == -1:
1214         document.warning("Malformed LyX document: Could not find mhchem setting.")
1215         return
1216     del document.header[k]
1217
1218
1219 def revert_fontenc(document):
1220     " Remove fontencoding param "
1221     i = find_token(document.header, '\\fontencoding', 0)
1222     if i == -1:
1223         document.warning("Malformed LyX document: Missing \\fontencoding.")
1224         return
1225     del document.header[i]
1226
1227
1228 def merge_gbrief(document):
1229     " Merge g-brief-en and g-brief-de to one class "
1230
1231     if document.textclass != "g-brief-de":
1232         if document.textclass == "g-brief-en":
1233             document.textclass = "g-brief"
1234             document.set_textclass()
1235         return
1236
1237     obsoletedby = { "Brieftext":       "Letter",
1238                     "Unterschrift":    "Signature",
1239                     "Strasse":         "Street",
1240                     "Zusatz":          "Addition",
1241                     "Ort":             "Town",
1242                     "Land":            "State",
1243                     "RetourAdresse":   "ReturnAddress",
1244                     "MeinZeichen":     "MyRef",
1245                     "IhrZeichen":      "YourRef",
1246                     "IhrSchreiben":    "YourMail",
1247                     "Telefon":         "Phone",
1248                     "BLZ":             "BankCode",
1249                     "Konto":           "BankAccount",
1250                     "Postvermerk":     "PostalComment",
1251                     "Adresse":         "Address",
1252                     "Datum":           "Date",
1253                     "Betreff":         "Reference",
1254                     "Anrede":          "Opening",
1255                     "Anlagen":         "Encl.",
1256                     "Verteiler":       "cc",
1257                     "Gruss":           "Closing"}
1258     i = 0
1259     while 1:
1260         i = find_token(document.body, "\\begin_layout", i)
1261         if i == -1:
1262             break
1263
1264         layout = document.body[i][14:]
1265         if layout in obsoletedby:
1266             document.body[i] = "\\begin_layout " + obsoletedby[layout]
1267
1268         i += 1
1269         
1270     document.textclass = "g-brief"
1271     document.set_textclass()
1272
1273
1274 def revert_gbrief(document):
1275     " Revert g-brief to g-brief-en "
1276     if document.textclass == "g-brief":
1277         document.textclass = "g-brief-en"
1278         document.set_textclass()
1279
1280
1281 def revert_html_options(document):
1282     " Remove html options "
1283     i = find_token(document.header, '\\html_use_mathml', 0)
1284     if i != -1:
1285         del document.header[i]
1286     i = find_token(document.header, '\\html_be_strict', 0)
1287     if i != -1:
1288         del document.header[i]
1289
1290
1291 def revert_includeonly(document):
1292     i = 0
1293     while True:
1294         i = find_token(document.header, "\\begin_includeonly", i)
1295         if i == -1:
1296             return
1297         j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
1298         if j == -1:
1299             # this should not happen
1300             break
1301         document.header[i : j + 1] = []
1302
1303
1304 def revert_includeall(document):
1305     " Remove maintain_unincluded_children param "
1306     i = find_token(document.header, '\\maintain_unincluded_children', 0)
1307     if i != -1:
1308         del document.header[i]
1309
1310
1311 def revert_multirow(document):
1312     " Revert multirow cells in tables to TeX-code"
1313     i = 0
1314     multirow = False
1315     while True:
1316       # cell type 3 is multirow begin cell
1317       i = find_token(document.body, '<cell multirow="3"', i)
1318       if i == -1:
1319           break
1320       # a multirow cell was found
1321       multirow = True
1322       # remove the multirow tag, set the valignment to top
1323       # and remove the bottom line
1324       document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
1325       document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1326       document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
1327       # write ERT to create the multirow cell
1328       # use 2 rows and 2cm as default with because the multirow span
1329       # and the column width is only hardly accessible
1330       subst = [old_put_cmd_in_ert("\\multirow{2}{2cm}{")]
1331       document.body[i + 4:i + 4] = subst
1332       i = find_token(document.body, "</cell>", i)
1333       if i == -1:
1334            document.warning("Malformed LyX document: Could not find end of tabular cell.")
1335            break
1336       subst = [old_put_cmd_in_ert("}")]
1337       document.body[i - 3:i - 3] = subst
1338       # cell type 4 is multirow part cell
1339       i = find_token(document.body, '<cell multirow="4"', i)
1340       if i == -1:
1341           break
1342       # remove the multirow tag, set the valignment to top
1343       # and remove the top line
1344       document.body[i] = document.body[i].replace(' multirow="4" ', ' ')
1345       document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1346       document.body[i] = document.body[i].replace(' topline="true" ', ' ')
1347       i = i + 1
1348     if multirow == True:
1349         add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1350         add_to_preamble(document, ["\\usepackage{multirow}"])
1351
1352
1353 def convert_math_output(document):
1354     " Convert \html_use_mathml to \html_math_output "
1355     i = find_token(document.header, "\\html_use_mathml", 0)
1356     if i == -1:
1357         return
1358     rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1359     m = rgx.match(document.header[i])
1360     newval = "0" # MathML
1361     if m:
1362       val = m.group(1)
1363       if val != "true":
1364         newval = "2" # Images
1365     else:
1366       document.warning("Can't match " + document.header[i])
1367     document.header[i] = "\\html_math_output " + newval
1368
1369
1370 def revert_math_output(document):
1371     " Revert \html_math_output to \html_use_mathml "
1372     i = find_token(document.header, "\\html_math_output", 0)
1373     if i == -1:
1374         return
1375     rgx = re.compile(r'\\html_math_output\s+(\d)')
1376     m = rgx.match(document.header[i])
1377     newval = "true"
1378     if m:
1379         val = m.group(1)
1380         if val == "1" or val == "2":
1381             newval = "false"
1382     else:
1383         document.warning("Unable to match " + document.header[i])
1384     document.header[i] = "\\html_use_mathml " + newval
1385                 
1386
1387
1388 def revert_inset_preview(document):
1389     " Dissolves the preview inset "
1390     i = 0
1391     j = 0
1392     k = 0
1393     while True:
1394       i = find_token(document.body, "\\begin_inset Preview", i)
1395       if i == -1:
1396           return
1397       j = find_end_of_inset(document.body, i)
1398       if j == -1:
1399           document.warning("Malformed LyX document: Could not find end of Preview inset.")
1400           return
1401       #If the layout is Standard we need to remove it, otherwise there
1402       #will be paragraph breaks that shouldn't be there.
1403       k = find_token(document.body, "\\begin_layout Standard", i)
1404       if k == i + 2:
1405           del document.body[i:i + 3]
1406           del document.body[j - 5:j - 2]
1407           i -= 6
1408       else:
1409           del document.body[i]
1410           del document.body[j - 1]
1411           i -= 2
1412                 
1413
1414 def revert_equalspacing_xymatrix(document):
1415     " Revert a Formula with xymatrix@! to an ERT inset "
1416     i = 0
1417     j = 0
1418     has_preamble = False
1419     has_equal_spacing = False
1420     while True:
1421       found = -1
1422       i = find_token(document.body, "\\begin_inset Formula", i)
1423       if i == -1:
1424           break
1425       j = find_end_of_inset(document.body, i)
1426       if j == -1:
1427           document.warning("Malformed LyX document: Could not find end of Formula inset.")
1428           break
1429           
1430       for curline in range(i,j):
1431           found = document.body[curline].find("\\xymatrix@!")
1432           if found != -1:
1433               break
1434  
1435       if found != -1:
1436           has_equal_spacing = True
1437           content = [document.body[i][21:]]
1438           content += document.body[i + 1:j]
1439           subst = put_cmd_in_ert(content)
1440           document.body[i:j + 1] = subst
1441           i += len(subst)
1442       else:
1443           for curline in range(i,j):
1444               l = document.body[curline].find("\\xymatrix")
1445               if l != -1:
1446                   has_preamble = True;
1447                   break;
1448           i = j + 1
1449     if has_equal_spacing and not has_preamble:
1450         add_to_preamble(document, ['\\usepackage[all]{xy}'])
1451
1452
1453 def revert_notefontcolor(document):
1454     " Reverts greyed-out note font color to preamble code "
1455     i = 0
1456     colorcode = ""
1457     while True:
1458       i = find_token(document.header, "\\notefontcolor", i)
1459       if i == -1:
1460           return
1461       colorcode = get_value(document.header, '\\notefontcolor', 0)
1462       del document.header[i]
1463       # the color code is in the form #rrggbb where every character denotes a hex number
1464       # convert the string to an int
1465       red = string.atoi(colorcode[1:3],16)
1466       # we want the output "0.5" for the value "127" therefore increment here
1467       if red != 0:
1468           red = red + 1
1469       redout = float(red) / 256
1470       green = string.atoi(colorcode[3:5],16)
1471       if green != 0:
1472           green = green + 1
1473       greenout = float(green) / 256
1474       blue = string.atoi(colorcode[5:7],16)
1475       if blue != 0:
1476           blue = blue + 1
1477       blueout = float(blue) / 256
1478       # write the preamble
1479       insert_to_preamble(0, document,
1480                            '% Commands inserted by lyx2lyx to set the font color\n'
1481                            '% for greyed-out notes\n'
1482                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1483                            + '\\definecolor{note_fontcolor}{rgb}{'
1484                            + str(redout) + ', ' + str(greenout)
1485                            + ', ' + str(blueout) + '}\n'
1486                            + '\\renewenvironment{lyxgreyedout}\n'
1487                            + ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}\n')
1488
1489
1490 def revert_turkmen(document):
1491     "Set language Turkmen to English" 
1492     i = 0 
1493     if document.language == "turkmen": 
1494         document.language = "english" 
1495         i = find_token(document.header, "\\language", 0) 
1496         if i != -1: 
1497             document.header[i] = "\\language english" 
1498     j = 0 
1499     while True: 
1500         j = find_token(document.body, "\\lang turkmen", j) 
1501         if j == -1: 
1502             return 
1503         document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english") 
1504         j = j + 1 
1505
1506
1507 def revert_fontcolor(document):
1508     " Reverts font color to preamble code "
1509     i = 0
1510     colorcode = ""
1511     while True:
1512       i = find_token(document.header, "\\fontcolor", i)
1513       if i == -1:
1514           return
1515       colorcode = get_value(document.header, '\\fontcolor', 0)
1516       del document.header[i]
1517       # don't clutter the preamble if backgroundcolor is not set
1518       if colorcode == "#000000":
1519           continue
1520       # the color code is in the form #rrggbb where every character denotes a hex number
1521       # convert the string to an int
1522       red = string.atoi(colorcode[1:3],16)
1523       # we want the output "0.5" for the value "127" therefore add here
1524       if red != 0:
1525           red = red + 1
1526       redout = float(red) / 256
1527       green = string.atoi(colorcode[3:5],16)
1528       if green != 0:
1529           green = green + 1
1530       greenout = float(green) / 256
1531       blue = string.atoi(colorcode[5:7],16)
1532       if blue != 0:
1533           blue = blue + 1
1534       blueout = float(blue) / 256
1535       # write the preamble
1536       insert_to_preamble(0, document,
1537                            '% Commands inserted by lyx2lyx to set the font color\n'
1538                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1539                            + '\\definecolor{document_fontcolor}{rgb}{'
1540                            + str(redout) + ', ' + str(greenout)
1541                            + ', ' + str(blueout) + '}\n'
1542                            + '\\color{document_fontcolor}\n')
1543
1544 def revert_shadedboxcolor(document):
1545     " Reverts shaded box color to preamble code "
1546     i = 0
1547     colorcode = ""
1548     while True:
1549       i = find_token(document.header, "\\boxbgcolor", i)
1550       if i == -1:
1551           return
1552       colorcode = get_value(document.header, '\\boxbgcolor', 0)
1553       del document.header[i]
1554       # the color code is in the form #rrggbb where every character denotes a hex number
1555       # convert the string to an int
1556       red = string.atoi(colorcode[1:3],16)
1557       # we want the output "0.5" for the value "127" therefore increment here
1558       if red != 0:
1559           red = red + 1
1560       redout = float(red) / 256
1561       green = string.atoi(colorcode[3:5],16)
1562       if green != 0:
1563           green = green + 1
1564       greenout = float(green) / 256
1565       blue = string.atoi(colorcode[5:7],16)
1566       if blue != 0:
1567           blue = blue + 1
1568       blueout = float(blue) / 256
1569       # write the preamble
1570       insert_to_preamble(0, document,
1571                            '% Commands inserted by lyx2lyx to set the color\n'
1572                            '% of boxes with shaded background\n'
1573                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1574                            + '\\definecolor{shadecolor}{rgb}{'
1575                            + str(redout) + ', ' + str(greenout)
1576                            + ', ' + str(blueout) + '}\n')
1577
1578
1579 def revert_lyx_version(document):
1580     " Reverts LyX Version information from Inset Info "
1581     version = "LyX version"
1582     try:
1583         import lyx2lyx_version
1584         version = lyx2lyx_version.version
1585     except:
1586         pass
1587
1588     i = 0
1589     while 1:
1590         i = find_token(document.body, '\\begin_inset Info', i)
1591         if i == -1:
1592             return
1593         j = find_end_of_inset(document.body, i + 1)
1594         if j == -1:
1595             # should not happen
1596             document.warning("Malformed LyX document: Could not find end of Info inset.")
1597         # We expect:
1598         # \begin_inset Info
1599         # type  "lyxinfo"
1600         # arg   "version"
1601         # \end_inset
1602         # but we shall try to be forgiving.
1603         arg = typ = ""
1604         for k in range(i, j):
1605             if document.body[k].startswith("arg"):
1606                 arg = document.body[k][3:].strip().strip('"')
1607             if document.body[k].startswith("type"):
1608                 typ = document.body[k][4:].strip().strip('"')
1609         if arg != "version" or typ != "lyxinfo":
1610             i = j + 1
1611             continue
1612
1613         # We do not actually know the version of LyX used to produce the document.
1614         # But we can use our version, since we are reverting.
1615         s = [version]
1616         # Now we want to check if the line after "\end_inset" is empty. It normally
1617         # is, so we want to remove it, too.
1618         lastline = j + 1
1619         if document.body[j + 1].strip() == "":
1620             lastline = j + 2
1621         document.body[i: lastline] = s
1622         i = i + 1
1623
1624
1625 def revert_math_scale(document):
1626   " Remove math scaling and LaTeX options "
1627   i = find_token(document.header, '\\html_math_img_scale', 0)
1628   if i != -1:
1629     del document.header[i]
1630   i = find_token(document.header, '\\html_latex_start', 0)
1631   if i != -1:
1632     del document.header[i]
1633   i = find_token(document.header, '\\html_latex_end', 0)
1634   if i != -1:
1635     del document.header[i]
1636
1637
1638 def revert_pagesizes(document):
1639   i = 0
1640   " Revert page sizes to default "
1641   i = find_token(document.header, '\\papersize', 0)
1642   if i != -1:
1643     size = document.header[i][11:]
1644     if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1645     or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1646     or size == "b2paper" or size == "b6paper" or size == "b0j" \
1647     or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1648     or size == "b5j" or size == "b6j":
1649       del document.header[i]
1650
1651
1652 def revert_DIN_C_pagesizes(document):
1653   i = 0
1654   " Revert DIN C page sizes to default "
1655   i = find_token(document.header, '\\papersize', 0)
1656   if i != -1:
1657     size = document.header[i][11:]
1658     if size == "c0paper" or size == "c1paper" or size == "c2paper" \
1659     or size == "c3paper" or size == "c4paper" or size == "c5paper" \
1660     or size == "c6paper":
1661       del document.header[i]
1662
1663
1664 def convert_html_quotes(document):
1665   " Remove quotes around html_latex_start and html_latex_end "
1666
1667   i = find_token(document.header, '\\html_latex_start', 0)
1668   if i != -1:
1669     line = document.header[i]
1670     l = re.compile(r'\\html_latex_start\s+"(.*)"')
1671     m = l.match(line)
1672     if m != None:
1673       document.header[i] = "\\html_latex_start " + m.group(1)
1674       
1675   i = find_token(document.header, '\\html_latex_end', 0)
1676   if i != -1:
1677     line = document.header[i]
1678     l = re.compile(r'\\html_latex_end\s+"(.*)"')
1679     m = l.match(line)
1680     if m != None:
1681       document.header[i] = "\\html_latex_end " + m.group(1)
1682       
1683
1684 def revert_html_quotes(document):
1685   " Remove quotes around html_latex_start and html_latex_end "
1686   
1687   i = find_token(document.header, '\\html_latex_start', 0)
1688   if i != -1:
1689     line = document.header[i]
1690     l = re.compile(r'\\html_latex_start\s+(.*)')
1691     m = l.match(line)
1692     document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1693       
1694   i = find_token(document.header, '\\html_latex_end', 0)
1695   if i != -1:
1696     line = document.header[i]
1697     l = re.compile(r'\\html_latex_end\s+(.*)')
1698     m = l.match(line)
1699     document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1700
1701
1702 def revert_output_sync(document):
1703   " Remove forward search options "
1704   i = find_token(document.header, '\\output_sync_macro', 0)
1705   if i != -1:
1706     del document.header[i]
1707   i = find_token(document.header, '\\output_sync', 0)
1708   if i != -1:
1709     del document.header[i]
1710
1711
1712 def convert_beamer_args(document):
1713   " Convert ERT arguments in Beamer to InsetArguments "
1714
1715   if document.textclass != "beamer" and document.textclass != "article-beamer":
1716     return
1717   
1718   layouts = ("Block", "ExampleBlock", "AlertBlock")
1719   for layout in layouts:
1720     blay = 0
1721     while True:
1722       blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1723       if blay == -1:
1724         break
1725       elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1726       if elay == -1:
1727         document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1728         blay += 1
1729         continue
1730       bert = find_token(document.body, '\\begin_inset ERT', blay)
1731       if bert == -1:
1732         document.warning("Malformed Beamer LyX document: Can't find argument of " + layout + " layout.")
1733         blay = elay + 1
1734         continue
1735       eert = find_end_of_inset(document.body, bert)
1736       if eert == -1:
1737         document.warning("Malformed LyX document: Can't find end of ERT.")
1738         blay = elay + 1
1739         continue
1740       
1741       # So the ERT inset begins at line k and goes to line l. We now wrap it in 
1742       # an argument inset.
1743       # Do the end first, so as not to mess up the variables.
1744       document.body[eert + 1:eert + 1] = ['', '\\end_layout', '', '\\end_inset', '']
1745       document.body[bert:bert] = ['\\begin_inset OptArg', 'status open', '', 
1746           '\\begin_layout Plain Layout']
1747       blay = elay + 9
1748
1749
1750 def revert_beamer_args(document):
1751   " Revert Beamer arguments to ERT "
1752   
1753   if document.textclass != "beamer" and document.textclass != "article-beamer":
1754     return
1755     
1756   layouts = ("Block", "ExampleBlock", "AlertBlock")
1757   for layout in layouts:
1758     blay = 0
1759     while True:
1760       blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1761       if blay == -1:
1762         break
1763       elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1764       if elay == -1:
1765         document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1766         blay += 1
1767         continue
1768       bopt = find_token(document.body, '\\begin_inset OptArg', blay)
1769       if bopt == -1:
1770         # it is legal not to have one of these
1771         blay = elay + 1
1772         continue
1773       eopt = find_end_of_inset(document.body, bopt)
1774       if eopt == -1:
1775         document.warning("Malformed LyX document: Can't find end of argument.")
1776         blay = elay + 1
1777         continue
1778       bplay = find_token(document.body, '\\begin_layout Plain Layout', blay)
1779       if bplay == -1:
1780         document.warning("Malformed LyX document: Can't find plain layout.")
1781         blay = elay + 1
1782         continue
1783       eplay = find_end_of(document.body, bplay, '\\begin_layout', '\\end_layout')
1784       if eplay == -1:
1785         document.warning("Malformed LyX document: Can't find end of plain layout.")
1786         blay = elay + 1
1787         continue
1788       # So the content of the argument inset goes from bplay + 1 to eplay - 1
1789       bcont = bplay + 1
1790       if bcont >= eplay:
1791         # Hmm.
1792         document.warning(str(bcont) + " " + str(eplay))
1793         blay = blay + 1
1794         continue
1795       # we convert the content of the argument into pure LaTeX...
1796       content = lyx2latex(document, document.body[bcont:eplay])
1797       strlist = put_cmd_in_ert(["{" + content + "}"])
1798       
1799       # now replace the optional argument with the ERT
1800       document.body[bopt:eopt + 1] = strlist
1801       blay = blay + 1
1802
1803
1804 def revert_align_decimal(document):
1805   l = 0
1806   while True:
1807     l = document.body[l].find('alignment=decimal')
1808     if l == -1:
1809         break
1810     remove_option(document, l, 'decimal_point')
1811     document.body[l].replace('decimal', 'center')
1812
1813
1814 def convert_optarg(document):
1815   " Convert \\begin_inset OptArg to \\begin_inset Argument "
1816   i = 0
1817   while 1:
1818     i = find_token(document.body, '\\begin_inset OptArg', i)
1819     if i == -1:
1820       return
1821     document.body[i] = "\\begin_inset Argument"
1822     i += 1
1823
1824
1825 def revert_argument(document):
1826   " Convert \\begin_inset Argument to \\begin_inset OptArg "
1827   i = 0
1828   while 1:
1829     i = find_token(document.body, '\\begin_inset Argument', i)
1830     if i == -1:
1831       return
1832     document.body[i] = "\\begin_inset OptArg"
1833     i += 1
1834
1835
1836 def revert_makebox(document):
1837   " Convert \\makebox to TeX code "
1838   i = 0
1839   while 1:
1840     # only revert frameless boxes without an inner box
1841     i = find_token(document.body, '\\begin_inset Box Frameless', i)
1842     if i == -1:
1843       # remove the option use_makebox
1844       revert_use_makebox(document)
1845       return
1846     z = find_end_of_inset(document.body, i)
1847     if z == -1:
1848       document.warning("Malformed LyX document: Can't find end of box inset.")
1849       return
1850     j = find_token(document.body, 'use_makebox 1', i)
1851     # assure we found the makebox of the current box
1852     if j < z and j != -1:
1853       y = find_token(document.body, "\\begin_layout", i)
1854       if y > z or y == -1:
1855         document.warning("Malformed LyX document: Can't find layout in box.")
1856         return
1857       # remove the \end_layout \end_inset pair
1858       document.body[z - 2:z + 1] = put_cmd_in_ert("}")
1859       # determine the alignment
1860       k = find_token(document.body, 'hor_pos', j - 4)
1861       align = document.body[k][9]
1862       # determine the width
1863       l = find_token(document.body, 'width "', j + 1)
1864       length = document.body[l][7:]
1865       # remove trailing '"'
1866       length = length[:-1]
1867       # latex_length returns "bool,length"
1868       length = latex_length(length).split(",")[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