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>
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.
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.
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.
19 from parser_tools import get_value, check_token, find_token,\
20 find_tokens, find_end_of, find_end_of_inset
28 version_lyx2lyx = "1.4.0cvs"
29 default_debug_level = 2
31 # Regular expressions used
32 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
33 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
34 original_version = re.compile(r"\#LyX (\S*)")
37 # file format information:
38 # file, supported formats, stable release versions
39 format_relation = [("0_10", [210], ["0.10.7","0.10"]),
40 ("0_12", [215], ["0.12","0.12.1","0.12"]),
41 ("1_0_0", [215], ["1.0.0","1.0"]),
42 ("1_0_1", [215], ["1.0.1","1.0.2","1.0.3","1.0.4", "1.1.2","1.1"]),
43 ("1_1_4", [215], ["1.1.4","1.1"]),
44 ("1_1_5", [216], ["1.1.5","1.1.5fix1","1.1.5fix2","1.1"]),
45 ("1_1_6", [217], ["1.1.6","1.1.6fix1","1.1.6fix2","1.1"]),
46 ("1_1_6fix3", [218], ["1.1.6fix3","1.1.6fix4","1.1"]),
47 ("1_2", [220], ["1.2.0","1.2.1","1.2.3","1.2.4","1.2"]),
48 ("1_3", [221], ["1.3.0","1.3.1","1.3.2","1.3.3","1.3.4","1.3.5","1.3"]),
49 ("1_4", range(223,242), ["1.4.0cvs","1.4"])]
53 " Returns a list with supported file formats."
55 for version in format_relation:
56 for format in version[1]:
57 if format not in formats:
58 formats.append(format)
63 " Returns the more recent file format available."
64 return format_relation[-1][1][-1]
67 def get_backend(textclass):
68 " For _textclass_ returns its backend."
69 if textclass == "linuxdoc" or textclass == "manpage":
71 if textclass[:7] == "docbook":
80 """This class carries all the information of the LyX file."""
81 def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0):
83 end_format: final format that the file should be converted. (integer)
84 input: the name of the input source, if empty resort to standard input.
85 output: the name of the output file, if empty use the standard output.
86 error: the name of the error file, if empty use the standard error.
87 debug: debug level, O means no debug, as its value increases be more verbose.
89 if input and input != '-':
90 self.input = self.open(input)
92 self.input = sys.stdin
94 self.output = open(output, "w")
96 self.output = sys.stdout
99 self.err = open(error, "w")
101 self.err = sys.stderr
104 self.try_hard = try_hard
107 self.end_format = self.lyxformat(end_format)
109 self.end_format = get_end_format()
111 self.backend = "latex"
112 self.textclass = "article"
118 def warning(self, message, debug_level= default_debug_level):
119 " Emits warning to self.error, if the debug_level is less than the self.debug."
120 if debug_level <= self.debug:
121 self.err.write("Warning: " + message + "\n")
124 def error(self, message):
125 " Emits a warning and exits if not in try_hard mode."
126 self.warning(message)
127 if not self.try_hard:
128 self.warning("Quiting.")
135 """Reads a file into the self.header and self.body parts, from self.input."""
139 line = self.input.readline()
141 self.error("Invalid LyX file.")
144 # remove '\r' from line's end, if present
145 if line[-1:] == '\r':
148 if check_token(line, '\\begin_preamble'):
150 if check_token(line, '\\end_preamble'):
154 line = string.strip(line)
160 if string.split(line)[0] in ("\\layout", "\\begin_layout", "\\begin_body"):
161 self.body.append(string.split(line)[0])
164 self.header.append(line)
167 line = self.input.readline()
170 # remove '\r' from line's end, if present
171 if line[-2:-1] == '\r':
172 self.body.append(line[:-2])
174 self.body.append(line[:-1])
176 self.textclass = get_value(self.header, "\\textclass", 0)
177 self.backend = get_backend(self.textclass)
178 self.format = self.read_format()
179 self.language = get_value(self.header, "\\language", 0)
180 if self.language == "":
181 self.language = "english"
182 self.initial_version = self.read_version()
186 " Writes the LyX file to self.output."
190 for line in self.header:
191 self.output.write(line+"\n")
192 self.output.write("\n")
193 for line in self.body:
194 self.output.write(line+"\n")
197 def open(self, file):
198 """Transparently deals with compressed files."""
200 self.dir = os.path.dirname(os.path.abspath(file))
202 gzip.open(file).readline()
203 self.output = gzip.GzipFile("","wb",6,self.output)
204 return gzip.open(file)
209 def lyxformat(self, format):
210 " Returns the file format representation, an integer."
211 result = format_re.match(format)
213 format = int(result.group(1) + result.group(2))
215 self.error(str(format) + ": " + "Invalid LyX file.")
217 if format in formats_list():
220 self.error(str(format) + ": " + "Format not supported.")
224 def read_version(self):
225 """ Searchs for clues of the LyX version used to write the file, returns the
226 most likely value, or None otherwise."""
227 for line in self.header:
231 result = original_version.match(line)
233 return result.group(1)
237 def set_version(self):
238 " Set the header with the version used."
239 self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version_lyx2lyx
240 if self.header[1][0] == '#':
244 def read_format(self):
245 " Read from the header the fileformat of the present LyX file."
246 for line in self.header:
247 result = fileformat.match(line)
249 return self.lyxformat(result.group(1))
251 self.error("Invalid LyX File.")
255 def set_format(self):
256 " Set the file format of the file, in the header."
257 if self.format <= 217:
258 format = str(float(self.format)/100)
260 format = str(self.format)
261 i = find_token(self.header, "\\lyxformat", 0)
262 self.header[i] = "\\lyxformat %s" % format
265 def set_parameter(self, param, value):
266 " Set the value of the header parameter."
267 i = find_token(self.header, '\\' + param, 0)
269 self.warning(3, 'Parameter not found in the header: %s' % param)
271 self.header[i] = '\\%s %s' % (param, str(value))
275 "Convert from current (self.format) to self.end_format."
276 mode, convertion_chain = self.chain()
277 self.warning("convertion chain: " + str(convertion_chain), 3)
279 for step in convertion_chain:
280 steps = getattr(__import__("lyx_" + step), mode)
282 self.warning("Convertion step: %s - %s" % (step, mode), default_debug_level + 1)
284 self.error("The convertion to an older format (%s) is not implemented." % self.format)
286 multi_conv = len(steps) != 1
287 for version, table in steps:
289 (self.format >= version and mode == "convert") or\
290 (self.format <= version and mode == "revert"):
298 self.warning("An error ocurred in %s, %s" % (version, str(conv)),
300 if not self.try_hard:
304 self.warning("%lf: Elapsed time on %s" % (time.time() - init_t, str(conv)),
305 default_debug_level + 1)
307 self.format = version
308 if self.end_format == self.format:
313 """ This is where all the decisions related with the convertion are taken.
314 It returns a list of modules needed to convert the LyX file from
315 self.format to self.end_format"""
317 self.start = self.format
321 for rel in format_relation:
322 if self.initial_version in rel[2]:
324 initial_step = rel[0]
328 if not correct_version:
330 self.warning("Version does not match file format, discarding it.")
331 for rel in format_relation:
333 initial_step = rel[0]
336 # This should not happen, really.
337 self.error("Format not supported.")
339 # Find the final step
340 for rel in format_relation:
341 if self.end_format in rel[1]:
345 self.error("Format not supported.")
347 # Convertion mode, back or forth
349 if (initial_step, self.start) < (final_step, self.end_format):
352 for step in format_relation:
353 if initial_step <= step[0] <= final_step:
354 if first_step and len(step[1]) == 1:
357 steps.append(step[0])
360 relation_format = format_relation
361 relation_format.reverse()
364 for step in relation_format:
365 if final_step <= step[0] <= initial_step:
366 steps.append(step[0])
369 if last_step[1][-1] == self.end_format:
375 def get_toc(self, depth = 4):
376 " Returns the TOC of this LyX document."
377 paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, 'Subsection' : 3, 'Subsubsection': 4}
378 allowed_insets = ['Quotes']
379 allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix"
382 for section in paragraphs_filter.keys():
383 sections.append('\\begin_layout %s' % section)
388 i = find_tokens(self.body, sections, i)
392 j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
394 self.warning('Incomplete file.', 0)
397 section = string.split(self.body[i])[1]
398 if section[-1] == '*':
399 section = section[:-1]
404 # skip paragraph parameters
405 while not string.strip(self.body[k]) and string.split(self.body[k])[0] in allowed_parameters:
409 if check_token(self.body[k], '\\begin_inset'):
410 inset = string.split(self.body[k])[1]
411 end = find_end_of_inset(self.body, k)
412 if end == -1 or end > j:
413 self.warning('Malformed file.', 0)
415 if inset in allowed_insets:
416 par.extend(self.body[k: end+1])
419 par.append(self.body[k])
422 # trim empty lines in the end.
423 while string.strip(par[-1]) == '' and par:
426 toc_par.append(Paragraph(section, par))
433 class File(LyX_Base):
434 " This class reads existing LyX files."
435 def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0):
436 LyX_Base.__init__(self, end_format, input, output, error, debug, try_hard)
440 class NewFile(LyX_Base):
441 " This class is to create new LyX files."
442 def set_header(self, **params):
445 "#LyX xxxx created this file. For more info see http://www.lyx.org/",
449 "\\textclass article",
450 "\\language english",
451 "\\inputencoding auto",
452 "\\fontscheme default",
453 "\\graphics default",
454 "\\paperfontsize default",
455 "\\papersize default",
456 "\\paperpackage none",
457 "\\use_geometry false",
459 "\\cite_engine basic",
460 "\\use_bibtopic false",
461 "\\paperorientation portrait",
464 "\\paragraph_separation indent",
466 "\\quotes_language english",
470 "\\paperpagestyle default",
471 "\\tracking_changes false",
474 self.format = get_end_format()
476 self.set_parameter(param, params[param])
479 def set_body(self, paragraphs):
480 self.body.extend(['\\begin_body',''])
482 for par in paragraphs:
483 self.body.extend(par.asLines())
485 self.body.extend(['','\\end_body', '\\end_document'])
489 # unfinished implementation, it is missing the Text and Insets representation.
490 " This class represents the LyX paragraphs."
491 def __init__(self, name, body=[], settings = [], child = []):
493 name: paragraph name.
494 body: list of lines of body text.
495 child: list of paragraphs that descend from this paragraph.
499 self.settings = settings
503 " Converts the paragraph to a list of strings, representing it in the LyX file."
504 result = ['','\\begin_layout %s' % self.name]
505 result.extend(self.settings)
507 result.extend(self.body)
508 result.append('\\end_layout')
513 result.append('\\begin_deeper')
514 for node in self.child:
515 result.extend(node.asLines())
516 result.append('\\end_deeper')
522 " This class represents the LyX insets."
527 " This class represents simple chuncks of text."