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