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