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