]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_1_4.py
4ad3c1534631e50417f8ce3299a9ca42095a0868
[lyx.git] / lib / lyx2lyx / lyx_1_4.py
1 # This file is part of lyx2lyx
2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2002 Dekel Tsur <dekel@lyx.org>
4 # Copyright (C) 2002-2004 José Matos <jamatos@lyx.org>
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 import re
21 from parser_tools import find_token, find_end_of_inset, get_next_paragraph, \
22                          get_paragraph, get_value, del_token, is_nonempty_line,\
23                          find_tokens, find_end_of
24 from string import replace, split, find, strip, join
25
26 ##
27 # Add \end_header
28 #
29 def add_end_header(header):
30     header.append("\\end_header");
31
32
33 def rm_end_header(lines):
34     i = find_token(lines, "\\end_header", 0)
35     if i == -1:
36         return
37     del lines[i]
38
39
40 ##
41 # \SpecialChar ~ -> \InsetSpace ~
42 #
43 def convert_spaces(lines):
44     for i in range(len(lines)):
45         lines[i] = replace(lines[i],"\\SpecialChar ~","\\InsetSpace ~")
46
47
48 def revert_spaces(lines):
49     for i in range(len(lines)):
50         lines[i] = replace(lines[i],"\\InsetSpace ~", "\\SpecialChar ~")
51
52
53 ##
54 # BibTeX changes
55 #
56 def convert_bibtex(lines):
57     for i in range(len(lines)):
58         lines[i] = replace(lines[i],"\\begin_inset LatexCommand \\BibTeX",
59                                   "\\begin_inset LatexCommand \\bibtex")
60
61
62 def revert_bibtex(lines):
63     for i in range(len(lines)):
64         lines[i] = replace(lines[i], "\\begin_inset LatexCommand \\bibtex",
65                                   "\\begin_inset LatexCommand \\BibTeX")
66
67
68 ##
69 # Remove \lyxparent
70 #
71 def remove_insetparent(lines):
72     i = 0
73     while 1:
74         i = find_token(lines, "\\begin_inset LatexCommand \\lyxparent", i)
75         if i == -1:
76             break
77         del lines[i:i+3]
78
79
80 ##
81 #  Inset External
82 #
83 def convert_external(lines):
84     external_rexp = re.compile(r'\\begin_inset External ([^,]*),"([^"]*)",')
85     external_header = "\\begin_inset External"
86     i = 0
87     while 1:
88         i = find_token(lines, external_header, i)
89         if i == -1:
90             break
91         look = external_rexp.search(lines[i])
92         args = ['','']
93         if look:
94             args[0] = look.group(1)
95             args[1] = look.group(2)
96         #FIXME: if the previous search fails then warn
97
98         if args[0] == "RasterImage":
99             # Convert a RasterImage External Inset to a Graphics Inset.
100             top = "\\begin_inset Graphics"
101             if args[1]:
102                 filename = "\tfilename " + args[1]
103             lines[i:i+1] = [top, filename]
104             i = i + 1
105         else:
106             # Convert the old External Inset format to the new.
107             top = external_header
108             template = "\ttemplate " + args[0]
109             if args[1]:
110                 filename = "\tfilename " + args[1]
111                 lines[i:i+1] = [top, template, filename]
112                 i = i + 2
113             else:
114                 lines[i:i+1] = [top, template]
115                 i = i + 1
116
117
118 def revert_external_1(lines):
119     external_header = "\\begin_inset External"
120     i = 0
121     while 1:
122         i = find_token(lines, external_header, i)
123         if i == -1:
124             break
125
126         template = split(lines[i+1])
127         template.reverse()
128         del lines[i+1]
129
130         filename = split(lines[i+1])
131         filename.reverse()
132         del lines[i+1]
133
134         params = split(lines[i+1])
135         params.reverse()
136         if lines[i+1]: del lines[i+1]
137
138         lines[i] = lines[i] + " " + template[0]+ ', "' + filename[0] + '", " '+ join(params[1:]) + '"'
139         i = i + 1
140
141
142 def revert_external_2(lines):
143     draft_token = '\tdraft'
144     i = 0
145     while 1:
146         i = find_token(lines, '\\begin_inset External', i)
147         if i == -1:
148             break
149         j = find_end_of_inset(lines, i + 1)
150         if j == -1:
151             #this should not happen
152             break
153         k = find_token(lines, draft_token, i+1, j-1)
154         if (k != -1 and len(draft_token) == len(lines[k])):
155             del lines[k]
156         i = j + 1
157
158
159 ##
160 # Comment
161 #
162 def convert_comment(lines):
163     i = 0
164     comment = "\\layout Comment"
165     while 1:
166         i = find_token(lines, comment, i)
167         if i == -1:
168             return
169
170         lines[i:i+1] = ["\\layout Standard","","",
171                         "\\begin_inset Comment",
172                         "collapsed true","",
173                         "\\layout Standard"]
174         i = i + 7
175
176         while 1:
177                 old_i = i
178                 i = find_token(lines, "\\layout", i)
179                 if i == -1:
180                     i = len(lines) - 1
181                     lines[i:i] = ["\\end_inset ","",""]
182                     return
183
184                 j = find_token(lines, '\\begin_deeper', old_i, i)
185                 if j == -1: j = i + 1
186                 k = find_token(lines, '\\begin_inset', old_i, i)
187                 if k == -1: k = i + 1
188
189                 if j < i and j < k:
190                     i = j
191                     del lines[i]
192                     i = find_end_of( lines, i, "\\begin_deeper","\\end_deeper")
193                     if i == -1:
194                         #This case should not happen
195                         #but if this happens deal with it greacefully adding
196                         #the missing \end_deeper.
197                         i = len(lines) - 1
198                         lines[i:i] = ["\end_deeper","","","\\end_inset ","",""]
199                         return
200                     else:
201                         del lines[i]
202                         continue
203
204                 if k < i:
205                     i = k
206                     i = find_end_of( lines, i, "\\begin_inset","\\end_inset")
207                     if i == -1:
208                         #This case should not happen
209                         #but if this happens deal with it greacefully adding
210                         #the missing \end_inset.
211                         i = len(lines) - 1
212                         lines[i:i] = ["\\end_inset ","","","\\end_inset ","",""]
213                         return
214                     else:
215                         i = i + 1
216                         continue
217
218                 if find(lines[i], comment) == -1:
219                     lines[i:i] = ["\\end_inset"]
220                     i = i + 1
221                     break
222                 lines[i:i+1] = ["\\layout Standard"]
223                 i = i + 1
224
225
226 def revert_comment(lines):
227     i = 0
228     while 1:
229         i = find_tokens(lines, ["\\begin_inset Comment", "\\begin_inset Greyedout"], i)
230
231         if i == -1:
232             return
233         lines[i] = "\\begin_inset Note"
234         i = i + 1
235
236
237 ##
238 # Add \end_layout
239 #
240 def add_end_layout(lines):
241     i = find_token(lines, '\\layout', 0)
242
243     if i == -1:
244         return
245
246     i = i + 1
247     struct_stack = ["\\layout"]
248     while 1:
249         i = find_tokens(lines, ["\\begin_inset", "\\end_inset", "\\layout",
250                                 "\\begin_deeper", "\\end_deeper", "\\the_end"], i)
251
252         token = split(lines[i])[0]
253
254         if token == "\\begin_inset":
255             struct_stack.append(token)
256             i = i + 1
257             continue
258
259         if token == "\\end_inset":
260             tail = struct_stack.pop()
261             if tail == "\\layout":
262                 lines.insert(i,"\\end_layout")
263                 i = i + 1
264                 #Check if it is the correct tag
265                 struct_stack.pop()
266             i = i + 1
267             continue
268
269         if token == "\\layout":
270             tail = struct_stack.pop()
271             if tail == token:
272                 lines.insert(i,"\\end_layout")
273                 i = i + 2
274             else:
275                 struct_stack.append(tail)
276                 i = i + 1
277             struct_stack.append(token)
278             continue
279
280         if token == "\\begin_deeper" or token == "\\end_deeper":
281             lines.insert(i,"\\end_layout")
282             i = i + 2
283             continue
284
285         #case \end_document
286         lines.insert(i, "\\end_layout")
287         return
288
289
290 def rm_end_layout(lines):
291     i = 0
292     while 1:
293         i = find_token(lines, '\\end_layout', i)
294
295         if i == -1:
296             return
297
298         del lines[i]
299
300
301 ##
302 # Remove change tracking keywords
303 #
304 def rm_tracking_changes(lines):
305     i = find_token(lines, "\\author", 0)
306     if i != -1:
307         del lines[i]
308
309     i = find_token(lines, "\\tracking_changes", 0)
310     if i == -1:
311         return
312     del lines[i]
313
314
315 def rm_body_changes(lines):
316     i = 0
317     while 1:
318         i = find_token(lines, "\\change_", i)
319         if i == -1:
320             return
321
322         del lines[i]
323
324
325 ##
326 # \layout -> \begin_layout
327 #
328 def layout2begin_layout(lines):
329     i = 0
330     while 1:
331         i = find_token(lines, '\\layout', i)
332         if i == -1:
333             return
334
335         lines[i] = replace(lines[i], '\\layout', '\\begin_layout')
336         i = i + 1
337
338
339 def begin_layout2layout(lines):
340     i = 0
341     while 1:
342         i = find_token(lines, '\\begin_layout', i)
343         if i == -1:
344             return
345
346         lines[i] = replace(lines[i], '\\begin_layout', '\\layout')
347         i = i + 1
348
349
350 ##
351 # valignment="center" -> valignment="middle"
352 #
353 def convert_valignment_middle(lines, start, end):
354     for i in range(start, end):
355         if re.search('^<(column|cell) .*valignment="center".*>$', lines[i]):
356             lines[i] = replace(lines[i], 'valignment="center"', 'valignment="middle"')
357
358
359 def convert_table_valignment_middle(lines):
360     i = 0
361     while 1:
362         i = find_token(lines, '\\begin_inset  Tabular', i)
363         if i == -1:
364             return
365         j = find_end_of_inset(lines, i + 1)
366         if j == -1:
367             #this should not happen
368             convert_valignment_middle(lines, i + 1, len(lines))
369             return
370         convert_valignment_middle(lines, i + 1, j)
371         i = j + 1
372
373
374 def revert_table_valignment_middle(lines, start, end):
375     for i in range(start, end):
376         if re.search('^<(column|cell) .*valignment="middle".*>$', lines[i]):
377             lines[i] = replace(lines[i], 'valignment="middle"', 'valignment="center"')
378
379
380 def revert_valignment_middle(lines):
381     i = 0
382     while 1:
383         i = find_token(lines, '\\begin_inset  Tabular', i)
384         if i == -1:
385             return
386         j = find_end_of_inset(lines, i + 1)
387         if j == -1:
388             #this should not happen
389             revert_table_valignment_middle(lines, i + 1, len(lines))
390             return
391         revert_table_valignment_middle(lines, i + 1, j)
392         i = j + 1
393
394
395 ##
396 #  \the_end -> \end_document
397 #
398 def convert_end_document(lines):
399     i = find_token(lines, "\\the_end", 0)
400     if i == -1:
401         lines.append("\\end_document")
402         return
403     lines[i] = "\\end_document"
404
405
406 def revert_end_document(lines):
407     i = find_token(lines, "\\end_document", 0)
408     if i == -1:
409         lines.append("\\the_end")
410         return
411     lines[i] = "\\the_end"
412
413
414 ##
415 # Convert line and page breaks
416 # Old:
417 #\layout Standard
418 #\line_top \line_bottom \pagebreak_top \pagebreak_bottom \added_space_top xxx \added_space_bottom yyy
419 #0
420 #
421 # New:
422 #\begin layout Standard
423 #
424 #\newpage 
425 #
426 #\lyxline
427 #\begin_inset VSpace xxx
428 #\end_inset
429 #
430 #\end_layout
431 #\begin_layout Standard
432 #
433 #0
434 #\end_layout
435 #\begin_layout Standard
436 #
437 #\begin_inset VSpace xxx
438 #\end_inset
439 #\lyxline 
440 #
441 #\newpage
442 #
443 #\end_layout
444 def convert_breaks(lines):    
445     i = 0
446     while 1:
447         i = find_token(lines, "\\begin_layout", i)
448         if i == -1:
449             return
450         i = i + 1
451         line_top   = find(lines[i],"\\line_top")
452         line_bot   = find(lines[i],"\\line_bottom")
453         pb_top     = find(lines[i],"\\pagebreak_top")
454         pb_bot     = find(lines[i],"\\pagebreak_bottom")
455         vspace_top = find(lines[i],"\\added_space_top")
456         vspace_bot = find(lines[i],"\\added_space_bottom")
457
458         if line_top == -1 and line_bot == -1 and pb_bot == -1 and pb_top == -1 and vspace_top == -1 and vspace_bot == -1:
459             continue
460
461         for tag in "\\line_top", "\\line_bottom", "\\pagebreak_top", "\\pagebreak_bottom":
462             lines[i] = replace(lines[i], tag, "")
463
464         if vspace_top != -1:
465             # the position could be change because of the removal of other
466             # paragraph properties above
467             vspace_top = find(lines[i],"\\added_space_top")
468             tmp_list = split(lines[i][vspace_top:])
469             vspace_top_value = tmp_list[1]
470             lines[i] = lines[i][:vspace_top] + join(tmp_list[2:])
471
472         if vspace_bot != -1:
473             # the position could be change because of the removal of other
474             # paragraph properties above
475             vspace_bot = find(lines[i],"\\added_space_bottom")
476             tmp_list = split(lines[i][vspace_bot:])
477             vspace_bot_value = tmp_list[1]
478             lines[i] = lines[i][:vspace_bot] + join(tmp_list[2:])
479
480         lines[i] = strip(lines[i])
481         i = i + 1
482
483         #  Create an empty paragraph for line and page break that belong
484         # above the paragraph
485         if pb_top !=-1 or line_top != -1 or vspace_bot != -1:
486             
487             paragraph_above = ['','\\begin_layout Standard','','']
488
489             if pb_top != -1:
490                 paragraph_above.extend(['\\newpage ',''])
491
492             if vspace_top != -1:
493                 paragraph_above.extend(['\\begin_inset VSpace ' + vspace_top_value,'\\end_inset ','',''])
494
495             if line_top != -1:
496                 paragraph_above.extend(['\\lyxline ',''])
497
498             paragraph_above.extend(['\\end_layout',''])
499
500             #inset new paragraph above the current paragraph
501             lines[i-2:i-2] = paragraph_above
502             i = i + len(paragraph_above)
503
504         # Ensure that nested style are converted later.
505         k = find_end_of(lines, i, "\\begin_layout", "\\end_layout")
506
507         if k == -1:
508             return
509
510         if pb_top !=-1 or line_top != -1 or vspace_bot != -1:
511             
512             paragraph_bellow = ['','\\begin_layout Standard','','']
513
514             if line_bot != -1:
515                 paragraph_bellow.extend(['\\lyxline ',''])
516
517             if vspace_bot != -1:
518                 paragraph_bellow.extend(['\\begin_inset VSpace ' + vspace_bot_value,'\\end_inset ','',''])
519
520             if pb_bot != -1:
521                 paragraph_bellow.extend(['\\newpage ',''])
522
523             paragraph_bellow.extend(['\\end_layout',''])
524
525             #inset new paragraph above the current paragraph
526             lines[k + 1: k + 1] = paragraph_bellow
527
528
529 ##
530 #  Notes
531 #
532 def convert_note(lines):
533     i = 0
534     while 1:
535         i = find_tokens(lines, ["\\begin_inset Note",
536                                 "\\begin_inset Comment",
537                                 "\\begin_inset Greyedout"], i)
538         if i == -1:
539             break
540
541         lines[i] = lines[i][0:13] + 'Note ' + lines[i][13:]
542         i = i + 1
543
544
545 def revert_note(lines):
546     note_header = "\\begin_inset Note "
547     i = 0
548     while 1:
549         i = find_token(lines, note_header, i)
550         if i == -1:
551             break
552
553         lines[i] = "\\begin_inset " + lines[i][len(note_header):]
554         i = i + 1
555
556
557 ##
558 # Box
559 #
560 def convert_box(lines):
561     i = 0
562     while 1:
563         i = find_tokens(lines, ["\\begin_inset Boxed",
564                                 "\\begin_inset Doublebox",
565                                 "\\begin_inset Frameless",
566                                 "\\begin_inset ovalbox",
567                                 "\\begin_inset Ovalbox",
568                                 "\\begin_inset Shadowbox"], i)
569         if i == -1:
570             break
571
572         lines[i] = lines[i][0:13] + 'Box ' + lines[i][13:]
573         i = i + 1
574
575
576 def revert_box(lines):
577     box_header = "\\begin_inset Box "
578     i = 0
579     while 1:
580         i = find_token(lines, box_header, i)
581         if i == -1:
582             break
583
584         lines[i] = "\\begin_inset " + lines[i][len(box_header):]
585         i = i + 1
586
587
588 ##
589 # Collapse
590 #
591 def convert_collapsable(lines, opt):
592     i = 0
593     while 1:
594         i = find_tokens(lines, ["\\begin_inset Box",
595                                 "\\begin_inset Branch",
596                                 "\\begin_inset CharStyle",
597                                 "\\begin_inset Float",
598                                 "\\begin_inset Foot",
599                                 "\\begin_inset Marginal",
600                                 "\\begin_inset Note",
601                                 "\\begin_inset OptArg",
602                                 "\\begin_inset Wrap"], i)
603         if i == -1:
604             break
605
606         # Seach for a line starting 'collapsed'
607         # If, however, we find a line starting '\begin_layout'
608         # (_always_ present) then break with a warning message
609         i = i + 1
610         while 1:
611             if (lines[i] == "collapsed false"):
612                 lines[i] = "status open"
613                 break
614             elif (lines[i] == "collapsed true"):
615                 lines[i] = "status collapsed"
616                 break
617             elif (lines[i][:13] == "\\begin_layout"):
618                 opt.warning("Malformed LyX file.")
619                 break
620             i = i + 1
621
622         i = i + 1
623
624
625 def revert_collapsable(lines, opt):
626     i = 0
627     while 1:
628         i = find_tokens(lines, ["\\begin_inset Box",
629                                 "\\begin_inset Branch",
630                                 "\\begin_inset CharStyle",
631                                 "\\begin_inset Float",
632                                 "\\begin_inset Foot",
633                                 "\\begin_inset Marginal",
634                                 "\\begin_inset Note",
635                                 "\\begin_inset OptArg",
636                                 "\\begin_inset Wrap"], i)
637         if i == -1:
638             break
639
640         # Seach for a line starting 'status'
641         # If, however, we find a line starting '\begin_layout'
642         # (_always_ present) then break with a warning message
643         i = i + 1
644         while 1:
645             if (lines[i] == "status open"):
646                 lines[i] = "collapsed false"
647                 break
648             elif (lines[i] == "status collapsed" or
649                   lines[i] == "status inlined"):
650                 lines[i] = "collapsed true"
651                 break
652             elif (lines[i][:13] == "\\begin_layout"):
653                 opt.warning("Malformed LyX file.")
654                 break
655             i = i + 1
656
657         i = i + 1
658
659
660 ##
661 #  ERT
662 #
663 def convert_ert(lines, opt):
664     i = 0
665     while 1:
666         i = find_token(lines, "\\begin_inset ERT", i)
667         if i == -1:
668             break
669
670         # Seach for a line starting 'status'
671         # If, however, we find a line starting '\begin_layout'
672         # (_always_ present) then break with a warning message
673         i = i + 1
674         while 1:
675             if (lines[i] == "status Open"):
676                 lines[i] = "status open"
677                 break
678             elif (lines[i] == "status Collapsed"):
679                 lines[i] = "status collapsed"
680                 break
681             elif (lines[i] == "status Inlined"):
682                 lines[i] = "status inlined"
683                 break
684             elif (lines[i][:13] == "\\begin_layout"):
685                 opt.warning("Malformed LyX file.")
686                 break
687             i = i + 1
688
689         i = i + 1
690
691
692 def revert_ert(lines, opt):
693     i = 0
694     while 1:
695         i = find_token(lines, "\\begin_inset ERT", i)
696         if i == -1:
697             break
698
699         # Seach for a line starting 'status'
700         # If, however, we find a line starting '\begin_layout'
701         # (_always_ present) then break with a warning message
702         i = i + 1
703         while 1:
704             if (lines[i] == "status open"):
705                 lines[i] = "status Open"
706                 break
707             elif (lines[i] == "status collapsed"):
708                 lines[i] = "status Collapsed"
709                 break
710             elif (lines[i] == "status inlined"):
711                 lines[i] = "status Inlined"
712                 break
713             elif (lines[i][:13] == "\\begin_layout"):
714                 opt.warning("Malformed LyX file.")
715                 break
716             i = i + 1
717
718         i = i + 1
719
720
721 ##
722 # Minipages
723 #
724 def convert_minipage(lines):
725     """ Convert minipages to the box inset.
726     We try to use the same order of arguments as lyx does.
727     """
728     pos = ["t","c","b"]
729     inner_pos = ["c","t","b","s"]
730
731     i = 0
732     while 1:
733         i = find_token(lines, "\\begin_inset Minipage", i)
734         if i == -1:
735             return
736
737         lines[i] = "\\begin_inset Box Frameless"
738         i = i + 1
739
740         # convert old to new position using the pos list
741         if lines[i][:8] == "position":
742             lines[i] = 'position "%s"' % pos[int(lines[i][9])]
743         else:
744             lines.insert(i, 'position "%s"' % pos[0])
745         i = i + 1
746
747         lines.insert(i, 'hor_pos "c"')
748         i = i + 1
749         lines.insert(i, 'has_inner_box 1')
750         i = i + 1
751
752         # convert the inner_position
753         if lines[i][:14] == "inner_position":
754             lines[i] = 'inner_pos "%s"' %  inner_pos[int(lines[i][15])]
755         else:
756             lines.insert('inner_pos "%s"' % inner_pos[0])
757         i = i + 1
758
759         # We need this since the new file format has a height and width
760         # in a different order.
761         if lines[i][:6] == "height":
762             height = lines[i][6:]
763             # test for default value of 221 and convert it accordingly
764             if height == ' "0pt"':
765                 height = ' "1pt"'
766             del lines[i]
767         else:
768             height = ' "1pt"'
769
770         if lines[i][:5] == "width":
771             width = lines[i][5:]
772             del lines[i]
773         else:
774             width = ' "0"'
775
776         if lines[i][:9] == "collapsed":
777             if lines[i][9:] == "true":
778                 status = "collapsed"
779             else:
780                 status = "open"
781             del lines[i]
782         else:
783             status = "collapsed"
784
785         lines.insert(i, 'use_parbox 0')
786         i = i + 1
787         lines.insert(i, 'width' + width)
788         i = i + 1
789         lines.insert(i, 'special "none"')
790         i = i + 1
791         lines.insert(i, 'height' + height)
792         i = i + 1
793         lines.insert(i, 'height_special "totalheight"')
794         i = i + 1
795         lines.insert(i, 'status ' + status)
796         i = i + 1
797
798
799 # -------------------------------------------------------------------------------------------
800 # Convert backslashes into valid ERT code, append the converted text to
801 # lines[i] and return the (maybe incremented) line index i
802 def convert_ertbackslash(lines, i, ert):
803     for c in ert:
804         if c == '\\':
805             lines[i] = lines[i] + '\\backslash '
806             lines.insert(i, '')
807             i = i + 1
808         else:
809             lines[i] = lines[i] + c
810     return i
811
812
813 def convert_vspace(header, lines, opt):
814
815     # Get default spaceamount
816     i = find_token(header, '\\defskip', 0)
817     if i == -1:
818         defskipamount = 'medskip'
819     else:
820         defskipamount = split(header[i])[1]
821
822     # Convert the insets
823     i = 0
824     while 1:
825         i = find_token(lines, '\\begin_inset VSpace', i)
826         if i == -1:
827             return
828         spaceamount = split(lines[i])[2]
829
830         # Are we at the beginning or end of a paragraph?
831         paragraph_start = 1
832         start = get_paragraph(lines, i) + 1
833         for k in range(start, i):
834             if is_nonempty_line(lines[k]):
835                 paragraph_start = 0
836                 break
837         paragraph_end = 1
838         j = find_end_of_inset(lines, i)
839         if j == -1:
840             opt.warning("Malformed LyX file: Missing '\\end_inset'.")
841             i = i + 1
842             continue
843         end = get_next_paragraph(lines, i)
844         for k in range(j + 1, end):
845             if is_nonempty_line(lines[k]):
846                 paragraph_end = 0
847                 break
848
849         # Convert to paragraph formatting if we are at the beginning or end
850         # of a paragraph and the resulting paragraph would not be empty
851         if ((paragraph_start and not paragraph_end) or
852             (paragraph_end   and not paragraph_start)):
853             # The order is important: del and insert invalidate some indices
854             del lines[j]
855             del lines[i]
856             if paragraph_start:
857                 lines.insert(start, '\\added_space_top ' + spaceamount + ' ')
858             else:
859                 lines.insert(start, '\\added_space_bottom ' + spaceamount + ' ')
860             continue
861
862         # Convert to ERT
863         lines[i:i+1] = ['\\begin_inset ERT', 'status Collapsed', '',
864                         '\\layout Standard', '', '\\backslash ']
865         i = i + 6
866         if spaceamount[-1] == '*':
867             spaceamount = spaceamount[:-1]
868             keep = 1
869         else:
870             keep = 0
871
872         # Replace defskip by the actual value
873         if spaceamount == 'defskip':
874             spaceamount = defskipamount
875
876         # LaTeX does not know \\smallskip* etc
877         if keep:
878             if spaceamount == 'smallskip':
879                 spaceamount = '\\smallskipamount'
880             elif spaceamount == 'medskip':
881                 spaceamount = '\\medskipamount'
882             elif spaceamount == 'bigskip':
883                 spaceamount = '\\bigskipamount'
884             elif spaceamount == 'vfill':
885                 spaceamount = '\\fill'
886
887         # Finally output the LaTeX code
888         if (spaceamount == 'smallskip' or spaceamount == 'medskip' or
889             spaceamount == 'bigskip'   or spaceamount == 'vfill'):
890             lines.insert(i, spaceamount)
891         else :
892             if keep:
893                 lines.insert(i, 'vspace*{')
894             else:
895                 lines.insert(i, 'vspace{')
896             i = convert_ertbackslash(lines, i, spaceamount)
897             lines[i] =  lines[i] + '}'
898         i = i + 1
899
900
901 # Convert a LyX length into valid ERT code and append it to lines[i]
902 # Return the (maybe incremented) line index i
903 def convert_ertlen(lines, i, len, special):
904     units = {"text%":"\\textwidth", "col%":"\\columnwidth",
905              "page%":"\\pagewidth", "line%":"\\linewidth",
906              "theight%":"\\textheight", "pheight%":"\\pageheight"}
907
908     # Convert special lengths
909     if special != 'none':
910         len = '%f\\' % len2value(len) + special
911
912     # Convert LyX units to LaTeX units
913     for unit in units.keys():
914         if find(len, unit) != -1:
915             len = '%f' % (len2value(len) / 100) + units[unit]
916             break
917
918     # Convert backslashes and insert the converted length into lines
919     return convert_ertbackslash(lines, i, len)
920
921
922 # Return the value of len without the unit in numerical form
923 def len2value(len):
924     result = re.search('([+-]?[0-9.]+)', len)
925     if result:
926         return float(result.group(1))
927     # No number means 1.0
928     return 1.0
929
930
931 def convert_frameless_box(lines, opt):
932     pos = ['t', 'c', 'b']
933     inner_pos = ['c', 't', 'b', 's']
934     i = 0
935     while 1:
936         i = find_token(lines, '\\begin_inset Frameless', i)
937         if i == -1:
938             return
939         j = find_end_of_inset(lines, i)
940         if j == -1:
941             opt.warning("Malformed LyX file: Missing '\\end_inset'\n")
942             i = i + 1
943             continue
944         del lines[i]
945
946         # Gather parameters
947         params = {'position':'0', 'hor_pos':'c', 'has_inner_box':'1',
948                   'inner_pos':'1', 'use_parbox':'0', 'width':'100col%',
949                   'special':'none', 'height':'1in',
950                   'height_special':'totalheight', 'collapsed':'false'}
951         for key in params.keys():
952             value = replace(get_value(lines, key, i, j), '"', '')
953             if value != "":
954                 if key == 'position':
955                     # convert new to old position: 'position "t"' -> 0
956                     value = find_token(pos, value, 0)
957                     if value != -1:
958                         params[key] = value
959                 elif key == 'inner_pos':
960                     # convert inner position
961                     value = find_token(inner_pos, value, 0)
962                     if value != -1:
963                         params[key] = value
964                 else:
965                     params[key] = value
966                 j = del_token(lines, key, i, j)
967         i = i + 1
968
969         # Convert to minipage or ERT?
970         # Note that the inner_position and height parameters of a minipage
971         # inset are ignored and not accessible for the user, although they
972         # are present in the file format and correctly read in and written.
973         # Therefore we convert to ERT if they do not have their LaTeX
974         # defaults. These are:
975         # - the value of "position" for "inner_pos"
976         # - "\totalheight"          for "height"
977         if (params['use_parbox'] != '0' or
978             params['has_inner_box'] != '1' or
979             params['special'] != 'none' or
980             inner_pos[params['inner_pos']] != pos[params['position']] or
981             params['height_special'] != 'totalheight' or
982             len2value(params['height']) != 1.0):
983
984             # Convert to ERT
985             if params['collapsed'] == 'true':
986                 params['collapsed'] = 'Collapsed'
987             else:
988                 params['collapsed'] = 'Open'
989             lines[i : i] = ['\\begin_inset ERT', 'status ' + params['collapsed'],
990                             '', '\\layout Standard', '', '\\backslash ']
991             i = i + 6
992             if params['use_parbox'] == '1':
993                 lines.insert(i, 'parbox')
994             else:
995                 lines.insert(i, 'begin{minipage}')
996             lines[i] = lines[i] + '[' + pos[params['position']] + ']['
997             i = convert_ertlen(lines, i, params['height'], params['height_special'])
998             lines[i] = lines[i] + '][' + inner_pos[params['inner_pos']] + ']{'
999             i = convert_ertlen(lines, i, params['width'], params['special'])
1000             if params['use_parbox'] == '1':
1001                 lines[i] = lines[i] + '}{'
1002             else:
1003                 lines[i] = lines[i] + '}'
1004             i = i + 1
1005             lines[i:i] = ['', '\\end_inset ']
1006             i = i + 2
1007             j = find_end_of_inset(lines, i)
1008             if j == -1:
1009                 opt.warning("Malformed LyX file: Missing '\\end_inset'.")
1010                 break
1011             lines[j-1:j-1] += ['\\begin_inset ERT', 'status ' + params['collapsed'],
1012                                '', '\\layout Standard', '']
1013             j = j + 4
1014             if params['use_parbox'] == '1':
1015                 lines.insert(j, '}')
1016             else:
1017                 lines[j:j] = ['\\backslash ', 'end{minipage}']
1018         else:
1019
1020             # Convert to minipage
1021             lines[i:i] = ['\\begin_inset Minipage',
1022                           'position %d' % params['position'],
1023                           'inner_position %d' % params['inner_pos'],
1024                           'height "' + params['height'] + '"',
1025                           'width "' + params['width'] + '"',
1026                           'collapsed ' + params['collapsed']]
1027             i = i + 6
1028
1029 ##
1030 # Convert jurabib
1031 #
1032
1033 def convert_jurabib(header, opt):
1034     i = find_token(header, '\\use_numerical_citations', 0)
1035     if i == -1:
1036         opt.warning("Malformed lyx file: Missing '\\use_numerical_citations'")
1037         return
1038     header.insert(i + 1, '\\use_jurabib 0')
1039
1040
1041 def revert_jurabib(header, opt):
1042     i = find_token(header, '\\use_jurabib', 0)
1043     if i == -1:
1044         opt.warning("Malformed lyx file: Missing '\\use_jurabib'")
1045         return
1046     if get_value(header, '\\use_jurabib', 0) != "0":
1047         opt.warning("Conversion of '\\use_jurabib = 1' not yet implemented.")
1048         # Don't remove '\\use_jurabib' so that people will get warnings by lyx
1049         return
1050     del header[i]
1051
1052 ##
1053 # Convert bibtopic
1054 #
1055
1056 def convert_bibtopic(header, opt):
1057     i = find_token(header, '\\use_jurabib', 0)
1058     if i == -1:
1059         opt.warning("Malformed lyx file: Missing '\\use_jurabib'")
1060         return
1061     header.insert(i + 1, '\\use_bibtopic 0')
1062
1063
1064 def revert_bibtopic(header, opt):
1065     i = find_token(header, '\\use_bibtopic', 0)
1066     if i == -1:
1067         opt.warning("Malformed lyx file: Missing '\\use_bibtopic'")
1068         return
1069     if get_value(header, '\\use_bibtopic', 0) != "0":
1070         opt.warning("Conversion of '\\use_bibtopic = 1' not yet implemented.")
1071         # Don't remove '\\use_jurabib' so that people will get warnings by lyx
1072     del header[i]
1073
1074 ##
1075 # Sideway Floats
1076 #
1077
1078 def convert_float(lines, opt):
1079     i = 0
1080     while 1:
1081         i = find_token(lines, '\\begin_inset Float', i)
1082         if i == -1:
1083             return
1084         # Seach for a line starting 'wide'
1085         # If, however, we find a line starting '\begin_layout'
1086         # (_always_ present) then break with a warning message
1087         i = i + 1
1088         while 1:
1089             if (lines[i][:4] == "wide"):
1090                 lines.insert(i + 1, 'sideways false')
1091                 break
1092             elif (lines[i][:13] == "\\begin_layout"):
1093                 opt.warning("Malformed lyx file")
1094                 break
1095             i = i + 1
1096         i = i + 1
1097
1098
1099 def revert_float(lines, opt):
1100     i = 0
1101     while 1:
1102         i = find_token(lines, '\\begin_inset Float', i)
1103         if i == -1:
1104             return
1105         j = find_end_of_inset(lines, i)
1106         if j == -1:
1107             opt.warning("Malformed lyx file: Missing '\\end_inset'")
1108             i = i + 1
1109             continue
1110         if get_value(lines, 'sideways', i, j) != "false":
1111             opt.warning("Conversion of 'sideways true' not yet implemented.")
1112             # Don't remove 'sideways' so that people will get warnings by lyx
1113             i = i + 1
1114             continue
1115         del_token(lines, 'sideways', i, j)
1116         i = i + 1
1117
1118 ##
1119 # Convertion hub
1120 #
1121
1122 def convert(header, body, opt):
1123     if opt.format < 223:
1124         add_end_header(header)
1125         convert_spaces(body)
1126         convert_bibtex(body)
1127         remove_insetparent(body)
1128         opt.format = 223
1129     if opt.end == opt.format: return
1130
1131     if opt.format < 224:
1132         convert_external(body)
1133         convert_comment(body)
1134         opt.format = 224
1135     if opt.end == opt.format: return
1136
1137     if opt.format < 225:
1138         add_end_layout(body)
1139         layout2begin_layout(body)
1140         convert_end_document(body)
1141         convert_table_valignment_middle(body)
1142         convert_breaks(body)
1143         opt.format = 225
1144     if opt.end == opt.format: return
1145
1146     if opt.format < 226:
1147         convert_note(body)
1148         opt.format = 226
1149     if opt.end == opt.format: return
1150
1151     if opt.format < 227:
1152         convert_box(body)
1153         opt.format = 227
1154     if opt.end == opt.format: return
1155
1156     if opt.format < 228:
1157         convert_collapsable(body, opt)
1158         convert_ert(body, opt)
1159         opt.format = 228
1160     if opt.end == opt.format: return
1161
1162     if opt.format < 229:
1163         convert_minipage(body)
1164         opt.format = 229
1165     if opt.end == opt.format: return
1166
1167     if opt.format < 230:
1168         convert_jurabib(header, opt)
1169         opt.format = 230
1170     if opt.end == opt.format: return
1171
1172     if opt.format < 231:
1173         convert_float(body, opt)
1174         opt.format = 231
1175     if opt.end == opt.format: return
1176
1177     if opt.format < 232:
1178         convert_bibtopic(header, opt)
1179         opt.format = 232
1180
1181 def revert(header, body, opt):
1182     if opt.format > 231:
1183         revert_bibtopic(header, opt)
1184         opt.format = 231
1185     if opt.end == opt.format: return
1186
1187     if opt.format > 230:
1188         revert_float(body, opt)
1189         opt.format = 230
1190     if opt.end == opt.format: return
1191
1192     if opt.format > 229:
1193         revert_jurabib(header, opt)
1194         opt.format = 229
1195     if opt.end == opt.format: return
1196
1197     if opt.format > 228:
1198         opt.format = 228
1199     if opt.end == opt.format: return
1200
1201     if opt.format > 227:
1202         revert_collapsable(body, opt)
1203         revert_ert(body, opt)
1204         opt.format = 227
1205     if opt.end == opt.format: return
1206
1207     if opt.format > 226:
1208         revert_box(body)
1209         revert_external_2(body)
1210         opt.format = 226
1211     if opt.end == opt.format: return
1212
1213     if opt.format > 225:
1214         revert_note(body)
1215         opt.format = 225
1216     if opt.end == opt.format: return
1217
1218     if opt.format > 224:
1219         rm_end_layout(body)
1220         begin_layout2layout(body)
1221         revert_end_document(body)
1222         revert_valignment_middle(body)
1223         convert_vspace(header, body, opt)
1224         convert_frameless_box(body, opt)
1225     if opt.end == opt.format: return
1226
1227     if opt.format > 223:
1228         revert_external_2(body)
1229         revert_comment(body)
1230         opt.format = 223
1231     if opt.end == opt.format: return
1232
1233     if opt.format > 221:
1234         rm_end_header(header)
1235         revert_spaces(body)
1236         revert_bibtex(body)
1237         rm_tracking_changes(header)
1238         rm_body_changes(body)
1239         opt.format = 221
1240
1241
1242 if __name__ == "__main__":
1243     pass