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