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