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