]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_2_0.py
4abacaaf2f0f866d1adcf243854ee3058a244798
[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, get_option_value
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         anum += 1
754         i += 1
755         
756     i = 0
757     while True:
758         i = find_token(document.body, "\\change_", i)
759         if i == -1:
760             break
761         change = document.body[i].split(' ');
762         if len(change) == 3:
763             type = change[0]
764             author_id = int(change[1])
765             time = change[2]
766             document.body[i] = "%s %i %s" % (type, author_id + 1, time)
767         i += 1
768
769
770 def revert_author_id(document):
771     " Remove the author_id from the \\author definition "
772     i = 0
773     anum = 0
774     rx = re.compile(r'(\\author)\s+(\d+)\s+(\".*\")\s*(.*)$')
775     idmap = dict()
776
777     while True:
778         i = find_token(document.header, "\\author", i)
779         if i == -1:
780             break
781         m = rx.match(document.header[i])
782         if m:
783             author_id = int(m.group(2))
784             idmap[author_id] = anum
785             name = m.group(3)
786             email = m.group(4)
787             document.header[i] = "\\author %s %s" % (name, email)
788         i += 1
789         # FIXME Should this be incremented if we didn't match?
790         anum += 1
791
792     i = 0
793     while True:
794         i = find_token(document.body, "\\change_", i)
795         if i == -1:
796             break
797         change = document.body[i].split(' ');
798         if len(change) == 3:
799             type = change[0]
800             author_id = int(change[1])
801             time = change[2]
802             document.body[i] = "%s %i %s" % (type, idmap[author_id], time)
803         i += 1
804
805
806 def revert_suppress_date(document):
807     " Revert suppressing of default document date to preamble code "
808     i = find_token(document.header, "\\suppress_date", 0)
809     if i == -1:
810         return
811     # remove the preamble line and write to the preamble
812     # when suppress_date was true
813     date = str2bool(get_value(document.header, "\\suppress_date", i))
814     if date:
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 == "off":
836       # don't load case
837       return 
838
839     if mhchem == "auto":
840         i = 0
841         while True:
842             i = find_token(document.body, "\\begin_inset Formula", i)
843             if i == -1:
844                break
845             line = document.body[i]
846             if line.find("\\ce{") != -1 or line.find("\\cf{") != -1:
847               mhchem = "on"
848               break
849             i += 1
850
851     if mhchem == "on":
852         pre = ["\\PassOptionsToPackage{version=3}{mhchem}", 
853           "\\usepackage{mhchem}"]
854         insert_to_preamble(document, pre) 
855
856
857 def revert_fontenc(document):
858     " Remove fontencoding param "
859     if not del_token(document.header, '\\fontencoding', 0):
860         document.warning("Malformed LyX document: Missing \\fontencoding.")
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     del_token(document.header, '\\html_use_mathml', 0)
919     del_token(document.header, '\\html_be_strict', 0)
920
921
922 def revert_includeonly(document):
923     i = 0
924     while True:
925         i = find_token(document.header, "\\begin_includeonly", i)
926         if i == -1:
927             return
928         j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
929         if j == -1:
930             document.warning("Unable to find end of includeonly section!!")
931             break
932         document.header[i : j + 1] = []
933
934
935 def revert_includeall(document):
936     " Remove maintain_unincluded_children param "
937     del_token(document.header, '\\maintain_unincluded_children', 0)
938
939
940 def revert_multirow(document):
941     " Revert multirow cells in tables to TeX-code"
942
943     # first, let's find out if we need to do anything
944     # cell type 3 is multirow begin cell
945     i = find_token(document.body, '<cell multirow="3"', 0)
946     if i == -1:
947       return
948
949     add_to_preamble(document, ["\\usepackage{multirow}"])
950
951     begin_table = 0
952     while True:
953         # find begin/end of table
954         begin_table = find_token(document.body, '<lyxtabular version=', begin_table)
955         if begin_table == -1:
956             break
957         end_table = find_end_of(document.body, begin_table, '<lyxtabular', '</lyxtabular>')
958         if end_table == -1:
959             document.warning("Malformed LyX document: Could not find end of table.")
960             begin_table += 1
961             continue
962         # does this table have multirow?
963         i = find_token(document.body, '<cell multirow="3"', begin_table, end_table)
964         if i == -1:
965             begin_table = end_table
966             continue
967         
968         # store the number of rows and columns
969         numrows = get_option_value(document.body[begin_table], "rows")
970         numcols = get_option_value(document.body[begin_table], "columns")
971         try:
972           numrows = int(numrows)
973           numcols = int(numcols)
974         except:
975           document.warning(numrows)
976           document.warning("Unable to determine rows and columns!")
977           begin_table = end_table
978           continue
979
980         mrstarts = []
981         multirows = []
982         # collect info on rows and columns of this table.
983         begin_row = begin_table
984         for row in range(numrows):
985             begin_row = find_token(document.body, '<row>', begin_row, end_table)
986             if begin_row == -1:
987               document.warning("Can't find row " + str(row + 1))
988               break
989             end_row = find_end_of(document.body, begin_row, '<row>', '</row>')
990             if end_row == -1:
991               document.warning("Can't find end of row " + str(row + 1))
992               break
993             begin_cell = begin_row
994             multirows.append([])
995             for column in range(numcols):            
996                 begin_cell = find_token(document.body, '<cell ', begin_cell, end_row)
997                 if begin_cell == -1:
998                   document.warning("Can't find column " + str(column + 1) + \
999                     "in row " + str(row + 1))
1000                   break
1001                 # NOTE 
1002                 # this will fail if someone puts "</cell>" in a cell, but
1003                 # that seems fairly unlikely.
1004                 end_cell = find_end_of(document.body, begin_cell, '<cell', '</cell>')
1005                 if end_cell == -1:
1006                   document.warning("Can't find end of column " + str(column + 1) + \
1007                     "in row " + str(row + 1))
1008                   break
1009                 multirows[row].append([begin_cell, end_cell, 0])
1010                 if document.body[begin_cell].find('multirow="3"') != -1:
1011                   multirows[row][column][2] = 3 # begin multirow
1012                   mrstarts.append([row, column])
1013                 elif document.body[begin_cell].find('multirow="4"') != -1:
1014                   multirows[row][column][2] = 4 # in multirow
1015                 begin_cell = end_cell
1016             begin_row = end_row
1017         # end of table info collection
1018
1019         # work from the back to avoid messing up numbering
1020         mrstarts.reverse()
1021         for m in mrstarts:
1022             row = m[0]
1023             col = m[1]
1024             # get column width
1025             col_width = get_option_value(document.body[begin_table + 2 + col], "width")
1026             # "0pt" means that no width is specified
1027             if not col_width or col_width == "0pt":
1028               col_width = "*"
1029             # determine the number of cells that are part of the multirow
1030             nummrs = 1
1031             for r in range(row + 1, numrows):
1032                 if multirows[r][col][2] != 4:
1033                   break
1034                 nummrs += 1
1035                 # take the opportunity to revert this line
1036                 lineno = multirows[r][col][0]
1037                 document.body[lineno] = document.body[lineno].\
1038                   replace(' multirow="4" ', ' ').\
1039                   replace('valignment="middle"', 'valignment="top"').\
1040                   replace(' topline="true" ', ' ')
1041                 # remove bottom line of previous multirow-part cell
1042                 lineno = multirows[r-1][col][0]
1043                 document.body[lineno] = document.body[lineno].replace(' bottomline="true" ', ' ')
1044             # revert beginning cell
1045             bcell = multirows[row][col][0]
1046             ecell = multirows[row][col][1]
1047             document.body[bcell] = document.body[bcell].\
1048               replace(' multirow="3" ', ' ').\
1049               replace('valignment="middle"', 'valignment="top"')
1050             blay = find_token(document.body, "\\begin_layout", bcell, ecell)
1051             if blay == -1:
1052               document.warning("Can't find layout for cell!")
1053               continue
1054             bend = find_end_of_layout(document.body, blay)
1055             if bend == -1:
1056               document.warning("Can't find end of layout for cell!")
1057               continue
1058             # do the later one first, so as not to mess up the numbering
1059             # we are wrapping the whole cell in this ert
1060             # so before the end of the layout...
1061             document.body[bend:bend] = put_cmd_in_ert("}")
1062             # ...and after the beginning
1063             document.body[blay + 1:blay + 1] = \
1064               put_cmd_in_ert("\\multirow{" + str(nummrs) + "}{" + col_width + "}{")
1065
1066         begin_table = end_table
1067
1068
1069 def convert_math_output(document):
1070     " Convert \html_use_mathml to \html_math_output "
1071     i = find_token(document.header, "\\html_use_mathml", 0)
1072     if i == -1:
1073         return
1074     rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1075     m = rgx.match(document.header[i])
1076     newval = "0" # MathML
1077     if m:
1078       val = str2bool(m.group(1))
1079       if not val:
1080         newval = "2" # Images
1081     else:
1082       document.warning("Can't match " + document.header[i])
1083     document.header[i] = "\\html_math_output " + newval
1084
1085
1086 def revert_math_output(document):
1087     " Revert \html_math_output to \html_use_mathml "
1088     i = find_token(document.header, "\\html_math_output", 0)
1089     if i == -1:
1090         return
1091     rgx = re.compile(r'\\html_math_output\s+(\d)')
1092     m = rgx.match(document.header[i])
1093     newval = "true"
1094     if m:
1095         val = m.group(1)
1096         if val == "1" or val == "2":
1097             newval = "false"
1098     else:
1099         document.warning("Unable to match " + document.header[i])
1100     document.header[i] = "\\html_use_mathml " + newval
1101                 
1102
1103
1104 def revert_inset_preview(document):
1105     " Dissolves the preview inset "
1106     i = 0
1107     while True:
1108       i = find_token(document.body, "\\begin_inset Preview", i)
1109       if i == -1:
1110           return
1111       iend = find_end_of_inset(document.body, i)
1112       if iend == -1:
1113           document.warning("Malformed LyX document: Could not find end of Preview inset.")
1114           i += 1
1115           continue
1116       
1117       # This has several issues.
1118       # We need to do something about the layouts inside InsetPreview.
1119       # If we just leave the first one, then we have something like:
1120       # \begin_layout Standard
1121       # ...
1122       # \begin_layout Standard
1123       # and we get a "no \end_layout" error. So something has to be done.
1124       # Ideally, we would check if it is the same as the layout we are in.
1125       # If so, we just remove it; if not, we end the active one. But it is 
1126       # not easy to know what layout we are in, due to depth changes, etc,
1127       # and it is not clear to me how much work it is worth doing. In most
1128       # cases, the layout will probably be the same.
1129       # 
1130       # For the same reason, we have to remove the \end_layout tag at the
1131       # end of the last layout in the inset. Again, that will sometimes be
1132       # wrong, but it will usually be right. To know what to do, we would
1133       # again have to know what layout the inset is in.
1134       
1135       blay = find_token(document.body, "\\begin_layout", i, iend)
1136       if blay == -1:
1137           document.warning("Can't find layout for preview inset!")
1138           # always do the later one first...
1139           del document.body[iend]
1140           del document.body[i]
1141           # deletions mean we do not need to reset i
1142           continue
1143
1144       # This is where we would check what layout we are in.
1145       # The check for Standard is definitely wrong.
1146       # 
1147       # lay = document.body[blay].split(None, 1)[1]
1148       # if lay != oldlayout:
1149       #     # record a boolean to tell us what to do later....
1150       #     # better to do it later, since (a) it won't mess up
1151       #     # the numbering and (b) we only modify at the end.
1152         
1153       # we want to delete the last \\end_layout in this inset, too.
1154       # note that this may not be the \\end_layout that goes with blay!!
1155       bend = find_end_of_layout(document.body, blay)
1156       while True:
1157           tmp = find_token(document.body, "\\end_layout", bend + 1, iend)
1158           if tmp == -1:
1159               break
1160           bend = tmp
1161       if bend == blay:
1162           document.warning("Unable to find last layout in preview inset!")
1163           del document.body[iend]
1164           del document.body[i]
1165           # deletions mean we do not need to reset i
1166           continue
1167       # always do the later one first...
1168       del document.body[iend]
1169       del document.body[bend]
1170       del document.body[i:blay + 1]
1171       # we do not need to reset i
1172                 
1173
1174 def revert_equalspacing_xymatrix(document):
1175     " Revert a Formula with xymatrix@! to an ERT inset "
1176     i = 0
1177     has_preamble = False
1178     has_equal_spacing = False
1179
1180     while True:
1181       i = find_token(document.body, "\\begin_inset Formula", i)
1182       if i == -1:
1183           break
1184       j = find_end_of_inset(document.body, i)
1185       if j == -1:
1186           document.warning("Malformed LyX document: Could not find end of Formula inset.")
1187           i += 1
1188           continue
1189       
1190       for curline in range(i,j):
1191           found = document.body[curline].find("\\xymatrix@!")
1192           if found != -1:
1193               break
1194  
1195       if found != -1:
1196           has_equal_spacing = True
1197           content = [document.body[i][21:]]
1198           content += document.body[i + 1:j]
1199           subst = put_cmd_in_ert(content)
1200           document.body[i:j + 1] = subst
1201           i += len(subst) - (j - i) + 1
1202       else:
1203           for curline in range(i,j):
1204               l = document.body[curline].find("\\xymatrix")
1205               if l != -1:
1206                   has_preamble = True;
1207                   break;
1208           i = j + 1
1209   
1210     if has_equal_spacing and not has_preamble:
1211         add_to_preamble(document, ['\\usepackage[all]{xy}'])
1212
1213
1214 def revert_notefontcolor(document):
1215     " Reverts greyed-out note font color to preamble code "
1216
1217     i = find_token(document.header, "\\notefontcolor", 0)
1218     if i == -1:
1219         return
1220
1221     colorcode = get_value(document.header, '\\notefontcolor', i)
1222     del document.header[i]
1223
1224     # are there any grey notes?
1225     if find_token(document.body, "\\begin_inset Note Greyedout", 0) == -1:
1226         # no need to do anything else, and \renewcommand will throw 
1227         # an error since lyxgreyedout will not exist.
1228         return
1229
1230     # the color code is in the form #rrggbb where every character denotes a hex number
1231     red = hex2ratio(colorcode[1:3])
1232     green = hex2ratio(colorcode[3:5])
1233     blue = hex2ratio(colorcode[5:7])
1234     # write the preamble
1235     insert_to_preamble(document,
1236       [ '%  for greyed-out notes',
1237         '\\@ifundefined{definecolor}{\\usepackage{color}}{}'
1238         '\\definecolor{note_fontcolor}{rgb}{%s,%s,%s}' % (red, green, blue),
1239         '\\renewenvironment{lyxgreyedout}',
1240         ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}'])
1241
1242
1243 def revert_turkmen(document):
1244     "Set language Turkmen to English" 
1245
1246     if document.language == "turkmen": 
1247         document.language = "english" 
1248         i = find_token(document.header, "\\language", 0) 
1249         if i != -1: 
1250             document.header[i] = "\\language english" 
1251
1252     j = 0 
1253     while True: 
1254         j = find_token(document.body, "\\lang turkmen", j) 
1255         if j == -1: 
1256             return 
1257         document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english") 
1258         j += 1 
1259
1260
1261 def revert_fontcolor(document):
1262     " Reverts font color to preamble code "
1263     i = find_token(document.header, "\\fontcolor", 0)
1264     if i == -1:
1265         return
1266     colorcode = get_value(document.header, '\\fontcolor', i)
1267     del document.header[i]
1268     # don't clutter the preamble if font color is not set
1269     if colorcode == "#000000":
1270         return
1271     # the color code is in the form #rrggbb where every character denotes a hex number
1272     red = hex2ratio(colorcode[1:3])
1273     green = hex2ratio(colorcode[3:5])
1274     blue = hex2ratio(colorcode[5:7])
1275     # write the preamble
1276     insert_to_preamble(document,
1277       ['%  Set the font color',
1278       '\\@ifundefined{definecolor}{\\usepackage{color}}{}',
1279       '\\definecolor{document_fontcolor}{rgb}{%s,%s,%s}' % (red, green, blue),
1280       '\\color{document_fontcolor}'])
1281
1282
1283 def revert_shadedboxcolor(document):
1284     " Reverts shaded box color to preamble code "
1285     i = find_token(document.header, "\\boxbgcolor", 0)
1286     if i == -1:
1287         return
1288     colorcode = get_value(document.header, '\\boxbgcolor', i)
1289     del document.header[i]
1290     # the color code is in the form #rrggbb
1291     red = hex2ratio(colorcode[1:3])
1292     green = hex2ratio(colorcode[3:5])
1293     blue = hex2ratio(colorcode[5:7])
1294     # write the preamble
1295     insert_to_preamble(document,
1296       ['%  Set the color of boxes with shaded background',
1297       '\\@ifundefined{definecolor}{\\usepackage{color}}{}',
1298       "\\definecolor{shadecolor}{rgb}{%s,%s,%s}" % (red, green, blue)])
1299
1300
1301 def revert_lyx_version(document):
1302     " Reverts LyX Version information from Inset Info "
1303     version = "LyX version"
1304     try:
1305         import lyx2lyx_version
1306         version = lyx2lyx_version.version
1307     except:
1308         pass
1309
1310     i = 0
1311     while 1:
1312         i = find_token(document.body, '\\begin_inset Info', i)
1313         if i == -1:
1314             return
1315         j = find_end_of_inset(document.body, i + 1)
1316         if j == -1:
1317             document.warning("Malformed LyX document: Could not find end of Info inset.")
1318             i += 1
1319             continue
1320
1321         # We expect:
1322         # \begin_inset Info
1323         # type  "lyxinfo"
1324         # arg   "version"
1325         # \end_inset
1326         typ = get_quoted_value(document.body, "type", i, j)
1327         arg = get_quoted_value(document.body, "arg", i, j)
1328         if arg != "version" or typ != "lyxinfo":
1329             i = j + 1
1330             continue
1331
1332         # We do not actually know the version of LyX used to produce the document.
1333         # But we can use our version, since we are reverting.
1334         s = [version]
1335         # Now we want to check if the line after "\end_inset" is empty. It normally
1336         # is, so we want to remove it, too.
1337         lastline = j + 1
1338         if document.body[j + 1].strip() == "":
1339             lastline = j + 2
1340         document.body[i: lastline] = s
1341         i = i + 1
1342
1343
1344 def revert_math_scale(document):
1345   " Remove math scaling and LaTeX options "
1346   del_token(document.header, '\\html_math_img_scale', 0)
1347   del_token(document.header, '\\html_latex_start', 0)
1348   del_token(document.header, '\\html_latex_end', 0)
1349
1350
1351 def revert_pagesizes(document):
1352   " Revert page sizes to default "
1353   i = find_token(document.header, '\\papersize', 0)
1354   if i != -1:
1355     size = document.header[i][11:]
1356     if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1357     or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1358     or size == "b2paper" or size == "b6paper" or size == "b0j" \
1359     or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1360     or size == "b5j" or size == "b6j":
1361       del document.header[i]
1362
1363
1364 def revert_DIN_C_pagesizes(document):
1365   " Revert DIN C page sizes to default "
1366   i = find_token(document.header, '\\papersize', 0)
1367   if i != -1:
1368     size = document.header[i][11:]
1369     if size == "c0paper" or size == "c1paper" or size == "c2paper" \
1370     or size == "c3paper" or size == "c4paper" or size == "c5paper" \
1371     or size == "c6paper":
1372       del document.header[i]
1373
1374
1375 def convert_html_quotes(document):
1376   " Remove quotes around html_latex_start and html_latex_end "
1377
1378   i = find_token(document.header, '\\html_latex_start', 0)
1379   if i != -1:
1380     line = document.header[i]
1381     l = re.compile(r'\\html_latex_start\s+"(.*)"')
1382     m = l.match(line)
1383     if m:
1384       document.header[i] = "\\html_latex_start " + m.group(1)
1385       
1386   i = find_token(document.header, '\\html_latex_end', 0)
1387   if i != -1:
1388     line = document.header[i]
1389     l = re.compile(r'\\html_latex_end\s+"(.*)"')
1390     m = l.match(line)
1391     if m:
1392       document.header[i] = "\\html_latex_end " + m.group(1)
1393       
1394
1395 def revert_html_quotes(document):
1396   " Remove quotes around html_latex_start and html_latex_end "
1397   
1398   i = find_token(document.header, '\\html_latex_start', 0)
1399   if i != -1:
1400     line = document.header[i]
1401     l = re.compile(r'\\html_latex_start\s+(.*)')
1402     m = l.match(line)
1403     if not m:
1404         document.warning("Weird html_latex_start line: " + line)
1405         del document.header[i]
1406     else:
1407         document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1408       
1409   i = find_token(document.header, '\\html_latex_end', 0)
1410   if i != -1:
1411     line = document.header[i]
1412     l = re.compile(r'\\html_latex_end\s+(.*)')
1413     m = l.match(line)
1414     if not m:
1415         document.warning("Weird html_latex_end line: " + line)
1416         del document.header[i]
1417     else:
1418         document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1419
1420
1421 def revert_output_sync(document):
1422   " Remove forward search options "
1423   del_token(document.header, '\\output_sync_macro', 0)
1424   del_token(document.header, '\\output_sync', 0)
1425
1426
1427 def revert_align_decimal(document):
1428   i = 0
1429   while True:
1430     i = find_token(document.body, "\\begin_inset Tabular", i)
1431     if i == -1:
1432       return
1433     j = find_end_of_inset(document.body, i)
1434     if j == -1:
1435       document.warning("Unable to find end of Tabular inset at line " + str(i))
1436       i += 1
1437       continue
1438     cell = find_token(document.body, "<cell", i, j)
1439     if cell == -1:
1440       document.warning("Can't find any cells in Tabular inset at line " + str(i))
1441       i = j
1442       continue
1443     k = i + 1
1444     while True:
1445       k = find_token(document.body, "<column", k, cell)
1446       if k == -1:
1447         return
1448       if document.body[k].find('alignment="decimal"') == -1:
1449         k += 1
1450         continue
1451       remove_option(document.body, k, 'decimal_point')
1452       document.body[k] = \
1453         document.body[k].replace('alignment="decimal"', 'alignment="center"')
1454       k += 1
1455
1456
1457 def convert_optarg(document):
1458   " Convert \\begin_inset OptArg to \\begin_inset Argument "
1459   i = 0
1460   while 1:
1461     i = find_token(document.body, '\\begin_inset OptArg', i)
1462     if i == -1:
1463       return
1464     document.body[i] = "\\begin_inset Argument"
1465     i += 1
1466
1467
1468 def revert_argument(document):
1469   " Convert \\begin_inset Argument to \\begin_inset OptArg "
1470   i = 0
1471   while 1:
1472     i = find_token(document.body, '\\begin_inset Argument', i)
1473     if i == -1:
1474       return
1475     document.body[i] = "\\begin_inset OptArg"
1476     i += 1
1477
1478
1479 def revert_makebox(document):
1480   " Convert \\makebox to TeX code "
1481   i = 0
1482   while 1:
1483     i = find_token(document.body, '\\begin_inset Box', i)
1484     if i == -1:
1485       break
1486     z = find_end_of_inset(document.body, i)
1487     if z == -1:
1488       document.warning("Malformed LyX document: Can't find end of box inset.")
1489       i += 1
1490       continue
1491     blay = find_token(document.body, "\\begin_layout", i, z)
1492     if blay == -1:
1493       document.warning("Malformed LyX document: Can't find layout in box.")
1494       i = z
1495       continue
1496     # by looking before the layout we make sure we're actually finding
1497     # an option, not text.
1498     j = find_token(document.body, 'use_makebox', i, blay)
1499     if j == -1:
1500         i = z
1501         continue
1502     
1503     if not check_token(document.body[i], "\\begin_inset Box Frameless") \
1504       or get_value(document.body, 'use_makebox', j) != 1:
1505         del document.body[j]
1506         i = z
1507         continue
1508     bend = find_end_of_layout(document.body, blay)
1509     if bend == -1 or bend > z:
1510         document.warning("Malformed LyX document: Can't find end of layout in box.")
1511         i = z
1512         continue
1513     # determine the alignment
1514     align = get_quoted_value(document.body, 'hor_pos', i, blay, "c")
1515     # determine the width
1516     length = get_quoted_value(document.body, 'width', i, blay, "50col%")
1517     length = latex_length(length)[1]
1518     # remove the \end_layout \end_inset pair
1519     document.body[bend:z + 1] = put_cmd_in_ert("}")
1520     subst = "\\makebox[" + length + "][" \
1521       + align + "]{"
1522     document.body[i:blay + 1] = put_cmd_in_ert(subst)
1523     i += 1
1524
1525
1526 def convert_use_makebox(document):
1527   " Adds use_makebox option for boxes "
1528   i = 0
1529   while 1:
1530     i = find_token(document.body, '\\begin_inset Box', i)
1531     if i == -1:
1532       return
1533     # all of this is to make sure we actually find the use_parbox
1534     # that is an option for this box, not some text elsewhere.
1535     z = find_end_of_inset(document.body, i)
1536     if z == -1:
1537       document.warning("Can't find end of box inset!!")
1538       i += 1
1539       continue
1540     blay = find_token(document.body, "\\begin_layout", i, z)
1541     if blay == -1:
1542       document.warning("Can't find layout in box inset!!")
1543       i = z
1544       continue
1545     # so now we are looking for use_parbox before the box's layout
1546     k = find_token(document.body, 'use_parbox', i, blay)
1547     if k == -1:
1548       document.warning("Malformed LyX document: Can't find use_parbox statement in box.")
1549       i = z
1550       continue
1551     document.body.insert(k + 1, "use_makebox 0")
1552     i = z + 1
1553
1554
1555 def revert_IEEEtran(document):
1556   " Convert IEEEtran layouts and styles to TeX code "
1557   if document.textclass != "IEEEtran":
1558     return
1559   revert_flex_inset(document.body, "IEEE membership", "\\IEEEmembership")
1560   revert_flex_inset(document.body, "Lowercase", "\\MakeLowercase")
1561   layouts = ("Special Paper Notice", "After Title Text", "Publication ID",
1562              "Page headings", "Biography without photo")
1563   latexcmd = {"Special Paper Notice": "\\IEEEspecialpapernotice",
1564               "After Title Text":     "\\IEEEaftertitletext",
1565               "Publication ID":       "\\IEEEpubid"}
1566   obsoletedby = {"Page headings":            "MarkBoth",
1567                  "Biography without photo":  "BiographyNoPhoto"}
1568   for layout in layouts:
1569     i = 0
1570     while True:
1571         i = find_token(document.body, '\\begin_layout ' + layout, i)
1572         if i == -1:
1573           break
1574         j = find_end_of_layout(document.body, i)
1575         if j == -1:
1576           document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1577           i += 1
1578           continue
1579         if layout in obsoletedby:
1580           document.body[i] = "\\begin_layout " + obsoletedby[layout]
1581           i = j
1582           continue
1583         content = lyx2latex(document, document.body[i:j + 1])
1584         add_to_preamble(document, [latexcmd[layout] + "{" + content + "}"])
1585         del document.body[i:j + 1]
1586         # no need to reset i
1587
1588
1589 def convert_prettyref(document):
1590         " Converts prettyref references to neutral formatted refs "
1591         re_ref = re.compile("^\s*reference\s+\"(\w+):(\S+)\"")
1592         nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
1593
1594         i = 0
1595         while True:
1596                 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
1597                 if i == -1:
1598                         break
1599                 j = find_end_of_inset(document.body, i)
1600                 if j == -1:
1601                         document.warning("Malformed LyX document: No end of InsetRef!")
1602                         i += 1
1603                         continue
1604                 k = find_token(document.body, "LatexCommand prettyref", i, j)
1605                 if k != -1:
1606                         document.body[k] = "LatexCommand formatted"
1607                 i = j + 1
1608         document.header.insert(-1, "\\use_refstyle 0")
1609                 
1610  
1611 def revert_refstyle(document):
1612         " Reverts neutral formatted refs to prettyref "
1613         re_ref = re.compile("^reference\s+\"(\w+):(\S+)\"")
1614         nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
1615
1616         i = 0
1617         while True:
1618                 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
1619                 if i == -1:
1620                         break
1621                 j = find_end_of_inset(document.body, i)
1622                 if j == -1:
1623                         document.warning("Malformed LyX document: No end of InsetRef")
1624                         i += 1
1625                         continue
1626                 k = find_token(document.body, "LatexCommand formatted", i, j)
1627                 if k != -1:
1628                         document.body[k] = "LatexCommand prettyref"
1629                 i = j + 1
1630         i = find_token(document.header, "\\use_refstyle", 0)
1631         if i != -1:
1632                 document.header.pop(i)
1633  
1634
1635 def revert_nameref(document):
1636   " Convert namerefs to regular references "
1637   cmds = ["Nameref", "nameref"]
1638   foundone = False
1639   rx = re.compile(r'reference "(.*)"')
1640   for cmd in cmds:
1641     i = 0
1642     oldcmd = "LatexCommand " + cmd
1643     while 1:
1644       # It seems better to look for this, as most of the reference
1645       # insets won't be ones we care about.
1646       i = find_token(document.body, oldcmd, i)
1647       if i == -1:
1648         break
1649       cmdloc = i
1650       i += 1
1651       # Make sure it is actually in an inset!
1652       # A normal line could begin with "LatexCommand nameref"!
1653       val = is_in_inset(document.body, cmdloc, \
1654           "\\begin_inset CommandInset ref")
1655       if not val:
1656           continue
1657       stins, endins = val
1658
1659       # ok, so it is in an InsetRef
1660       refline = find_token(document.body, "reference", stins, endins)
1661       if refline == -1:
1662         document.warning("Can't find reference for inset at line " + stinst + "!!")
1663         continue
1664       m = rx.match(document.body[refline])
1665       if not m:
1666         document.warning("Can't match reference line: " + document.body[ref])
1667         continue
1668       foundone = True
1669       ref = m.group(1)
1670       newcontent = put_cmd_in_ert('\\' + cmd + '{' + ref + '}')
1671       document.body[stins:endins + 1] = newcontent
1672
1673   if foundone:
1674     add_to_preamble(document, ["\usepackage{nameref}"])
1675
1676
1677 def remove_Nameref(document):
1678   " Convert Nameref commands to nameref commands "
1679   i = 0
1680   while 1:
1681     # It seems better to look for this, as most of the reference
1682     # insets won't be ones we care about.
1683     i = find_token(document.body, "LatexCommand Nameref" , i)
1684     if i == -1:
1685       break
1686     cmdloc = i
1687     i += 1
1688     
1689     # Make sure it is actually in an inset!
1690     val = is_in_inset(document.body, cmdloc, \
1691         "\\begin_inset CommandInset ref")
1692     if not val:
1693       continue
1694     document.body[cmdloc] = "LatexCommand nameref"
1695
1696
1697 def revert_mathrsfs(document):
1698     " Load mathrsfs if \mathrsfs us use in the document "
1699     i = 0
1700     for line in document.body:
1701       if line.find("\\mathscr{") != -1:
1702         add_to_preamble(document, ["\\usepackage{mathrsfs}"])
1703         return
1704
1705
1706 def convert_flexnames(document):
1707     "Convert \\begin_inset Flex Custom:Style to \\begin_inset Flex Style and similarly for CharStyle and Element."
1708     
1709     i = 0
1710     rx = re.compile(r'^\\begin_inset Flex (?:Custom|CharStyle|Element):(.+)$')
1711     while True:
1712       i = find_token(document.body, "\\begin_inset Flex", i)
1713       if i == -1:
1714         return
1715       m = rx.match(document.body[i])
1716       if m:
1717         document.body[i] = "\\begin_inset Flex " + m.group(1)
1718       i += 1
1719
1720
1721 flex_insets = {
1722   "Alert" : "CharStyle:Alert",
1723   "Code" : "CharStyle:Code",
1724   "Concepts" : "CharStyle:Concepts",
1725   "E-Mail" : "CharStyle:E-Mail",
1726   "Emph" : "CharStyle:Emph",
1727   "Expression" : "CharStyle:Expression",
1728   "Initial" : "CharStyle:Initial",
1729   "Institute" : "CharStyle:Institute",
1730   "Meaning" : "CharStyle:Meaning",
1731   "Noun" : "CharStyle:Noun",
1732   "Strong" : "CharStyle:Strong",
1733   "Structure" : "CharStyle:Structure",
1734   "ArticleMode" : "Custom:ArticleMode",
1735   "Endnote" : "Custom:Endnote",
1736   "Glosse" : "Custom:Glosse",
1737   "PresentationMode" : "Custom:PresentationMode",
1738   "Tri-Glosse" : "Custom:Tri-Glosse"
1739 }
1740
1741 flex_elements = {
1742   "Abbrev" : "Element:Abbrev",
1743   "CCC-Code" : "Element:CCC-Code",
1744   "Citation-number" : "Element:Citation-number",
1745   "City" : "Element:City",
1746   "Code" : "Element:Code",
1747   "CODEN" : "Element:CODEN",
1748   "Country" : "Element:Country",
1749   "Day" : "Element:Day",
1750   "Directory" : "Element:Directory",
1751   "Dscr" : "Element:Dscr",
1752   "Email" : "Element:Email",
1753   "Emph" : "Element:Emph",
1754   "Filename" : "Element:Filename",
1755   "Firstname" : "Element:Firstname",
1756   "Fname" : "Element:Fname",
1757   "GuiButton" : "Element:GuiButton",
1758   "GuiMenu" : "Element:GuiMenu",
1759   "GuiMenuItem" : "Element:GuiMenuItem",
1760   "ISSN" : "Element:ISSN",
1761   "Issue-day" : "Element:Issue-day",
1762   "Issue-months" : "Element:Issue-months",
1763   "Issue-number" : "Element:Issue-number",
1764   "KeyCap" : "Element:KeyCap",
1765   "KeyCombo" : "Element:KeyCombo",
1766   "Keyword" : "Element:Keyword",
1767   "Literal" : "Element:Literal",
1768   "MenuChoice" : "Element:MenuChoice",
1769   "Month" : "Element:Month",
1770   "Orgdiv" : "Element:Orgdiv",
1771   "Orgname" : "Element:Orgname",
1772   "Postcode" : "Element:Postcode",
1773   "SS-Code" : "Element:SS-Code",
1774   "SS-Title" : "Element:SS-Title",
1775   "State" : "Element:State",
1776   "Street" : "Element:Street",
1777   "Surname" : "Element:Surname",
1778   "Volume" : "Element:Volume",
1779   "Year" : "Element:Year"
1780 }
1781
1782
1783 def revert_flexnames(document):
1784   if document.backend == "latex":
1785     flexlist = flex_insets
1786   else:
1787     flexlist = flex_elements
1788   
1789   rx = re.compile(r'^\\begin_inset Flex\s+(.+)$')
1790   i = 0
1791   while True:
1792     i = find_token(document.body, "\\begin_inset Flex", i)
1793     if i == -1:
1794       return
1795     m = rx.match(document.body[i])
1796     if not m:
1797       document.warning("Illegal flex inset: " + document.body[i])
1798       i += 1
1799       continue
1800     style = m.group(1)
1801     if style in flexlist:
1802       document.body[i] = "\\begin_inset Flex " + flexlist[style]
1803     i += 1
1804
1805
1806 def convert_mathdots(document):
1807     " Load mathdots automatically "
1808     i = find_token(document.header, "\\use_esint" , 0)
1809     if i != -1:
1810       document.header.insert(i + 1, "\\use_mathdots 1")
1811
1812
1813 def revert_mathdots(document):
1814     " Load mathdots if used in the document "
1815
1816     mathdots = find_token(document.header, "\\use_mathdots" , 0)
1817     if mathdots == -1:
1818       document.warning("No \\usemathdots line. Assuming auto.")
1819     else:
1820       val = get_value(document.header, "\\use_mathdots", mathdots)
1821       del document.header[mathdots]
1822       try:
1823         usedots = int(val)
1824       except:
1825         document.warning("Invalid \\use_mathdots value: " + val + ". Assuming auto.")
1826         # probably usedots has not been changed, but be safe.
1827         usedots = 1
1828
1829       if usedots == 0:
1830         # do not load case
1831         return
1832       if usedots == 2:
1833         # force load case
1834         add_to_preamble(["\\usepackage{mathdots}"])
1835         return
1836     
1837     # so we are in the auto case. we want to load mathdots if \iddots is used.
1838     i = 0
1839     while True:
1840       i = find_token(document.body, '\\begin_inset Formula', i)
1841       if i == -1:
1842         return
1843       j = find_end_of_inset(document.body, i)
1844       if j == -1:
1845         document.warning("Malformed LyX document: Can't find end of Formula inset at line " + str(i))
1846         i += 1
1847         continue
1848       code = "\n".join(document.body[i:j])
1849       if code.find("\\iddots") != -1:
1850         add_to_preamble(document, ["\\@ifundefined{iddots}{\\usepackage{mathdots}}"])
1851         return
1852       i = j
1853
1854
1855 def convert_rule(document):
1856     " Convert \\lyxline to CommandInset line. "
1857     i = 0
1858     
1859     inset = ['\\begin_inset CommandInset line',
1860       'LatexCommand rule',
1861       'offset "0.5ex"',
1862       'width "100line%"',
1863       'height "1pt"', '',
1864       '\\end_inset', '', '']
1865
1866     # if paragraphs are indented, we may have to unindent to get the
1867     # line to be full-width.
1868     indent = get_value(document.header, "\\paragraph_separation", 0)
1869     have_indent = (indent == "indent")
1870
1871     while True:
1872       i = find_token(document.body, "\\lyxline" , i)
1873       if i == -1:
1874         return
1875
1876       # we need to find out if this line follows other content
1877       # in its paragraph. find its layout....
1878       lastlay = find_token_backwards(document.body, "\\begin_layout", i)
1879       if lastlay == -1:
1880         document.warning("Can't find layout for line at " + str(i))
1881         # do the best we can.
1882         document.body[i:i+1] = inset
1883         i += len(inset)
1884         continue
1885
1886       # ...and look for other content before it.
1887       lineisfirst = True
1888       for line in document.body[lastlay + 1:i]:
1889         # is it empty or a paragraph option?
1890         if not line or line[0] == '\\':
1891           continue
1892         lineisfirst = False
1893         break
1894
1895       if lineisfirst:
1896         document.body[i:i+1] = inset
1897         if indent:
1898           # we need to unindent, lest the line be too long
1899           document.body.insert(lastlay + 1, "\\noindent")
1900         i += len(inset)
1901       else:
1902         # so our line is in the middle of a paragraph
1903         # we need to add a new line, lest this line follow the
1904         # other content on that line and run off the side of the page
1905         document.body[i:i+1] = inset
1906         document.body[i:i] = ["\\begin_inset Newline newline", "\\end_inset", ""]
1907       i += len(inset)
1908
1909
1910 def revert_rule(document):
1911     " Revert line insets to Tex code "
1912     i = 0
1913     while 1:
1914       i = find_token(document.body, "\\begin_inset CommandInset line" , i)
1915       if i == -1:
1916         return
1917       # find end of inset
1918       j = find_token(document.body, "\\end_inset" , i)
1919       if j == -1:
1920         document.warning("Malformed LyX document: Can't find end of line inset.")
1921         return
1922       # determine the optional offset
1923       offset = get_quoted_value(document.body, 'offset', i, j)
1924       if offset:
1925         offset = '[' + offset + ']'
1926       # determine the width
1927       width = get_quoted_value(document.body, 'width', i, j, "100col%")
1928       width = latex_length(width)[1]
1929       # determine the height
1930       height = get_quoted_value(document.body, 'height', i, j, "1pt")
1931       height = latex_length(height)[1]
1932       # output the \rule command
1933       subst = "\\rule[" + offset + "]{" + width + "}{" + height + "}"
1934       document.body[i:j + 1] = put_cmd_in_ert(subst)
1935       i += len(subst) - (j - i)
1936
1937
1938 def revert_diagram(document):
1939   " Add the feyn package if \\Diagram is used in math "
1940   i = 0
1941   while True:
1942     i = find_token(document.body, '\\begin_inset Formula', i)
1943     if i == -1:
1944       return
1945     j = find_end_of_inset(document.body, i)
1946     if j == -1:
1947         document.warning("Malformed LyX document: Can't find end of Formula inset.")
1948         return 
1949     lines = "\n".join(document.body[i:j])
1950     if lines.find("\\Diagram") == -1:
1951       i = j
1952       continue
1953     add_to_preamble(document, ["\\usepackage{feyn}"])
1954     # only need to do it once!
1955     return
1956
1957
1958 def convert_bibtex_clearpage(document):
1959   " insert a clear(double)page bibliographystyle if bibtotoc option is used "
1960
1961   i = find_token(document.header, '\\papersides', 0)
1962   sides = 0
1963   if i == -1:
1964     document.warning("Malformed LyX document: Can't find papersides definition.")
1965     document.warning("Assuming single sided.")
1966     sides = 1
1967   else:
1968     val = get_value(document.header, "\\papersides", i)
1969     try:
1970       sides = int(val)
1971     except:
1972       pass
1973     if sides != 1 and sides != 2:
1974       document.warning("Invalid papersides value: " + val)
1975       document.warning("Assuming single sided.")
1976       sides = 1
1977
1978   j = 0
1979   while True:
1980     j = find_token(document.body, "\\begin_inset CommandInset bibtex", j)
1981     if j == -1:
1982       return
1983
1984     k = find_end_of_inset(document.body, j)
1985     if k == -1:
1986       document.warning("Can't find end of Bibliography inset at line " + str(j))
1987       j += 1
1988       continue
1989
1990     # only act if there is the option "bibtotoc"
1991     val = get_value(document.body, 'options', j, k)
1992     if not val:
1993       document.warning("Can't find options for bibliography inset at line " + str(j))
1994       j = k
1995       continue
1996     
1997     if val.find("bibtotoc") == -1:
1998       j = k
1999       continue
2000     
2001     # so we want to insert a new page right before the paragraph that
2002     # this bibliography thing is in. 
2003     lay = find_token_backwards(document.body, "\\begin_layout", j)
2004     if lay == -1:
2005       document.warning("Can't find layout containing bibliography inset at line " + str(j))
2006       j = k
2007       continue
2008
2009     if sides == 1:
2010       cmd = "clearpage"
2011     else:
2012       cmd = "cleardoublepage"
2013     subst = ['\\begin_layout Standard',
2014         '\\begin_inset Newpage ' + cmd,
2015         '\\end_inset', '', '',
2016         '\\end_layout', '']
2017     document.body[lay:lay] = subst
2018     j = k + len(subst)
2019
2020
2021 def check_passthru(document):
2022   tc = document.textclass
2023   ok = (tc == "literate-article" or tc == "literate-book" or tc == "literate-report")
2024   if not ok:
2025     mods = document.get_module_list()
2026     for mod in mods:
2027       if mod == "sweave" or mod == "noweb":
2028         ok = True
2029         break
2030   return ok
2031
2032
2033 def convert_passthru(document):
2034     " http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg161298.html "
2035     if not check_passthru:
2036       return
2037     
2038     rx = re.compile("\\\\begin_layout \s*(\w+)")
2039     beg = 0
2040     for lay in ["Chunk", "Scrap"]:
2041       while True:
2042         beg = find_token(document.body, "\\begin_layout " + lay, beg)
2043         if beg == -1:
2044           break
2045         end = find_end_of_layout(document.body, beg)
2046         if end == -1:
2047           document.warning("Can't find end of layout at line " + str(beg))
2048           beg += 1
2049           continue
2050         # we are now going to replace newline insets within this layout
2051         # by new instances of this layout. so we have repeated layouts
2052         # instead of newlines.
2053         ns = beg
2054         while True:
2055           ns = find_token(document.body, "\\begin_inset Newline newline", ns, end)
2056           if ns == -1:
2057             break
2058           ne = find_end_of_inset(document.body, ns)
2059           if ne == -1 or ne > end:
2060             document.warning("Can't find end of inset at line " + str(nb))
2061             ns += 1
2062             continue
2063           if document.body[ne + 1] == "":
2064             ne += 1
2065           subst = ["\\end_layout", "", "\\begin_layout " + lay]
2066           document.body[ns:ne + 1] = subst
2067           # now we need to adjust end, in particular, but might as well
2068           # do ns properly, too
2069           newlines = (ne - ns) - len(subst)
2070           ns += newlines + 2
2071           end += newlines + 1
2072         # ok, we now want to find out if the next layout is the
2073         # same as this one. if so, we will insert an extra copy of it
2074         didit = False
2075         next = find_token(document.body, "\\begin_layout", end)
2076         if next != -1:
2077           m = rx.match(document.body[next])
2078           if m:
2079             nextlay = m.group(1)
2080             if nextlay == lay:
2081               subst = ["\\begin_layout " + lay, "", "\\end_layout", ""]
2082               document.body[next:next] = subst
2083               didit = True
2084         beg = end + 1
2085         if didit:
2086           beg += 4 # for the extra layout
2087     
2088
2089 def revert_passthru(document):
2090     " http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg161298.html "
2091     if not check_passthru:
2092       return
2093     rx = re.compile("\\\\begin_layout \s*(\w+)")
2094     beg = 0
2095     for lay in ["Chunk", "Scrap"]:
2096       while True:
2097         beg = find_token(document.body, "\\begin_layout " + lay, beg)
2098         if beg == -1:
2099           break
2100         end = find_end_of_layout(document.body, beg)
2101         if end == -1:
2102           document.warning("Can't find end of layout at line " + str(beg))
2103           beg += 1
2104           continue
2105         
2106         # we now want to find out if the next layout is the
2107         # same as this one. but we will need to do this over and
2108         # over again.
2109         while True:
2110           next = find_token(document.body, "\\begin_layout", end)
2111           if next == -1:
2112             break
2113           m = rx.match(document.body[next])
2114           if not m:
2115             break
2116           nextlay = m.group(1)
2117           if nextlay != lay:
2118             break
2119           # so it is the same layout again. we now want to know if it is empty.
2120           # but first let's check and make sure there is no content between the
2121           # two layouts. i'm not sure if that can happen or not.
2122           for l in range(end + 1, next):
2123             document.warning("c'" + document.body[l] + "'")
2124             if document.body[l] != "":
2125               document.warning("Found content between adjacent " + lay + " layouts!")
2126               break
2127           nextend = find_end_of_layout(document.body, next)
2128           if nextend == -1:
2129             document.warning("Can't find end of layout at line " + str(next))
2130             break
2131           empty = True
2132           for l in range(next + 1, nextend):
2133             document.warning("e'" + document.body[l] + "'")
2134             if document.body[l] != "":
2135               empty = False
2136               break
2137           if empty:
2138             # empty layouts just get removed
2139             # should we check if it's before yet another such layout?
2140             del document.body[next : nextend + 1]
2141             # and we do not want to check again. we know the next layout
2142             # should be another Chunk and should be left as is.
2143             break
2144           else:
2145             # if it's not empty, then we want to insert a newline in place
2146             # of the layout switch
2147             subst = ["\\begin_inset Newline newline", "\\end_inset", ""]
2148             document.body[end : next + 1] = subst
2149             # and now we have to find the end of the new, larger layout
2150             newend = find_end_of_layout(document.body, beg)
2151             if newend == -1:
2152               document.warning("Can't find end of new layout at line " + str(beg))
2153               break
2154             end = newend
2155         beg = end + 1
2156
2157
2158 def revert_multirowOffset(document):
2159     " Revert multirow cells with offset in tables to TeX-code"
2160     # this routine is the same as the revert_multirow routine except that
2161     # it checks additionally for the offset
2162     i = 0
2163     begin_table = 0
2164     bottom_index = 0
2165     multirowOffset = False
2166     # cell type 3 is multirow begin cell
2167     i = find_token(document.body, '<cell multirow="3" mroffset=', i)
2168     if i == -1:
2169       return
2170     # a multirow cell with offset was found
2171     multirowOffset = True
2172     while True:
2173       # find begin/end of table
2174       begin_table = find_token(document.body, '<lyxtabular version=', begin_table)
2175       if begin_table == -1:
2176           break
2177       end_table = find_token(document.body, '</lyxtabular>', begin_table)
2178       if end_table == -1:
2179           document.warning("Malformed LyX document: Could not find end of table.")
2180           break
2181       # store the number of rows
2182       begin = document.body[begin_table].find('rows="')
2183       end = document.body[begin_table].find('" ', begin)
2184       rows = document.body[begin_table][begin + 6:end]
2185       # store the number of columns
2186       begin = document.body[begin_table].find('columns="')
2187       end = document.body[begin_table].find('">', begin)
2188       columns = document.body[begin_table][begin + 9:end]
2189       # find column number of the multirows with offset
2190       begin_row = begin_table
2191       for row in range(int(rows)):
2192         begin_row = find_token(document.body, '<row>', begin_row)
2193         begin_cell = begin_row
2194         for column in range(int(columns)):            
2195           begin_cell = find_token(document.body, '<cell ', begin_cell)
2196           i = document.body[begin_cell].find('multirow="3" mroffset=')
2197           if i <> -1:
2198             # we found a multirow in column number column - 1
2199             # store column width
2200             begin = document.body[begin_table + 2 + column].find('width="')
2201             end = document.body[begin_table + 2 + column].find('">', begin)
2202             col_width = document.body[begin_table + 2 + column][begin + 7:end]
2203             # "0pt" means that no width is specified
2204             if col_width == "0pt":
2205               col_width = "*"
2206             # determine the number of cells that are part of the multirow
2207             begin_row2 = begin_table
2208             # we have the multirow begin cell as minimal span
2209             span = 1
2210             # go one row behind the row where we found the multirow begin
2211             row2 = -1
2212             while row2 < row:
2213               begin_row2 = find_token(document.body, '<row>', begin_row2)
2214               row2 += 1
2215               begin_row2 += 1
2216             # step now through all rows until we reach the last table row
2217             rows2 = row
2218             while row2 < rows:
2219               begin_row2 = find_token(document.body, '<row>', begin_row2)
2220               begin_cell2 = begin_row2
2221               # look now for the column-th cell in the row
2222               column2 = 0
2223               while column2 < column:
2224                 begin_cell2 = find_token(document.body, '<cell ', begin_cell2)
2225                 column2 += 1
2226                 begin_cell2 += 1
2227               # cell type 4 is multirow-part cell
2228               begin_cell2 = find_token(document.body, '<cell ', begin_cell2)
2229               j = document.body[begin_cell2].find('multirow="4"')
2230               if j <> -1:
2231                 span += 1
2232                 # remove bottom line of previous multirow-part cell
2233                 if span > 1:
2234                   document.body[bottom_index] = document.body[bottom_index].replace(' bottomline="true" ', ' ')
2235                 # save index to be later able to remove bottom line
2236                 bottom_index = begin_cell2
2237                 # remove the multirow tag, set the valignment to top
2238                 # and remove the top line
2239                 document.body[begin_cell2] = document.body[begin_cell2].replace(' multirow="4" ', ' ')
2240                 document.body[begin_cell2] = document.body[begin_cell2].replace('valignment="middle"', 'valignment="top"')
2241                 document.body[begin_cell2] = document.body[begin_cell2].replace(' topline="true" ', ' ')
2242               else:
2243                 break
2244               begin_row2 = find_token(document.body, '</row>', begin_row2)
2245             # remove the multirow tag, set the valignment to top,
2246             # remove the the bottom line and offset
2247             document.body[begin_cell] = document.body[begin_cell].replace(' multirow="3" ', ' ')
2248             document.body[begin_cell] = document.body[begin_cell].replace('valignment="middle"', 'valignment="top"')
2249             # only remove the bottom line if it is not a single cell as multirow
2250             if span > 1:
2251               document.body[begin_cell] = document.body[begin_cell].replace(' bottomline="true" ', ' ')
2252             document.body[begin_cell] = document.body[begin_cell].replace(' mroffset=', '')
2253             # store the offset and remove it
2254             begin = document.body[begin_cell].find('"')
2255             end = document.body[begin_cell].find('" ', begin)
2256             offset = document.body[begin_cell][begin + 1:end]
2257             document.body[begin_cell] = document.body[begin_cell].replace(document.body[begin_cell][begin:end + 1], '')
2258             # write ERT to create the multirow cell
2259             cend = find_token(document.body, "</cell>", begin_cell)
2260             if cend == -1:
2261               document.warning("Malformed LyX document: Could not find end of tabular cell.")
2262               i += 1
2263               continue
2264             blay = find_token(document.body, "\\begin_layout", begin_cell, cend)
2265             if blay == -1:
2266               document.warning("Can't find layout for cell!")
2267               i = j
2268               continue
2269             bend = find_end_of_layout(document.body, blay)
2270             if bend == -1:
2271               document.warning("Can't find end of layout for cell!")
2272               i = cend
2273               continue
2274             # do the later one first, so as not to mess up the numbering
2275             # we are wrapping the whole cell in this ert
2276             # so before the end of the layout...
2277             document.body[bend:bend] = put_cmd_in_ert("}")
2278             # ...and after the beginning
2279             document.body[blay + 1:blay + 1] = put_cmd_in_ert("\\multirow{" + str(span) + "}{" + col_width + "}[" + offset + "]{")
2280           # set index to end of current cell (that is now much bigger due to the ERT addition)
2281           begin_cell = find_token(document.body, '</cell>', begin_cell) + 1
2282         begin_row = find_token(document.body, '</row>', begin_row) + 1
2283
2284       # go to the next table
2285       begin_table = end_table + 1
2286
2287     if multirowOffset == True:
2288         add_to_preamble(document, ["\\usepackage{multirow}"])
2289
2290
2291 ##
2292 # Conversion hub
2293 #
2294
2295 supported_versions = ["2.0.0","2.0"]
2296 convert = [[346, []],
2297            [347, []],
2298            [348, []],
2299            [349, []],
2300            [350, []],
2301            [351, []],
2302            [352, [convert_splitindex]],
2303            [353, []],
2304            [354, []],
2305            [355, []],
2306            [356, []],
2307            [357, []],
2308            [358, []],
2309            [359, [convert_nomencl_width]],
2310            [360, []],
2311            [361, []],
2312            [362, []],
2313            [363, []],
2314            [364, []],
2315            [365, []],
2316            [366, []],
2317            [367, []],
2318            [368, []],
2319            [369, [convert_author_id]],
2320            [370, []],
2321            [371, []],
2322            [372, []],
2323            [373, [merge_gbrief]],
2324            [374, []],
2325            [375, []],
2326            [376, []],
2327            [377, []],
2328            [378, []],
2329            [379, [convert_math_output]],
2330            [380, []],
2331            [381, []],
2332            [382, []],
2333            [383, []],
2334            [384, []],
2335            [385, []],
2336            [386, []],
2337            [387, []],
2338            [388, []],
2339            [389, [convert_html_quotes]],
2340            [390, []],
2341            [391, []],
2342            [392, []],
2343            [393, [convert_optarg]],
2344            [394, [convert_use_makebox]],
2345            [395, []],
2346            [396, []],
2347            [397, [remove_Nameref]],
2348            [398, []],
2349            [399, [convert_mathdots]],
2350            [400, [convert_rule]],
2351            [401, []],
2352            [402, [convert_bibtex_clearpage]],
2353            [403, [convert_flexnames]],
2354            [404, [convert_prettyref]],
2355            [405, []],
2356            [406, [convert_passthru]],
2357            [407, []]
2358 ]
2359
2360 revert =  [[406, [revert_multirowOffset]],
2361            [405, [revert_passthru]],
2362            [404, []],
2363            [403, [revert_refstyle]],
2364            [402, [revert_flexnames]],
2365            [401, []],
2366            [400, [revert_diagram]],
2367            [399, [revert_rule]],
2368            [398, [revert_mathdots]],
2369            [397, [revert_mathrsfs]],
2370            [396, []],
2371            [395, [revert_nameref]],
2372            [394, [revert_DIN_C_pagesizes]],
2373            [393, [revert_makebox]],
2374            [392, [revert_argument]],
2375            [391, []],
2376            [390, [revert_align_decimal, revert_IEEEtran]],
2377            [389, [revert_output_sync]],
2378            [388, [revert_html_quotes]],
2379            [387, [revert_pagesizes]],
2380            [386, [revert_math_scale]],
2381            [385, [revert_lyx_version]],
2382            [384, [revert_shadedboxcolor]],
2383            [383, [revert_fontcolor]],
2384            [382, [revert_turkmen]],
2385            [381, [revert_notefontcolor]],
2386            [380, [revert_equalspacing_xymatrix]],
2387            [379, [revert_inset_preview]],
2388            [378, [revert_math_output]],
2389            [377, []],
2390            [376, [revert_multirow]],
2391            [375, [revert_includeall]],
2392            [374, [revert_includeonly]],
2393            [373, [revert_html_options]],
2394            [372, [revert_gbrief]],
2395            [371, [revert_fontenc]],
2396            [370, [revert_mhchem]],
2397            [369, [revert_suppress_date]],
2398            [368, [revert_author_id]],
2399            [367, [revert_hspace_glue_lengths]],
2400            [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
2401            [365, [revert_percent_skip_lengths]],
2402            [364, [revert_paragraph_indentation]],
2403            [363, [revert_branch_filename]],
2404            [362, [revert_longtable_align]],
2405            [361, [revert_applemac]],
2406            [360, []],
2407            [359, [revert_nomencl_cwidth]],
2408            [358, [revert_nomencl_width]],
2409            [357, [revert_custom_processors]],
2410            [356, [revert_ulinelatex]],
2411            [355, []],
2412            [354, [revert_strikeout]],
2413            [353, [revert_printindexall]],
2414            [352, [revert_subindex]],
2415            [351, [revert_splitindex]],
2416            [350, [revert_backgroundcolor]],
2417            [349, [revert_outputformat]],
2418            [348, [revert_xetex]],
2419            [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2420            [346, [revert_tabularvalign]],
2421            [345, [revert_swiss]]
2422           ]
2423
2424
2425 if __name__ == "__main__":
2426     pass