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