X-Git-Url: https://git.lyx.org/gitweb/?a=blobdiff_plain;f=lib%2Flyx2lyx%2FLyX.py;h=7e0276199b07d9f3c5b60fb27927942b076d0c1d;hb=9da74fe2078e24e1e7891784ecbfe33ff77e7f85;hp=081ad0f893bbedc2c079f45a9847d6a0e6c4dd43;hpb=0ef6b7c5fe1163f4583a23af9a969d54b6a300f3;p=lyx.git diff --git a/lib/lyx2lyx/LyX.py b/lib/lyx2lyx/LyX.py index 081ad0f893..7e0276199b 100644 --- a/lib/lyx2lyx/LyX.py +++ b/lib/lyx2lyx/LyX.py @@ -1,5 +1,6 @@ # This file is part of lyx2lyx # -*- coding: utf-8 -*- +# Copyright (C) 2002-2011 The LyX Team # Copyright (C) 2002-2004 Dekel Tsur # Copyright (C) 2002-2006 José Matos # @@ -15,7 +16,7 @@ # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA " The LyX module has all the rules related with different lyx file formats." @@ -32,7 +33,7 @@ try: import lyx2lyx_version version__ = lyx2lyx_version.version except: # we are running from build directory so assume the last version - version__ = '1.6.0svn' + version__ = '2.1' default_debug__ = 2 @@ -73,15 +74,29 @@ format_relation = [("0_06", [200], minor_versions("0.6" , 4)), ("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_1_5", [216], ["1.1", "1.1.5","1.1.5.1","1.1.5.2"]), + ("1_1_6_0", [217], ["1.1", "1.1.6","1.1.6.1","1.1.6.2"]), + ("1_1_6_3", [218], ["1.1", "1.1.6.3","1.1.6.4"]), ("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,304), minor_versions("1.6" , 0))] # Uwe: Serbocroatian + ("1_5", range(246,277), minor_versions("1.5" , 7)), + ("1_6", range(277,346), minor_versions("1.6" , 10)), + ("2_0", range(347,414), minor_versions("2.0", 0)), + ("2_1", [], minor_versions("2.1", 0)) + ] +#################################################################### +# This is useful just for development versions # +# if the list of supported formats is empty get it from last step # +if not format_relation[-1][1]: + step, mode = format_relation[-1][0], "convert" + convert = getattr(__import__("lyx_" + step), mode) + format_relation[-1] = (step, + [conv[0] for conv in convert], + format_relation[-1][2]) +# # +#################################################################### def formats_list(): " Returns a list with supported file formats." @@ -93,16 +108,37 @@ def formats_list(): return formats +def format_info(): + " Returns a list with supported file formats." + out = """Major version: + minor versions + formats +""" + for version in format_relation: + major = str(version[2][0]) + versions = str(version[2][1:]) + if len(version[1]) == 1: + formats = str(version[1][0]) + else: + formats = "%s - %s" % (version[1][-1], version[1][0]) + out += "%s\n\t%s\n\t%s\n\n" % (major, versions, formats) + return out + '\n' + + def get_end_format(): " Returns the more recent file format available." - return format_relation[-1][1][-1] + # this check will fail only when we have a new version + # and there is no format change yet. + if format_relation[-1][1]: + return format_relation[-1][1][-1] + return format_relation[-2][1][-1] def get_backend(textclass): " For _textclass_ returns its backend." if textclass == "linuxdoc" or textclass == "manpage": return "linuxdoc" - if textclass[:7] == "docbook": + if textclass.startswith("docbook") or textclass.startswith("agu-"): return "docbook" return "latex" @@ -132,6 +168,8 @@ def get_encoding(language, inputencoding, format, cjk_encoding): return lang[language][3] if inputencoding == "": return "latin1" + if inputencoding == "utf8x": + return "utf8" # python does not know the alias latin9 if inputencoding == "latin9": return "iso-8859-15" @@ -142,10 +180,10 @@ def get_encoding(language, inputencoding, format, cjk_encoding): # 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__, try_hard = 0, cjk_encoding = '', - language = "english", encoding = "auto"): + final_version = "", language = "english", encoding = "auto"): """Arguments: end_format: final format that the file should be converted. (integer) @@ -167,9 +205,37 @@ class LyX_base: if end_format: self.end_format = self.lyxformat(end_format) + + # In case the target version and format are both specified + # verify that they are compatible. If not send a warning + # and ignore the version. + if final_version: + message = "Incompatible version %s for specified format %d" % ( + final_version, self.end_format) + for version in format_relation: + if self.end_format in version[1]: + if final_version not in version[2]: + self.warning(message) + final_version = "" + elif final_version: + for version in format_relation: + if final_version in version[2]: + # set the last format for that version + self.end_format = version[1][-1] + break + else: + final_version = "" else: self.end_format = get_end_format() + if not final_version: + for step in format_relation: + if self.end_format in step[1]: + final_version = step[2][1] + self.final_version = final_version + self.warning("Final version: %s" % self.final_version, 10) + self.warning("Final format: %d" % self.end_format, 10) + self.backend = "latex" self.textclass = "article" # This is a hack: We use '' since we don't know the default @@ -195,7 +261,7 @@ class LyX_base: " Emits a warning and exits if not in try_hard mode." self.warning(message) if not self.try_hard: - self.warning("Quiting.") + self.warning("Quitting.") sys.exit(1) self.status = 2 @@ -220,10 +286,10 @@ class LyX_base: 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" @@ -245,6 +311,12 @@ class LyX_base: self.header.append(line) + i = find_token(self.header, '\\textclass', 0) + if i == -1: + self.warning("Malformed LyX file: Missing '\\textclass'.") + i = find_token(self.header, '\\lyxformat', 0) + 1 + self.header[i:i] = ['\\textclass article'] + self.textclass = get_value(self.header, "\\textclass", 0) self.backend = get_backend(self.textclass) self.format = self.read_format() @@ -258,6 +330,8 @@ class LyX_base: self.initial_version = self.read_version() # Second pass over header and preamble, now we know the file encoding + # Do not forget the textclass (Debian bug #700828) + self.textclass = self.textclass.decode(self.encoding) for i in range(len(self.header)): self.header[i] = self.header[i].decode(self.encoding) for i in range(len(self.preamble)): @@ -282,10 +356,7 @@ class LyX_base: 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:] + header = self.header[:i] + preamble + self.header[i:] else: header = self.header @@ -307,7 +378,7 @@ class LyX_base: try: gzip.open(input).readline() self.input = gzip.open(input) - self.output = gzip.GzipFile(mode="wb", fileobj=self.output) + self.output = gzip.GzipFile(mode="wb", fileobj=self.output) except: self.input = open(input) else: @@ -390,6 +461,56 @@ class LyX_base: self.header[i] = "\\textclass %s" % self.textclass + #Note that the module will be added at the END of the extant ones + def add_module(self, module): + i = find_token(self.header, "\\begin_modules", 0) + if i == -1: + #No modules yet included + i = find_token(self.header, "\\textclass", 0) + if i == -1: + self.warning("Malformed LyX document: No \\textclass!!") + return + modinfo = ["\\begin_modules", module, "\\end_modules"] + self.header[i + 1: i + 1] = modinfo + return + j = find_token(self.header, "\\end_modules", i) + if j == -1: + self.warning("(add_module)Malformed LyX document: No \\end_modules.") + return + k = find_token(self.header, module, i) + if k != -1 and k < j: + return + self.header.insert(j, module) + + + def get_module_list(self): + i = find_token(self.header, "\\begin_modules", 0) + if (i == -1): + return [] + j = find_token(self.header, "\\end_modules", i) + return self.header[i + 1 : j] + + + def set_module_list(self, mlist): + modbegin = find_token(self.header, "\\begin_modules", 0) + newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules'] + if (modbegin == -1): + #No modules yet included + tclass = find_token(self.header, "\\textclass", 0) + if tclass == -1: + self.warning("Malformed LyX document: No \\textclass!!") + return + modbegin = tclass + 1 + self.header[modbegin:modbegin] = newmodlist + return + modend = find_token(self.header, "\\end_modules", modbegin) + if modend == -1: + self.warning("(set_module_list)Malformed LyX document: No \\end_modules.") + return + newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules'] + self.header[modbegin:modend + 1] = newmodlist + + def set_parameter(self, param, value): " Set the value of the header parameter." i = find_token(self.header, '\\' + param, 0) @@ -409,16 +530,16 @@ class LyX_base: def convert(self): "Convert from current (self.format) to self.end_format." - mode, convertion_chain = self.chain() - self.warning("convertion chain: " + str(convertion_chain), 3) + mode, conversion_chain = self.chain() + self.warning("conversion chain: " + str(conversion_chain), 3) - for step in convertion_chain: + for step in conversion_chain: steps = getattr(__import__("lyx_" + step), mode) self.warning("Convertion step: %s - %s" % (step, mode), default_debug__ + 1) if not steps: - self.error("The convertion to an older " + self.error("The conversion to an older " "format (%s) is not implemented." % self.format) multi_conv = len(steps) != 1 @@ -451,7 +572,7 @@ class LyX_base: def chain(self): """ This is where all the decisions related with the - convertion are taken. It returns a list of modules needed to + conversion 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 @@ -490,13 +611,14 @@ class LyX_base: steps = [] if (initial_step, self.start) < (final_step, self.end_format): mode = "convert" - first_step = 1 + full_steps = [] for step in format_relation: - if initial_step <= step[0] <= final_step: - if first_step and len(step[1]) == 1: - first_step = 0 - continue - steps.append(step[0]) + if initial_step <= step[0] <= final_step and step[2][0] <= self.final_version: + full_steps.append(step) + if full_steps[0][1][-1] == self.format: + full_steps = full_steps[1:] + for step in full_steps: + steps.append(step[0]) else: mode = "revert" relation_format = format_relation[:] @@ -515,162 +637,167 @@ class LyX_base: 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} - allowed_insets = ['Quotes'] - allowed_parameters = ('\\paragraph_spacing', '\\noindent', - '\\align', '\\labelwidthstring', - "\\start_of_appendix", "\\leftindent") - sections = [] - for section in paragraphs_filter.keys(): - sections.append('\\begin_layout %s' % section) - - toc_par = [] - i = 0 - while 1: - i = find_tokens(self.body, sections, i) - if i == -1: - break - - j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout') - if j == -1: - self.warning('Incomplete file.', 0) - break - - section = self.body[i].split()[1] - if section[-1] == '*': - section = section[:-1] - - par = [] - - k = i + 1 - # skip paragraph parameters - 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 = self.body[k].split()[1] - end = find_end_of_inset(self.body, k) - if end == -1 or end > j: - self.warning('Malformed file.', 0) - - if inset in allowed_insets: - par.extend(self.body[k: end+1]) - k = end + 1 - else: - par.append(self.body[k]) - k += 1 - - # trim empty lines in the end. - while par and par[-1].strip() == '': - par.pop() - - toc_par.append(Paragraph(section, par)) - - i = j + 1 - - return toc_par +# Part of an unfinished attempt to make lyx2lyx gave a more +# structured view of the document. +# 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} +# allowed_insets = ['Quotes'] +# allowed_parameters = ('\\paragraph_spacing', '\\noindent', +# '\\align', '\\labelwidthstring', +# "\\start_of_appendix", "\\leftindent") +# sections = [] +# for section in paragraphs_filter.keys(): +# sections.append('\\begin_layout %s' % section) + +# toc_par = [] +# i = 0 +# while 1: +# i = find_tokens(self.body, sections, i) +# if i == -1: +# break + +# j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout') +# if j == -1: +# self.warning('Incomplete file.', 0) +# break + +# section = self.body[i].split()[1] +# if section[-1] == '*': +# section = section[:-1] + +# par = [] + +# k = i + 1 +# # skip paragraph parameters +# 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 = self.body[k].split()[1] +# end = find_end_of_inset(self.body, k) +# if end == -1 or end > j: +# self.warning('Malformed file.', 0) + +# if inset in allowed_insets: +# par.extend(self.body[k: end+1]) +# k = end + 1 +# else: +# par.append(self.body[k]) +# k += 1 + +# # trim empty lines in the end. +# while par and par[-1].strip() == '': +# par.pop() + +# toc_par.append(Paragraph(section, par)) + +# i = j + 1 + +# return toc_par class File(LyX_base): " This class reads existing LyX files." def __init__(self, end_format = 0, input = "", output = "", error = "", - debug = default_debug__, try_hard = 0, cjk_encoding = ''): + debug = default_debug__, try_hard = 0, cjk_encoding = '', + final_version = ''): LyX_base.__init__(self, end_format, input, output, error, - debug, try_hard, cjk_encoding) + debug, try_hard, cjk_encoding, final_version) self.read() -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/", - "\\lyxformat xxx", - "\\begin_document", - "\\begin_header", - "\\textclass article", - "\\language english", - "\\inputencoding auto", - "\\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", - "\\use_geometry false", - "\\use_amsmath 1", - "\\cite_engine basic", - "\\use_bibtopic false", - "\\paperorientation portrait", - "\\secnumdepth 3", - "\\tocdepth 3", - "\\paragraph_separation indent", - "\\defskip medskip", - "\\quotes_language english", - "\\papercolumns 1", - "\\papersides 1", - "\\paperpagestyle default", - "\\tracking_changes false", - "\\end_header"]) - - self.format = get_end_format() - for param in params: - self.set_parameter(param, params[param]) - - - def set_body(self, paragraphs): - self.body.extend(['\\begin_body','']) - - for par in paragraphs: - self.body.extend(par.asLines()) - - self.body.extend(['','\\end_body', '\\end_document']) - - -class Paragraph: - # unfinished implementation, it is missing the Text and Insets - # representation. - " This class represents the LyX paragraphs." - def __init__(self, name, body=[], settings = [], child = []): - """ Parameters: - name: paragraph name. - body: list of lines of body text. - child: list of paragraphs that descend from this paragraph. - """ - self.name = name - self.body = body - self.settings = settings - self.child = child - - def asLines(self): - """ 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('') - result.extend(self.body) - result.append('\\end_layout') - - if not self.child: - return result - - result.append('\\begin_deeper') - for node in self.child: - result.extend(node.asLines()) - result.append('\\end_deeper') - - return result +#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/", +# "\\lyxformat xxx", +# "\\begin_document", +# "\\begin_header", +# "\\textclass article", +# "\\language english", +# "\\inputencoding auto", +# "\\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", +# "\\use_geometry false", +# "\\use_amsmath 1", +# "\\cite_engine basic", +# "\\use_bibtopic false", +# "\\paperorientation portrait", +# "\\secnumdepth 3", +# "\\tocdepth 3", +# "\\paragraph_separation indent", +# "\\defskip medskip", +# "\\quotes_language english", +# "\\papercolumns 1", +# "\\papersides 1", +# "\\paperpagestyle default", +# "\\tracking_changes false", +# "\\end_header"]) + +# self.format = get_end_format() +# for param in params: +# self.set_parameter(param, params[param]) + + +# def set_body(self, paragraphs): +# self.body.extend(['\\begin_body','']) + +# for par in paragraphs: +# self.body.extend(par.asLines()) + +# self.body.extend(['','\\end_body', '\\end_document']) + + +# Part of an unfinished attempt to make lyx2lyx gave a more +# structured view of the document. +#class Paragraph: +# # unfinished implementation, it is missing the Text and Insets +# # representation. +# " This class represents the LyX paragraphs." +# def __init__(self, name, body=[], settings = [], child = []): +# """ Parameters: +# name: paragraph name. +# body: list of lines of body text. +# child: list of paragraphs that descend from this paragraph. +# """ +# self.name = name +# self.body = body +# self.settings = settings +# self.child = child + +# def asLines(self): +# """ 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('') +# result.extend(self.body) +# result.append('\\end_layout') + +# if not self.child: +# return result + +# result.append('\\begin_deeper') +# for node in self.child: +# result.extend(node.asLines()) +# result.append('\\end_deeper') + +# return result