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