X-Git-Url: https://git.lyx.org/gitweb/?a=blobdiff_plain;f=lib%2Flyx2lyx%2FLyX.py;h=55754c0a56ffefc4829bb627f8f9ed939f8c3cf8;hb=bb46fe5f0e94e768cc4269c1f8418479189bfa9a;hp=7d8016c082e7e80cc1a411805a8ff87ee7b8ece0;hpb=9745fb81877d211470580c5bdf67876e8f0baa5d;p=lyx.git diff --git a/lib/lyx2lyx/LyX.py b/lib/lyx2lyx/LyX.py index 7d8016c082..55754c0a56 100644 --- a/lib/lyx2lyx/LyX.py +++ b/lib/lyx2lyx/LyX.py @@ -1,6 +1,7 @@ # This file is part of lyx2lyx -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2002-2004 Dekel Tsur , José Matos +# -*- coding: utf-8 -*- +# Copyright (C) 2002-2004 Dekel Tsur +# Copyright (C) 2002-2006 José Matos # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License @@ -16,37 +17,70 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -from parser_tools import get_value, check_token, find_token,\ - find_tokens, find_end_of, find_end_of_inset +" The LyX module has all the rules related with different lyx file formats." + +from parser_tools import get_value, check_token, find_token, \ + find_tokens, find_end_of import os.path import gzip +import locale import sys import re -import string import time -version_lyx2lyx = "1.4.0cvs" -default_debug_level = 2 +try: + import lyx2lyx_version + version__ = lyx2lyx_version.version +except: # we are running from build directory so assume the last version + version__ = '1.6.0svn' + +default_debug__ = 2 + +#################################################################### +# Private helper functions + +def find_end_of_inset(lines, i): + " Find beginning of inset, where lines[i] is included." + return find_end_of(lines, i, "\\begin_inset", "\\end_inset") + +def minor_versions(major, last_minor_version): + """ Generate minor versions, using major as prefix and minor + versions from 0 until last_minor_version, plus the generic version. + + Example: + + minor_versions("1.2", 4) -> + [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"] + """ + return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)] + + +# End of helper functions +#################################################################### + # Regular expressions used format_re = re.compile(r"(\d)[\.,]?(\d\d)") fileformat = re.compile(r"\\lyxformat\s*(\S*)") -original_version = re.compile(r"\#LyX (\S*)") +original_version = re.compile(r".*?LyX ([\d.]*)") ## # file format information: # file, supported formats, stable release versions -format_relation = [("0_10", [210], ["0.10.7","0.10"]), - ("0_12", [215], ["0.12","0.12.1","0.12"]), - ("1_0_0", [215], ["1.0.0","1.0"]), - ("1_0_1", [215], ["1.0.1","1.0.2","1.0.3","1.0.4", "1.1.2","1.1"]), - ("1_1_4", [215], ["1.1.4","1.1"]), - ("1_1_5", [216], ["1.1.5","1.1.5fix1","1.1.5fix2","1.1"]), - ("1_1_6", [217], ["1.1.6","1.1.6fix1","1.1.6fix2","1.1"]), - ("1_1_6fix3", [218], ["1.1.6fix3","1.1.6fix4","1.1"]), - ("1_2", [220], ["1.2.0","1.2.1","1.2.3","1.2.4","1.2"]), - ("1_3", [221], ["1.3.0","1.3.1","1.3.2","1.3.3","1.3.4","1.3.5","1.3"]), - ("1_4", range(223,244), ["1.4.0cvs","1.4"])] +format_relation = [("0_06", [200], minor_versions("0.6" , 4)), + ("0_08", [210], minor_versions("0.8" , 6) + ["0.7"]), + ("0_10", [210], minor_versions("0.10", 7) + ["0.9"]), + ("0_12", [215], minor_versions("0.12", 1) + ["0.11"]), + ("1_0", [215], minor_versions("1.0" , 4)), + ("1_1", [215], minor_versions("1.1" , 4)), + ("1_1_5", [216], ["1.1.5","1.1.5.1","1.1.5.2","1.1"]), + ("1_1_6_0", [217], ["1.1.6","1.1.6.1","1.1.6.2","1.1"]), + ("1_1_6_3", [218], ["1.1.6.3","1.1.6.4","1.1"]), + ("1_2", [220], minor_versions("1.2" , 4)), + ("1_3", [221], minor_versions("1.3" , 7)), + ("1_4", range(222,246), minor_versions("1.4" , 5)), + ("1_5", range(246,277), minor_versions("1.5" , 2)), + ("1_6", range(277,298), minor_versions("1.6" , 0))] # Uwe: Albanian, lower Sorbian def formats_list(): @@ -73,12 +107,46 @@ def get_backend(textclass): return "latex" +def trim_eol(line): + " Remove end of line char(s)." + if line[-2:-1] == '\r': + return line[:-2] + else: + return line[:-1] + + +def get_encoding(language, inputencoding, format, cjk_encoding): + " Returns enconding of the lyx file" + if format > 248: + return "utf8" + # CJK-LyX encodes files using the current locale encoding. + # This means that files created by CJK-LyX can only be converted using + # the correct locale settings unless the encoding is given as commandline + # argument. + if cjk_encoding == 'auto': + return locale.getpreferredencoding() + elif cjk_encoding: + return cjk_encoding + from lyx2lyx_lang import lang + if inputencoding == "auto" or inputencoding == "default": + return lang[language][3] + if inputencoding == "": + return "latin1" + # python does not know the alias latin9 + if inputencoding == "latin9": + return "iso-8859-15" + return inputencoding + ## # Class # -class LyX_Base: +class LyX_base: """This class carries all the information of the LyX file.""" - def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0): + + def __init__(self, end_format = 0, input = "", output = "", error = "", + debug = default_debug__, try_hard = 0, cjk_encoding = '', + language = "english", encoding = "auto"): + """Arguments: end_format: final format that the file should be converted. (integer) input: the name of the input source, if empty resort to standard input. @@ -86,14 +154,7 @@ class LyX_Base: error: the name of the error file, if empty use the standard error. debug: debug level, O means no debug, as its value increases be more verbose. """ - if input and input != '-': - self.input = self.open(input) - else: - self.input = sys.stdin - if output: - self.output = open(output, "w") - else: - self.output = sys.stdout + self.choose_io(input, output) if error: self.err = open(error, "w") @@ -102,6 +163,7 @@ class LyX_Base: self.debug = debug self.try_hard = try_hard + self.cjk_encoding = cjk_encoding if end_format: self.end_format = self.lyxformat(end_format) @@ -110,13 +172,21 @@ class LyX_Base: self.backend = "latex" self.textclass = "article" + # This is a hack: We use '' since we don't know the default + # layout of the text class. LyX will parse it as default layout. + # FIXME: Read the layout file and use the real default layout + self.default_layout = '' self.header = [] + self.preamble = [] self.body = [] self.status = 0 + self.encoding = encoding + self.language = language - def warning(self, message, debug_level= default_debug_level): - " Emits warning to self.error, if the debug_level is less than the self.debug." + def warning(self, message, debug_level= default_debug__): + """ Emits warning to self.error, if the debug_level is less + than the self.debug.""" if debug_level <= self.debug: self.err.write("Warning: " + message + "\n") @@ -132,78 +202,117 @@ class LyX_Base: def read(self): - """Reads a file into the self.header and self.body parts, from self.input.""" - preamble = 0 + """Reads a file into the self.header and + self.body parts, from self.input.""" - while 1: + while True: line = self.input.readline() if not line: self.error("Invalid LyX file.") - line = line[:-1] - # remove '\r' from line's end, if present - if line[-1:] == '\r': - line = line[:-1] - + line = trim_eol(line) if check_token(line, '\\begin_preamble'): - preamble = 1 - if check_token(line, '\\end_preamble'): - preamble = 0 + while 1: + line = self.input.readline() + if not line: + self.error("Invalid LyX file.") + + line = trim_eol(line) + if check_token(line, '\\end_preamble'): + break + + if line.split()[:0] in ("\\layout", + "\\begin_layout", "\\begin_body"): + + self.warning("Malformed LyX file:" + "Missing '\\end_preamble'." + "\nAdding it now and hoping" + "for the best.") + + self.preamble.append(line) - if not preamble: - line = string.strip(line) + if check_token(line, '\\end_preamble'): + continue - if not preamble: - if not line: - continue + line = line.strip() + if not line: + continue - if string.split(line)[0] in ("\\layout", "\\begin_layout", "\\begin_body"): - self.body.append(line) - break + if line.split()[0] in ("\\layout", "\\begin_layout", + "\\begin_body", "\\begin_deeper"): + self.body.append(line) + break self.header.append(line) - while 1: - line = self.input.readline() - if not line: - break - # remove '\r' from line's end, if present - if line[-2:-1] == '\r': - self.body.append(line[:-2]) - else: - self.body.append(line[:-1]) - self.textclass = get_value(self.header, "\\textclass", 0) self.backend = get_backend(self.textclass) self.format = self.read_format() - self.language = get_value(self.header, "\\language", 0) - if self.language == "": - self.language = "english" + self.language = get_value(self.header, "\\language", 0, + default = "english") + self.inputencoding = get_value(self.header, "\\inputencoding", + 0, default = "auto") + self.encoding = get_encoding(self.language, + self.inputencoding, self.format, + self.cjk_encoding) self.initial_version = self.read_version() + # Second pass over header and preamble, now we know the file encoding + for i in range(len(self.header)): + self.header[i] = self.header[i].decode(self.encoding) + for i in range(len(self.preamble)): + self.preamble[i] = self.preamble[i].decode(self.encoding) + + # Read document body + while 1: + line = self.input.readline().decode(self.encoding) + if not line: + break + self.body.append(trim_eol(line)) + def write(self): " Writes the LyX file to self.output." self.set_version() self.set_format() + self.set_textclass() + if self.encoding == "auto": + self.encoding = get_encoding(self.language, self.encoding, + self.format, self.cjk_encoding) + if self.preamble: + i = find_token(self.header, '\\textclass', 0) + 1 + preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble'] + if i == 0: + self.error("Malformed LyX file: Missing '\\textclass'.") + else: + header = self.header[:i] + preamble + self.header[i:] + else: + header = self.header - for line in self.header: - self.output.write(line+"\n") - self.output.write("\n") - for line in self.body: - self.output.write(line+"\n") + for line in header + [''] + self.body: + self.output.write(line.encode(self.encoding)+"\n") - def open(self, file): - """Transparently deals with compressed files.""" + def choose_io(self, input, output): + """Choose input and output streams, dealing transparently with + compressed files.""" - self.dir = os.path.dirname(os.path.abspath(file)) - try: - gzip.open(file).readline() - self.output = gzip.GzipFile("","wb",6,self.output) - return gzip.open(file) - except: - return open(file) + if output: + self.output = open(output, "wb") + else: + self.output = sys.stdout + + if input and input != '-': + self.dir = os.path.dirname(os.path.abspath(input)) + try: + gzip.open(input).readline() + self.input = gzip.open(input) + self.output = gzip.GzipFile(mode="wb", fileobj=self.output) + except: + self.input = open(input) + else: + self.dir = '' + self.input = sys.stdin def lyxformat(self, format): @@ -211,6 +320,8 @@ class LyX_Base: result = format_re.match(format) if result: format = int(result.group(1) + result.group(2)) + elif format == '2': + format = 200 else: self.error(str(format) + ": " + "Invalid LyX file.") @@ -222,21 +333,33 @@ class LyX_Base: def read_version(self): - """ Searchs for clues of the LyX version used to write the file, returns the - most likely value, or None otherwise.""" + """ Searchs for clues of the LyX version used to write the + file, returns the most likely value, or None otherwise.""" + for line in self.header: if line[0] != "#": return None + line = line.replace("fix",".") result = original_version.match(line) if result: - return result.group(1) + # Special know cases: reLyX and KLyX + if line.find("reLyX") != -1 or line.find("KLyX") != -1: + return "0.12" + + res = result.group(1) + if not res: + self.warning(line) + #self.warning("Version %s" % result.group(1)) + return res + self.warning(str(self.header[:2])) return None def set_version(self): " Set the header with the version used." - self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version_lyx2lyx + self.header[0] = " ".join(["#LyX %s created this file." % version__, + "For more info see http://www.lyx.org/"]) if self.header[1][0] == '#': del self.header[1] @@ -262,15 +385,28 @@ class LyX_Base: self.header[i] = "\\lyxformat %s" % format + def set_textclass(self): + i = find_token(self.header, "\\textclass", 0) + self.header[i] = "\\textclass %s" % self.textclass + + def set_parameter(self, param, value): " Set the value of the header parameter." i = find_token(self.header, '\\' + param, 0) if i == -1: - self.warning(3, 'Parameter not found in the header: %s' % param) + self.warning('Parameter not found in the header: %s' % param, 3) return self.header[i] = '\\%s %s' % (param, str(value)) + def is_default_layout(self, layout): + " Check whether a layout is the default layout of this class." + # FIXME: Check against the real text class default layout + if layout == 'Standard' or layout == self.default_layout: + return 1 + return 0 + + def convert(self): "Convert from current (self.format) to self.end_format." mode, convertion_chain = self.chain() @@ -279,9 +415,11 @@ class LyX_Base: for step in convertion_chain: steps = getattr(__import__("lyx_" + step), mode) - self.warning("Convertion step: %s - %s" % (step, mode), default_debug_level + 1) + self.warning("Convertion step: %s - %s" % (step, mode), + default_debug__ + 1) if not steps: - self.error("The convertion to an older format (%s) is not implemented." % self.format) + self.error("The convertion to an older " + "format (%s) is not implemented." % self.format) multi_conv = len(steps) != 1 for version, table in steps: @@ -295,24 +433,26 @@ class LyX_Base: try: conv(self) except: - self.warning("An error ocurred in %s, %s" % (version, str(conv)), - default_debug_level) + self.warning("An error ocurred in %s, %s" % + (version, str(conv)), + default_debug__) if not self.try_hard: raise self.status = 2 else: - self.warning("%lf: Elapsed time on %s" % (time.time() - init_t, str(conv)), - default_debug_level + 1) - + self.warning("%lf: Elapsed time on %s" % + (time.time() - init_t, + str(conv)), default_debug__ + + 1) self.format = version if self.end_format == self.format: return def chain(self): - """ This is where all the decisions related with the convertion are taken. - It returns a list of modules needed to convert the LyX file from - self.format to self.end_format""" + """ This is where all the decisions related with the + convertion are taken. It returns a list of modules needed to + convert the LyX file from self.format to self.end_format""" self.start = self.format format = self.format @@ -327,7 +467,9 @@ class LyX_Base: if not correct_version: if format <= 215: - self.warning("Version does not match file format, discarding it.") + self.warning("Version does not match file format, " + "discarding it. (Version %s, format %d)" % + (self.initial_version, self.format)) for rel in format_relation: if format in rel[1]: initial_step = rel[0] @@ -357,7 +499,7 @@ class LyX_Base: steps.append(step[0]) else: mode = "revert" - relation_format = format_relation + relation_format = format_relation[:] relation_format.reverse() last_step = None @@ -369,15 +511,18 @@ class LyX_Base: if last_step[1][-1] == self.end_format: steps.pop() + self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10) return mode, steps def get_toc(self, depth = 4): " Returns the TOC of this LyX document." - paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, 'Subsection' : 3, 'Subsubsection': 4} + paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, + 'Subsection' : 3, 'Subsubsection': 4} allowed_insets = ['Quotes'] - allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix" - + allowed_parameters = ('\\paragraph_spacing', '\\noindent', + '\\align', '\\labelwidthstring', + "\\start_of_appendix", "\\leftindent") sections = [] for section in paragraphs_filter.keys(): sections.append('\\begin_layout %s' % section) @@ -394,7 +539,7 @@ class LyX_Base: self.warning('Incomplete file.', 0) break - section = string.split(self.body[i])[1] + section = self.body[i].split()[1] if section[-1] == '*': section = section[:-1] @@ -402,12 +547,13 @@ class LyX_Base: k = i + 1 # skip paragraph parameters - while not string.strip(self.body[k]) and string.split(self.body[k])[0] in allowed_parameters: - k = k +1 + while not self.body[k].strip() or self.body[k].split()[0] \ + in allowed_parameters: + k += 1 while k < j: if check_token(self.body[k], '\\begin_inset'): - inset = string.split(self.body[k])[1] + inset = self.body[k].split()[1] end = find_end_of_inset(self.body, k) if end == -1 or end > j: self.warning('Malformed file.', 0) @@ -417,10 +563,10 @@ class LyX_Base: k = end + 1 else: par.append(self.body[k]) - k = k + 1 + k += 1 # trim empty lines in the end. - while string.strip(par[-1]) == '' and par: + while par and par[-1].strip() == '': par.pop() toc_par.append(Paragraph(section, par)) @@ -430,30 +576,40 @@ class LyX_Base: return toc_par -class File(LyX_Base): +class File(LyX_base): " This class reads existing LyX files." - def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0): - LyX_Base.__init__(self, end_format, input, output, error, debug, try_hard) + + def __init__(self, end_format = 0, input = "", output = "", error = "", + debug = default_debug__, try_hard = 0, cjk_encoding = ''): + LyX_base.__init__(self, end_format, input, output, error, + debug, try_hard, cjk_encoding) self.read() -class NewFile(LyX_Base): +class NewFile(LyX_base): " This class is to create new LyX files." def set_header(self, **params): # set default values self.header.extend([ - "#LyX xxxx created this file. For more info see http://www.lyx.org/", + "#LyX xxxx created this file." + "For more info see http://www.lyx.org/", "\\lyxformat xxx", "\\begin_document", "\\begin_header", "\\textclass article", "\\language english", "\\inputencoding auto", - "\\fontscheme default", + "\\font_roman default", + "\\font_sans default", + "\\font_typewriter default", + "\\font_default_family default", + "\\font_sc false", + "\\font_osf false", + "\\font_sf_scale 100", + "\\font_tt_scale 100", "\\graphics default", "\\paperfontsize default", "\\papersize default", - "\\paperpackage none", "\\use_geometry false", "\\use_amsmath 1", "\\cite_engine basic", @@ -464,7 +620,6 @@ class NewFile(LyX_Base): "\\paragraph_separation indent", "\\defskip medskip", "\\quotes_language english", - "\\quotes_times 2", "\\papercolumns 1", "\\papersides 1", "\\paperpagestyle default", @@ -486,7 +641,8 @@ class NewFile(LyX_Base): class Paragraph: - # unfinished implementation, it is missing the Text and Insets representation. + # unfinished implementation, it is missing the Text and Insets + # representation. " This class represents the LyX paragraphs." def __init__(self, name, body=[], settings = [], child = []): """ Parameters: @@ -500,7 +656,9 @@ class Paragraph: self.child = child def asLines(self): - " Converts the paragraph to a list of strings, representing it in the LyX file." + """ Converts the paragraph to a list of strings, representing + it in the LyX file.""" + result = ['','\\begin_layout %s' % self.name] result.extend(self.settings) result.append('') @@ -516,13 +674,3 @@ class Paragraph: result.append('\\end_deeper') return result - - -class Inset: - " This class represents the LyX insets." - pass - - -class Text: - " This class represents simple chuncks of text." - pass