]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/LyX.py
41c12b63743d924fbe2e91496f392ab6575f0235
[lyx.git] / lib / lyx2lyx / LyX.py
1 # This file is part of lyx2lyx
2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2002-2004 Dekel Tsur <dekel@lyx.org>, José Matos <jamatos@lyx.org>
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 from parser_tools import get_value, check_token, find_token
20 import os.path
21 import gzip
22 import sys
23 import re
24 import string
25
26 ##
27 # file format version
28 #
29 version = "1.4.0cvs"
30 default_debug_level = 2
31 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
32 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
33 original_version = re.compile(r"\#LyX (\S*)")
34
35 format_relation = [("0_10",  [210], ["0.10.7","0.10"]),
36                    ("0_12",  [215], ["0.12","0.12.1","0.12"]),
37                    ("1_0_0", [215], ["1.0.0","1.0"]),
38                    ("1_0_1", [215], ["1.0.1","1.0.2","1.0.3","1.0.4", "1.1.2","1.1"]),
39                    ("1_1_4", [215], ["1.1.4","1.1"]),
40                    ("1_1_5", [216], ["1.1.5","1.1.5fix1","1.1.5fix2","1.1"]),
41                    ("1_1_6", [217], ["1.1.6","1.1.6fix1","1.1.6fix2","1.1"]),
42                    ("1_1_6fix3", [218], ["1.1.6fix3","1.1.6fix4","1.1"]),
43                    ("1_2", [220], ["1.2.0","1.2.1","1.2.3","1.2.4","1.2"]),
44                    ("1_3", [221], ["1.3.0","1.3.1","1.3.2","1.3.3","1.3.4","1.3.5","1.3"]),
45                    ("1_4", range(223,238), ["1.4.0cvs","1.4"])]
46
47
48 def formats_list():
49     formats = []
50     for version in format_relation:
51         for format in version[1]:
52             if format not in formats:
53                 formats.append(format)
54     return formats
55
56
57 def get_end_format():
58     return format_relation[-1][1][-1]
59
60
61 def get_backend(textclass):
62     if textclass == "linuxdoc" or textclass == "manpage":
63         return "linuxdoc"
64     if textclass[:7] == "docbook":
65         return "docbook"
66     return "latex"
67
68
69 ##
70 # Class
71 #
72 class FileInfo:
73     """This class carries all the information of the LyX file."""
74     def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level):
75         if input and input != '-':
76             self.input = self.open(input)
77         else:
78             self.input = sys.stdin
79         if output:
80             self.output = open(output, "w")
81         else:
82             self.output = sys.stdout
83
84         if error:
85             self.err = open(error, "w")
86         else:
87             self.err = sys.stderr
88
89         self.debug = debug
90
91         if end_format:
92             self.end_format = self.lyxformat(end_format)
93         else:
94             self.end_format = get_end_format()
95
96         self.backend = "latex"
97         self.textclass = "article"
98         self.header = []
99         self.body = []
100         self.read()
101
102     def warning(self, message, debug_level= default_debug_level):
103         if debug_level <= self.debug:
104             self.err.write(message + "\n")
105
106     def error(self, message):
107         self.warning(message)
108         self.warning("Quiting.")
109         sys.exit(1)
110
111     def read(self):
112         """Reads a file into the self.header and self.body parts"""
113         preamble = 0
114
115         while 1:
116             line = self.input.readline()
117             if not line:
118                 self.error("Invalid LyX file.")
119
120             line = line[:-1]
121             # remove '\r' from line's end, if present
122             if line[-1:] == '\r':
123                 line = line[:-1]
124
125             if check_token(line, '\\begin_preamble'):
126                 preamble = 1
127             if check_token(line, '\\end_preamble'):
128                 preamble = 0
129
130             if not preamble:
131                 line = string.strip(line)
132
133             if not line and not preamble:
134                 break
135
136             self.header.append(line)
137
138         while 1:
139             line = self.input.readline()
140             if not line:
141                 break
142             # remove '\r' from line's end, if present
143             if line[-2:-1] == '\r':
144                 self.body.append(line[:-2])
145             else:
146                 self.body.append(line[:-1])
147
148         self.textclass = get_value(self.header, "\\textclass", 0)
149         self.backend = get_backend(self.textclass)
150         self.format  = self.read_format()
151         self.language = get_value(self.header, "\\language", 0)
152         if self.language == "":
153             self.language = "english"
154         self.initial_version = self.read_version()
155
156     def write(self):
157         self.set_version()
158         self.set_format()
159
160         for line in self.header:
161             self.output.write(line+"\n")
162         self.output.write("\n")
163         for line in self.body:
164             self.output.write(line+"\n")
165
166
167     def open(self, file):
168         """Transparently deals with compressed files."""
169
170         self.dir = os.path.dirname(os.path.abspath(file))
171         try:
172             gzip.open(file).readline()
173             self.output = gzip.GzipFile("","wb",6,self.output)
174             return gzip.open(file)
175         except:
176             return open(file)
177
178     def lyxformat(self, format):
179         result = format_re.match(format)
180         if result:
181             format = int(result.group(1) + result.group(2))
182         else:
183             self.error(str(format) + ": " + "Invalid LyX file.")
184
185         if format in formats_list():
186             return format
187
188         self.error(str(format) + ": " + "Format not supported.")
189         return None
190
191     def read_version(self):
192         for line in self.header:
193             if line[0] != "#":
194                 return None
195
196             result = original_version.match(line)
197             if result:
198                 return result.group(1)
199         return None
200
201     def set_version(self):
202         self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version
203         if self.header[1][0] == '#':
204             del self.header[1]
205
206     def read_format(self):
207         for line in self.header:
208             result = fileformat.match(line)
209             if result:
210                 return self.lyxformat(result.group(1))
211         else:
212             self.error("Invalid LyX File.")
213         return None
214
215
216     def set_format(self):
217         if self.format <= 217:
218             format = str(float(format)/100)
219         else:
220             format = str(self.format)
221         i = find_token(self.header, "\\lyxformat", 0)
222         self.header[i] = "\\lyxformat %s" % format
223
224
225     def chain(self):
226         """ This is where all the decisions related with the convertion are taken"""
227
228         self.start =  self.format
229         format = self.format
230         correct_version = 0
231
232         for rel in format_relation:
233             if self.initial_version in rel[2]:
234                 if format in rel[1]:
235                     initial_step = rel[0]
236                     correct_version = 1
237                     break
238
239         if not correct_version:
240             if format <= 215:
241                 self.warning("Version does not match file format, discarding it.")
242             for rel in format_relation:
243                 if format in rel[1]:
244                     initial_step = rel[0]
245                     break
246             else:
247                 # This should not happen, really.
248                 self.error("Format not supported.")
249
250         # Find the final step
251         for rel in format_relation:
252             if self.end_format in rel[1]:
253                 final_step = rel[0]
254                 break
255         else:
256             self.error("Format not supported.")
257
258         # Convertion mode, back or forth
259         steps = []
260         if (initial_step, self.start) < (final_step, self.end_format):
261             mode = "convert"
262             first_step = 1
263             for step in format_relation:
264                 if  initial_step <= step[0] <= final_step:
265                     if first_step and len(step[1]) == 1:
266                         first_step = 0
267                         continue
268                     steps.append(step[0])
269         else:
270             mode = "revert"
271             relation_format = format_relation
272             relation_format.reverse()
273             last_step = None
274
275             for step in relation_format:
276                 if  final_step <= step[0] <= initial_step:
277                     steps.append(step[0])
278                     last_step = step
279
280             if last_step[1][-1] == self.end_format:
281                 steps.pop()
282
283         return mode, steps