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