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