]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyxconvert_218.py
Matrix and delimiter.
[lyx.git] / lib / lyx2lyx / lyxconvert_218.py
1 # This file is part of lyx2lyx
2 # Copyright (C) 2002 Dekel Tsur <dekel@lyx.org>
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17
18
19 import sys,string,re
20 from parser_tools import *
21
22 floats = {
23     "footnote": ["\\begin_inset Foot",
24                  "collapsed true"],
25     "margin":   ["\\begin_inset Marginal",
26                  "collapsed true"],
27     "fig":      ["\\begin_inset Float figure",
28                  "wide false",
29                  "collapsed false"],
30     "tab":      ["\\begin_inset Float table",
31                  "wide false",
32                  "collapsed false"],
33     "alg":      ["\\begin_inset Float algorithm",
34                  "wide false",
35                  "collapsed false"],
36     "wide-fig": ["\\begin_inset Float figure",
37                  "wide true",
38                  "collapsed false"],
39     "wide-tab": ["\\begin_inset Float table",
40                  "wide true",
41                  "collapsed false"]
42 }
43
44 font_tokens = ["\\family", "\\series", "\\shape", "\\size", "\\emph",
45                "\\bar", "\\noun", "\\color", "\\lang", "\\latex"]
46
47 #
48 # Change \begin_float .. \end_float into \begin_inset Float .. \end_inset
49 #
50
51 pextra_type3_rexp = re.compile(r".*\\pextra_type\s+3")
52 pextra_rexp = re.compile(r"\\pextra_type\s+(\S+)"+\
53                          r"(\s+\\pextra_alignment\s+(\S+))?"+\
54                          r"(\s+\\pextra_hfill\s+(\S+))?"+\
55                          r"(\s+\\pextra_start_minipage\s+(\S+))?"+\
56                          r"(\s+(\\pextra_widthp?)\s+(\S*))?")
57
58 def get_width(mo):
59     if mo.group(10):
60         if mo.group(9) == "\\pextra_widthp":
61             return mo.group(10)+"col%"
62         else:
63             return mo.group(10)
64     else:
65         return "100col%"
66
67 def remove_oldfloat(lines, language):
68     i = 0
69     while 1:
70         i = find_token(lines, "\\begin_float", i)
71         if i == -1:
72             break
73         # There are no nested floats, so finding the end of the float is simple
74         j = find_token(lines, "\\end_float", i+1)
75
76         floattype = string.split(lines[i])[1]
77         if not floats.has_key(floattype):
78             sys.stderr.write("Error! Unknown float type "+floattype+"\n")
79             floattype = "fig"
80
81         # skip \end_deeper tokens
82         i2 = i+1
83         while check_token(lines[i2], "\\end_deeper"):
84             i2 = i2+1
85         if i2 > i+1:
86             j2 = get_next_paragraph(lines, j+1)
87             lines[j2:j2] = ["\\end_deeper "]*(i2-(i+1))
88
89         new = floats[floattype]+[""]
90
91         # Check if the float is floatingfigure
92         k = find_re(lines, pextra_type3_rexp, i, j)
93         if k != -1:
94             mo = pextra_rexp.search(lines[k])
95             width = get_width(mo)
96             lines[k] = re.sub(pextra_rexp, "", lines[k])
97             new = ["\\begin_inset Wrap figure",
98                    'width "%s"' % width,
99                    "collapsed false",
100                    ""]
101
102         new = new+lines[i2:j]+["\\end_inset ", ""]
103
104         # After a float, all font attributes are reseted.
105         # We need to output '\foo default' for every attribute foo
106         # whose value is not default before the float.
107         # The check here is not accurate, but it doesn't matter
108         # as extra '\foo default' commands are ignored.
109         # In fact, it might be safer to output '\foo default' for all 
110         # font attributes.
111         k = get_paragraph(lines, i)
112         flag = 0
113         for token in font_tokens:
114             if find_token(lines, token, k, i) != -1:
115                 if not flag:
116                     # This is not necessary, but we want the output to be
117                     # as similar as posible to the lyx format
118                     flag = 1
119                     new.append("")
120                 if token == "\\lang":
121                     new.append(token+" "+language)
122                 else:
123                     new.append(token+" default ")
124
125         lines[i:j+1] = new
126         i = i+1
127
128 pextra_type2_rexp = re.compile(r".*\\pextra_type\s+2")
129 pextra_type2_rexp2 = re.compile(r".*(\\layout|\\pextra_type\s+2)")
130
131 def remove_oldminipage(lines):
132     i = 0
133     flag = 0
134     while 1:
135         i = find_re(lines, pextra_type2_rexp, i)
136         if i == -1:
137             break
138         
139         mo = pextra_rexp.search(lines[i])
140         position = mo.group(3)
141         hfill = mo.group(5)
142         width = get_width(mo)
143         lines[i] = re.sub(pextra_rexp, "", lines[i])
144
145         start = ["\\begin_inset Minipage",
146                  "position " + position,
147                  "inner_position 0",
148                  'height "0pt"',
149                  'width "%s"' % width,
150                  "collapsed false"
151                  ]
152         if flag:
153             flag = 0
154             if hfill:
155                 start = ["","\hfill",""]+start
156         else:
157             start = ["\\layout Standard"] + start
158
159         j = find_token_backwards(lines,"\\layout", i-1)
160         j0 = j
161
162         j = find_tokens(lines, ["\\layout", "\\end_float"], i+1)
163         # j can be -1
164
165         count = 0
166         while 1:
167             # collect more paragraphs to the minipage
168             count = count+1
169             if j == -1 or not check_token(lines[j], "\\layout"):
170                 break
171             i = find_re(lines, pextra_type2_rexp2, j+1)
172             if i == -1:
173                 break
174             mo = pextra_rexp.search(lines[i])
175             if not mo:
176                 break
177             if mo.group(7) == "1":
178                 flag = 1
179                 break
180             lines[i] = re.sub(pextra_rexp, "", lines[i])
181             j = find_tokens(lines, ["\\layout", "\\end_float"], i+1)
182
183         mid = lines[j0:j]
184         end = ["\\end_inset "]
185
186         lines[j0:j] = start+mid+end
187         i = i+1
188
189 def is_empty(lines):
190     return filter(is_nonempty_line, lines) == []
191
192 font_rexp =  re.compile(r"\\(family|series|shape|size|emph|numeric|bar|noun)")
193 ert_rexp = re.compile(r"\\begin_inset|.*\\SpecialChar")
194 spchar_rexp = re.compile(r"(.*)(\\SpecialChar.*)")
195 ert_begin = ["\\begin_inset ERT",
196              "status Collapsed",
197              "",
198              "\\layout Standard"]
199
200 def remove_oldert(lines):
201     i = 0
202     while 1:
203         i = find_tokens(lines, ["\\latex latex", "\\layout LaTeX"], i)
204         if i == -1:
205             break
206         j = i+1
207         while 1:
208             j = find_tokens(lines, ["\\latex default", "\\begin_inset", "\\layout", "\\end_float", "\\the_end"],
209                             j)
210             if check_token(lines[j], "\\begin_inset"):
211                 j = find_end_of_inset(lines, j)
212             else:
213                 break
214
215         if check_token(lines[j], "\\layout"):
216             while j-1 >= 0 and check_token(lines[j-1], "\\begin_deeper"):
217                 j = j-1
218
219         # We need to remove insets, special chars & font commands from ERT text
220         new = []
221         new2 = []
222         if check_token(lines[i], "\\layout LaTeX"):
223             new = ["\layout Standard", "", ""]
224             # We have a problem with classes in which Standard is not the default layout!
225
226         k = i+1
227         while 1:
228             k2 = find_re(lines, ert_rexp, k, j)
229             inset = specialchar = 0
230             if k2 == -1:
231                 k2 = j
232             elif check_token(lines[k2], "\\begin_inset"):
233                 inset = 1
234             else:
235                 specialchar = 1
236                 mo = spchar_rexp.match(lines[k2])
237                 lines[k2] = mo.group(1)
238                 specialchar_str = mo.group(2)
239                 k2 = k2+1
240
241             tmp = []
242             for line in lines[k:k2]:
243                 if font_rexp.match(line):
244                     if new2 == []:
245                         # This is not necessary, but we want the output to be
246                         # as similar as posible to the lyx format
247                         new2 = [""]
248                     new2.append(line)
249                 elif not check_token(line, "\\latex"):
250                     tmp.append(line)
251
252             if is_empty(tmp):
253                 if filter(lambda x:x != "", tmp) != []:
254                     if new == []:
255                         # This is not necessary, but we want the output to be
256                         # as similar as posible to the lyx format
257                         lines[i-1] = lines[i-1]+" "
258                     else:
259                         new = new+[" "]
260             else:
261                 new = new+ert_begin+tmp+["\\end_inset ", ""]
262
263             if inset:
264                 k3 = find_end_of_inset(lines, k2)
265                 new = new+[""]+lines[k2:k3+1]+[""] # Put an empty line after \end_inset
266                 k = k3+1
267                 # Skip the empty line after \end_inset
268                 if not is_nonempty_line(lines[k]):
269                     k = k+1
270                     new.append("")
271             elif specialchar:
272                 if new == []:
273                     # This is not necessary, but we want the output to be
274                     # as similar as posible to the lyx format
275                     lines[i-1] = lines[i-1]+specialchar_str
276                     new = [""]
277                 else:
278                     new = new+[specialchar_str, ""]
279                 k = k2
280             else:
281                 break
282
283         new = new+new2
284         if not check_token(lines[j], "\\latex "):
285             new = new+[""]+[lines[j]]
286         lines[i:j+1] = new
287         i = i+1
288
289     i = 0
290     while 1:
291         i = find_token(lines, "\\latex ", i)
292         if i == -1:
293             break
294         del lines[i]
295
296
297 def remove_oldertinset(lines):
298     i = 0
299     while 1:
300         i = find_token(lines, "\\begin_inset ERT", i)
301         if i == -1:
302             break
303         j = find_end_of_inset(lines, i)
304         k = find_token(lines, "\\layout", i+1)
305         l = get_paragraph(lines, i)
306         if lines[k] == lines[l]: # same layout
307             k = k+1
308         new = lines[k:j]
309         lines[i:j+1] = new
310         i = i+1
311
312 def is_ert_paragraph(lines, i):
313     i = find_nonempty_line(lines, i+1)
314     if not check_token(lines[i], "\\begin_inset ERT"):
315         return 0
316     j = find_end_of_inset(lines, i)
317     k = find_nonempty_line(lines, j+1)
318     return check_token(lines[k], "\\layout")
319
320 def combine_ert(lines):
321     i = 0
322     while 1:
323         i = find_token(lines, "\\begin_inset ERT", i)
324         if i == -1:
325             break
326         j = find_token_backwards(lines,"\\layout", i-1)
327         count = 0
328         text = []
329         while is_ert_paragraph(lines, j):
330
331             count = count+1
332             i2 = find_token(lines, "\\layout", j+1)
333             k = find_token(lines, "\\end_inset", i2+1)
334             text = text+lines[i2:k]
335             j = find_token(lines, "\\layout", k+1)
336             if j == -1:
337                 break
338
339         if count >= 2:
340             j = find_token(lines, "\\layout", i+1)
341             lines[j:k] = text
342
343         i = i+1
344         
345 oldunits = ["pt", "cm", "in", "text%", "col%"]
346
347 def get_length(lines, name, start, end):
348     i = find_token(lines, name, start, end)
349     if i == -1:
350         return ""
351     x = string.split(lines[i])
352     return x[2]+oldunits[int(x[1])]
353
354 def write_attribute(x, token, value):
355     if value != "":
356         x.append("\t"+token+" "+value)
357
358 def remove_figinset(lines):
359     i = 0
360     while 1:
361         i = find_token(lines, "\\begin_inset Figure", i)
362         if i == -1:
363             break
364         j = find_end_of_inset(lines, i)
365
366         lyxwidth = string.split(lines[i])[3]+"pt"
367         lyxheight = string.split(lines[i])[4]+"pt"
368
369         filename = get_value(lines, "file", i+1, j)
370
371         width = get_length(lines, "width", i+1, j)
372         # what does width=5 mean ?
373         height = get_length(lines, "height", i+1, j)
374         rotateAngle = get_value(lines, "angle", i+1, j)
375         if width == "" and height == "":
376             size_type = "0"
377         else:
378             size_type = "1"
379
380         flags = get_value(lines, "flags", i+1, j)
381         x = int(flags)%4
382         if x == 1:
383             display = "monochrome"
384         elif x == 2:
385             display = "gray"
386         else:
387             display = "color"
388
389         subcaptionText = get_value(lines, "subcaption", i+1, j)
390         if subcaptionText != "":
391             subcaptionText = '"'+subcaptionText+'"'
392         k = find_token(lines, "subfigure", i+1,j)
393         if k == -1:
394             subcaption = 0
395         else:
396             subcaption = 1
397
398         new = ["\\begin_inset Graphics FormatVersion 1"]
399         write_attribute(new, "filename", filename)
400         write_attribute(new, "display", display)
401         if subcaption:
402             new.append("\tsubcaption")
403         write_attribute(new, "subcaptionText", subcaptionText)
404         write_attribute(new, "size_type", size_type)
405         write_attribute(new, "width", width)
406         write_attribute(new, "height", height)
407         if rotateAngle != "":
408             new.append("\trotate")
409             write_attribute(new, "rotateAngle", rotateAngle)
410         write_attribute(new, "rotateOrigin", "leftBaseline")
411         write_attribute(new, "lyxsize_type", "1")
412         write_attribute(new, "lyxwidth", lyxwidth)
413         write_attribute(new, "lyxheight", lyxheight)
414         new = new + ["\end_inset"]
415         lines[i:j+1] = new
416
417 attr_re = re.compile(r' \w*="(false|0|)"')
418 line_re = re.compile(r'<(features|column|row|cell)')
419
420 def update_tabular(lines):
421     i = 0
422     while 1:
423         i = find_token(lines, '\\begin_inset  Tabular', i)
424         if i == -1:
425             break
426
427         for k in get_tabular_lines(lines, i):
428             if check_token(lines[k], "<lyxtabular"):
429                 lines[k] = string.replace(lines[k], 'version="2"', 'version="3"')
430             elif check_token(lines[k], "<column"):
431                 lines[k] = string.replace(lines[k], 'width=""', 'width="0pt"')
432
433             if line_re.match(lines[k]):
434                 lines[k] = re.sub(attr_re, "", lines[k])
435
436         i = i+1
437
438 def change_preamble(lines):
439     i = find_token(lines, "\\use_amsmath", 0)
440     if i == -1:
441         return
442     lines[i+1:i+1] = ["\\use_natbib 0",
443                       "\use_numerical_citations 0"]
444
445 def convert(header, body):
446     language = get_value(header, "\\language", 0)
447     if language == "":
448         language = "english"
449
450     change_preamble(header)
451     update_tabular(body)
452     remove_oldminipage(body)
453     remove_oldfloat(body, language)
454     remove_figinset(body)
455     remove_oldertinset(body)
456     remove_oldert(body)
457     combine_ert(body)
458
459 if __name__ == "__main__":
460     pass