]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_1_4.py
6cdc0391b4cea92d8cf14f8f7a75d724a270e49c
[lyx.git] / lib / lyx2lyx / lyx_1_4.py
1 # This file is part of lyx2lyx
2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2002 Dekel Tsur <dekel@lyx.org>
4 # Copyright (C) 2002-2004 José Matos <jamatos@lyx.org>
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 import re
21 from os import access, F_OK
22 import os.path
23 from parser_tools import find_token, find_end_of_inset, get_next_paragraph, \
24                          get_paragraph, get_value, del_token, is_nonempty_line,\
25                          find_tokens, find_end_of, find_token2
26 from sys import stdin
27 from string import replace, split, find, strip, join
28
29 ##
30 # Remove \color default
31 #
32 def remove_color_default(file):
33     i = 0
34     while 1:
35         i = find_token(file.body, "\\color default", i)
36         if i == -1:
37             return
38         file.body[i] = replace(file.body[i], "\\color default",
39                            "\\color inherit")
40
41
42 ##
43 # Add \end_header
44 #
45 def add_end_header(file):
46     file.header.append("\\end_header");
47
48
49 def rm_end_header(file):
50     i = find_token(file.header, "\\end_header", 0)
51     if i == -1:
52         return
53     del file.header[i]
54
55
56 ##
57 # \SpecialChar ~ -> \InsetSpace ~
58 #
59 def convert_spaces(file):
60     for i in range(len(file.body)):
61         file.body[i] = replace(file.body[i],"\\SpecialChar ~","\\InsetSpace ~")
62
63
64 def revert_spaces(file):
65     for i in range(len(file.body)):
66         file.body[i] = replace(file.body[i],"\\InsetSpace ~", "\\SpecialChar ~")
67
68
69 ##
70 # BibTeX changes
71 #
72 def convert_bibtex(file):
73     for i in range(len(file.body)):
74         file.body[i] = replace(file.body[i],"\\begin_inset LatexCommand \\BibTeX",
75                                   "\\begin_inset LatexCommand \\bibtex")
76
77
78 def revert_bibtex(file):
79     for i in range(len(file.body)):
80         file.body[i] = replace(file.body[i], "\\begin_inset LatexCommand \\bibtex",
81                                   "\\begin_inset LatexCommand \\BibTeX")
82
83
84 ##
85 # Remove \lyxparent
86 #
87 def remove_insetparent(file):
88     i = 0
89     while 1:
90         i = find_token(file.body, "\\begin_inset LatexCommand \\lyxparent", i)
91         if i == -1:
92             break
93         del file.body[i:i+3]
94
95
96 ##
97 #  Inset External
98 #
99 def convert_external(file):
100     external_rexp = re.compile(r'\\begin_inset External ([^,]*),"([^"]*)",')
101     external_header = "\\begin_inset External"
102     i = 0
103     while 1:
104         i = find_token(file.body, external_header, i)
105         if i == -1:
106             break
107         look = external_rexp.search(file.body[i])
108         args = ['','']
109         if look:
110             args[0] = look.group(1)
111             args[1] = look.group(2)
112         #FIXME: if the previous search fails then warn
113
114         if args[0] == "RasterImage":
115             # Convert a RasterImage External Inset to a Graphics Inset.
116             top = "\\begin_inset Graphics"
117             if args[1]:
118                 filename = "\tfilename " + args[1]
119             file.body[i:i+1] = [top, filename]
120             i = i + 1
121         else:
122             # Convert the old External Inset format to the new.
123             top = external_header
124             template = "\ttemplate " + args[0]
125             if args[1]:
126                 filename = "\tfilename " + args[1]
127                 file.body[i:i+1] = [top, template, filename]
128                 i = i + 2
129             else:
130                 file.body[i:i+1] = [top, template]
131                 i = i + 1
132
133
134 def revert_external_1(file):
135     external_header = "\\begin_inset External"
136     i = 0
137     while 1:
138         i = find_token(file.body, external_header, i)
139         if i == -1:
140             break
141
142         template = split(file.body[i+1])
143         template.reverse()
144         del file.body[i+1]
145
146         filename = split(file.body[i+1])
147         filename.reverse()
148         del file.body[i+1]
149
150         params = split(file.body[i+1])
151         params.reverse()
152         if file.body[i+1]: del file.body[i+1]
153
154         file.body[i] = file.body[i] + " " + template[0]+ ', "' + filename[0] + '", " '+ join(params[1:]) + '"'
155         i = i + 1
156
157
158 def revert_external_2(file):
159     draft_token = '\tdraft'
160     i = 0
161     while 1:
162         i = find_token(file.body, '\\begin_inset External', i)
163         if i == -1:
164             break
165         j = find_end_of_inset(file.body, i + 1)
166         if j == -1:
167             #this should not happen
168             break
169         k = find_token(file.body, draft_token, i+1, j-1)
170         if (k != -1 and len(draft_token) == len(file.body[k])):
171             del file.body[k]
172         i = j + 1
173
174
175 ##
176 # Comment
177 #
178 def convert_comment(file):
179     i = 0
180     comment = "\\layout Comment"
181     while 1:
182         i = find_token(file.body, comment, i)
183         if i == -1:
184             return
185
186         file.body[i:i+1] = ["\\layout Standard","","",
187                         "\\begin_inset Comment",
188                         "collapsed true","",
189                         "\\layout Standard"]
190         i = i + 7
191
192         while 1:
193                 old_i = i
194                 i = find_token(file.body, "\\layout", i)
195                 if i == -1:
196                     i = len(file.body) - 1
197                     file.body[i:i] = ["\\end_inset","",""]
198                     return
199
200                 j = find_token(file.body, '\\begin_deeper', old_i, i)
201                 if j == -1: j = i + 1
202                 k = find_token(file.body, '\\begin_inset', old_i, i)
203                 if k == -1: k = i + 1
204
205                 if j < i and j < k:
206                     i = j
207                     del file.body[i]
208                     i = find_end_of( file.body, i, "\\begin_deeper","\\end_deeper")
209                     if i == -1:
210                         #This case should not happen
211                         #but if this happens deal with it greacefully adding
212                         #the missing \end_deeper.
213                         i = len(file.body) - 1
214                         file.body[i:i] = ["\end_deeper",""]
215                         return
216                     else:
217                         del file.body[i]
218                         continue
219
220                 if k < i:
221                     i = k
222                     i = find_end_of( file.body, i, "\\begin_inset","\\end_inset")
223                     if i == -1:
224                         #This case should not happen
225                         #but if this happens deal with it greacefully adding
226                         #the missing \end_inset.
227                         i = len(file.body) - 1
228                         file.body[i:i] = ["\\end_inset","","","\\end_inset","",""]
229                         return
230                     else:
231                         i = i + 1
232                         continue
233
234                 if find(file.body[i], comment) == -1:
235                     file.body[i:i] = ["\\end_inset"]
236                     i = i + 1
237                     break
238                 file.body[i:i+1] = ["\\layout Standard"]
239                 i = i + 1
240
241
242 def revert_comment(file):
243     i = 0
244     while 1:
245         i = find_tokens(file.body, ["\\begin_inset Comment", "\\begin_inset Greyedout"], i)
246
247         if i == -1:
248             return
249         file.body[i] = "\\begin_inset Note"
250         i = i + 1
251
252
253 ##
254 # Add \end_layout
255 #
256 def add_end_layout(file):
257     i = find_token(file.body, '\\layout', 0)
258
259     if i == -1:
260         return
261
262     i = i + 1
263     struct_stack = ["\\layout"]
264
265     while 1:
266         i = find_tokens(file.body, ["\\begin_inset", "\\end_inset", "\\layout",
267                                 "\\begin_deeper", "\\end_deeper", "\\the_end"], i)
268
269         token = split(file.body[i])[0]
270
271         if token == "\\begin_inset":
272             struct_stack.append(token)
273             i = i + 1
274             continue
275
276         if token == "\\end_inset":
277             tail = struct_stack.pop()
278             if tail == "\\layout":
279                 file.body.insert(i,"")
280                 file.body.insert(i,"\\end_layout")
281                 i = i + 2
282                 #Check if it is the correct tag
283                 struct_stack.pop()
284             i = i + 1
285             continue
286
287         if token == "\\layout":
288             tail = struct_stack.pop()
289             if tail == token:
290                 file.body.insert(i,"")
291                 file.body.insert(i,"\\end_layout")
292                 i = i + 3
293             else:
294                 struct_stack.append(tail)
295                 i = i + 1
296             struct_stack.append(token)
297             continue
298
299         if token == "\\begin_deeper":
300             file.body.insert(i,"")
301             file.body.insert(i,"\\end_layout")
302             i = i + 3
303             struct_stack.append(token)
304             continue
305
306         if token == "\\end_deeper":
307             if struct_stack[-1] == '\\layout':
308                 file.body.insert(i, '\\end_layout')
309                 i = i + 1
310                 struct_stack.pop()
311             i = i + 1
312             continue
313
314         #case \end_document
315         file.body.insert(i, "")
316         file.body.insert(i, "\\end_layout")
317         return
318
319
320 def rm_end_layout(file):
321     i = 0
322     while 1:
323         i = find_token(file.body, '\\end_layout', i)
324
325         if i == -1:
326             return
327
328         del file.body[i]
329
330
331 ##
332 # Handle change tracking keywords
333 #
334 def insert_tracking_changes(file):
335     i = find_token(file.header, "\\tracking_changes", 0)
336     if i == -1:
337         file.header.append("\\tracking_changes 0")
338
339
340 def rm_tracking_changes(file):
341     i = find_token(file.header, "\\author", 0)
342     if i != -1:
343         del file.header[i]
344
345     i = find_token(file.header, "\\tracking_changes", 0)
346     if i == -1:
347         return
348     del file.header[i]
349
350
351 def rm_body_changes(file):
352     i = 0
353     while 1:
354         i = find_token(file.body, "\\change_", i)
355         if i == -1:
356             return
357
358         del file.body[i]
359
360
361 ##
362 # \layout -> \begin_layout
363 #
364 def layout2begin_layout(file):
365     i = 0
366     while 1:
367         i = find_token(file.body, '\\layout', i)
368         if i == -1:
369             return
370
371         file.body[i] = replace(file.body[i], '\\layout', '\\begin_layout')
372         i = i + 1
373
374
375 def begin_layout2layout(file):
376     i = 0
377     while 1:
378         i = find_token(file.body, '\\begin_layout', i)
379         if i == -1:
380             return
381
382         file.body[i] = replace(file.body[i], '\\begin_layout', '\\layout')
383         i = i + 1
384
385
386 ##
387 # valignment="center" -> valignment="middle"
388 #
389 def convert_valignment_middle(body, start, end):
390     for i in range(start, end):
391         if re.search('^<(column|cell) .*valignment="center".*>$', body[i]):
392             body[i] = replace(body[i], 'valignment="center"', 'valignment="middle"')
393
394
395 def convert_table_valignment_middle(file):
396     i = 0
397     while 1:
398         i = find_token(file.body, '\\begin_inset  Tabular', i)
399         if i == -1:
400             return
401         j = find_end_of_inset(file.body, i + 1)
402         if j == -1:
403             #this should not happen
404             convert_valignment_middle(file.body, i + 1, len(file.body))
405             return
406         convert_valignment_middle(file.body, i + 1, j)
407         i = j + 1
408
409
410 def revert_table_valignment_middle(body, start, end):
411     for i in range(start, end):
412         if re.search('^<(column|cell) .*valignment="middle".*>$', body[i]):
413             body[i] = replace(body[i], 'valignment="middle"', 'valignment="center"')
414
415
416 def revert_valignment_middle(file):
417     i = 0
418     while 1:
419         i = find_token(file.body, '\\begin_inset  Tabular', i)
420         if i == -1:
421             return
422         j = find_end_of_inset(file.body, i + 1)
423         if j == -1:
424             #this should not happen
425             revert_table_valignment_middle(file.body, i + 1, len(file.body))
426             return
427         revert_table_valignment_middle(file.body, i + 1, j)
428         i = j + 1
429
430
431 ##
432 #  \the_end -> \end_document
433 #
434 def convert_end_document(file):
435     i = find_token(file.body, "\\the_end", 0)
436     if i == -1:
437         file.body.append("\\end_document")
438         return
439     file.body[i] = "\\end_document"
440
441
442 def revert_end_document(file):
443     i = find_token(file.body, "\\end_document", 0)
444     if i == -1:
445         file.body.append("\\the_end")
446         return
447     file.body[i] = "\\the_end"
448
449
450 ##
451 # Convert line and page breaks
452 # Old:
453 #\layout Standard
454 #\line_top \line_bottom \pagebreak_top \pagebreak_bottom \added_space_top xxx \added_space_bottom yyy
455 #0
456 #
457 # New:
458 #\begin layout Standard
459 #
460 #\newpage
461 #
462 #\lyxline
463 #\begin_inset VSpace xxx
464 #\end_inset
465 #
466 #\end_layout
467 #\begin_layout Standard
468 #
469 #0
470 #\end_layout
471 #\begin_layout Standard
472 #
473 #\begin_inset VSpace xxx
474 #\end_inset
475 #\lyxline
476 #
477 #\newpage
478 #
479 #\end_layout
480 def convert_breaks(file):
481     i = 0
482     while 1:
483         i = find_token(file.body, "\\begin_layout", i)
484         if i == -1:
485             return
486         i = i + 1
487         line_top   = find(file.body[i],"\\line_top")
488         line_bot   = find(file.body[i],"\\line_bottom")
489         pb_top     = find(file.body[i],"\\pagebreak_top")
490         pb_bot     = find(file.body[i],"\\pagebreak_bottom")
491         vspace_top = find(file.body[i],"\\added_space_top")
492         vspace_bot = find(file.body[i],"\\added_space_bottom")
493
494         if line_top == -1 and line_bot == -1 and pb_bot == -1 and pb_top == -1 and vspace_top == -1 and vspace_bot == -1:
495             continue
496
497         for tag in "\\line_top", "\\line_bottom", "\\pagebreak_top", "\\pagebreak_bottom":
498             file.body[i] = replace(file.body[i], tag, "")
499
500         if vspace_top != -1:
501             # the position could be change because of the removal of other
502             # paragraph properties above
503             vspace_top = find(file.body[i],"\\added_space_top")
504             tmp_list = split(file.body[i][vspace_top:])
505             vspace_top_value = tmp_list[1]
506             file.body[i] = file.body[i][:vspace_top] + join(tmp_list[2:])
507
508         if vspace_bot != -1:
509             # the position could be change because of the removal of other
510             # paragraph properties above
511             vspace_bot = find(file.body[i],"\\added_space_bottom")
512             tmp_list = split(file.body[i][vspace_bot:])
513             vspace_bot_value = tmp_list[1]
514             file.body[i] = file.body[i][:vspace_bot] + join(tmp_list[2:])
515
516         file.body[i] = strip(file.body[i])
517         i = i + 1
518
519         #  Create an empty paragraph for line and page break that belong
520         # above the paragraph
521         if pb_top !=-1 or line_top != -1 or vspace_bot != -1:
522
523             paragraph_above = ['','\\begin_layout Standard','','']
524
525             if pb_top != -1:
526                 paragraph_above.extend(['\\newpage ',''])
527
528             if vspace_top != -1:
529                 paragraph_above.extend(['\\begin_inset VSpace ' + vspace_top_value,'\\end_inset','',''])
530
531             if line_top != -1:
532                 paragraph_above.extend(['\\lyxline ',''])
533
534             paragraph_above.extend(['\\end_layout',''])
535
536             #inset new paragraph above the current paragraph
537             file.body[i-2:i-2] = paragraph_above
538             i = i + len(paragraph_above)
539
540         # Ensure that nested style are converted later.
541         k = find_end_of(file.body, i, "\\begin_layout", "\\end_layout")
542
543         if k == -1:
544             return
545
546         if pb_top !=-1 or line_top != -1 or vspace_bot != -1:
547
548             paragraph_bellow = ['','\\begin_layout Standard','','']
549
550             if line_bot != -1:
551                 paragraph_bellow.extend(['\\lyxline ',''])
552
553             if vspace_bot != -1:
554                 paragraph_bellow.extend(['\\begin_inset VSpace ' + vspace_bot_value,'\\end_inset','',''])
555
556             if pb_bot != -1:
557                 paragraph_bellow.extend(['\\newpage ',''])
558
559             paragraph_bellow.extend(['\\end_layout',''])
560
561             #inset new paragraph above the current paragraph
562             file.body[k + 1: k + 1] = paragraph_bellow
563
564
565 ##
566 #  Notes
567 #
568 def convert_note(file):
569     i = 0
570     while 1:
571         i = find_tokens(file.body, ["\\begin_inset Note",
572                                 "\\begin_inset Comment",
573                                 "\\begin_inset Greyedout"], i)
574         if i == -1:
575             break
576
577         file.body[i] = file.body[i][0:13] + 'Note ' + file.body[i][13:]
578         i = i + 1
579
580
581 def revert_note(file):
582     note_header = "\\begin_inset Note "
583     i = 0
584     while 1:
585         i = find_token(file.body, note_header, i)
586         if i == -1:
587             break
588
589         file.body[i] = "\\begin_inset " + file.body[i][len(note_header):]
590         i = i + 1
591
592
593 ##
594 # Box
595 #
596 def convert_box(file):
597     i = 0
598     while 1:
599         i = find_tokens(file.body, ["\\begin_inset Boxed",
600                                 "\\begin_inset Doublebox",
601                                 "\\begin_inset Frameless",
602                                 "\\begin_inset ovalbox",
603                                 "\\begin_inset Ovalbox",
604                                 "\\begin_inset Shadowbox"], i)
605         if i == -1:
606             break
607
608         file.body[i] = file.body[i][0:13] + 'Box ' + file.body[i][13:]
609         i = i + 1
610
611
612 def revert_box(file):
613     box_header = "\\begin_inset Box "
614     i = 0
615     while 1:
616         i = find_token(file.body, box_header, i)
617         if i == -1:
618             break
619
620         file.body[i] = "\\begin_inset " + file.body[i][len(box_header):]
621         i = i + 1
622
623
624 ##
625 # Collapse
626 #
627 def convert_collapsable(file):
628     i = 0
629     while 1:
630         i = find_tokens(file.body, ["\\begin_inset Box",
631                                 "\\begin_inset Branch",
632                                 "\\begin_inset CharStyle",
633                                 "\\begin_inset Float",
634                                 "\\begin_inset Foot",
635                                 "\\begin_inset Marginal",
636                                 "\\begin_inset Note",
637                                 "\\begin_inset OptArg",
638                                 "\\begin_inset Wrap"], i)
639         if i == -1:
640             break
641
642         # Seach for a line starting 'collapsed'
643         # If, however, we find a line starting '\begin_layout'
644         # (_always_ present) then break with a warning message
645         i = i + 1
646         while 1:
647             if (file.body[i] == "collapsed false"):
648                 file.body[i] = "status open"
649                 break
650             elif (file.body[i] == "collapsed true"):
651                 file.body[i] = "status collapsed"
652                 break
653             elif (file.body[i][:13] == "\\begin_layout"):
654                 file.warning("Malformed LyX file.")
655                 break
656             i = i + 1
657
658         i = i + 1
659
660
661 def revert_collapsable(file):
662     i = 0
663     while 1:
664         i = find_tokens(file.body, ["\\begin_inset Box",
665                                 "\\begin_inset Branch",
666                                 "\\begin_inset CharStyle",
667                                 "\\begin_inset Float",
668                                 "\\begin_inset Foot",
669                                 "\\begin_inset Marginal",
670                                 "\\begin_inset Note",
671                                 "\\begin_inset OptArg",
672                                 "\\begin_inset Wrap"], i)
673         if i == -1:
674             break
675
676         # Seach for a line starting 'status'
677         # If, however, we find a line starting '\begin_layout'
678         # (_always_ present) then break with a warning message
679         i = i + 1
680         while 1:
681             if (file.body[i] == "status open"):
682                 file.body[i] = "collapsed false"
683                 break
684             elif (file.body[i] == "status collapsed" or
685                   file.body[i] == "status inlined"):
686                 file.body[i] = "collapsed true"
687                 break
688             elif (file.body[i][:13] == "\\begin_layout"):
689                 file.warning("Malformed LyX file.")
690                 break
691             i = i + 1
692
693         i = i + 1
694
695
696 ##
697 #  ERT
698 #
699 def convert_ert(file):
700     i = 0
701     while 1:
702         i = find_token(file.body, "\\begin_inset ERT", i)
703         if i == -1:
704             break
705
706         # Seach for a line starting 'status'
707         # If, however, we find a line starting '\begin_layout'
708         # (_always_ present) then break with a warning message
709         i = i + 1
710         while 1:
711             if (file.body[i] == "status Open"):
712                 file.body[i] = "status open"
713                 break
714             elif (file.body[i] == "status Collapsed"):
715                 file.body[i] = "status collapsed"
716                 break
717             elif (file.body[i] == "status Inlined"):
718                 file.body[i] = "status inlined"
719                 break
720             elif (file.body[i][:13] == "\\begin_layout"):
721                 file.warning("Malformed LyX file.")
722                 break
723             i = i + 1
724
725         i = i + 1
726
727
728 def revert_ert(file):
729     i = 0
730     while 1:
731         i = find_token(file.body, "\\begin_inset ERT", i)
732         if i == -1:
733             break
734
735         # Seach for a line starting 'status'
736         # If, however, we find a line starting '\begin_layout'
737         # (_always_ present) then break with a warning message
738         i = i + 1
739         while 1:
740             if (file.body[i] == "status open"):
741                 file.body[i] = "status Open"
742                 break
743             elif (file.body[i] == "status collapsed"):
744                 file.body[i] = "status Collapsed"
745                 break
746             elif (file.body[i] == "status inlined"):
747                 file.body[i] = "status Inlined"
748                 break
749             elif (file.body[i][:13] == "\\begin_layout"):
750                 file.warning("Malformed LyX file.")
751                 break
752             i = i + 1
753
754         i = i + 1
755
756
757 ##
758 # Minipages
759 #
760 def convert_minipage(file):
761     """ Convert minipages to the box inset.
762     We try to use the same order of arguments as lyx does.
763     """
764     pos = ["t","c","b"]
765     inner_pos = ["c","t","b","s"]
766
767     i = 0
768     while 1:
769         i = find_token(file.body, "\\begin_inset Minipage", i)
770         if i == -1:
771             return
772
773         file.body[i] = "\\begin_inset Box Frameless"
774         i = i + 1
775
776         # convert old to new position using the pos list
777         if file.body[i][:8] == "position":
778             file.body[i] = 'position "%s"' % pos[int(file.body[i][9])]
779         else:
780             file.body.insert(i, 'position "%s"' % pos[0])
781         i = i + 1
782
783         file.body.insert(i, 'hor_pos "c"')
784         i = i + 1
785         file.body.insert(i, 'has_inner_box 1')
786         i = i + 1
787
788         # convert the inner_position
789         if file.body[i][:14] == "inner_position":
790             file.body[i] = 'inner_pos "%s"' %  inner_pos[int(file.body[i][15])]
791         else:
792             file.body.insert('inner_pos "%s"' % inner_pos[0])
793         i = i + 1
794
795         # We need this since the new file format has a height and width
796         # in a different order.
797         if file.body[i][:6] == "height":
798             height = file.body[i][6:]
799             # test for default value of 221 and convert it accordingly
800             if height == ' "0pt"':
801                 height = ' "1pt"'
802             del file.body[i]
803         else:
804             height = ' "1pt"'
805
806         if file.body[i][:5] == "width":
807             width = file.body[i][5:]
808             del file.body[i]
809         else:
810             width = ' "0"'
811
812         if file.body[i][:9] == "collapsed":
813             if file.body[i][9:] == "true":
814                 status = "collapsed"
815             else:
816                 status = "open"
817             del file.body[i]
818         else:
819             status = "collapsed"
820
821         file.body.insert(i, 'use_parbox 0')
822         i = i + 1
823         file.body.insert(i, 'width' + width)
824         i = i + 1
825         file.body.insert(i, 'special "none"')
826         i = i + 1
827         file.body.insert(i, 'height' + height)
828         i = i + 1
829         file.body.insert(i, 'height_special "totalheight"')
830         i = i + 1
831         file.body.insert(i, 'status ' + status)
832         i = i + 1
833
834
835 # -------------------------------------------------------------------------------------------
836 # Convert backslashes into valid ERT code, append the converted text to
837 # file.body[i] and return the (maybe incremented) line index i
838 def convert_ertbackslash(body, i, ert):
839     for c in ert:
840         if c == '\\':
841             body[i] = body[i] + '\\backslash '
842             i = i + 1
843             body.insert(i, '')
844         else:
845             body[i] = body[i] + c
846     return i
847
848
849 def convert_vspace(file):
850
851     # Get default spaceamount
852     i = find_token(file.header, '\\defskip', 0)
853     if i == -1:
854         defskipamount = 'medskip'
855     else:
856         defskipamount = split(file.header[i])[1]
857
858     # Convert the insets
859     i = 0
860     while 1:
861         i = find_token(file.body, '\\begin_inset VSpace', i)
862         if i == -1:
863             return
864         spaceamount = split(file.body[i])[2]
865
866         # Are we at the beginning or end of a paragraph?
867         paragraph_start = 1
868         start = get_paragraph(file.body, i) + 1
869         for k in range(start, i):
870             if is_nonempty_line(file.body[k]):
871                 paragraph_start = 0
872                 break
873         paragraph_end = 1
874         j = find_end_of_inset(file.body, i)
875         if j == -1:
876             file.warning("Malformed LyX file: Missing '\\end_inset'.")
877             i = i + 1
878             continue
879         end = get_next_paragraph(file.body, i)
880         for k in range(j + 1, end):
881             if is_nonempty_line(file.body[k]):
882                 paragraph_end = 0
883                 break
884
885         # Convert to paragraph formatting if we are at the beginning or end
886         # of a paragraph and the resulting paragraph would not be empty
887         if ((paragraph_start and not paragraph_end) or
888             (paragraph_end   and not paragraph_start)):
889             # The order is important: del and insert invalidate some indices
890             del file.body[j]
891             del file.body[i]
892             if paragraph_start:
893                 file.body.insert(start, '\\added_space_top ' + spaceamount + ' ')
894             else:
895                 file.body.insert(start, '\\added_space_bottom ' + spaceamount + ' ')
896             continue
897
898         # Convert to ERT
899         file.body[i:i+1] = ['\\begin_inset ERT', 'status Collapsed', '',
900                         '\\layout Standard', '', '\\backslash ']
901         i = i + 6
902         if spaceamount[-1] == '*':
903             spaceamount = spaceamount[:-1]
904             keep = 1
905         else:
906             keep = 0
907
908         # Replace defskip by the actual value
909         if spaceamount == 'defskip':
910             spaceamount = defskipamount
911
912         # LaTeX does not know \\smallskip* etc
913         if keep:
914             if spaceamount == 'smallskip':
915                 spaceamount = '\\smallskipamount'
916             elif spaceamount == 'medskip':
917                 spaceamount = '\\medskipamount'
918             elif spaceamount == 'bigskip':
919                 spaceamount = '\\bigskipamount'
920             elif spaceamount == 'vfill':
921                 spaceamount = '\\fill'
922
923         # Finally output the LaTeX code
924         if (spaceamount == 'smallskip' or spaceamount == 'medskip' or
925             spaceamount == 'bigskip'   or spaceamount == 'vfill'):
926             file.body.insert(i, spaceamount)
927         else :
928             if keep:
929                 file.body.insert(i, 'vspace*{')
930             else:
931                 file.body.insert(i, 'vspace{')
932             i = convert_ertbackslash(file.body, i, spaceamount)
933             file.body[i] =  file.body[i] + '}'
934         i = i + 1
935
936
937 # Convert a LyX length into valid ERT code and append it to body[i]
938 # Return the (maybe incremented) line index i
939 def convert_ertlen(body, i, len, special):
940     units = {"text%":"\\textwidth", "col%":"\\columnwidth",
941              "page%":"\\pagewidth", "line%":"\\linewidth",
942              "theight%":"\\textheight", "pheight%":"\\pageheight"}
943
944     # Convert special lengths
945     if special != 'none':
946         len = '%f\\' % len2value(len) + special
947
948     # Convert LyX units to LaTeX units
949     for unit in units.keys():
950         if find(len, unit) != -1:
951             len = '%f' % (len2value(len) / 100) + units[unit]
952             break
953
954     # Convert backslashes and insert the converted length into body
955     return convert_ertbackslash(body, i, len)
956
957
958 # Return the value of len without the unit in numerical form
959 def len2value(len):
960     result = re.search('([+-]?[0-9.]+)', len)
961     if result:
962         return float(result.group(1))
963     # No number means 1.0
964     return 1.0
965
966
967 def convert_frameless_box(file):
968     pos = ['t', 'c', 'b']
969     inner_pos = ['c', 't', 'b', 's']
970     i = 0
971     while 1:
972         i = find_token(file.body, '\\begin_inset Frameless', i)
973         if i == -1:
974             return
975         j = find_end_of_inset(file.body, i)
976         if j == -1:
977             file.warning("Malformed LyX file: Missing '\\end_inset'.")
978             i = i + 1
979             continue
980         del file.body[i]
981
982         # Gather parameters
983         params = {'position':'0', 'hor_pos':'c', 'has_inner_box':'1',
984                   'inner_pos':'1', 'use_parbox':'0', 'width':'100col%',
985                   'special':'none', 'height':'1in',
986                   'height_special':'totalheight', 'collapsed':'false'}
987         for key in params.keys():
988             value = replace(get_value(file.body, key, i, j), '"', '')
989             if value != "":
990                 if key == 'position':
991                     # convert new to old position: 'position "t"' -> 0
992                     value = find_token(pos, value, 0)
993                     if value != -1:
994                         params[key] = value
995                 elif key == 'inner_pos':
996                     # convert inner position
997                     value = find_token(inner_pos, value, 0)
998                     if value != -1:
999                         params[key] = value
1000                 else:
1001                     params[key] = value
1002                 j = del_token(file.body, key, i, j)
1003         i = i + 1
1004
1005         # Convert to minipage or ERT?
1006         # Note that the inner_position and height parameters of a minipage
1007         # inset are ignored and not accessible for the user, although they
1008         # are present in the file format and correctly read in and written.
1009         # Therefore we convert to ERT if they do not have their LaTeX
1010         # defaults. These are:
1011         # - the value of "position" for "inner_pos"
1012         # - "\totalheight"          for "height"
1013         if (params['use_parbox'] != '0' or
1014             params['has_inner_box'] != '1' or
1015             params['special'] != 'none' or
1016             inner_pos[params['inner_pos']] != pos[params['position']] or
1017             params['height_special'] != 'totalheight' or
1018             len2value(params['height']) != 1.0):
1019
1020             # Convert to ERT
1021             if params['collapsed'] == 'true':
1022                 params['collapsed'] = 'Collapsed'
1023             else:
1024                 params['collapsed'] = 'Open'
1025             file.body[i : i] = ['\\begin_inset ERT', 'status ' + params['collapsed'],
1026                             '', '\\layout Standard', '', '\\backslash ']
1027             i = i + 6
1028             if params['use_parbox'] == '1':
1029                 file.body.insert(i, 'parbox')
1030             else:
1031                 file.body.insert(i, 'begin{minipage}')
1032             file.body[i] = file.body[i] + '[' + pos[params['position']] + ']['
1033             i = convert_ertlen(file.body, i, params['height'], params['height_special'])
1034             file.body[i] = file.body[i] + '][' + inner_pos[params['inner_pos']] + ']{'
1035             i = convert_ertlen(file.body, i, params['width'], params['special'])
1036             if params['use_parbox'] == '1':
1037                 file.body[i] = file.body[i] + '}{'
1038             else:
1039                 file.body[i] = file.body[i] + '}'
1040             i = i + 1
1041             file.body[i:i] = ['', '\\end_inset']
1042             i = i + 2
1043             j = find_end_of_inset(file.body, i)
1044             if j == -1:
1045                 file.warning("Malformed LyX file: Missing '\\end_inset'.")
1046                 break
1047             file.body[j-1:j-1] = ['\\begin_inset ERT', 'status ' + params['collapsed'],
1048                                '', '\\layout Standard', '']
1049             j = j + 4
1050             if params['use_parbox'] == '1':
1051                 file.body.insert(j, '}')
1052             else:
1053                 file.body[j:j] = ['\\backslash ', 'end{minipage}']
1054         else:
1055
1056             # Convert to minipage
1057             file.body[i:i] = ['\\begin_inset Minipage',
1058                           'position %d' % params['position'],
1059                           'inner_position %d' % params['inner_pos'],
1060                           'height "' + params['height'] + '"',
1061                           'width "' + params['width'] + '"',
1062                           'collapsed ' + params['collapsed']]
1063             i = i + 6
1064
1065 ##
1066 # Convert jurabib
1067 #
1068
1069 def convert_jurabib(file):
1070     i = find_token(file.header, '\\use_numerical_citations', 0)
1071     if i == -1:
1072         file.warning("Malformed lyx file: Missing '\\use_numerical_citations'.")
1073         return
1074     file.header.insert(i + 1, '\\use_jurabib 0')
1075
1076
1077 def revert_jurabib(file):
1078     i = find_token(file.header, '\\use_jurabib', 0)
1079     if i == -1:
1080         file.warning("Malformed lyx file: Missing '\\use_jurabib'.")
1081         return
1082     if get_value(file.header, '\\use_jurabib', 0) != "0":
1083         file.warning("Conversion of '\\use_jurabib = 1' not yet implemented.")
1084         # Don't remove '\\use_jurabib' so that people will get warnings by lyx
1085         return
1086     del file.header[i]
1087
1088 ##
1089 # Convert bibtopic
1090 #
1091
1092 def convert_bibtopic(file):
1093     i = find_token(file.header, '\\use_jurabib', 0)
1094     if i == -1:
1095         file.warning("Malformed lyx file: Missing '\\use_jurabib'.")
1096         return
1097     file.header.insert(i + 1, '\\use_bibtopic 0')
1098
1099
1100 def revert_bibtopic(file):
1101     i = find_token(file.header, '\\use_bibtopic', 0)
1102     if i == -1:
1103         file.warning("Malformed lyx file: Missing '\\use_bibtopic'.")
1104         return
1105     if get_value(file.header, '\\use_bibtopic', 0) != "0":
1106         file.warning("Conversion of '\\use_bibtopic = 1' not yet implemented.")
1107         # Don't remove '\\use_jurabib' so that people will get warnings by lyx
1108     del file.header[i]
1109
1110 ##
1111 # Sideway Floats
1112 #
1113
1114 def convert_float(file):
1115     i = 0
1116     while 1:
1117         i = find_token(file.body, '\\begin_inset Float', i)
1118         if i == -1:
1119             return
1120         # Seach for a line starting 'wide'
1121         # If, however, we find a line starting '\begin_layout'
1122         # (_always_ present) then break with a warning message
1123         i = i + 1
1124         while 1:
1125             if (file.body[i][:4] == "wide"):
1126                 file.body.insert(i + 1, 'sideways false')
1127                 break
1128             elif (file.body[i][:13] == "\\begin_layout"):
1129                 file.warning("Malformed lyx file.")
1130                 break
1131             i = i + 1
1132         i = i + 1
1133
1134
1135 def revert_float(file):
1136     i = 0
1137     while 1:
1138         i = find_token(file.body, '\\begin_inset Float', i)
1139         if i == -1:
1140             return
1141         j = find_end_of_inset(file.body, i)
1142         if j == -1:
1143             file.warning("Malformed lyx file: Missing '\\end_inset'.")
1144             i = i + 1
1145             continue
1146         if get_value(file.body, 'sideways', i, j) != "false":
1147             file.warning("Conversion of 'sideways true' not yet implemented.")
1148             # Don't remove 'sideways' so that people will get warnings by lyx
1149             i = i + 1
1150             continue
1151         del_token(file.body, 'sideways', i, j)
1152         i = i + 1
1153
1154
1155 def convert_graphics(file):
1156     """ Add extension to filenames of insetgraphics if necessary.
1157     """
1158     i = 0
1159     while 1:
1160         i = find_token(file.body, "\\begin_inset Graphics", i)
1161         if i == -1:
1162             return
1163
1164         j = find_token2(file.body, "filename", i)
1165         if j == -1:
1166             return
1167         i = i + 1
1168         filename = split(file.body[j])[1]
1169         absname = os.path.normpath(os.path.join(file.dir, filename))
1170         if file.input == stdin and not os.path.isabs(filename):
1171             # We don't know the directory and cannot check the file.
1172             # We could use a heuristic and take the current directory,
1173             # and we could try to find out if filename has an extension,
1174             # but that would be just guesses and could be wrong.
1175             file.warning("""Warning: Can not determine whether file
1176          %s
1177          needs an extension when reading from standard input.
1178          You may need to correct the file manually or run
1179          lyx2lyx again with the .lyx file as commandline argument.""" % filename)
1180             continue
1181         # This needs to be the same algorithm as in pre 233 insetgraphics
1182         if access(absname, F_OK):
1183             continue
1184         if access(absname + ".ps", F_OK):
1185             file.body[j] = replace(file.body[j], filename, filename + ".ps")
1186             continue
1187         if access(absname + ".eps", F_OK):
1188             file.body[j] = replace(file.body[j], filename, filename + ".eps")
1189
1190
1191 ##
1192 # Convert firstname and surname from styles -> char styles
1193 #
1194 def convert_names(file):
1195     """ Convert in the docbook backend from firstname and surname style
1196     to charstyles.
1197     """
1198     if file.backend != "docbook":
1199         return
1200
1201     i = 0
1202
1203     while 1:
1204         i = find_token(file.body, "\\begin_layout Author", i)
1205         if i == -1:
1206             return
1207
1208         i = i + 1
1209         while file.body[i] == "":
1210             i = i + 1
1211
1212         if file.body[i][:11] != "\\end_layout" or file.body[i+2][:13] != "\\begin_deeper":
1213             i = i + 1
1214             continue
1215
1216         k = i
1217         i = find_end_of( file.body, i+3, "\\begin_deeper","\\end_deeper")
1218         if i == -1:
1219             # something is really wrong, abort
1220             file.warning("Missing \\end_deeper, after style Author.")
1221             file.warning("Aborted attempt to parse FirstName and Surname.")
1222             return
1223         firstname, surname = "", ""
1224
1225         name = file.body[k:i]
1226
1227         j = find_token(name, "\\begin_layout FirstName", 0)
1228         if j != -1:
1229             j = j + 1
1230             while(name[j] != "\\end_layout"):
1231                 firstname = firstname + name[j]
1232                 j = j + 1
1233
1234         j = find_token(name, "\\begin_layout Surname", 0)
1235         if j != -1:
1236             j = j + 1
1237             while(name[j] != "\\end_layout"):
1238                 surname = surname + name[j]
1239                 j = j + 1
1240
1241         # delete name
1242         del file.body[k+2:i+1]
1243
1244         file.body[k-1:k-1] = ["", "",
1245                           "\\begin_inset CharStyle Firstname",
1246                           "status inlined",
1247                           "",
1248                           "\\begin_layout Standard",
1249                           "",
1250                           "%s" % firstname,
1251                           "\end_layout",
1252                           "",
1253                           "\end_inset",
1254                           "",
1255                           "",
1256                           "\\begin_inset CharStyle Surname",
1257                           "status inlined",
1258                           "",
1259                           "\\begin_layout Standard",
1260                           "",
1261                           "%s" % surname,
1262                           "\\end_layout",
1263                           "",
1264                           "\\end_inset",
1265                           ""]
1266
1267
1268 def revert_names(file):
1269     """ Revert in the docbook backend from firstname and surname char style
1270     to styles.
1271     """
1272     if file.backend != "docbook":
1273         return
1274
1275
1276 ##
1277 #    \use_natbib 1                       \cite_engine <style>
1278 #    \use_numerical_citations 0     ->   where <style> is one of
1279 #    \use_jurabib 0                      "basic", "natbib_authoryear",
1280 #                                        "natbib_numerical" or "jurabib"
1281 def convert_cite_engine(file):
1282     a = find_token(file.header, "\\use_natbib", 0)
1283     if a == -1:
1284         file.warning("Malformed lyx file: Missing '\\use_natbib'.")
1285         return
1286
1287     b = find_token(file.header, "\\use_numerical_citations", 0)
1288     if b == -1 or b != a+1:
1289         file.warning("Malformed lyx file: Missing '\\use_numerical_citations'.")
1290         return
1291
1292     c = find_token(file.header, "\\use_jurabib", 0)
1293     if c == -1 or c != b+1:
1294         file.warning("Malformed lyx file: Missing '\\use_jurabib'.")
1295         return
1296
1297     use_natbib = int(split(file.header[a])[1])
1298     use_numerical_citations = int(split(file.header[b])[1])
1299     use_jurabib = int(split(file.header[c])[1])
1300
1301     cite_engine = "basic"
1302     if use_natbib:
1303         if use_numerical_citations:
1304             cite_engine = "natbib_numerical"
1305         else:
1306              cite_engine = "natbib_authoryear"
1307     elif use_jurabib:
1308         cite_engine = "jurabib"
1309
1310     del file.header[a:c+1]
1311     file.header.insert(a, "\\cite_engine " + cite_engine)
1312
1313
1314 def revert_cite_engine(file):
1315     i = find_token(file.header, "\\cite_engine", 0)
1316     if i == -1:
1317         file.warning("Malformed lyx file: Missing '\\cite_engine'.")
1318         return
1319
1320     cite_engine = split(file.header[i])[1]
1321
1322     use_natbib = '0'
1323     use_numerical = '0'
1324     use_jurabib = '0'
1325     if cite_engine == "natbib_numerical":
1326         use_natbib = '1'
1327         use_numerical = '1'
1328     elif cite_engine == "natbib_authoryear":
1329         use_natbib = '1'
1330     elif cite_engine == "jurabib":
1331         use_jurabib = '1'
1332
1333     del file.header[i]
1334     file.header.insert(i, "\\use_jurabib " + use_jurabib)
1335     file.header.insert(i, "\\use_numerical_citations " + use_numerical)
1336     file.header.insert(i, "\\use_natbib " + use_natbib)
1337
1338
1339 ##
1340 # Paper package
1341 #
1342 def convert_paperpackage(file):
1343     i = find_token(file.header, "\\paperpackage", 0)
1344     if i == -1:
1345         file.warning("Malformed lyx file: Missing '\\paperpackage'.")
1346         return
1347
1348     packages = {'a4':'none', 'a4wide':'a4', 'widemarginsa4':'a4wide'}
1349     paperpackage = split(file.header[i])[1]
1350     file.header[i] = replace(file.header[i], paperpackage, packages[paperpackage])
1351
1352
1353 def revert_paperpackage(file):
1354     i = find_token(file.header, "\\paperpackage", 0)
1355     if i == -1:
1356         file.warning("Malformed lyx file: Missing '\\paperpackage'.")
1357         return
1358
1359     packages = {'none':'a4', 'a4':'a4wide', 'a4wide':'widemarginsa4',
1360                 'widemarginsa4':''}
1361     paperpackage = split(file.header[i])[1]
1362     file.header[i] = replace(file.header[i], paperpackage, packages[paperpackage])
1363
1364
1365 ##
1366 # Bullets
1367 #
1368 def convert_bullets(file):
1369     i = 0
1370     while 1:
1371         i = find_token(file.header, "\\bullet", i)
1372         if i == -1:
1373             return
1374         if file.header[i][:12] == '\\bulletLaTeX':
1375             file.header[i] = file.header[i] + ' ' + strip(file.header[i+1])
1376             n = 3
1377         else:
1378             file.header[i] = file.header[i] + ' ' + strip(file.header[i+1]) +\
1379                         ' ' + strip(file.header[i+2]) + ' ' + strip(file.header[i+3])
1380             n = 5
1381         del file.header[i+1:i + n]
1382         i = i + 1
1383
1384
1385 def revert_bullets(file):
1386     i = 0
1387     while 1:
1388         i = find_token(file.header, "\\bullet", i)
1389         if i == -1:
1390             return
1391         if file.header[i][:12] == '\\bulletLaTeX':
1392             n = find(file.header[i], '"')
1393             if n == -1:
1394                 file.warning("Malformed header.")
1395                 return
1396             else:
1397                 file.header[i:i+1] = [file.header[i][:n-1],'\t' + file.header[i][n:], '\\end_bullet']
1398             i = i + 3
1399         else:
1400             frag = split(file.header[i])
1401             if len(frag) != 5:
1402                 file.warning("Malformed header.")
1403                 return
1404             else:
1405                 file.header[i:i+1] = [frag[0] + ' ' + frag[1],
1406                                  '\t' + frag[2],
1407                                  '\t' + frag[3],
1408                                  '\t' + frag[4],
1409                                  '\\end_bullet']
1410                 i = i + 5
1411
1412
1413 ##
1414 # \begin_header and \begin_document
1415 #
1416 def add_begin_header(file):
1417     i = find_token(file.header, '\\lyxformat', 0)
1418     file.header.insert(i+1, '\\begin_header')
1419     file.header.insert(i+1, '\\begin_document')
1420
1421
1422 def remove_begin_header(file):
1423     i = find_token(file.header, "\\begin_document", 0)
1424     if i != -1:
1425         del file.header[i]
1426     i = find_token(file.header, "\\begin_header", 0)
1427     if i != -1:
1428         del file.header[i]
1429
1430
1431 ##
1432 # \begin_file.body and \end_file.body
1433 #
1434 def add_begin_body(file):
1435     file.body.insert(0, '\\begin_body')
1436     file.body.insert(1, '')
1437     i = find_token(file.body, "\\end_document", 0)
1438     file.body.insert(i, '\\end_body')
1439
1440 def remove_begin_body(file):
1441     i = find_token(file.body, "\\begin_body", 0)
1442     if i != -1:
1443         del file.body[i]
1444         if not file.body[i]:
1445             del file.body[i]
1446     i = find_token(file.body, "\\end_body", 0)
1447     if i != -1:
1448         del file.body[i]
1449
1450
1451 ##
1452 # \papersize
1453 #
1454 def normalize_papersize(file):
1455     i = find_token(file.header, '\\papersize', 0)
1456     if i == -1:
1457         return
1458
1459     tmp = split(file.header[i])
1460     if tmp[1] == "Default":
1461         file.header[i] = '\\papersize default'
1462         return
1463     if tmp[1] == "Custom":
1464         file.header[i] = '\\papersize custom'
1465
1466
1467 def denormalize_papersize(file):
1468     i = find_token(file.header, '\\papersize', 0)
1469     if i == -1:
1470         return
1471
1472     tmp = split(file.header[i])
1473     if tmp[1] == "custom":
1474         file.header[i] = '\\papersize Custom'
1475
1476
1477 ##
1478 # Strip spaces at end of command line
1479 #
1480 def strip_end_space(file):
1481     for i in range(len(file.body)):
1482         if file.body[i][:1] == '\\':
1483             file.body[i] = strip(file.body[i])
1484
1485
1486 ##
1487 # Use boolean values for \use_geometry, \use_bibtopic and \tracking_changes
1488 #
1489 def use_x_boolean(file):
1490     bin2bool = {'0': 'false', '1': 'true'}
1491     for use in '\\use_geometry', '\\use_bibtopic', '\\tracking_changes':
1492         i = find_token(file.header, use, 0)
1493         if i == -1:
1494             continue
1495         decompose = split(file.header[i])
1496         file.header[i] = decompose[0] + ' ' + bin2bool[decompose[1]]
1497
1498
1499 def use_x_binary(file):
1500     bool2bin = {'false': '0', 'true': '1'}
1501     for use in '\\use_geometry', '\\use_bibtopic', '\\tracking_changes':
1502         i = find_token(file.header, use, 0)
1503         if i == -1:
1504             continue
1505         decompose = split(file.header[i])
1506         file.header[i] = decompose[0] + ' ' + bool2bin[decompose[1]]
1507
1508 ##
1509 # Convertion hub
1510 #
1511 def convert(file):
1512     table = { 223 : [insert_tracking_changes, add_end_header, remove_color_default,
1513                      convert_spaces, convert_bibtex, remove_insetparent],
1514               224 : [convert_external, convert_comment],
1515               225 : [add_end_layout, layout2begin_layout, convert_end_document,
1516                      convert_table_valignment_middle, convert_breaks],
1517               226 : [convert_note],
1518               227 : [convert_box],
1519               228 : [convert_collapsable, convert_ert],
1520               229 : [convert_minipage],
1521               230 : [convert_jurabib],
1522               231 : [convert_float],
1523               232 : [convert_bibtopic],
1524               233 : [convert_graphics, convert_names],
1525               234 : [convert_cite_engine],
1526               235 : [convert_paperpackage],
1527               236 : [convert_bullets, add_begin_header, add_begin_body,
1528                      normalize_papersize, strip_end_space],
1529               237 : [use_x_boolean]}
1530
1531     chain = table.keys()
1532     chain.sort()
1533
1534     for version in chain:
1535         if file.format >= version:
1536             continue
1537         for convert in table[version]:
1538             convert(file)
1539         file.format = version
1540         if file.end_format == file.format:
1541             return
1542
1543
1544 def revert(file):
1545     table = { 236: [use_x_binary],
1546               235: [denormalize_papersize, remove_begin_body,remove_begin_header,
1547                     revert_bullets],
1548               234: [revert_paperpackage],
1549               233: [revert_cite_engine],
1550               232: [revert_names],
1551               231: [revert_bibtopic],
1552               230: [revert_float],
1553               229: [revert_jurabib],
1554               228: [],
1555               227: [revert_collapsable, revert_ert],
1556               226: [revert_box, revert_external_2],
1557               225: [revert_note],
1558               224: [rm_end_layout, begin_layout2layout, revert_end_document,
1559                     revert_valignment_middle, convert_vspace, convert_frameless_box],
1560               223: [revert_external_2, revert_comment],
1561               221: [rm_end_header, revert_spaces, revert_bibtex,
1562                     rm_tracking_changes, rm_body_changes]}
1563
1564     chain = table.keys()
1565     chain.sort()
1566     chain.reverse()
1567
1568     for version in chain:
1569         if file.format <= version:
1570             continue
1571         for convert in table[version]:
1572             convert(file)
1573         file.format = version
1574         if file.end_format == file.format:
1575             return
1576
1577 if __name__ == "__main__":
1578     pass