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