1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2002 Dekel Tsur <dekel@lyx.org>
4 # Copyright (C) 2004 José Matos <jamatos@lyx.org>
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.
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.
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.
20 """ Convert files to the file format generated by lyx 1.2"""
25 from parser_tools import find_token, find_token_backwards, \
26 find_tokens, find_tokens_backwards,
27 find_beginning_of, find_end_of, find_re, \
28 is_nonempty_line, find_nonempty_line, \
29 get_value, check_token
31 ####################################################################
32 # Private helper functions
34 def get_layout(line, default_layout):
35 " Get layout, if empty return the default layout."
36 tokens = string.split(line)
42 def get_paragraph(lines, i, format):
43 " Finds the paragraph that contains line i."
44 begin_layout = "\\layout"
47 i = find_tokens_backwards(lines, ["\\end_inset", begin_layout], i)
49 if check_token(lines[i], begin_layout):
51 i = find_beginning_of_inset(lines, i)
55 def get_next_paragraph(lines, i, format):
56 " Finds the paragraph after the paragraph that contains line i."
57 tokens = ["\\begin_inset", "\\layout", "\\end_float", "\\the_end"]
60 i = find_tokens(lines, tokens, i)
61 if not check_token(lines[i], "\\begin_inset"):
63 i = find_end_of_inset(lines, i)
67 def find_beginning_of_inset(lines, i):
68 " Find beginning of inset, where lines[i] is included."
69 return find_beginning_of(lines, i, "\\begin_inset", "\\end_inset")
72 def find_end_of_inset(lines, i):
73 " Finds the matching \end_inset"
74 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
77 def find_end_of_tabular(lines, i):
78 " Finds the matching end of tabular."
79 return find_end_of(lines, i, "<lyxtabular", "</lyxtabular")
82 def get_tabular_lines(lines, i):
83 " Returns a lists of tabular lines."
86 j = find_end_of_tabular(lines, i)
91 if check_token(lines[i], "\\begin_inset"):
92 i = find_end_of_inset(lines, i)+1
98 # End of helper functions
99 ####################################################################
103 "footnote": ["\\begin_inset Foot",
105 "margin": ["\\begin_inset Marginal",
107 "fig": ["\\begin_inset Float figure",
110 "tab": ["\\begin_inset Float table",
113 "alg": ["\\begin_inset Float algorithm",
116 "wide-fig": ["\\begin_inset Float figure",
119 "wide-tab": ["\\begin_inset Float table",
124 font_tokens = ["\\family", "\\series", "\\shape", "\\size", "\\emph",
125 "\\bar", "\\noun", "\\color", "\\lang", "\\latex"]
127 pextra_type3_rexp = re.compile(r".*\\pextra_type\s+3")
128 pextra_rexp = re.compile(r"\\pextra_type\s+(\S+)"+\
129 r"(\s+\\pextra_alignment\s+(\S+))?"+\
130 r"(\s+\\pextra_hfill\s+(\S+))?"+\
131 r"(\s+\\pextra_start_minipage\s+(\S+))?"+\
132 r"(\s+(\\pextra_widthp?)\s+(\S*))?")
136 " Get width from a regular expression. "
138 if mo.group(9) == "\\pextra_widthp":
139 return mo.group(10)+"col%"
146 def remove_oldfloat(document):
147 " Change \begin_float .. \end_float into \begin_inset Float .. \end_inset"
148 lines = document.body
151 i = find_token(lines, "\\begin_float", i)
154 # There are no nested floats, so finding the end of the float is simple
155 j = find_token(lines, "\\end_float", i+1)
157 floattype = string.split(lines[i])[1]
158 if not floats.has_key(floattype):
159 document.warning("Error! Unknown float type " + floattype)
162 # skip \end_deeper tokens
164 while check_token(lines[i2], "\\end_deeper"):
167 j2 = get_next_paragraph(lines, j + 1, document.format + 1)
168 lines[j2:j2] = ["\\end_deeper "]*(i2-(i+1))
170 new = floats[floattype]+[""]
172 # Check if the float is floatingfigure
173 k = find_re(lines, pextra_type3_rexp, i, j)
175 mo = pextra_rexp.search(lines[k])
176 width = get_width(mo)
177 lines[k] = re.sub(pextra_rexp, "", lines[k])
178 new = ["\\begin_inset Wrap figure",
179 'width "%s"' % width,
183 new = new+lines[i2:j]+["\\end_inset ", ""]
185 # After a float, all font attributes are reseted.
186 # We need to output '\foo default' for every attribute foo
187 # whose value is not default before the float.
188 # The check here is not accurate, but it doesn't matter
189 # as extra '\foo default' commands are ignored.
190 # In fact, it might be safer to output '\foo default' for all
192 k = get_paragraph(lines, i, document.format + 1)
194 for token in font_tokens:
195 if find_token(lines, token, k, i) != -1:
197 # This is not necessary, but we want the output to be
198 # as similar as posible to the lyx format
201 if token == "\\lang":
202 new.append(token+" "+ document.language)
204 new.append(token+" default ")
210 pextra_type2_rexp = re.compile(r".*\\pextra_type\s+[12]")
211 pextra_type2_rexp2 = re.compile(r".*(\\layout|\\pextra_type\s+2)")
212 pextra_widthp = re.compile(r"\\pextra_widthp")
214 def remove_pextra(document):
215 " Remove pextra token."
216 lines = document.body
220 i = find_re(lines, pextra_type2_rexp, i)
224 # Sometimes the \pextra_widthp argument comes in it own
225 # line. If that happens insert it back in this line.
226 if pextra_widthp.search(lines[i+1]):
227 lines[i] = lines[i] + ' ' + lines[i+1]
230 mo = pextra_rexp.search(lines[i])
231 width = get_width(mo)
233 if mo.group(1) == "1":
234 # handle \pextra_type 1 (indented paragraph)
235 lines[i] = re.sub(pextra_rexp, "\\leftindent "+width+" ", lines[i])
239 # handle \pextra_type 2 (minipage)
240 position = mo.group(3)
242 lines[i] = re.sub(pextra_rexp, "", lines[i])
244 start = ["\\begin_inset Minipage",
245 "position " + position,
248 'width "%s"' % width,
254 start = ["","\hfill",""]+start
256 start = ['\\layout %s' % document.default_layout,''] + start
258 j0 = find_token_backwards(lines,"\\layout", i-1)
259 j = get_next_paragraph(lines, i, document.format + 1)
263 # collect more paragraphs to the minipage
265 if j == -1 or not check_token(lines[j], "\\layout"):
267 i = find_re(lines, pextra_type2_rexp2, j+1)
270 mo = pextra_rexp.search(lines[i])
273 if mo.group(7) == "1":
276 lines[i] = re.sub(pextra_rexp, "", lines[i])
277 j = find_tokens(lines, ["\\layout", "\\end_float"], i+1)
280 end = ["\\end_inset "]
282 lines[j0:j] = start+mid+end
287 " Are all the lines empty?"
288 return filter(is_nonempty_line, lines) == []
291 move_rexp = re.compile(r"\\(family|series|shape|size|emph|numeric|bar|noun|end_deeper)")
292 ert_rexp = re.compile(r"\\begin_inset|\\hfill|.*\\SpecialChar")
293 spchar_rexp = re.compile(r"(.*)(\\SpecialChar.*)")
296 def remove_oldert(document):
297 " Remove old ERT inset."
298 ert_begin = ["\\begin_inset ERT",
301 '\\layout %s' % document.default_layout,
303 lines = document.body
306 i = find_tokens(lines, ["\\latex latex", "\\layout LaTeX"], i)
311 # \end_inset is for ert inside a tabular cell. The other tokens
313 j = find_tokens(lines, ["\\latex default", "\\layout", "\\begin_inset", "\\end_inset", "\\end_float", "\\the_end"],
315 if check_token(lines[j], "\\begin_inset"):
316 j = find_end_of_inset(lines, j)+1
320 if check_token(lines[j], "\\layout"):
321 while j-1 >= 0 and check_token(lines[j-1], "\\begin_deeper"):
324 # We need to remove insets, special chars & font commands from ERT text
327 if check_token(lines[i], "\\layout LaTeX"):
328 new = ['\layout %s' % document.default_layout, "", ""]
332 k2 = find_re(lines, ert_rexp, k, j)
333 inset = hfill = specialchar = 0
336 elif check_token(lines[k2], "\\begin_inset"):
338 elif check_token(lines[k2], "\\hfill"):
344 mo = spchar_rexp.match(lines[k2])
345 lines[k2] = mo.group(1)
346 specialchar_str = mo.group(2)
350 for line in lines[k:k2]:
351 # Move some lines outside the ERT inset:
352 if move_rexp.match(line):
354 # This is not necessary, but we want the output to be
355 # as similar as posible to the lyx format
358 elif not check_token(line, "\\latex"):
362 if filter(lambda x:x != "", tmp) != []:
364 # This is not necessary, but we want the output to be
365 # as similar as posible to the lyx format
366 lines[i-1] = lines[i-1]+" "
370 new = new+ert_begin+tmp+["\\end_inset ", ""]
373 k3 = find_end_of_inset(lines, k2)
374 new = new+[""]+lines[k2:k3+1]+[""] # Put an empty line after \end_inset
376 # Skip the empty line after \end_inset
377 if not is_nonempty_line(lines[k]):
381 new = new + ["\\hfill", ""]
385 # This is not necessary, but we want the output to be
386 # as similar as posible to the lyx format
387 lines[i-1] = lines[i-1]+specialchar_str
390 new = new+[specialchar_str, ""]
396 if not check_token(lines[j], "\\latex "):
397 new = new+[""]+[lines[j]]
401 # Delete remaining "\latex xxx" tokens
404 i = find_token(lines, "\\latex ", i)
410 def remove_oldertinset(document):
411 " ERT insert are hidden feature of lyx 1.1.6. This might be removed in the future."
412 lines = document.body
415 i = find_token(lines, "\\begin_inset ERT", i)
418 j = find_end_of_inset(lines, i)
419 k = find_token(lines, "\\layout", i+1)
420 l = get_paragraph(lines, i, document.format + 1)
421 if lines[k] == lines[l]: # same layout
428 def is_ert_paragraph(document, i):
429 " Is this a ert paragraph? "
430 lines = document.body
431 if not check_token(lines[i], "\\layout"):
433 if not document.is_default_layout(get_layout(lines[i], document.default_layout)):
436 i = find_nonempty_line(lines, i+1)
437 if not check_token(lines[i], "\\begin_inset ERT"):
440 j = find_end_of_inset(lines, i)
441 k = find_nonempty_line(lines, j+1)
442 return check_token(lines[k], "\\layout")
445 def combine_ert(document):
446 " Combine ERT paragraphs."
447 lines = document.body
450 i = find_token(lines, "\\begin_inset ERT", i)
453 j = get_paragraph(lines, i, document.format + 1)
456 while is_ert_paragraph(document, j):
459 i2 = find_token(lines, "\\layout", j+1)
460 k = find_token(lines, "\\end_inset", i2+1)
461 text = text+lines[i2:k]
462 j = find_token(lines, "\\layout", k+1)
467 j = find_token(lines, "\\layout", i+1)
473 oldunits = ["pt", "cm", "in", "text%", "col%"]
475 def get_length(lines, name, start, end):
477 i = find_token(lines, name, start, end)
480 x = string.split(lines[i])
481 return x[2]+oldunits[int(x[1])]
484 def write_attribute(x, token, value):
487 x.append("\t"+token+" "+value)
490 def remove_figinset(document):
492 lines = document.body
495 i = find_token(lines, "\\begin_inset Figure", i)
498 j = find_end_of_inset(lines, i)
500 if ( len(string.split(lines[i])) > 2 ):
501 lyxwidth = string.split(lines[i])[3]+"pt"
502 lyxheight = string.split(lines[i])[4]+"pt"
507 filename = get_value(lines, "file", i+1, j)
509 width = get_length(lines, "width", i+1, j)
510 # what does width=5 mean ?
511 height = get_length(lines, "height", i+1, j)
512 rotateAngle = get_value(lines, "angle", i+1, j)
513 if width == "" and height == "":
518 flags = get_value(lines, "flags", i+1, j)
521 display = "monochrome"
528 subcaptionLine = find_token(lines, "subcaption", i+1, j)
529 if subcaptionLine != -1:
530 subcaptionText = lines[subcaptionLine][11:]
531 if subcaptionText != "":
532 subcaptionText = '"'+subcaptionText+'"'
534 k = find_token(lines, "subfigure", i+1,j)
540 new = ["\\begin_inset Graphics FormatVersion 1"]
541 write_attribute(new, "filename", filename)
542 write_attribute(new, "display", display)
544 new.append("\tsubcaption")
545 write_attribute(new, "subcaptionText", subcaptionText)
546 write_attribute(new, "size_type", size_type)
547 write_attribute(new, "width", width)
548 write_attribute(new, "height", height)
549 if rotateAngle != "":
550 new.append("\trotate")
551 write_attribute(new, "rotateAngle", rotateAngle)
552 write_attribute(new, "rotateOrigin", "leftBaseline")
553 write_attribute(new, "lyxsize_type", "1")
554 write_attribute(new, "lyxwidth", lyxwidth)
555 write_attribute(new, "lyxheight", lyxheight)
556 new = new + ["\\end_inset"]
560 attr_re = re.compile(r' \w*="(false|0|)"')
561 line_re = re.compile(r'<(features|column|row|cell)')
563 def update_tabular(document):
564 " Convert tabular format 2 to 3."
565 regexp = re.compile(r'^\\begin_inset\s+Tabular')
566 lines = document.body
569 i = find_re(lines, regexp, i)
573 for k in get_tabular_lines(lines, i):
574 if check_token(lines[k], "<lyxtabular"):
575 lines[k] = string.replace(lines[k], 'version="2"', 'version="3"')
576 elif check_token(lines[k], "<column"):
577 lines[k] = string.replace(lines[k], 'width=""', 'width="0pt"')
579 if line_re.match(lines[k]):
580 lines[k] = re.sub(attr_re, "", lines[k])
586 # Convert tabular format 2 to 3
588 # compatibility read for old longtable options. Now we can make any
589 # row part of the header/footer type we want before it was strict
590 # sequential from the first row down (as LaTeX does it!). So now when
591 # we find a header/footer line we have to go up the rows and set it
592 # on all preceding rows till the first or one with already a h/f option
593 # set. If we find a firstheader on the same line as a header or a
594 # lastfooter on the same line as a footer then this should be set empty.
597 # just for compatibility with old python versions
598 # python >= 2.3 has real booleans (False and True)
603 " Simple data structure to deal with long table info."
605 self.endhead = false # header row
606 self.endfirsthead = false # first header row
607 self.endfoot = false # footer row
608 self.endlastfoot = false # last footer row
611 def haveLTFoot(row_info):
612 " Does row has LTFoot?"
613 for row_ in row_info:
619 def setHeaderFooterRows(hr, fhr, fr, lfr, rows_, row_info):
620 " Set Header/Footer rows."
621 endfirsthead_empty = false
622 endlastfoot_empty = false
626 row_info[hr].endhead = true
628 # set firstheader info
629 if fhr and fhr < rows_:
630 if row_info[fhr].endhead:
633 row_info[fhr].endfirsthead = true
634 row_info[fhr].endhead = false
635 elif row_info[fhr - 1].endhead:
636 endfirsthead_empty = true
638 while fhr > 0 and not row_info[fhr - 1].endhead:
640 row_info[fhr].endfirsthead = true
643 if fr and fr < rows_:
644 if row_info[fr].endhead and row_info[fr - 1].endhead:
645 while fr > 0 and not row_info[fr - 1].endhead:
647 row_info[fr].endfoot = true
648 row_info[fr].endhead = false
649 elif row_info[fr].endfirsthead and row_info[fr - 1].endfirsthead:
650 while fr > 0 and not row_info[fr - 1].endfirsthead:
652 row_info[fr].endfoot = true
653 row_info[fr].endfirsthead = false
654 elif not row_info[fr - 1].endhead and not row_info[fr - 1].endfirsthead:
655 while fr > 0 and not row_info[fr - 1].endhead and not row_info[fr - 1].endfirsthead:
657 row_info[fr].endfoot = true
659 # set lastfooter info
660 if lfr and lfr < rows_:
661 if row_info[lfr].endhead and row_info[lfr - 1].endhead:
662 while lfr > 0 and not row_info[lfr - 1].endhead:
664 row_info[lfr].endlastfoot = true
665 row_info[lfr].endhead = false
666 elif row_info[lfr].endfirsthead and row_info[lfr - 1].endfirsthead:
667 while lfr > 0 and not row_info[lfr - 1].endfirsthead:
669 row_info[lfr].endlastfoot = true
670 row_info[lfr].endfirsthead = false
671 elif row_info[lfr].endfoot and row_info[lfr - 1].endfoot:
672 while lfr > 0 and not row_info[lfr - 1].endfoot:
674 row_info[lfr].endlastfoot = true
675 row_info[lfr].endfoot = false
676 elif not row_info[fr - 1].endhead and not row_info[fr - 1].endfirsthead and not row_info[fr - 1].endfoot:
677 while lfr > 0 and not row_info[lfr - 1].endhead and not row_info[lfr - 1].endfirsthead and not row_info[lfr - 1].endfoot:
679 row_info[lfr].endlastfoot = true
680 elif haveLTFoot(row_info):
681 endlastfoot_empty = true
683 return endfirsthead_empty, endlastfoot_empty
686 def insert_attribute(lines, i, attribute):
687 " Insert attribute in lines[i]."
688 last = string.find(lines[i],'>')
689 lines[i] = lines[i][:last] + ' ' + attribute + lines[i][last:]
692 rows_re = re.compile(r'rows="(\d*)"')
693 longtable_re = re.compile(r'islongtable="(\w)"')
694 ltvalues_re = re.compile(r'endhead="(-?\d*)" endfirsthead="(-?\d*)" endfoot="(-?\d*)" endlastfoot="(-?\d*)"')
695 lt_features_re = re.compile(r'(endhead="-?\d*" endfirsthead="-?\d*" endfoot="-?\d*" endlastfoot="-?\d*")')
696 def update_longtables(document):
697 " Update longtables to new format."
698 regexp = re.compile(r'^\\begin_inset\s+Tabular')
702 i = find_re(body, regexp, i)
706 i = find_token(body, "<lyxtabular", i)
710 # get number of rows in the table
711 rows = int(rows_re.search(body[i]).group(1))
714 i = find_token(body, '<features', i)
718 # is this a longtable?
719 longtable = longtable_re.search(body[i])
722 # islongtable is missing add it
723 body[i] = body[i][:10] + 'islongtable="false" ' + body[i][10:]
725 if not longtable or longtable.group(1) != "true":
726 # remove longtable elements from features
727 features = lt_features_re.search(body[i])
729 body[i] = string.replace(body[i], features.group(1), "")
732 row_info = row() * rows
733 res = ltvalues_re.search(body[i])
737 endfirsthead_empty, endlastfoot_empty = setHeaderFooterRows(res.group(1), res.group(2), res.group(3), res.group(4), rows, row_info)
739 if endfirsthead_empty:
740 insert_attribute(body, i, 'firstHeadEmpty="true"')
742 if endfirsthead_empty:
743 insert_attribute(body, i, 'lastFootEmpty="true"')
746 for j in range(rows):
747 i = find_token(body, '<row', i)
749 self.endfoot = false # footer row
750 self.endlastfoot = false # last footer row
751 if row_info[j].endhead:
752 insert_attribute(body, i, 'endhead="true"')
754 if row_info[j].endfirsthead:
755 insert_attribute(body, i, 'endfirsthead="true"')
757 if row_info[j].endfoot:
758 insert_attribute(body, i, 'endfoot="true"')
760 if row_info[j].endlastfoot:
761 insert_attribute(body, i, 'endlastfoot="true"')
766 def fix_oldfloatinset(document):
767 " Figure insert are hidden feature of lyx 1.1.6. This might be removed in the future."
768 lines = document.body
771 i = find_token(lines, "\\begin_inset Float ", i)
774 j = find_token(lines, "collapsed", i)
776 lines[j:j] = ["wide false"]
780 def change_listof(document):
781 " Change listof insets."
782 lines = document.body
785 i = find_token(lines, "\\begin_inset LatexCommand \\listof", i)
788 type = re.search(r"listof(\w*)", lines[i]).group(1)[:-1]
789 lines[i] = "\\begin_inset FloatList "+type
793 def change_infoinset(document):
794 " Change info inset."
795 lines = document.body
798 i = find_token(lines, "\\begin_inset Info", i)
801 txt = string.lstrip(lines[i][18:])
802 new = ["\\begin_inset Note", "collapsed true", ""]
803 j = find_token(lines, "\\end_inset", i)
807 note_lines = lines[i+1:j]
809 note_lines = [txt]+note_lines
811 for line in note_lines:
812 new = new + ['\layout %s' % document.default_layout, ""]
813 tmp = string.split(line, '\\')
816 new = new + ["\\backslash ", x]
821 def change_header(document):
823 lines = document.header
824 i = find_token(lines, "\\use_amsmath", 0)
827 lines[i+1:i+1] = ["\\use_natbib 0",
828 "\use_numerical_citations 0"]
831 supported_versions = ["1.2.%d" % i for i in range(5)] + ["1.2"]
832 convert = [[220, [change_header, change_listof, fix_oldfloatinset,
833 update_tabular, update_longtables, remove_pextra,
834 remove_oldfloat, remove_figinset, remove_oldertinset,
835 remove_oldert, combine_ert, change_infoinset]]]
839 if __name__ == "__main__":