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