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