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