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, get_next_paragraph,\
24 find_tokens, find_end_of_inset, find_re, \
25 is_nonempty_line, get_paragraph, find_nonempty_line, \
26 get_value, get_tabular_lines, check_token
29 "footnote": ["\\begin_inset Foot",
31 "margin": ["\\begin_inset Marginal",
33 "fig": ["\\begin_inset Float figure",
36 "tab": ["\\begin_inset Float table",
39 "alg": ["\\begin_inset Float algorithm",
42 "wide-fig": ["\\begin_inset Float figure",
45 "wide-tab": ["\\begin_inset Float table",
50 font_tokens = ["\\family", "\\series", "\\shape", "\\size", "\\emph",
51 "\\bar", "\\noun", "\\color", "\\lang", "\\latex"]
53 pextra_type3_rexp = re.compile(r".*\\pextra_type\s+3")
54 pextra_rexp = re.compile(r"\\pextra_type\s+(\S+)"+\
55 r"(\s+\\pextra_alignment\s+(\S+))?"+\
56 r"(\s+\\pextra_hfill\s+(\S+))?"+\
57 r"(\s+\\pextra_start_minipage\s+(\S+))?"+\
58 r"(\s+(\\pextra_widthp?)\s+(\S*))?")
63 if mo.group(9) == "\\pextra_widthp":
64 return mo.group(10)+"col%"
72 # Change \begin_float .. \end_float into \begin_inset Float .. \end_inset
74 def remove_oldfloat(file):
78 i = find_token(lines, "\\begin_float", i)
81 # There are no nested floats, so finding the end of the float is simple
82 j = find_token(lines, "\\end_float", i+1)
84 floattype = string.split(lines[i])[1]
85 if not floats.has_key(floattype):
86 file.warning("Error! Unknown float type " + floattype)
89 # skip \end_deeper tokens
91 while check_token(lines[i2], "\\end_deeper"):
94 j2 = get_next_paragraph(lines, j+1)
95 lines[j2:j2] = ["\\end_deeper "]*(i2-(i+1))
97 new = floats[floattype]+[""]
99 # Check if the float is floatingfigure
100 k = find_re(lines, pextra_type3_rexp, i, j)
102 mo = pextra_rexp.search(lines[k])
103 width = get_width(mo)
104 lines[k] = re.sub(pextra_rexp, "", lines[k])
105 new = ["\\begin_inset Wrap figure",
106 'width "%s"' % width,
110 new = new+lines[i2:j]+["\\end_inset ", ""]
112 # After a float, all font attributes are reseted.
113 # We need to output '\foo default' for every attribute foo
114 # whose value is not default before the float.
115 # The check here is not accurate, but it doesn't matter
116 # as extra '\foo default' commands are ignored.
117 # In fact, it might be safer to output '\foo default' for all
119 k = get_paragraph(lines, i)
121 for token in font_tokens:
122 if find_token(lines, token, k, i) != -1:
124 # This is not necessary, but we want the output to be
125 # as similar as posible to the lyx format
128 if token == "\\lang":
129 new.append(token+" "+ file.language)
131 new.append(token+" default ")
137 pextra_type2_rexp = re.compile(r".*\\pextra_type\s+[12]")
138 pextra_type2_rexp2 = re.compile(r".*(\\layout|\\pextra_type\s+2)")
139 pextra_widthp = re.compile(r"\\pextra_widthp")
141 def remove_pextra(file):
146 i = find_re(lines, pextra_type2_rexp, i)
150 # Sometimes the \pextra_widthp argument comes in it own
151 # line. If that happens insert it back in this line.
152 if pextra_widthp.search(lines[i+1]):
153 lines[i] = lines[i] + ' ' + lines[i+1]
156 mo = pextra_rexp.search(lines[i])
157 width = get_width(mo)
159 if mo.group(1) == "1":
160 # handle \pextra_type 1 (indented paragraph)
161 lines[i] = re.sub(pextra_rexp, "\\leftindent "+width+" ", lines[i])
165 # handle \pextra_type 2 (minipage)
166 position = mo.group(3)
168 lines[i] = re.sub(pextra_rexp, "", lines[i])
170 start = ["\\begin_inset Minipage",
171 "position " + position,
174 'width "%s"' % width,
180 start = ["","\hfill",""]+start
182 start = ["\\layout Standard"] + start
184 j0 = find_token_backwards(lines,"\\layout", i-1)
185 j = get_next_paragraph(lines, i)
189 # collect more paragraphs to the minipage
191 if j == -1 or not check_token(lines[j], "\\layout"):
193 i = find_re(lines, pextra_type2_rexp2, j+1)
196 mo = pextra_rexp.search(lines[i])
199 if mo.group(7) == "1":
202 lines[i] = re.sub(pextra_rexp, "", lines[i])
203 j = find_tokens(lines, ["\\layout", "\\end_float"], i+1)
206 end = ["\\end_inset "]
208 lines[j0:j] = start+mid+end
213 return filter(is_nonempty_line, lines) == []
216 move_rexp = re.compile(r"\\(family|series|shape|size|emph|numeric|bar|noun|end_deeper)")
217 ert_rexp = re.compile(r"\\begin_inset|\\hfill|.*\\SpecialChar")
218 spchar_rexp = re.compile(r"(.*)(\\SpecialChar.*)")
219 ert_begin = ["\\begin_inset ERT",
225 def remove_oldert(file):
229 i = find_tokens(lines, ["\\latex latex", "\\layout LaTeX"], i)
234 # \end_inset is for ert inside a tabular cell. The other tokens
236 j = find_tokens(lines, ["\\latex default", "\\layout", "\\begin_inset", "\\end_inset", "\\end_float", "\\the_end"],
238 if check_token(lines[j], "\\begin_inset"):
239 j = find_end_of_inset(lines, j)+1
243 if check_token(lines[j], "\\layout"):
244 while j-1 >= 0 and check_token(lines[j-1], "\\begin_deeper"):
247 # We need to remove insets, special chars & font commands from ERT text
250 if check_token(lines[i], "\\layout LaTeX"):
251 new = ["\layout Standard", "", ""]
252 # We have a problem with classes in which Standard is not the default layout!
256 k2 = find_re(lines, ert_rexp, k, j)
257 inset = hfill = specialchar = 0
260 elif check_token(lines[k2], "\\begin_inset"):
262 elif check_token(lines[k2], "\\hfill"):
268 mo = spchar_rexp.match(lines[k2])
269 lines[k2] = mo.group(1)
270 specialchar_str = mo.group(2)
274 for line in lines[k:k2]:
275 # Move some lines outside the ERT inset:
276 if move_rexp.match(line):
278 # This is not necessary, but we want the output to be
279 # as similar as posible to the lyx format
282 elif not check_token(line, "\\latex"):
286 if filter(lambda x:x != "", tmp) != []:
288 # This is not necessary, but we want the output to be
289 # as similar as posible to the lyx format
290 lines[i-1] = lines[i-1]+" "
294 new = new+ert_begin+tmp+["\\end_inset ", ""]
297 k3 = find_end_of_inset(lines, k2)
298 new = new+[""]+lines[k2:k3+1]+[""] # Put an empty line after \end_inset
300 # Skip the empty line after \end_inset
301 if not is_nonempty_line(lines[k]):
305 new = new + ["\\hfill", ""]
309 # This is not necessary, but we want the output to be
310 # as similar as posible to the lyx format
311 lines[i-1] = lines[i-1]+specialchar_str
314 new = new+[specialchar_str, ""]
320 if not check_token(lines[j], "\\latex "):
321 new = new+[""]+[lines[j]]
325 # Delete remaining "\latex xxx" tokens
328 i = find_token(lines, "\\latex ", i)
334 # ERT insert are hidden feature of lyx 1.1.6. This might be removed in the future.
335 def remove_oldertinset(file):
339 i = find_token(lines, "\\begin_inset ERT", i)
342 j = find_end_of_inset(lines, i)
343 k = find_token(lines, "\\layout", i+1)
344 l = get_paragraph(lines, i)
345 if lines[k] == lines[l]: # same layout
352 def is_ert_paragraph(lines, i):
353 if not check_token(lines[i], "\\layout Standard"):
356 i = find_nonempty_line(lines, i+1)
357 if not check_token(lines[i], "\\begin_inset ERT"):
360 j = find_end_of_inset(lines, i)
361 k = find_nonempty_line(lines, j+1)
362 return check_token(lines[k], "\\layout")
365 def combine_ert(file):
369 i = find_token(lines, "\\begin_inset ERT", i)
372 j = get_paragraph(lines, i)
375 while is_ert_paragraph(lines, j):
378 i2 = find_token(lines, "\\layout", j+1)
379 k = find_token(lines, "\\end_inset", i2+1)
380 text = text+lines[i2:k]
381 j = find_token(lines, "\\layout", k+1)
386 j = find_token(lines, "\\layout", i+1)
392 oldunits = ["pt", "cm", "in", "text%", "col%"]
394 def get_length(lines, name, start, end):
395 i = find_token(lines, name, start, end)
398 x = string.split(lines[i])
399 return x[2]+oldunits[int(x[1])]
402 def write_attribute(x, token, value):
404 x.append("\t"+token+" "+value)
407 def remove_figinset(file):
411 i = find_token(lines, "\\begin_inset Figure", i)
414 j = find_end_of_inset(lines, i)
416 if ( len(string.split(lines[i])) > 2 ):
417 lyxwidth = string.split(lines[i])[3]+"pt"
418 lyxheight = string.split(lines[i])[4]+"pt"
423 filename = get_value(lines, "file", i+1, j)
425 width = get_length(lines, "width", i+1, j)
426 # what does width=5 mean ?
427 height = get_length(lines, "height", i+1, j)
428 rotateAngle = get_value(lines, "angle", i+1, j)
429 if width == "" and height == "":
434 flags = get_value(lines, "flags", i+1, j)
437 display = "monochrome"
444 subcaptionLine = find_token(lines, "subcaption", i+1, j)
445 if subcaptionLine != -1:
446 subcaptionText = lines[subcaptionLine][11:]
447 if subcaptionText != "":
448 subcaptionText = '"'+subcaptionText+'"'
450 k = find_token(lines, "subfigure", i+1,j)
456 new = ["\\begin_inset Graphics FormatVersion 1"]
457 write_attribute(new, "filename", filename)
458 write_attribute(new, "display", display)
460 new.append("\tsubcaption")
461 write_attribute(new, "subcaptionText", subcaptionText)
462 write_attribute(new, "size_type", size_type)
463 write_attribute(new, "width", width)
464 write_attribute(new, "height", height)
465 if rotateAngle != "":
466 new.append("\trotate")
467 write_attribute(new, "rotateAngle", rotateAngle)
468 write_attribute(new, "rotateOrigin", "leftBaseline")
469 write_attribute(new, "lyxsize_type", "1")
470 write_attribute(new, "lyxwidth", lyxwidth)
471 write_attribute(new, "lyxheight", lyxheight)
472 new = new + ["\\end_inset"]
477 # Convert tabular format 2 to 3
479 attr_re = re.compile(r' \w*="(false|0|)"')
480 line_re = re.compile(r'<(features|column|row|cell)')
482 def update_tabular(file):
486 i = find_token(lines, '\\begin_inset Tabular', i)
490 for k in get_tabular_lines(lines, i):
491 if check_token(lines[k], "<lyxtabular"):
492 lines[k] = string.replace(lines[k], 'version="2"', 'version="3"')
493 elif check_token(lines[k], "<column"):
494 lines[k] = string.replace(lines[k], 'width=""', 'width="0pt"')
496 if line_re.match(lines[k]):
497 lines[k] = re.sub(attr_re, "", lines[k])
503 # Convert tabular format 2 to 3
505 # compatibility read for old longtable options. Now we can make any
506 # row part of the header/footer type we want before it was strict
507 # sequential from the first row down (as LaTeX does it!). So now when
508 # we find a header/footer line we have to go up the rows and set it
509 # on all preceding rows till the first or one with already a h/f option
510 # set. If we find a firstheader on the same line as a header or a
511 # lastfooter on the same line as a footer then this should be set empty.
514 # just for compatibility with old python versions
515 # python >= 2.3 has real booleans (False and True)
519 # simple data structure to deal with long table info
522 self.endhead = false # header row
523 self.endfirsthead = false # first header row
524 self.endfoot = false # footer row
525 self.endlastfoot = false # last footer row
528 def haveLTFoot(row_info):
529 for row_ in row_info:
535 def setHeaderFooterRows(hr, fhr, fr, lfr, rows_, row_info):
536 endfirsthead_empty = false
537 endlastfoot_empty = false
541 row_info[hr].endhead = true
543 # set firstheader info
544 if fhr and fhr < rows_:
545 if row_info[fhr].endhead:
548 row_info[fhr].endfirsthead = true
549 row_info[fhr].endhead = false
550 elif row_info[fhr - 1].endhead:
551 endfirsthead_empty = true
553 while fhr > 0 and not row_info[fhr - 1].endhead:
555 row_info[fhr].endfirsthead = true
558 if fr and fr < rows_:
559 if row_info[fr].endhead and row_info[fr - 1].endhead:
560 while fr > 0 and not row_info[fr - 1].endhead:
562 row_info[fr].endfoot = true
563 row_info[fr].endhead = false
564 elif row_info[fr].endfirsthead and row_info[fr - 1].endfirsthead:
565 while fr > 0 and not row_info[fr - 1].endfirsthead:
567 row_info[fr].endfoot = true
568 row_info[fr].endfirsthead = false
569 elif not row_info[fr - 1].endhead and not row_info[fr - 1].endfirsthead:
570 while fr > 0 and not row_info[fr - 1].endhead and not row_info[fr - 1].endfirsthead:
572 row_info[fr].endfoot = true
574 # set lastfooter info
575 if lfr and lfr < rows_:
576 if row_info[lfr].endhead and row_info[lfr - 1].endhead:
577 while lfr > 0 and not row_info[lfr - 1].endhead:
579 row_info[lfr].endlastfoot = true
580 row_info[lfr].endhead = false
581 elif row_info[lfr].endfirsthead and row_info[lfr - 1].endfirsthead:
582 while lfr > 0 and not row_info[lfr - 1].endfirsthead:
584 row_info[lfr].endlastfoot = true
585 row_info[lfr].endfirsthead = false
586 elif row_info[lfr].endfoot and row_info[lfr - 1].endfoot:
587 while lfr > 0 and not row_info[lfr - 1].endfoot:
589 row_info[lfr].endlastfoot = true
590 row_info[lfr].endfoot = false
591 elif not row_info[fr - 1].endhead and not row_info[fr - 1].endfirsthead and not row_info[fr - 1].endfoot:
592 while lfr > 0 and not row_info[lfr - 1].endhead and not row_info[lfr - 1].endfirsthead and not row_info[lfr - 1].endfoot:
594 row_info[lfr].endlastfoot = true
595 elif haveLTFoot(row_info):
596 endlastfoot_empty = true
598 return endfirsthead_empty, endlastfoot_empty
601 def insert_attribute(lines, i, attribute):
602 last = string.find(lines[i],'>')
603 lines[i] = lines[i][:last] + ' ' + attribute + lines[i][last:]
606 rows_re = re.compile(r'rows="(\d*)"')
607 longtable_re = re.compile(r'islongtable="(\w)"')
608 ltvalues_re = re.compile(r'endhead="(-?\d*)" endfirsthead="(-?\d*)" endfoot="(-?\d*)" endlastfoot="(-?\d*)"')
609 lt_features_re = re.compile(r'(endhead="-?\d*" endfirsthead="-?\d*" endfoot="-?\d*" endlastfoot="-?\d*")')
610 def update_longtables(file):
614 i = find_token(body, '\\begin_inset Tabular', i)
618 i = find_token(body, "<lyxtabular", i)
622 # get number of rows in the table
623 rows = int(rows_re.search(body[i]).group(1))
626 i = find_token(body, '<features', i)
630 # is this a longtable?
631 longtable = longtable_re.search(body[i])
634 # islongtable is missing add it
635 body[i] = body[i][:10] + 'islongtable="false" ' + body[i][10:]
637 if not longtable or longtable.group(1) != "true":
638 # remove longtable elements from features
639 features = lt_features_re.search(body[i])
641 body[i] = string.replace(body[i], features.group(1), "")
644 row_info = row() * rows
645 res = ltvalues_re.search(body[i])
649 endfirsthead_empty, endlastfoot_empty = setHeaderFooterRows(res.group(1), res.group(2), res.group(3), res.group(4), rows, row_info)
651 if endfirsthead_empty:
652 insert_attribute(body, i, 'firstHeadEmpty="true"')
654 if endfirsthead_empty:
655 insert_attribute(body, i, 'lastFootEmpty="true"')
658 for j in range(rows):
659 i = find_token(body, '<row', i)
661 self.endfoot = false # footer row
662 self.endlastfoot = false # last footer row
663 if row_info[j].endhead:
664 insert_attribute(body, i, 'endhead="true"')
666 if row_info[j].endfirsthead:
667 insert_attribute(body, i, 'endfirsthead="true"')
669 if row_info[j].endfoot:
670 insert_attribute(body, i, 'endfoot="true"')
672 if row_info[j].endlastfoot:
673 insert_attribute(body, i, 'endlastfoot="true"')
678 # Figure insert are hidden feature of lyx 1.1.6. This might be removed in the future.
679 def fix_oldfloatinset(file):
683 i = find_token(lines, "\\begin_inset Float ", i)
686 j = find_token(lines, "collapsed", i)
688 lines[j:j] = ["wide false"]
692 def change_listof(file):
696 i = find_token(lines, "\\begin_inset LatexCommand \\listof", i)
699 type = re.search(r"listof(\w*)", lines[i]).group(1)[:-1]
700 lines[i] = "\\begin_inset FloatList "+type
704 def change_infoinset(file):
708 i = find_token(lines, "\\begin_inset Info", i)
711 txt = string.lstrip(lines[i][18:])
712 new = ["\\begin_inset Note", "collapsed true", ""]
713 j = find_token(lines, "\\end_inset", i)
717 note_lines = lines[i+1:j]
719 note_lines = [txt]+note_lines
721 for line in note_lines:
722 new = new + ["\layout Standard", ""]
723 tmp = string.split(line, '\\')
726 new = new + ["\\backslash ", x]
731 def change_preamble(file):
733 i = find_token(lines, "\\use_amsmath", 0)
736 lines[i+1:i+1] = ["\\use_natbib 0",
737 "\use_numerical_citations 0"]
740 convert = [[220, [change_preamble, change_listof, fix_oldfloatinset,
741 update_tabular, update_longtables, remove_pextra,
742 remove_oldfloat, remove_figinset, remove_oldertinset,
743 remove_oldert, combine_ert, change_infoinset]]]
747 if __name__ == "__main__":