1 # This file is part of lyx2lyx
2 # -*- coding: iso-8859-1 -*-
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.
23 from parser_tools import find_token, find_token_backwards, \
24 find_tokens, find_tokens_backwards, find_beginning_of, find_end_of, find_re, \
25 is_nonempty_line, find_nonempty_line, \
26 get_value, check_token
28 ####################################################################
29 # Private helper functions
31 def get_layout(line, default_layout):
32 tokens = string.split(line)
38 # Finds the paragraph that contains line i.
39 def get_paragraph(lines, i, format):
40 begin_layout = "\\layout"
43 i = find_tokens_backwards(lines, ["\\end_inset", begin_layout], i)
45 if check_token(lines[i], begin_layout):
47 i = find_beginning_of_inset(lines, i)
51 # Finds the paragraph after the paragraph that contains line i.
52 def get_next_paragraph(lines, i, format):
53 tokens = ["\\begin_inset", "\\layout", "\\end_float", "\\the_end"]
56 i = find_tokens(lines, tokens, i)
57 if not check_token(lines[i], "\\begin_inset"):
59 i = find_end_of_inset(lines, i)
63 def find_beginning_of_inset(lines, i):
64 return find_beginning_of(lines, i, "\\begin_inset", "\\end_inset")
67 # Finds the matching \end_inset
68 def find_end_of_inset(lines, i):
69 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
72 def find_end_of_tabular(lines, i):
73 return find_end_of(lines, i, "<lyxtabular", "</lyxtabular")
76 def get_tabular_lines(lines, i):
79 j = find_end_of_tabular(lines, i)
84 if check_token(lines[i], "\\begin_inset"):
85 i = find_end_of_inset(lines, i)+1
91 # End of helper functions
92 ####################################################################
96 "footnote": ["\\begin_inset Foot",
98 "margin": ["\\begin_inset Marginal",
100 "fig": ["\\begin_inset Float figure",
103 "tab": ["\\begin_inset Float table",
106 "alg": ["\\begin_inset Float algorithm",
109 "wide-fig": ["\\begin_inset Float figure",
112 "wide-tab": ["\\begin_inset Float table",
117 font_tokens = ["\\family", "\\series", "\\shape", "\\size", "\\emph",
118 "\\bar", "\\noun", "\\color", "\\lang", "\\latex"]
120 pextra_type3_rexp = re.compile(r".*\\pextra_type\s+3")
121 pextra_rexp = re.compile(r"\\pextra_type\s+(\S+)"+\
122 r"(\s+\\pextra_alignment\s+(\S+))?"+\
123 r"(\s+\\pextra_hfill\s+(\S+))?"+\
124 r"(\s+\\pextra_start_minipage\s+(\S+))?"+\
125 r"(\s+(\\pextra_widthp?)\s+(\S*))?")
130 if mo.group(9) == "\\pextra_widthp":
131 return mo.group(10)+"col%"
139 # Change \begin_float .. \end_float into \begin_inset Float .. \end_inset
141 def remove_oldfloat(file):
145 i = find_token(lines, "\\begin_float", i)
148 # There are no nested floats, so finding the end of the float is simple
149 j = find_token(lines, "\\end_float", i+1)
151 floattype = string.split(lines[i])[1]
152 if not floats.has_key(floattype):
153 file.warning("Error! Unknown float type " + floattype)
156 # skip \end_deeper tokens
158 while check_token(lines[i2], "\\end_deeper"):
161 j2 = get_next_paragraph(lines, j + 1, file.format + 1)
162 lines[j2:j2] = ["\\end_deeper "]*(i2-(i+1))
164 new = floats[floattype]+[""]
166 # Check if the float is floatingfigure
167 k = find_re(lines, pextra_type3_rexp, i, j)
169 mo = pextra_rexp.search(lines[k])
170 width = get_width(mo)
171 lines[k] = re.sub(pextra_rexp, "", lines[k])
172 new = ["\\begin_inset Wrap figure",
173 'width "%s"' % width,
177 new = new+lines[i2:j]+["\\end_inset ", ""]
179 # After a float, all font attributes are reseted.
180 # We need to output '\foo default' for every attribute foo
181 # whose value is not default before the float.
182 # The check here is not accurate, but it doesn't matter
183 # as extra '\foo default' commands are ignored.
184 # In fact, it might be safer to output '\foo default' for all
186 k = get_paragraph(lines, i, file.format + 1)
188 for token in font_tokens:
189 if find_token(lines, token, k, i) != -1:
191 # This is not necessary, but we want the output to be
192 # as similar as posible to the lyx format
195 if token == "\\lang":
196 new.append(token+" "+ file.language)
198 new.append(token+" default ")
204 pextra_type2_rexp = re.compile(r".*\\pextra_type\s+[12]")
205 pextra_type2_rexp2 = re.compile(r".*(\\layout|\\pextra_type\s+2)")
206 pextra_widthp = re.compile(r"\\pextra_widthp")
208 def remove_pextra(file):
213 i = find_re(lines, pextra_type2_rexp, i)
217 # Sometimes the \pextra_widthp argument comes in it own
218 # line. If that happens insert it back in this line.
219 if pextra_widthp.search(lines[i+1]):
220 lines[i] = lines[i] + ' ' + lines[i+1]
223 mo = pextra_rexp.search(lines[i])
224 width = get_width(mo)
226 if mo.group(1) == "1":
227 # handle \pextra_type 1 (indented paragraph)
228 lines[i] = re.sub(pextra_rexp, "\\leftindent "+width+" ", lines[i])
232 # handle \pextra_type 2 (minipage)
233 position = mo.group(3)
235 lines[i] = re.sub(pextra_rexp, "", lines[i])
237 start = ["\\begin_inset Minipage",
238 "position " + position,
241 'width "%s"' % width,
247 start = ["","\hfill",""]+start
249 start = ['\\layout %s' % file.default_layout,''] + start
251 j0 = find_token_backwards(lines,"\\layout", i-1)
252 j = get_next_paragraph(lines, i, file.format + 1)
256 # collect more paragraphs to the minipage
258 if j == -1 or not check_token(lines[j], "\\layout"):
260 i = find_re(lines, pextra_type2_rexp2, j+1)
263 mo = pextra_rexp.search(lines[i])
266 if mo.group(7) == "1":
269 lines[i] = re.sub(pextra_rexp, "", lines[i])
270 j = find_tokens(lines, ["\\layout", "\\end_float"], i+1)
273 end = ["\\end_inset "]
275 lines[j0:j] = start+mid+end
280 return filter(is_nonempty_line, lines) == []
283 move_rexp = re.compile(r"\\(family|series|shape|size|emph|numeric|bar|noun|end_deeper)")
284 ert_rexp = re.compile(r"\\begin_inset|\\hfill|.*\\SpecialChar")
285 spchar_rexp = re.compile(r"(.*)(\\SpecialChar.*)")
288 def remove_oldert(file):
289 ert_begin = ["\\begin_inset ERT",
292 '\\layout %s' % file.default_layout,
297 i = find_tokens(lines, ["\\latex latex", "\\layout LaTeX"], i)
302 # \end_inset is for ert inside a tabular cell. The other tokens
304 j = find_tokens(lines, ["\\latex default", "\\layout", "\\begin_inset", "\\end_inset", "\\end_float", "\\the_end"],
306 if check_token(lines[j], "\\begin_inset"):
307 j = find_end_of_inset(lines, j)+1
311 if check_token(lines[j], "\\layout"):
312 while j-1 >= 0 and check_token(lines[j-1], "\\begin_deeper"):
315 # We need to remove insets, special chars & font commands from ERT text
318 if check_token(lines[i], "\\layout LaTeX"):
319 new = ['\layout %s' % file.default_layout, "", ""]
323 k2 = find_re(lines, ert_rexp, k, j)
324 inset = hfill = specialchar = 0
327 elif check_token(lines[k2], "\\begin_inset"):
329 elif check_token(lines[k2], "\\hfill"):
335 mo = spchar_rexp.match(lines[k2])
336 lines[k2] = mo.group(1)
337 specialchar_str = mo.group(2)
341 for line in lines[k:k2]:
342 # Move some lines outside the ERT inset:
343 if move_rexp.match(line):
345 # This is not necessary, but we want the output to be
346 # as similar as posible to the lyx format
349 elif not check_token(line, "\\latex"):
353 if filter(lambda x:x != "", tmp) != []:
355 # This is not necessary, but we want the output to be
356 # as similar as posible to the lyx format
357 lines[i-1] = lines[i-1]+" "
361 new = new+ert_begin+tmp+["\\end_inset ", ""]
364 k3 = find_end_of_inset(lines, k2)
365 new = new+[""]+lines[k2:k3+1]+[""] # Put an empty line after \end_inset
367 # Skip the empty line after \end_inset
368 if not is_nonempty_line(lines[k]):
372 new = new + ["\\hfill", ""]
376 # This is not necessary, but we want the output to be
377 # as similar as posible to the lyx format
378 lines[i-1] = lines[i-1]+specialchar_str
381 new = new+[specialchar_str, ""]
387 if not check_token(lines[j], "\\latex "):
388 new = new+[""]+[lines[j]]
392 # Delete remaining "\latex xxx" tokens
395 i = find_token(lines, "\\latex ", i)
401 # ERT insert are hidden feature of lyx 1.1.6. This might be removed in the future.
402 def remove_oldertinset(file):
406 i = find_token(lines, "\\begin_inset ERT", i)
409 j = find_end_of_inset(lines, i)
410 k = find_token(lines, "\\layout", i+1)
411 l = get_paragraph(lines, i, file.format + 1)
412 if lines[k] == lines[l]: # same layout
419 def is_ert_paragraph(file, i):
421 if not check_token(lines[i], "\\layout"):
423 if not file.is_default_layout(get_layout(lines[i], file.default_layout)):
426 i = find_nonempty_line(lines, i+1)
427 if not check_token(lines[i], "\\begin_inset ERT"):
430 j = find_end_of_inset(lines, i)
431 k = find_nonempty_line(lines, j+1)
432 return check_token(lines[k], "\\layout")
435 def combine_ert(file):
439 i = find_token(lines, "\\begin_inset ERT", i)
442 j = get_paragraph(lines, i, file.format + 1)
445 while is_ert_paragraph(file, j):
448 i2 = find_token(lines, "\\layout", j+1)
449 k = find_token(lines, "\\end_inset", i2+1)
450 text = text+lines[i2:k]
451 j = find_token(lines, "\\layout", k+1)
456 j = find_token(lines, "\\layout", i+1)
462 oldunits = ["pt", "cm", "in", "text%", "col%"]
464 def get_length(lines, name, start, end):
465 i = find_token(lines, name, start, end)
468 x = string.split(lines[i])
469 return x[2]+oldunits[int(x[1])]
472 def write_attribute(x, token, value):
474 x.append("\t"+token+" "+value)
477 def remove_figinset(file):
481 i = find_token(lines, "\\begin_inset Figure", i)
484 j = find_end_of_inset(lines, i)
486 if ( len(string.split(lines[i])) > 2 ):
487 lyxwidth = string.split(lines[i])[3]+"pt"
488 lyxheight = string.split(lines[i])[4]+"pt"
493 filename = get_value(lines, "file", i+1, j)
495 width = get_length(lines, "width", i+1, j)
496 # what does width=5 mean ?
497 height = get_length(lines, "height", i+1, j)
498 rotateAngle = get_value(lines, "angle", i+1, j)
499 if width == "" and height == "":
504 flags = get_value(lines, "flags", i+1, j)
507 display = "monochrome"
514 subcaptionLine = find_token(lines, "subcaption", i+1, j)
515 if subcaptionLine != -1:
516 subcaptionText = lines[subcaptionLine][11:]
517 if subcaptionText != "":
518 subcaptionText = '"'+subcaptionText+'"'
520 k = find_token(lines, "subfigure", i+1,j)
526 new = ["\\begin_inset Graphics FormatVersion 1"]
527 write_attribute(new, "filename", filename)
528 write_attribute(new, "display", display)
530 new.append("\tsubcaption")
531 write_attribute(new, "subcaptionText", subcaptionText)
532 write_attribute(new, "size_type", size_type)
533 write_attribute(new, "width", width)
534 write_attribute(new, "height", height)
535 if rotateAngle != "":
536 new.append("\trotate")
537 write_attribute(new, "rotateAngle", rotateAngle)
538 write_attribute(new, "rotateOrigin", "leftBaseline")
539 write_attribute(new, "lyxsize_type", "1")
540 write_attribute(new, "lyxwidth", lyxwidth)
541 write_attribute(new, "lyxheight", lyxheight)
542 new = new + ["\\end_inset"]
547 # Convert tabular format 2 to 3
549 attr_re = re.compile(r' \w*="(false|0|)"')
550 line_re = re.compile(r'<(features|column|row|cell)')
552 def update_tabular(file):
553 regexp = re.compile(r'^\\begin_inset\s+Tabular')
557 i = find_re(lines, regexp, i)
561 for k in get_tabular_lines(lines, i):
562 if check_token(lines[k], "<lyxtabular"):
563 lines[k] = string.replace(lines[k], 'version="2"', 'version="3"')
564 elif check_token(lines[k], "<column"):
565 lines[k] = string.replace(lines[k], 'width=""', 'width="0pt"')
567 if line_re.match(lines[k]):
568 lines[k] = re.sub(attr_re, "", lines[k])
574 # Convert tabular format 2 to 3
576 # compatibility read for old longtable options. Now we can make any
577 # row part of the header/footer type we want before it was strict
578 # sequential from the first row down (as LaTeX does it!). So now when
579 # we find a header/footer line we have to go up the rows and set it
580 # on all preceding rows till the first or one with already a h/f option
581 # set. If we find a firstheader on the same line as a header or a
582 # lastfooter on the same line as a footer then this should be set empty.
585 # just for compatibility with old python versions
586 # python >= 2.3 has real booleans (False and True)
590 # simple data structure to deal with long table info
593 self.endhead = false # header row
594 self.endfirsthead = false # first header row
595 self.endfoot = false # footer row
596 self.endlastfoot = false # last footer row
599 def haveLTFoot(row_info):
600 for row_ in row_info:
606 def setHeaderFooterRows(hr, fhr, fr, lfr, rows_, row_info):
607 endfirsthead_empty = false
608 endlastfoot_empty = false
612 row_info[hr].endhead = true
614 # set firstheader info
615 if fhr and fhr < rows_:
616 if row_info[fhr].endhead:
619 row_info[fhr].endfirsthead = true
620 row_info[fhr].endhead = false
621 elif row_info[fhr - 1].endhead:
622 endfirsthead_empty = true
624 while fhr > 0 and not row_info[fhr - 1].endhead:
626 row_info[fhr].endfirsthead = true
629 if fr and fr < rows_:
630 if row_info[fr].endhead and row_info[fr - 1].endhead:
631 while fr > 0 and not row_info[fr - 1].endhead:
633 row_info[fr].endfoot = true
634 row_info[fr].endhead = false
635 elif row_info[fr].endfirsthead and row_info[fr - 1].endfirsthead:
636 while fr > 0 and not row_info[fr - 1].endfirsthead:
638 row_info[fr].endfoot = true
639 row_info[fr].endfirsthead = false
640 elif not row_info[fr - 1].endhead and not row_info[fr - 1].endfirsthead:
641 while fr > 0 and not row_info[fr - 1].endhead and not row_info[fr - 1].endfirsthead:
643 row_info[fr].endfoot = true
645 # set lastfooter info
646 if lfr and lfr < rows_:
647 if row_info[lfr].endhead and row_info[lfr - 1].endhead:
648 while lfr > 0 and not row_info[lfr - 1].endhead:
650 row_info[lfr].endlastfoot = true
651 row_info[lfr].endhead = false
652 elif row_info[lfr].endfirsthead and row_info[lfr - 1].endfirsthead:
653 while lfr > 0 and not row_info[lfr - 1].endfirsthead:
655 row_info[lfr].endlastfoot = true
656 row_info[lfr].endfirsthead = false
657 elif row_info[lfr].endfoot and row_info[lfr - 1].endfoot:
658 while lfr > 0 and not row_info[lfr - 1].endfoot:
660 row_info[lfr].endlastfoot = true
661 row_info[lfr].endfoot = false
662 elif not row_info[fr - 1].endhead and not row_info[fr - 1].endfirsthead and not row_info[fr - 1].endfoot:
663 while lfr > 0 and not row_info[lfr - 1].endhead and not row_info[lfr - 1].endfirsthead and not row_info[lfr - 1].endfoot:
665 row_info[lfr].endlastfoot = true
666 elif haveLTFoot(row_info):
667 endlastfoot_empty = true
669 return endfirsthead_empty, endlastfoot_empty
672 def insert_attribute(lines, i, attribute):
673 last = string.find(lines[i],'>')
674 lines[i] = lines[i][:last] + ' ' + attribute + lines[i][last:]
677 rows_re = re.compile(r'rows="(\d*)"')
678 longtable_re = re.compile(r'islongtable="(\w)"')
679 ltvalues_re = re.compile(r'endhead="(-?\d*)" endfirsthead="(-?\d*)" endfoot="(-?\d*)" endlastfoot="(-?\d*)"')
680 lt_features_re = re.compile(r'(endhead="-?\d*" endfirsthead="-?\d*" endfoot="-?\d*" endlastfoot="-?\d*")')
681 def update_longtables(file):
682 regexp = re.compile(r'^\\begin_inset\s+Tabular')
686 i = find_re(body, regexp, i)
690 i = find_token(body, "<lyxtabular", i)
694 # get number of rows in the table
695 rows = int(rows_re.search(body[i]).group(1))
698 i = find_token(body, '<features', i)
702 # is this a longtable?
703 longtable = longtable_re.search(body[i])
706 # islongtable is missing add it
707 body[i] = body[i][:10] + 'islongtable="false" ' + body[i][10:]
709 if not longtable or longtable.group(1) != "true":
710 # remove longtable elements from features
711 features = lt_features_re.search(body[i])
713 body[i] = string.replace(body[i], features.group(1), "")
716 row_info = row() * rows
717 res = ltvalues_re.search(body[i])
721 endfirsthead_empty, endlastfoot_empty = setHeaderFooterRows(res.group(1), res.group(2), res.group(3), res.group(4), rows, row_info)
723 if endfirsthead_empty:
724 insert_attribute(body, i, 'firstHeadEmpty="true"')
726 if endfirsthead_empty:
727 insert_attribute(body, i, 'lastFootEmpty="true"')
730 for j in range(rows):
731 i = find_token(body, '<row', i)
733 self.endfoot = false # footer row
734 self.endlastfoot = false # last footer row
735 if row_info[j].endhead:
736 insert_attribute(body, i, 'endhead="true"')
738 if row_info[j].endfirsthead:
739 insert_attribute(body, i, 'endfirsthead="true"')
741 if row_info[j].endfoot:
742 insert_attribute(body, i, 'endfoot="true"')
744 if row_info[j].endlastfoot:
745 insert_attribute(body, i, 'endlastfoot="true"')
750 # Figure insert are hidden feature of lyx 1.1.6. This might be removed in the future.
751 def fix_oldfloatinset(file):
755 i = find_token(lines, "\\begin_inset Float ", i)
758 j = find_token(lines, "collapsed", i)
760 lines[j:j] = ["wide false"]
764 def change_listof(file):
768 i = find_token(lines, "\\begin_inset LatexCommand \\listof", i)
771 type = re.search(r"listof(\w*)", lines[i]).group(1)[:-1]
772 lines[i] = "\\begin_inset FloatList "+type
776 def change_infoinset(file):
780 i = find_token(lines, "\\begin_inset Info", i)
783 txt = string.lstrip(lines[i][18:])
784 new = ["\\begin_inset Note", "collapsed true", ""]
785 j = find_token(lines, "\\end_inset", i)
789 note_lines = lines[i+1:j]
791 note_lines = [txt]+note_lines
793 for line in note_lines:
794 new = new + ['\layout %s' % file.default_layout, ""]
795 tmp = string.split(line, '\\')
798 new = new + ["\\backslash ", x]
803 def change_header(file):
805 i = find_token(lines, "\\use_amsmath", 0)
808 lines[i+1:i+1] = ["\\use_natbib 0",
809 "\use_numerical_citations 0"]
812 convert = [[220, [change_header, change_listof, fix_oldfloatinset,
813 update_tabular, update_longtables, remove_pextra,
814 remove_oldfloat, remove_figinset, remove_oldertinset,
815 remove_oldert, combine_ert, change_infoinset]]]
819 if __name__ == "__main__":