1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2002-2004 Dekel Tsur <dekel@lyx.org>
4 # Copyright (C) 2002-2006 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.
20 from parser_tools import get_value, check_token, find_token,\
21 find_tokens, find_end_of
29 import lyx2lyx_version
30 version_lyx2lyx = lyx2lyx_version.version
32 default_debug_level = 2
34 ####################################################################
35 # Private helper functions
37 def find_end_of_inset(lines, i):
38 " Find beginning of inset, where lines[i] is included."
39 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
41 def generate_minor_versions(major, last_minor_version):
42 """ Generate minor versions, using major as prefix and minor
43 versions from 0 until last_minor_version, plus the generic version.
47 generate_minor_versions("1.2", 4) ->
48 [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
50 return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
53 # End of helper functions
54 ####################################################################
57 # Regular expressions used
58 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
59 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
60 original_version = re.compile(r".*?LyX ([\d.]*)")
63 # file format information:
64 # file, supported formats, stable release versions
65 format_relation = [("0_06", [200], generate_minor_versions("0.6" , 4)),
66 ("0_08", [210], generate_minor_versions("0.8" , 6) + ["0.7"]),
67 ("0_10", [210], generate_minor_versions("0.10", 7) + ["0.9"]),
68 ("0_12", [215], generate_minor_versions("0.12", 1) + ["0.11"]),
69 ("1_0", [215], generate_minor_versions("1.0" , 4)),
70 ("1_1", [215], generate_minor_versions("1.1" , 4)),
71 ("1_1_5", [216], ["1.1.5","1.1.5.1","1.1.5.2","1.1"]),
72 ("1_1_6_0", [217], ["1.1.6","1.1.6.1","1.1.6.2","1.1"]),
73 ("1_1_6_3", [218], ["1.1.6.3","1.1.6.4","1.1"]),
74 ("1_2", [220], generate_minor_versions("1.2" , 4)),
75 ("1_3", [221], generate_minor_versions("1.3" , 7)),
76 ("1_4", range(222,246), generate_minor_versions("1.4" , 3)),
77 ("1_5", range(246,261), generate_minor_versions("1.5" , 0))]
81 " Returns a list with supported file formats."
83 for version in format_relation:
84 for format in version[1]:
85 if format not in formats:
86 formats.append(format)
91 " Returns the more recent file format available."
92 return format_relation[-1][1][-1]
95 def get_backend(textclass):
96 " For _textclass_ returns its backend."
97 if textclass == "linuxdoc" or textclass == "manpage":
99 if textclass[:7] == "docbook":
105 " Remove end of line char(s)."
106 if line[-2:-1] == '\r':
112 def get_encoding(language, inputencoding, format, cjk_encoding):
115 # CJK-LyX encodes files using the current locale encoding.
116 # This means that files created by CJK-LyX can only be converted using
117 # the correct locale settings unless the encoding is given as commandline
119 if cjk_encoding == 'auto':
120 return locale.getpreferredencoding()
121 elif cjk_encoding != '':
123 from lyx2lyx_lang import lang
124 if inputencoding == "auto" or inputencoding == "default":
125 return lang[language][3]
126 if inputencoding == "":
128 # python does not know the alias latin9
129 if inputencoding == "latin9":
137 """This class carries all the information of the LyX file."""
139 def __init__(self, end_format = 0, input = "", output = "", error
140 = "", debug = default_debug_level, try_hard = 0, cjk_encoding = '',
141 language = "english", encoding = "auto"):
144 end_format: final format that the file should be converted. (integer)
145 input: the name of the input source, if empty resort to standard input.
146 output: the name of the output file, if empty use the standard output.
147 error: the name of the error file, if empty use the standard error.
148 debug: debug level, O means no debug, as its value increases be more verbose.
150 self.choose_io(input, output)
153 self.err = open(error, "w")
155 self.err = sys.stderr
158 self.try_hard = try_hard
159 self.cjk_encoding = cjk_encoding
162 self.end_format = self.lyxformat(end_format)
164 self.end_format = get_end_format()
166 self.backend = "latex"
167 self.textclass = "article"
168 # This is a hack: We use '' since we don't know the default
169 # layout of the text class. LyX will parse it as default layout.
170 # FIXME: Read the layout file and use the real default layout
171 self.default_layout = ''
176 self.encoding = encoding
177 self.language = language
180 def warning(self, message, debug_level= default_debug_level):
181 " Emits warning to self.error, if the debug_level is less than the self.debug."
182 if debug_level <= self.debug:
183 self.err.write("Warning: " + message + "\n")
186 def error(self, message):
187 " Emits a warning and exits if not in try_hard mode."
188 self.warning(message)
189 if not self.try_hard:
190 self.warning("Quiting.")
197 """Reads a file into the self.header and self.body parts, from self.input."""
200 line = self.input.readline()
202 self.error("Invalid LyX file.")
204 line = trim_eol(line)
205 if check_token(line, '\\begin_preamble'):
207 line = self.input.readline()
209 self.error("Invalid LyX file.")
211 line = trim_eol(line)
212 if check_token(line, '\\end_preamble'):
215 if line.split()[:0] in ("\\layout", "\\begin_layout", "\\begin_body"):
216 self.warning("Malformed LyX file: Missing '\\end_preamble'.")
217 self.warning("Adding it now and hoping for the best.")
219 self.preamble.append(line)
221 if check_token(line, '\\end_preamble'):
228 if line.split()[0] in ("\\layout", "\\begin_layout", "\\begin_body"):
229 self.body.append(line)
232 self.header.append(line)
234 self.textclass = get_value(self.header, "\\textclass", 0)
235 self.backend = get_backend(self.textclass)
236 self.format = self.read_format()
237 self.language = get_value(self.header, "\\language", 0, default = "english")
238 self.inputencoding = get_value(self.header, "\\inputencoding", 0, default = "auto")
239 self.encoding = get_encoding(self.language, self.inputencoding, self.format, self.cjk_encoding)
240 self.initial_version = self.read_version()
242 # Second pass over header and preamble, now we know the file encoding
243 for i in range(len(self.header)):
244 self.header[i] = self.header[i].decode(self.encoding)
245 for i in range(len(self.preamble)):
246 self.preamble[i] = self.preamble[i].decode(self.encoding)
250 line = self.input.readline().decode(self.encoding)
253 self.body.append(trim_eol(line))
257 " Writes the LyX file to self.output."
260 if self.encoding == "auto":
261 self.encoding = get_encoding(self.language, self.encoding, self.format, self.cjk_encoding)
264 i = find_token(self.header, '\\textclass', 0) + 1
265 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
267 self.error("Malformed LyX file: Missing '\\textclass'.")
269 header = self.header[:i] + preamble + self.header[i:]
273 for line in header + [''] + self.body:
274 self.output.write(line.encode(self.encoding)+"\n")
277 def choose_io(self, input, output):
278 """Choose input and output streams, dealing transparently with
282 self.output = open(output, "wb")
284 self.output = sys.stdout
286 if input and input != '-':
287 self.dir = os.path.dirname(os.path.abspath(input))
289 gzip.open(input).readline()
290 self.input = gzip.open(input)
291 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
293 self.input = open(input)
296 self.input = sys.stdin
299 def lyxformat(self, format):
300 " Returns the file format representation, an integer."
301 result = format_re.match(format)
303 format = int(result.group(1) + result.group(2))
307 self.error(str(format) + ": " + "Invalid LyX file.")
309 if format in formats_list():
312 self.error(str(format) + ": " + "Format not supported.")
316 def read_version(self):
317 """ Searchs for clues of the LyX version used to write the file, returns the
318 most likely value, or None otherwise."""
319 for line in self.header:
323 line = line.replace("fix",".")
324 result = original_version.match(line)
326 # Special know cases: reLyX and KLyX
327 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
330 res = result.group(1)
333 #self.warning("Version %s" % result.group(1))
335 self.warning(str(self.header[:2]))
339 def set_version(self):
340 " Set the header with the version used."
341 self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version_lyx2lyx
342 if self.header[1][0] == '#':
346 def read_format(self):
347 " Read from the header the fileformat of the present LyX file."
348 for line in self.header:
349 result = fileformat.match(line)
351 return self.lyxformat(result.group(1))
353 self.error("Invalid LyX File.")
357 def set_format(self):
358 " Set the file format of the file, in the header."
359 if self.format <= 217:
360 format = str(float(self.format)/100)
362 format = str(self.format)
363 i = find_token(self.header, "\\lyxformat", 0)
364 self.header[i] = "\\lyxformat %s" % format
367 def set_parameter(self, param, value):
368 " Set the value of the header parameter."
369 i = find_token(self.header, '\\' + param, 0)
371 self.warning('Parameter not found in the header: %s' % param, 3)
373 self.header[i] = '\\%s %s' % (param, str(value))
376 def is_default_layout(self, layout):
377 " Check whether a layout is the default layout of this class."
378 # FIXME: Check against the real text class default layout
379 if layout == 'Standard' or layout == self.default_layout:
385 "Convert from current (self.format) to self.end_format."
386 mode, convertion_chain = self.chain()
387 self.warning("convertion chain: " + str(convertion_chain), 3)
389 for step in convertion_chain:
390 steps = getattr(__import__("lyx_" + step), mode)
392 self.warning("Convertion step: %s - %s" % (step, mode), default_debug_level + 1)
394 self.error("The convertion to an older format (%s) is not implemented." % self.format)
396 multi_conv = len(steps) != 1
397 for version, table in steps:
399 (self.format >= version and mode == "convert") or\
400 (self.format <= version and mode == "revert"):
408 self.warning("An error ocurred in %s, %s" % (version, str(conv)),
410 if not self.try_hard:
414 self.warning("%lf: Elapsed time on %s" % (time.time() - init_t, str(conv)),
415 default_debug_level + 1)
417 self.format = version
418 if self.end_format == self.format:
423 """ This is where all the decisions related with the convertion are taken.
424 It returns a list of modules needed to convert the LyX file from
425 self.format to self.end_format"""
427 self.start = self.format
431 for rel in format_relation:
432 if self.initial_version in rel[2]:
434 initial_step = rel[0]
438 if not correct_version:
440 self.warning("Version does not match file format, discarding it. (Version %s, format %d)" %(self.initial_version, self.format))
441 for rel in format_relation:
443 initial_step = rel[0]
446 # This should not happen, really.
447 self.error("Format not supported.")
449 # Find the final step
450 for rel in format_relation:
451 if self.end_format in rel[1]:
455 self.error("Format not supported.")
457 # Convertion mode, back or forth
459 if (initial_step, self.start) < (final_step, self.end_format):
462 for step in format_relation:
463 if initial_step <= step[0] <= final_step:
464 if first_step and len(step[1]) == 1:
467 steps.append(step[0])
470 relation_format = format_relation[:]
471 relation_format.reverse()
474 for step in relation_format:
475 if final_step <= step[0] <= initial_step:
476 steps.append(step[0])
479 if last_step[1][-1] == self.end_format:
485 def get_toc(self, depth = 4):
486 " Returns the TOC of this LyX document."
487 paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, 'Subsection' : 3, 'Subsubsection': 4}
488 allowed_insets = ['Quotes']
489 allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix", "\\leftindent"
492 for section in paragraphs_filter.keys():
493 sections.append('\\begin_layout %s' % section)
498 i = find_tokens(self.body, sections, i)
502 j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
504 self.warning('Incomplete file.', 0)
507 section = self.body[i].split()[1]
508 if section[-1] == '*':
509 section = section[:-1]
514 # skip paragraph parameters
515 while not self.body[k].strip() or self.body[k].split()[0] in allowed_parameters:
519 if check_token(self.body[k], '\\begin_inset'):
520 inset = self.body[k].split()[1]
521 end = find_end_of_inset(self.body, k)
522 if end == -1 or end > j:
523 self.warning('Malformed file.', 0)
525 if inset in allowed_insets:
526 par.extend(self.body[k: end+1])
529 par.append(self.body[k])
532 # trim empty lines in the end.
533 while par[-1].strip() == '' and par:
536 toc_par.append(Paragraph(section, par))
543 class File(LyX_Base):
544 " This class reads existing LyX files."
545 def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0, cjk_encoding = ''):
546 LyX_Base.__init__(self, end_format, input, output, error, debug, try_hard, cjk_encoding)
550 class NewFile(LyX_Base):
551 " This class is to create new LyX files."
552 def set_header(self, **params):
555 "#LyX xxxx created this file. For more info see http://www.lyx.org/",
559 "\\textclass article",
560 "\\language english",
561 "\\inputencoding auto",
562 "\\font_roman default",
563 "\\font_sans default",
564 "\\font_typewriter default",
565 "\\font_default_family default",
568 "\\font_sf_scale 100",
569 "\\font_tt_scale 100",
570 "\\graphics default",
571 "\\paperfontsize default",
572 "\\papersize default",
573 "\\use_geometry false",
575 "\\cite_engine basic",
576 "\\use_bibtopic false",
577 "\\paperorientation portrait",
580 "\\paragraph_separation indent",
582 "\\quotes_language english",
585 "\\paperpagestyle default",
586 "\\tracking_changes false",
589 self.format = get_end_format()
591 self.set_parameter(param, params[param])
594 def set_body(self, paragraphs):
595 self.body.extend(['\\begin_body',''])
597 for par in paragraphs:
598 self.body.extend(par.asLines())
600 self.body.extend(['','\\end_body', '\\end_document'])
604 # unfinished implementation, it is missing the Text and Insets representation.
605 " This class represents the LyX paragraphs."
606 def __init__(self, name, body=[], settings = [], child = []):
608 name: paragraph name.
609 body: list of lines of body text.
610 child: list of paragraphs that descend from this paragraph.
614 self.settings = settings
618 " Converts the paragraph to a list of strings, representing it in the LyX file."
619 result = ['','\\begin_layout %s' % self.name]
620 result.extend(self.settings)
622 result.extend(self.body)
623 result.append('\\end_layout')
628 result.append('\\begin_deeper')
629 for node in self.child:
630 result.extend(node.asLines())
631 result.append('\\end_deeper')
637 " This class represents the LyX insets."
642 " This class represents simple chuncks of text."