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