]> git.lyx.org Git - features.git/blob - lib/lyx2lyx/lyx_1_4.py
* parser_tools.py (find_tokens_exact): new, extract tokens with
[features.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             file.body[i] = 'inner_pos "%s"' %  inner_pos[int(file.body[i][15])]
991         else:
992             file.body.insert('inner_pos "%s"' % inner_pos[0])
993         i = i + 1
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         file.body.insert(i, 'use_parbox 0')
1022         i = i + 1
1023         file.body.insert(i, 'width' + width)
1024         i = i + 1
1025         file.body.insert(i, 'special "none"')
1026         i = i + 1
1027         file.body.insert(i, 'height' + height)
1028         i = i + 1
1029         file.body.insert(i, 'height_special "totalheight"')
1030         i = i + 1
1031         file.body.insert(i, 'status ' + status)
1032         i = i + 1
1033
1034
1035 # -------------------------------------------------------------------------------------------
1036 # Convert backslashes and '\n' into valid ERT code, append the converted
1037 # text to body[i] and return the (maybe incremented) line index i
1038 def convert_ertbackslash(body, i, ert, format, default_layout):
1039     for c in ert:
1040         if c == '\\':
1041             body[i] = body[i] + '\\backslash '
1042             i = i + 1
1043             body.insert(i, '')
1044         elif c == '\n':
1045             if format <= 240:
1046                 body[i+1:i+1] = ['\\newline ', '']
1047                 i = i + 2
1048             else:
1049                 body[i+1:i+1] = ['\\end_layout', '', '\\begin_layout %s' % default_layout, '']
1050                 i = i + 4
1051         else:
1052             body[i] = body[i] + c
1053     return i
1054
1055
1056 # Converts lines in ERT code to LaTeX
1057 # The surrounding \begin_layout ... \end_layout pair must not be included
1058 def ert2latex(lines, format):
1059     backslash = re.compile(r'\\backslash\s*$')
1060     newline = re.compile(r'\\newline\s*$')
1061     if format <= 224:
1062         begin_layout = re.compile(r'\\layout\s*\S+$')
1063     else:
1064         begin_layout = re.compile(r'\\begin_layout\s*\S+$')
1065     end_layout = re.compile(r'\\end_layout\s*$')
1066     ert = ''
1067     for i in range(len(lines)):
1068         line = backslash.sub('\\\\', lines[i])
1069         if format <= 240:
1070             if begin_layout.match(line):
1071                 line = '\n\n'
1072             else:
1073                 line = newline.sub('\n', line)
1074         else:
1075             if begin_layout.match(line):
1076                 line = '\n'
1077         if format > 224 and end_layout.match(line):
1078             line = ''
1079         ert = ert + line
1080     return ert
1081
1082
1083 # get all paragraph parameters. They can be all on one line or on several lines.
1084 # lines[i] must be the first parameter line
1085 def get_par_params(lines, i):
1086     par_params = ('added_space_bottom', 'added_space_top', 'align',
1087                  'labelwidthstring', 'line_bottom', 'line_top', 'noindent',
1088                  'pagebreak_bottom', 'pagebreak_top', 'paragraph_spacing',
1089                  'start_of_appendix')
1090     # We cannot check for '\\' only because paragraphs may start e.g.
1091     # with '\\backslash'
1092     params = ''
1093     while lines[i][:1] == '\\' and split(lines[i][1:])[0] in par_params:
1094         params = params + ' ' + strip(lines[i])
1095         i = i + 1
1096     return strip(params)
1097
1098
1099 # convert LyX font size to LaTeX fontsize
1100 def lyxsize2latexsize(lyxsize):
1101     sizes = {"tiny" : "tiny", "scriptsize" : "scriptsize",
1102              "footnotesize" : "footnotesize", "small" : "small",
1103              "normal" : "normalsize", "large" : "large", "larger" : "Large",
1104              "largest" : "LARGE", "huge" : "huge", "giant" : "Huge"}
1105     if lyxsize in sizes:
1106         return '\\' + sizes[lyxsize]
1107     return ''
1108
1109
1110 # Change vspace insets, page breaks and lyxlines to paragraph options
1111 # (if possible) or ERT
1112 def revert_breaks(file):
1113
1114     # Get default spaceamount
1115     i = find_token(file.header, '\\defskip', 0)
1116     if i == -1:
1117         defskipamount = 'medskip'
1118     else:
1119         defskipamount = split(file.header[i])[1]
1120
1121     keys = {"\\begin_inset" : "vspace", "\\lyxline" : "lyxline",
1122             "\\newpage" : "newpage"}
1123     keywords_top = {"vspace" : "\\added_space_top", "lyxline" : "\\line_top",
1124                     "newpage" : "\\pagebreak_top"}
1125     keywords_bot = {"vspace" : "\\added_space_bottom", "lyxline" : "\\line_bottom",
1126                     "newpage" : "\\pagebreak_bottom"}
1127     tokens = ["\\begin_inset VSpace", "\\lyxline", "\\newpage"]
1128
1129     # Convert the insets
1130     i = 0
1131     while 1:
1132         i = find_tokens(file.body, tokens, i)
1133         if i == -1:
1134             return
1135
1136         # Are we at the beginning of a paragraph?
1137         paragraph_start = 1
1138         this_par = get_paragraph(file.body, i, file.format - 1)
1139         start = this_par + 1
1140         params = get_par_params(file.body, start)
1141         size = "normal"
1142         # Paragraph parameters may be on one or more lines.
1143         # Find the start of the real paragraph text.
1144         while file.body[start][:1] == '\\' and split(file.body[start])[0] in params:
1145             start = start + 1
1146         for k in range(start, i):
1147             if find(file.body[k], "\\size") != -1:
1148                 # store font size
1149                 size = split(file.body[k])[1]
1150             elif is_nonempty_line(file.body[k]):
1151                 paragraph_start = 0
1152                 break
1153         # Find the end of the real paragraph text.
1154         next_par = get_next_paragraph(file.body, i, file.format - 1)
1155         if next_par == -1:
1156             file.warning("Malformed LyX file: Missing next paragraph.")
1157             i = i + 1
1158             continue
1159
1160         # first line of our insets
1161         inset_start = i
1162         # last line of our insets
1163         inset_end = inset_start
1164         # Are we at the end of a paragraph?
1165         paragraph_end = 1
1166         # start and end line numbers to delete if we convert this inset
1167         del_lines = list()
1168         # is this inset a lyxline above a paragraph?
1169         top = list()
1170         # raw inset information
1171         lines = list()
1172         # name of this inset
1173         insets = list()
1174         # font size of this inset
1175         sizes = list()
1176
1177         # Detect subsequent lyxline, vspace and pagebreak insets created by convert_breaks()
1178         n = 0
1179         k = inset_start
1180         while k < next_par:
1181             if find_tokens(file.body, tokens, k) == k:
1182                 # inset to convert
1183                 lines.append(split(file.body[k]))
1184                 insets.append(keys[lines[n][0]])
1185                 del_lines.append([k, k])
1186                 top.append(0)
1187                 sizes.append(size)
1188                 n = n + 1
1189                 inset_end = k
1190             elif find(file.body[k], "\\size") != -1:
1191                 # store font size
1192                 size = split(file.body[k])[1]
1193             elif find_token(file.body, "\\begin_inset ERT", k) == k:
1194                 ert_begin = find_token(file.body, "\\layout", k) + 1
1195                 if ert_begin == 0:
1196                     file.warning("Malformed LyX file: Missing '\\layout'.")
1197                     continue
1198                 ert_end = find_end_of_inset(file.body, k)
1199                 if ert_end == -1:
1200                     file.warning("Malformed LyX file: Missing '\\end_inset'.")
1201                     continue
1202                 ert = ert2latex(file.body[ert_begin:ert_end], file.format - 1)
1203                 if (n > 0 and insets[n - 1] == "lyxline" and
1204                     ert == '\\vspace{-1\\parskip}\n'):
1205                     # vspace ERT created by convert_breaks() for top lyxline
1206                     top[n - 1] = 1
1207                     del_lines[n - 1][1] = ert_end
1208                     inset_end = ert_end
1209                     k = ert_end
1210                 else:
1211                     paragraph_end = 0
1212                     break
1213             elif (n > 0 and insets[n - 1] == "vspace" and
1214                   find_token(file.body, "\\end_inset", k) == k):
1215                 # ignore end of vspace inset
1216                 del_lines[n - 1][1] = k
1217                 inset_end = k
1218             elif is_nonempty_line(file.body[k]):
1219                 paragraph_end = 0
1220                 break
1221             k = k + 1
1222
1223         # Determine space amount for vspace insets
1224         spaceamount = list()
1225         arguments = list()
1226         for k in range(n):
1227             if insets[k] == "vspace":
1228                 spaceamount.append(lines[k][2])
1229                 arguments.append(' ' + spaceamount[k] + ' ')
1230             else:
1231                 spaceamount.append('')
1232                 arguments.append(' ')
1233
1234         # Can we convert to top paragraph parameters?
1235         before = 0
1236         if ((n == 3 and insets[0] == "newpage" and insets[1] == "vspace" and
1237              insets[2] == "lyxline" and top[2]) or
1238             (n == 2 and
1239              ((insets[0] == "newpage" and insets[1] == "vspace") or
1240               (insets[0] == "newpage" and insets[1] == "lyxline" and top[1]) or
1241               (insets[0] == "vspace"  and insets[1] == "lyxline" and top[1]))) or
1242             (n == 1 and insets[0] == "lyxline" and top[0])):
1243             # These insets have been created before a paragraph by
1244             # convert_breaks()
1245             before = 1
1246
1247         # Can we convert to bottom paragraph parameters?
1248         after = 0
1249         if ((n == 3 and insets[0] == "lyxline" and not top[0] and
1250              insets[1] == "vspace" and insets[2] == "newpage") or
1251             (n == 2 and
1252              ((insets[0] == "lyxline" and not top[0] and insets[1] == "vspace") or
1253               (insets[0] == "lyxline" and not top[0] and insets[1] == "newpage") or
1254               (insets[0] == "vspace"  and insets[1] == "newpage"))) or
1255             (n == 1 and insets[0] == "lyxline" and not top[0])):
1256             # These insets have been created after a paragraph by
1257             # convert_breaks()
1258             after = 1
1259
1260         if paragraph_start and paragraph_end:
1261             # We are in a paragraph of our own.
1262             # We must not delete this paragraph if it has parameters
1263             if params == '':
1264                 # First try to merge with the previous paragraph.
1265                 # We try the previous paragraph first because we would
1266                 # otherwise need ERT for two subsequent vspaces.
1267                 prev_par = get_paragraph(file.body, this_par - 1, file.format - 1) + 1
1268                 if prev_par > 0 and not before:
1269                     prev_params = get_par_params(file.body, prev_par + 1)
1270                     ert = 0
1271                     # determine font size
1272                     prev_size = "normal"
1273                     k = prev_par + 1
1274                     while file.body[k][:1] == '\\' and split(file.body[k])[0] in prev_params:
1275                         k = k + 1
1276                     while k < this_par:
1277                         if find(file.body[k], "\\size") != -1:
1278                             prev_size = split(file.body[k])[1]
1279                             break
1280                         elif find(file.body[k], "\\begin_inset") != -1:
1281                             # skip insets
1282                             k = find_end_of_inset(file.body, k)
1283                         elif is_nonempty_line(file.body[k]):
1284                             break
1285                         k = k + 1
1286                     for k in range(n):
1287                         if (keywords_bot[insets[k]] in prev_params or
1288                             (insets[k] == "lyxline" and sizes[k] != prev_size)):
1289                             ert = 1
1290                             break
1291                     if not ert:
1292                         for k in range(n):
1293                             file.body.insert(prev_par + 1,
1294                                              keywords_bot[insets[k]] + arguments[k])
1295                         del file.body[this_par+n:next_par-1+n]
1296                         i = this_par + n
1297                         continue
1298                 # Then try next paragraph
1299                 if next_par > 0 and not after:
1300                     next_params = get_par_params(file.body, next_par + 1)
1301                     ert = 0
1302                     while file.body[k][:1] == '\\' and split(file.body[k])[0] in next_params:
1303                         k = k + 1
1304                     # determine font size
1305                     next_size = "normal"
1306                     k = next_par + 1
1307                     while k < this_par:
1308                         if find(file.body[k], "\\size") != -1:
1309                             next_size = split(file.body[k])[1]
1310                             break
1311                         elif is_nonempty_line(file.body[k]):
1312                             break
1313                         k = k + 1
1314                     for k in range(n):
1315                         if (keywords_top[insets[k]] in next_params or
1316                             (insets[k] == "lyxline" and sizes[k] != next_size)):
1317                             ert = 1
1318                             break
1319                     if not ert:
1320                         for k in range(n):
1321                             file.body.insert(next_par + 1,
1322                                              keywords_top[insets[k]] + arguments[k])
1323                         del file.body[this_par:next_par-1]
1324                         i = this_par
1325                         continue
1326         elif paragraph_start or paragraph_end:
1327             # Convert to paragraph formatting if we are at the beginning or end
1328             # of a paragraph and the resulting paragraph would not be empty
1329             # The order is important: del and insert invalidate some indices
1330             if paragraph_start:
1331                 keywords = keywords_top
1332             else:
1333                 keywords = keywords_bot
1334             ert = 0
1335             for k in range(n):
1336                 if keywords[insets[k]] in params:
1337                     ert = 1
1338                     break
1339             if not ert:
1340                 for k in range(n):
1341                     file.body.insert(this_par + 1,
1342                                      keywords[insets[k]] + arguments[k])
1343                     for j in range(k, n):
1344                         del_lines[j][0] = del_lines[j][0] + 1
1345                         del_lines[j][1] = del_lines[j][1] + 1
1346                     del file.body[del_lines[k][0]:del_lines[k][1]+1]
1347                     deleted = del_lines[k][1] - del_lines[k][0] + 1
1348                     for j in range(k + 1, n):
1349                         del_lines[j][0] = del_lines[j][0] - deleted
1350                         del_lines[j][1] = del_lines[j][1] - deleted
1351                 i = this_par
1352                 continue
1353
1354         # Convert the first inset to ERT.
1355         # The others are converted in the next loop runs (if they exist)
1356         if insets[0] == "vspace":
1357             file.body[i:i+1] = ['\\begin_inset ERT', 'status Collapsed', '',
1358                                 '\\layout %s' % file.default_layout, '', '\\backslash ']
1359             i = i + 6
1360             if spaceamount[0][-1] == '*':
1361                 spaceamount[0] = spaceamount[0][:-1]
1362                 keep = 1
1363             else:
1364                 keep = 0
1365
1366             # Replace defskip by the actual value
1367             if spaceamount[0] == 'defskip':
1368                 spaceamount[0] = defskipamount
1369
1370             # LaTeX does not know \\smallskip* etc
1371             if keep:
1372                 if spaceamount[0] == 'smallskip':
1373                     spaceamount[0] = '\\smallskipamount'
1374                 elif spaceamount[0] == 'medskip':
1375                     spaceamount[0] = '\\medskipamount'
1376                 elif spaceamount[0] == 'bigskip':
1377                     spaceamount[0] = '\\bigskipamount'
1378                 elif spaceamount[0] == 'vfill':
1379                     spaceamount[0] = '\\fill'
1380
1381             # Finally output the LaTeX code
1382             if (spaceamount[0] == 'smallskip' or spaceamount[0] == 'medskip' or
1383                 spaceamount[0] == 'bigskip'   or spaceamount[0] == 'vfill'):
1384                 file.body.insert(i, spaceamount[0] + '{}')
1385             else :
1386                 if keep:
1387                     file.body.insert(i, 'vspace*{')
1388                 else:
1389                     file.body.insert(i, 'vspace{')
1390                 i = convert_ertbackslash(file.body, i, spaceamount[0], file.format - 1, file.default_layout)
1391                 file.body[i] = file.body[i] + '}'
1392             i = i + 1
1393         elif insets[0] == "lyxline":
1394             file.body[i] = ''
1395             latexsize = lyxsize2latexsize(size)
1396             if latexsize == '':
1397                 file.warning("Could not convert LyX fontsize '%s' to LaTeX font size." % size)
1398                 latexsize = '\\normalsize'
1399             i = insert_ert(file.body, i, 'Collapsed',
1400                            '\\lyxline{%s}' % latexsize,
1401                            file.format - 1, file.default_layout)
1402             # We use \providecommand so that we don't get an error if native
1403             # lyxlines are used (LyX writes first its own preamble and then
1404             # the user specified one)
1405             add_to_preamble(file,
1406                             ['% Commands inserted by lyx2lyx for lyxlines',
1407                              '\\providecommand{\\lyxline}[1]{',
1408                              '  {#1 \\vspace{1ex} \\hrule width \\columnwidth \\vspace{1ex}}'
1409                              '}'])
1410         elif insets[0] == "newpage":
1411             file.body[i] = ''
1412             i = insert_ert(file.body, i, 'Collapsed', '\\newpage{}',
1413                            file.format - 1, file.default_layout)
1414
1415
1416 # Convert a LyX length into a LaTeX length
1417 def convert_len(len, special):
1418     units = {"text%":"\\textwidth", "col%":"\\columnwidth",
1419              "page%":"\\pagewidth", "line%":"\\linewidth",
1420              "theight%":"\\textheight", "pheight%":"\\pageheight"}
1421
1422     # Convert special lengths
1423     if special != 'none':
1424         len = '%f\\' % len2value(len) + special
1425
1426     # Convert LyX units to LaTeX units
1427     for unit in units.keys():
1428         if find(len, unit) != -1:
1429             len = '%f' % (len2value(len) / 100) + units[unit]
1430             break
1431
1432     return len
1433
1434
1435 # Convert a LyX length into valid ERT code and append it to body[i]
1436 # Return the (maybe incremented) line index i
1437 def convert_ertlen(body, i, len, special, format, default_layout):
1438     # Convert backslashes and insert the converted length into body
1439     return convert_ertbackslash(body, i, convert_len(len, special), format, default_layout)
1440
1441
1442 # Return the value of len without the unit in numerical form
1443 def len2value(len):
1444     result = re.search('([+-]?[0-9.]+)', len)
1445     if result:
1446         return float(result.group(1))
1447     # No number means 1.0
1448     return 1.0
1449
1450
1451 # Convert text to ERT and insert it at body[i]
1452 # Return the index of the line after the inserted ERT
1453 def insert_ert(body, i, status, text, format, default_layout):
1454     body[i:i] = ['\\begin_inset ERT', 'status ' + status, '']
1455     i = i + 3
1456     if format <= 224:
1457         body[i:i] = ['\\layout %s' % default_layout, '']
1458     else:
1459         body[i:i] = ['\\begin_layout %s' % default_layout, '']
1460     i = i + 1       # i points now to the just created empty line
1461     i = convert_ertbackslash(body, i, text, format, default_layout) + 1
1462     if format > 224:
1463         body[i:i] = ['\\end_layout']
1464         i = i + 1
1465     body[i:i] = ['', '\\end_inset', '']
1466     i = i + 3
1467     return i
1468
1469
1470 # Add text to the preamble if it is not already there.
1471 # Only the first line is checked!
1472 def add_to_preamble(file, text):
1473     if find_token(file.preamble, text[0], 0) != -1:
1474         return
1475
1476     file.preamble.extend(text)
1477
1478
1479 def convert_frameless_box(file):
1480     pos = ['t', 'c', 'b']
1481     inner_pos = ['c', 't', 'b', 's']
1482     i = 0
1483     while 1:
1484         i = find_token(file.body, '\\begin_inset Frameless', i)
1485         if i == -1:
1486             return
1487         j = find_end_of_inset(file.body, i)
1488         if j == -1:
1489             file.warning("Malformed LyX file: Missing '\\end_inset'.")
1490             i = i + 1
1491             continue
1492         del file.body[i]
1493         j = j - 1
1494
1495         # Gather parameters
1496         params = {'position':0, 'hor_pos':'c', 'has_inner_box':'1',
1497                   'inner_pos':1, 'use_parbox':'0', 'width':'100col%',
1498                   'special':'none', 'height':'1in',
1499                   'height_special':'totalheight', 'collapsed':'false'}
1500         for key in params.keys():
1501             value = replace(get_value(file.body, key, i, j), '"', '')
1502             if value != "":
1503                 if key == 'position':
1504                     # convert new to old position: 'position "t"' -> 0
1505                     value = find_token(pos, value, 0)
1506                     if value != -1:
1507                         params[key] = value
1508                 elif key == 'inner_pos':
1509                     # convert inner position
1510                     value = find_token(inner_pos, value, 0)
1511                     if value != -1:
1512                         params[key] = value
1513                 else:
1514                     params[key] = value
1515                 j = del_token(file.body, key, i, j)
1516         i = i + 1
1517
1518         # Convert to minipage or ERT?
1519         # Note that the inner_position and height parameters of a minipage
1520         # inset are ignored and not accessible for the user, although they
1521         # are present in the file format and correctly read in and written.
1522         # Therefore we convert to ERT if they do not have their LaTeX
1523         # defaults. These are:
1524         # - the value of "position" for "inner_pos"
1525         # - "\totalheight"          for "height"
1526         if (params['use_parbox'] != '0' or
1527             params['has_inner_box'] != '1' or
1528             params['special'] != 'none' or
1529             params['height_special'] != 'totalheight' or
1530             len2value(params['height']) != 1.0):
1531
1532             # Here we know that this box is not supported in file format 224.
1533             # Therefore we need to convert it to ERT. We can't simply convert
1534             # the beginning and end of the box to ERT, because the
1535             # box inset may contain layouts that are different from the
1536             # surrounding layout. After the conversion the contents of the
1537             # box inset is on the same level as the surrounding text, and
1538             # paragraph layouts and align parameters can get mixed up.
1539
1540             # A possible solution for this problem:
1541             # Convert the box to a minipage and redefine the minipage
1542             # environment in ERT so that the original box is simulated.
1543             # For minipages we could do this in a way that the width and
1544             # position can still be set from LyX, but this did not work well.
1545             # This is not possible for parboxes either, so we convert the
1546             # original box to ERT, put the minipage inset inside the box
1547             # and redefine the minipage environment to be empty.
1548
1549             # Commands that are independant of a particular box can go to
1550             # the preamble.
1551             # We need to define lyxtolyxrealminipage with 3 optional
1552             # arguments although LyX 1.3 uses only the first one.
1553             # Otherwise we will get LaTeX errors if this document is
1554             # converted to format 225 or above again (LyX 1.4 uses all
1555             # optional arguments).
1556             add_to_preamble(file,
1557                 ['% Commands inserted by lyx2lyx for frameless boxes',
1558                  '% Save the original minipage environment',
1559                  '\\let\\lyxtolyxrealminipage\\minipage',
1560                  '\\let\\endlyxtolyxrealminipage\\endminipage',
1561                  '% Define an empty lyxtolyximinipage environment',
1562                  '% with 3 optional arguments',
1563                  '\\newenvironment{lyxtolyxiiiminipage}[4]{}{}',
1564                  '\\newenvironment{lyxtolyxiiminipage}[2][\\lyxtolyxargi]%',
1565                  '  {\\begin{lyxtolyxiiiminipage}{\\lyxtolyxargi}{\\lyxtolyxargii}{#1}{#2}}%',
1566                  '  {\\end{lyxtolyxiiiminipage}}',
1567                  '\\newenvironment{lyxtolyximinipage}[1][\\totalheight]%',
1568                  '  {\\def\\lyxtolyxargii{{#1}}\\begin{lyxtolyxiiminipage}}%',
1569                  '  {\\end{lyxtolyxiiminipage}}',
1570                  '\\newenvironment{lyxtolyxminipage}[1][c]%',
1571                  '  {\\def\\lyxtolyxargi{{#1}}\\begin{lyxtolyximinipage}}',
1572                  '  {\\end{lyxtolyximinipage}}'])
1573
1574             if params['use_parbox'] != '0':
1575                 ert = '\\parbox'
1576             else:
1577                 ert = '\\begin{lyxtolyxrealminipage}'
1578
1579             # convert optional arguments only if not latex default
1580             if (pos[params['position']] != 'c' or
1581                 inner_pos[params['inner_pos']] != pos[params['position']] or
1582                 params['height_special'] != 'totalheight' or
1583                 len2value(params['height']) != 1.0):
1584                 ert = ert + '[' + pos[params['position']] + ']'
1585             if (inner_pos[params['inner_pos']] != pos[params['position']] or
1586                 params['height_special'] != 'totalheight' or
1587                 len2value(params['height']) != 1.0):
1588                 ert = ert + '[' + convert_len(params['height'],
1589                                               params['height_special']) + ']'
1590             if inner_pos[params['inner_pos']] != pos[params['position']]:
1591                 ert = ert + '[' + inner_pos[params['inner_pos']] + ']'
1592
1593             ert = ert + '{' + convert_len(params['width'],
1594                                           params['special']) + '}'
1595
1596             if params['use_parbox'] != '0':
1597                 ert = ert + '{'
1598             ert = ert + '\\let\\minipage\\lyxtolyxminipage%\n'
1599             ert = ert + '\\let\\endminipage\\endlyxtolyxminipage%\n'
1600
1601             old_i = i
1602             i = insert_ert(file.body, i, 'Collapsed', ert, file.format - 1, file.default_layout)
1603             j = j + i - old_i - 1
1604
1605             file.body[i:i] = ['\\begin_inset Minipage',
1606                               'position %d' % params['position'],
1607                               'inner_position 1',
1608                               'height "1in"',
1609                               'width "' + params['width'] + '"',
1610                               'collapsed ' + params['collapsed']]
1611             i = i + 6
1612             j = j + 6
1613
1614             # Restore the original minipage environment since we may have
1615             # minipages inside this box.
1616             # Start a new paragraph because the following may be nonstandard
1617             file.body[i:i] = ['\\layout %s' % file.default_layout, '', '']
1618             i = i + 2
1619             j = j + 3
1620             ert = '\\let\\minipage\\lyxtolyxrealminipage%\n'
1621             ert = ert + '\\let\\endminipage\\lyxtolyxrealendminipage%'
1622             old_i = i
1623             i = insert_ert(file.body, i, 'Collapsed', ert, file.format - 1, file.default_layout)
1624             j = j + i - old_i - 1
1625
1626             # Redefine the minipage end before the inset end.
1627             # Start a new paragraph because the previous may be nonstandard
1628             file.body[j:j] = ['\\layout %s' % file.default_layout, '', '']
1629             j = j + 2
1630             ert = '\\let\\endminipage\\endlyxtolyxminipage'
1631             j = insert_ert(file.body, j, 'Collapsed', ert, file.format - 1, file.default_layout)
1632             j = j + 1
1633             file.body.insert(j, '')
1634             j = j + 1
1635
1636             # LyX writes '%\n' after each box. Therefore we need to end our
1637             # ERT with '%\n', too, since this may swallow a following space.
1638             if params['use_parbox'] != '0':
1639                 ert = '}%\n'
1640             else:
1641                 ert = '\\end{lyxtolyxrealminipage}%\n'
1642             j = insert_ert(file.body, j, 'Collapsed', ert, file.format - 1, file.default_layout)
1643
1644             # We don't need to restore the original minipage after the inset
1645             # end because the scope of the redefinition is the original box.
1646
1647         else:
1648
1649             # Convert to minipage
1650             file.body[i:i] = ['\\begin_inset Minipage',
1651                               'position %d' % params['position'],
1652                               'inner_position %d' % params['inner_pos'],
1653                               'height "' + params['height'] + '"',
1654                               'width "' + params['width'] + '"',
1655                               'collapsed ' + params['collapsed']]
1656             i = i + 6
1657
1658
1659 def remove_branches(file):
1660     i = 0
1661     while 1:
1662         i = find_token(file.header, "\\branch", i)
1663         if i == -1:
1664             break
1665         file.warning("Removing branch %s." % split(file.header[i])[1])
1666         j = find_token(file.header, "\\end_branch", i)
1667         if j == -1:
1668             file.warning("Malformed LyX file: Missing '\\end_branch'.")
1669             break
1670         del file.header[i:j+1]
1671
1672     i = 0
1673     while 1:
1674         i = find_token(file.body, "\\begin_inset Branch", i)
1675         if i == -1:
1676             return
1677         j = find_end_of_inset(file.body, i)
1678         if j == -1:
1679             file.warning("Malformed LyX file: Missing '\\end_inset'.")
1680             i = i + 1
1681             continue
1682         del file.body[i]
1683         del file.body[j - 1]
1684         # Seach for a line starting 'collapsed'
1685         # If, however, we find a line starting '\layout'
1686         # (_always_ present) then break with a warning message
1687         collapsed_found = 0
1688         while 1:
1689             if (file.body[i][:9] == "collapsed"):
1690                 del file.body[i]
1691                 collapsed_found = 1
1692                 continue
1693             elif (file.body[i][:7] == "\\layout"):
1694                 if collapsed_found == 0:
1695                     file.warning("Malformed LyX file: Missing 'collapsed'.")
1696                 # Delete this new paragraph, since it would not appear in
1697                 # .tex output. This avoids also empty paragraphs.
1698                 del file.body[i]
1699                 break
1700             i = i + 1
1701
1702
1703 ##
1704 # Convert jurabib
1705 #
1706
1707 def convert_jurabib(file):
1708     i = find_token(file.header, '\\use_numerical_citations', 0)
1709     if i == -1:
1710         file.warning("Malformed lyx file: Missing '\\use_numerical_citations'.")
1711         return
1712     file.header.insert(i + 1, '\\use_jurabib 0')
1713
1714
1715 def revert_jurabib(file):
1716     i = find_token(file.header, '\\use_jurabib', 0)
1717     if i == -1:
1718         file.warning("Malformed lyx file: Missing '\\use_jurabib'.")
1719         return
1720     if get_value(file.header, '\\use_jurabib', 0) != "0":
1721         file.warning("Conversion of '\\use_jurabib = 1' not yet implemented.")
1722         # Don't remove '\\use_jurabib' so that people will get warnings by lyx
1723         return
1724     del file.header[i]
1725
1726 ##
1727 # Convert bibtopic
1728 #
1729
1730 def convert_bibtopic(file):
1731     i = find_token(file.header, '\\use_jurabib', 0)
1732     if i == -1:
1733         file.warning("Malformed lyx file: Missing '\\use_jurabib'.")
1734         return
1735     file.header.insert(i + 1, '\\use_bibtopic 0')
1736
1737
1738 def revert_bibtopic(file):
1739     i = find_token(file.header, '\\use_bibtopic', 0)
1740     if i == -1:
1741         file.warning("Malformed lyx file: Missing '\\use_bibtopic'.")
1742         return
1743     if get_value(file.header, '\\use_bibtopic', 0) != "0":
1744         file.warning("Conversion of '\\use_bibtopic = 1' not yet implemented.")
1745         # Don't remove '\\use_jurabib' so that people will get warnings by lyx
1746     del file.header[i]
1747
1748 ##
1749 # Sideway Floats
1750 #
1751
1752 def convert_float(file):
1753     i = 0
1754     while 1:
1755         i = find_token_exact(file.body, '\\begin_inset Float', i)
1756         if i == -1:
1757             return
1758         # Seach for a line starting 'wide'
1759         # If, however, we find a line starting '\begin_layout'
1760         # (_always_ present) then break with a warning message
1761         i = i + 1
1762         while 1:
1763             if (file.body[i][:4] == "wide"):
1764                 file.body.insert(i + 1, 'sideways false')
1765                 break
1766             elif (file.body[i][:13] == "\\begin_layout"):
1767                 file.warning("Malformed lyx file: Missing 'wide'.")
1768                 break
1769             i = i + 1
1770         i = i + 1
1771
1772
1773 def revert_float(file):
1774     i = 0
1775     while 1:
1776         i = find_token_exact(file.body, '\\begin_inset Float', i)
1777         if i == -1:
1778             return
1779         j = find_end_of_inset(file.body, i)
1780         if j == -1:
1781             file.warning("Malformed lyx file: Missing '\\end_inset'.")
1782             i = i + 1
1783             continue
1784         if get_value(file.body, 'sideways', i, j) != "false":
1785             file.warning("Conversion of 'sideways true' not yet implemented.")
1786             # Don't remove 'sideways' so that people will get warnings by lyx
1787             i = i + 1
1788             continue
1789         del_token(file.body, 'sideways', i, j)
1790         i = i + 1
1791
1792
1793 def convert_graphics(file):
1794     """ Add extension to filenames of insetgraphics if necessary.
1795     """
1796     i = 0
1797     while 1:
1798         i = find_token(file.body, "\\begin_inset Graphics", i)
1799         if i == -1:
1800             return
1801
1802         j = find_token_exact(file.body, "filename", i)
1803         if j == -1:
1804             return
1805         i = i + 1
1806         filename = split(file.body[j])[1]
1807         absname = os.path.normpath(os.path.join(file.dir, filename))
1808         if file.input == stdin and not os.path.isabs(filename):
1809             # We don't know the directory and cannot check the file.
1810             # We could use a heuristic and take the current directory,
1811             # and we could try to find out if filename has an extension,
1812             # but that would be just guesses and could be wrong.
1813             file.warning("""Warning: Can not determine whether file
1814          %s
1815          needs an extension when reading from standard input.
1816          You may need to correct the file manually or run
1817          lyx2lyx again with the .lyx file as commandline argument.""" % filename)
1818             continue
1819         # This needs to be the same algorithm as in pre 233 insetgraphics
1820         if access(absname, F_OK):
1821             continue
1822         if access(absname + ".ps", F_OK):
1823             file.body[j] = replace(file.body[j], filename, filename + ".ps")
1824             continue
1825         if access(absname + ".eps", F_OK):
1826             file.body[j] = replace(file.body[j], filename, filename + ".eps")
1827
1828
1829 ##
1830 # Convert firstname and surname from styles -> char styles
1831 #
1832 def convert_names(file):
1833     """ Convert in the docbook backend from firstname and surname style
1834     to charstyles.
1835     """
1836     if file.backend != "docbook":
1837         return
1838
1839     i = 0
1840
1841     while 1:
1842         i = find_token(file.body, "\\begin_layout Author", i)
1843         if i == -1:
1844             return
1845
1846         i = i + 1
1847         while file.body[i] == "":
1848             i = i + 1
1849
1850         if file.body[i][:11] != "\\end_layout" or file.body[i+2][:13] != "\\begin_deeper":
1851             i = i + 1
1852             continue
1853
1854         k = i
1855         i = find_end_of( file.body, i+3, "\\begin_deeper","\\end_deeper")
1856         if i == -1:
1857             # something is really wrong, abort
1858             file.warning("Missing \\end_deeper, after style Author.")
1859             file.warning("Aborted attempt to parse FirstName and Surname.")
1860             return
1861         firstname, surname = "", ""
1862
1863         name = file.body[k:i]
1864
1865         j = find_token(name, "\\begin_layout FirstName", 0)
1866         if j != -1:
1867             j = j + 1
1868             while(name[j] != "\\end_layout"):
1869                 firstname = firstname + name[j]
1870                 j = j + 1
1871
1872         j = find_token(name, "\\begin_layout Surname", 0)
1873         if j != -1:
1874             j = j + 1
1875             while(name[j] != "\\end_layout"):
1876                 surname = surname + name[j]
1877                 j = j + 1
1878
1879         # delete name
1880         del file.body[k+2:i+1]
1881
1882         file.body[k-1:k-1] = ["", "",
1883                           "\\begin_inset CharStyle Firstname",
1884                           "status inlined",
1885                           "",
1886                           '\\begin_layout %s' % file.default_layout,
1887                           "",
1888                           "%s" % firstname,
1889                           "\end_layout",
1890                           "",
1891                           "\end_inset",
1892                           "",
1893                           "",
1894                           "\\begin_inset CharStyle Surname",
1895                           "status inlined",
1896                           "",
1897                           '\\begin_layout %s' % file.default_layout,
1898                           "",
1899                           "%s" % surname,
1900                           "\\end_layout",
1901                           "",
1902                           "\\end_inset",
1903                           ""]
1904
1905
1906 def revert_names(file):
1907     """ Revert in the docbook backend from firstname and surname char style
1908     to styles.
1909     """
1910     if file.backend != "docbook":
1911         return
1912
1913
1914 ##
1915 #    \use_natbib 1                       \cite_engine <style>
1916 #    \use_numerical_citations 0     ->   where <style> is one of
1917 #    \use_jurabib 0                      "basic", "natbib_authoryear",
1918 #                                        "natbib_numerical" or "jurabib"
1919 def convert_cite_engine(file):
1920     a = find_token(file.header, "\\use_natbib", 0)
1921     if a == -1:
1922         file.warning("Malformed lyx file: Missing '\\use_natbib'.")
1923         return
1924
1925     b = find_token(file.header, "\\use_numerical_citations", 0)
1926     if b == -1 or b != a+1:
1927         file.warning("Malformed lyx file: Missing '\\use_numerical_citations'.")
1928         return
1929
1930     c = find_token(file.header, "\\use_jurabib", 0)
1931     if c == -1 or c != b+1:
1932         file.warning("Malformed lyx file: Missing '\\use_jurabib'.")
1933         return
1934
1935     use_natbib = int(split(file.header[a])[1])
1936     use_numerical_citations = int(split(file.header[b])[1])
1937     use_jurabib = int(split(file.header[c])[1])
1938
1939     cite_engine = "basic"
1940     if use_natbib:
1941         if use_numerical_citations:
1942             cite_engine = "natbib_numerical"
1943         else:
1944              cite_engine = "natbib_authoryear"
1945     elif use_jurabib:
1946         cite_engine = "jurabib"
1947
1948     del file.header[a:c+1]
1949     file.header.insert(a, "\\cite_engine " + cite_engine)
1950
1951
1952 def revert_cite_engine(file):
1953     i = find_token(file.header, "\\cite_engine", 0)
1954     if i == -1:
1955         file.warning("Malformed lyx file: Missing '\\cite_engine'.")
1956         return
1957
1958     cite_engine = split(file.header[i])[1]
1959
1960     use_natbib = '0'
1961     use_numerical = '0'
1962     use_jurabib = '0'
1963     if cite_engine == "natbib_numerical":
1964         use_natbib = '1'
1965         use_numerical = '1'
1966     elif cite_engine == "natbib_authoryear":
1967         use_natbib = '1'
1968     elif cite_engine == "jurabib":
1969         use_jurabib = '1'
1970
1971     del file.header[i]
1972     file.header.insert(i, "\\use_jurabib " + use_jurabib)
1973     file.header.insert(i, "\\use_numerical_citations " + use_numerical)
1974     file.header.insert(i, "\\use_natbib " + use_natbib)
1975
1976
1977 ##
1978 # Paper package
1979 #
1980 def convert_paperpackage(file):
1981     i = find_token(file.header, "\\paperpackage", 0)
1982     if i == -1:
1983         return
1984
1985     packages = {'default':'none','a4':'none', 'a4wide':'a4', 'widemarginsa4':'a4wide'}
1986     if len(split(file.header[i])) > 1:
1987         paperpackage = split(file.header[i])[1]
1988         file.header[i] = replace(file.header[i], paperpackage, packages[paperpackage])
1989     else:
1990         file.header[i] = file.header[i] + ' widemarginsa4'
1991
1992
1993 def revert_paperpackage(file):
1994     i = find_token(file.header, "\\paperpackage", 0)
1995     if i == -1:
1996         return
1997
1998     packages = {'none':'a4', 'a4':'a4wide', 'a4wide':'widemarginsa4',
1999                 'widemarginsa4':'', 'default': 'default'}
2000     if len(split(file.header[i])) > 1:
2001         paperpackage = split(file.header[i])[1]
2002     else:
2003         paperpackage = 'default'
2004     file.header[i] = replace(file.header[i], paperpackage, packages[paperpackage])
2005
2006
2007 ##
2008 # Bullets
2009 #
2010 def convert_bullets(file):
2011     i = 0
2012     while 1:
2013         i = find_token(file.header, "\\bullet", i)
2014         if i == -1:
2015             return
2016         if file.header[i][:12] == '\\bulletLaTeX':
2017             file.header[i] = file.header[i] + ' ' + strip(file.header[i+1])
2018             n = 3
2019         else:
2020             file.header[i] = file.header[i] + ' ' + strip(file.header[i+1]) +\
2021                         ' ' + strip(file.header[i+2]) + ' ' + strip(file.header[i+3])
2022             n = 5
2023         del file.header[i+1:i + n]
2024         i = i + 1
2025
2026
2027 def revert_bullets(file):
2028     i = 0
2029     while 1:
2030         i = find_token(file.header, "\\bullet", i)
2031         if i == -1:
2032             return
2033         if file.header[i][:12] == '\\bulletLaTeX':
2034             n = find(file.header[i], '"')
2035             if n == -1:
2036                 file.warning("Malformed header.")
2037                 return
2038             else:
2039                 file.header[i:i+1] = [file.header[i][:n-1],'\t' + file.header[i][n:], '\\end_bullet']
2040             i = i + 3
2041         else:
2042             frag = split(file.header[i])
2043             if len(frag) != 5:
2044                 file.warning("Malformed header.")
2045                 return
2046             else:
2047                 file.header[i:i+1] = [frag[0] + ' ' + frag[1],
2048                                  '\t' + frag[2],
2049                                  '\t' + frag[3],
2050                                  '\t' + frag[4],
2051                                  '\\end_bullet']
2052                 i = i + 5
2053
2054
2055 ##
2056 # \begin_header and \begin_document
2057 #
2058 def add_begin_header(file):
2059     i = find_token(file.header, '\\lyxformat', 0)
2060     file.header.insert(i+1, '\\begin_header')
2061     file.header.insert(i+1, '\\begin_document')
2062
2063
2064 def remove_begin_header(file):
2065     i = find_token(file.header, "\\begin_document", 0)
2066     if i != -1:
2067         del file.header[i]
2068     i = find_token(file.header, "\\begin_header", 0)
2069     if i != -1:
2070         del file.header[i]
2071
2072
2073 ##
2074 # \begin_file.body and \end_file.body
2075 #
2076 def add_begin_body(file):
2077     file.body.insert(0, '\\begin_body')
2078     file.body.insert(1, '')
2079     i = find_token(file.body, "\\end_document", 0)
2080     file.body.insert(i, '\\end_body')
2081
2082 def remove_begin_body(file):
2083     i = find_token(file.body, "\\begin_body", 0)
2084     if i != -1:
2085         del file.body[i]
2086         if not file.body[i]:
2087             del file.body[i]
2088     i = find_token(file.body, "\\end_body", 0)
2089     if i != -1:
2090         del file.body[i]
2091
2092
2093 ##
2094 # \papersize
2095 #
2096 def normalize_papersize(file):
2097     i = find_token(file.header, '\\papersize', 0)
2098     if i == -1:
2099         return
2100
2101     tmp = split(file.header[i])
2102     if tmp[1] == "Default":
2103         file.header[i] = '\\papersize default'
2104         return
2105     if tmp[1] == "Custom":
2106         file.header[i] = '\\papersize custom'
2107
2108
2109 def denormalize_papersize(file):
2110     i = find_token(file.header, '\\papersize', 0)
2111     if i == -1:
2112         return
2113
2114     tmp = split(file.header[i])
2115     if tmp[1] == "custom":
2116         file.header[i] = '\\papersize Custom'
2117
2118
2119 ##
2120 # Strip spaces at end of command line
2121 #
2122 def strip_end_space(file):
2123     for i in range(len(file.body)):
2124         if file.body[i][:1] == '\\':
2125             file.body[i] = strip(file.body[i])
2126
2127
2128 ##
2129 # Use boolean values for \use_geometry, \use_bibtopic and \tracking_changes
2130 #
2131 def use_x_boolean(file):
2132     bin2bool = {'0': 'false', '1': 'true'}
2133     for use in '\\use_geometry', '\\use_bibtopic', '\\tracking_changes':
2134         i = find_token(file.header, use, 0)
2135         if i == -1:
2136             continue
2137         decompose = split(file.header[i])
2138         file.header[i] = decompose[0] + ' ' + bin2bool[decompose[1]]
2139
2140
2141 def use_x_binary(file):
2142     bool2bin = {'false': '0', 'true': '1'}
2143     for use in '\\use_geometry', '\\use_bibtopic', '\\tracking_changes':
2144         i = find_token(file.header, use, 0)
2145         if i == -1:
2146             continue
2147         decompose = split(file.header[i])
2148         file.header[i] = decompose[0] + ' ' + bool2bin[decompose[1]]
2149
2150 ##
2151 # Place all the paragraph parameters in their own line
2152 #
2153 def normalize_paragraph_params(file):
2154     body = file.body
2155     allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix", "\\leftindent"
2156
2157     i = 0
2158     while 1:
2159         i = find_token(file.body, '\\begin_layout', i)
2160         if i == -1:
2161             return
2162
2163         i = i + 1
2164         while 1:
2165             if strip(body[i]) and split(body[i])[0] not in allowed_parameters:
2166                 break
2167
2168             j = find(body[i],'\\', 1)
2169
2170             if j != -1:
2171                 body[i:i+1] = [strip(body[i][:j]), body[i][j:]]
2172
2173             i = i + 1
2174
2175
2176 ##
2177 # Add/remove output_changes parameter
2178 #
2179 def convert_output_changes (file):
2180     i = find_token(file.header, '\\tracking_changes', 0)
2181     if i == -1:
2182         file.warning("Malformed lyx file: Missing '\\tracking_changes'.")
2183         return
2184     file.header.insert(i+1, '\\output_changes true')
2185
2186
2187 def revert_output_changes (file):
2188     i = find_token(file.header, '\\output_changes', 0)
2189     if i == -1:
2190         return
2191     del file.header[i]
2192
2193
2194 ##
2195 # Convert paragraph breaks and sanitize paragraphs
2196 #
2197 def convert_ert_paragraphs(file):
2198     forbidden_settings = [
2199                           # paragraph parameters
2200                           '\\paragraph_spacing', '\\labelwidthstring',
2201                           '\\start_of_appendix', '\\noindent',
2202                           '\\leftindent', '\\align',
2203                           # font settings
2204                           '\\family', '\\series', '\\shape', '\\size',
2205                           '\\emph', '\\numeric', '\\bar', '\\noun',
2206                           '\\color', '\\lang']
2207     i = 0
2208     while 1:
2209         i = find_token(file.body, '\\begin_inset ERT', i)
2210         if i == -1:
2211             return
2212         j = find_end_of_inset(file.body, i)
2213         if j == -1:
2214             file.warning("Malformed lyx file: Missing '\\end_inset'.")
2215             i = i + 1
2216             continue
2217
2218         # convert non-standard paragraphs to standard
2219         k = i
2220         while 1:
2221             k = find_token(file.body, "\\begin_layout", k, j)
2222             if k == -1:
2223                 break
2224             file.body[k] = '\\begin_layout %s' % file.default_layout
2225             k = k + 1
2226
2227         # remove all paragraph parameters and font settings
2228         k = i
2229         while k < j:
2230             if (strip(file.body[k]) and
2231                 split(file.body[k])[0] in forbidden_settings):
2232                 del file.body[k]
2233                 j = j - 1
2234             else:
2235                 k = k + 1
2236
2237         # insert an empty paragraph before each paragraph but the first
2238         k = i
2239         first_pagraph = 1
2240         while 1:
2241             k = find_token(file.body, "\\begin_layout", k, j)
2242             if k == -1:
2243                 break
2244             if first_pagraph:
2245                 first_pagraph = 0
2246                 k = k + 1
2247                 continue
2248             file.body[k:k] = ['\\begin_layout %s' % file.default_layout, "",
2249                               "\\end_layout", ""]
2250             k = k + 5
2251             j = j + 4
2252
2253         # convert \\newline to new paragraph
2254         k = i
2255         while 1:
2256             k = find_token(file.body, "\\newline", k, j)
2257             if k == -1:
2258                 break
2259             file.body[k:k+1] = ["\\end_layout", "", '\\begin_layout %s' % file.default_layout]
2260             k = k + 4
2261             j = j + 3
2262             # We need an empty line if file.default_layout == ''
2263             if file.body[k-1] != '':
2264                 file.body.insert(k-1, '')
2265                 k = k + 1
2266                 j = j + 1
2267         i = i + 1
2268
2269
2270 ##
2271 # Remove double paragraph breaks
2272 #
2273 def revert_ert_paragraphs(file):
2274     i = 0
2275     while 1:
2276         i = find_token(file.body, '\\begin_inset ERT', i)
2277         if i == -1:
2278             return
2279         j = find_end_of_inset(file.body, i)
2280         if j == -1:
2281             file.warning("Malformed lyx file: Missing '\\end_inset'.")
2282             i = i + 1
2283             continue
2284
2285         # replace paragraph breaks with \newline
2286         k = i
2287         while 1:
2288             k = find_token(file.body, "\\end_layout", k, j)
2289             l = find_token(file.body, "\\begin_layout", k, j)
2290             if k == -1 or l == -1:
2291                 break
2292             file.body[k:l+1] = ["\\newline"]
2293             j = j - l + k
2294             k = k + 1
2295
2296         # replace double \newlines with paragraph breaks
2297         k = i
2298         while 1:
2299             k = find_token(file.body, "\\newline", k, j)
2300             if k == -1:
2301                 break
2302             l = k + 1
2303             while file.body[l] == "":
2304                 l = l + 1
2305             if strip(file.body[l]) and split(file.body[l])[0] == "\\newline":
2306                 file.body[k:l+1] = ["\\end_layout", "",
2307                                     '\\begin_layout %s' % file.default_layout]
2308                 j = j - l + k + 2
2309                 k = k + 3
2310                 # We need an empty line if file.default_layout == ''
2311                 if file.body[l+1] != '':
2312                     file.body.insert(l+1, '')
2313                     k = k + 1
2314                     j = j + 1
2315             else:
2316                 k = k + 1
2317         i = i + 1
2318
2319
2320 def convert_french(file):
2321     regexp = re.compile(r'^\\language\s+frenchb')
2322     i = find_re(file.header, regexp, 0)
2323     if i != -1:
2324         file.header[i] = "\\language french"
2325
2326     # Change language in the document body
2327     regexp = re.compile(r'^\\lang\s+frenchb')
2328     i = 0
2329     while 1:
2330         i = find_re(file.body, regexp, i)
2331         if i == -1:
2332             break
2333         file.body[i] = "\\lang french"
2334         i = i + 1
2335
2336
2337 def remove_paperpackage(file):
2338     i = find_token(file.header, '\\paperpackage', 0)
2339
2340     if i == -1:
2341         return
2342
2343     paperpackage = split(file.header[i])[1]
2344
2345     del file.header[i]
2346
2347     if paperpackage not in ("a4", "a4wide", "widemarginsa4"):
2348         return
2349
2350     conv = {"a4":"\\usepackage{a4}","a4wide": "\\usepackage{a4wide}",
2351             "widemarginsa4": "\\usepackage[widemargins]{a4}"}
2352     # for compatibility we ensure it is the first entry in preamble
2353     file.preamble[0:0] = [conv[paperpackage]]
2354
2355     i = find_token(file.header, '\\papersize', 0)
2356     if i != -1:
2357         file.header[i] = "\\papersize default"
2358
2359
2360 def remove_quotestimes(file):
2361     i = find_token(file.header, '\\quotes_times', 0)
2362     if i == -1:
2363         return
2364     del file.header[i]
2365
2366
2367 ##
2368 # Convertion hub
2369 #
2370
2371 convert = [[222, [insert_tracking_changes, add_end_header, convert_amsmath]],
2372            [223, [remove_color_default, convert_spaces, convert_bibtex, remove_insetparent]],
2373            [224, [convert_external, convert_comment]],
2374            [225, [add_end_layout, layout2begin_layout, convert_end_document,
2375                   convert_table_valignment_middle, convert_breaks]],
2376            [226, [convert_note]],
2377            [227, [convert_box]],
2378            [228, [convert_collapsable, convert_ert]],
2379            [229, [convert_minipage]],
2380            [230, [convert_jurabib]],
2381            [231, [convert_float]],
2382            [232, [convert_bibtopic]],
2383            [233, [convert_graphics, convert_names]],
2384            [234, [convert_cite_engine]],
2385            [235, [convert_paperpackage]],
2386            [236, [convert_bullets, add_begin_header, add_begin_body,
2387                   normalize_papersize, strip_end_space]],
2388            [237, [use_x_boolean]],
2389            [238, [update_latexaccents]],
2390            [239, [normalize_paragraph_params]],
2391            [240, [convert_output_changes]],
2392            [241, [convert_ert_paragraphs]],
2393            [242, [convert_french]],
2394            [243, [remove_paperpackage]],
2395            [244, [rename_spaces]],
2396            [245, [remove_quotestimes]]]
2397
2398 revert =  [[244, []],
2399            [243, [revert_space_names]],
2400            [242, []],
2401            [241, []],
2402            [240, [revert_ert_paragraphs]],
2403            [239, [revert_output_changes]],
2404            [238, []],
2405            [237, []],
2406            [236, [use_x_binary]],
2407            [235, [denormalize_papersize, remove_begin_body,remove_begin_header,
2408                   revert_bullets]],
2409            [234, [revert_paperpackage]],
2410            [233, [revert_cite_engine]],
2411            [232, [revert_names]],
2412            [231, [revert_bibtopic]],
2413            [230, [revert_float]],
2414            [229, [revert_jurabib]],
2415            [228, []],
2416            [227, [revert_collapsable, revert_ert]],
2417            [226, [revert_box, revert_external_2]],
2418            [225, [revert_note]],
2419            [224, [rm_end_layout, begin_layout2layout, revert_end_document,
2420                   revert_valignment_middle, revert_breaks, convert_frameless_box,
2421                   remove_branches]],
2422            [223, [revert_external_2, revert_comment, revert_eqref]],
2423            [222, [revert_spaces, revert_bibtex]],
2424            [221, [revert_amsmath, rm_end_header, rm_tracking_changes, rm_body_changes]]]
2425
2426
2427 if __name__ == "__main__":
2428     pass