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