]> git.lyx.org Git - features.git/blob - lib/lyx2lyx/LyX.py
Set \origin correctly when upgrading docs
[features.git] / lib / lyx2lyx / LyX.py
1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2002-2015 The LyX Team
4 # Copyright (C) 2002-2004 Dekel Tsur <dekel@lyx.org>
5 # Copyright (C) 2002-2006 José Matos <jamatos@lyx.org>
6 #
7 # This program is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License
9 # as published by the Free Software Foundation; either version 2
10 # of the License, or (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20
21 " The LyX module has all the rules related with different lyx file formats."
22
23 from parser_tools import get_value, check_token, find_token, \
24      find_tokens, find_end_of
25 import os.path
26 import gzip
27 import locale
28 import sys
29 import re
30 import time
31
32 try:
33     import lyx2lyx_version
34     version__ = lyx2lyx_version.version
35 except: # we are running from build directory so assume the last version
36     version__ = '2.2'
37
38 default_debug__ = 2
39
40 ####################################################################
41 # Private helper functions
42
43 def find_end_of_inset(lines, i):
44     " Find beginning of inset, where lines[i] is included."
45     return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
46
47 def minor_versions(major, last_minor_version):
48     """ Generate minor versions, using major as prefix and minor
49     versions from 0 until last_minor_version, plus the generic version.
50
51     Example:
52
53       minor_versions("1.2", 4) ->
54       [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
55     """
56     return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
57
58
59 # End of helper functions
60 ####################################################################
61
62
63 # Regular expressions used
64 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
65 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
66 original_version = re.compile(r".*?LyX ([\d.]*)")
67 original_tex2lyx_version = re.compile(r".*?tex2lyx ([\d.]*)")
68
69 ##
70 # file format information:
71 #  file, supported formats, stable release versions
72 format_relation = [("0_06",    [200], minor_versions("0.6" , 4)),
73                    ("0_08",    [210], minor_versions("0.8" , 6) + ["0.7"]),
74                    ("0_10",    [210], minor_versions("0.10", 7) + ["0.9"]),
75                    ("0_12",    [215], minor_versions("0.12", 1) + ["0.11"]),
76                    ("1_0",     [215], minor_versions("1.0" , 4)),
77                    ("1_1",     [215], minor_versions("1.1" , 4)),
78                    ("1_1_5",   [216], ["1.1", "1.1.5","1.1.5.1","1.1.5.2"]),
79                    ("1_1_6_0", [217], ["1.1", "1.1.6","1.1.6.1","1.1.6.2"]),
80                    ("1_1_6_3", [218], ["1.1", "1.1.6.3","1.1.6.4"]),
81                    ("1_2",     [220], minor_versions("1.2" , 4)),
82                    ("1_3",     [221], minor_versions("1.3" , 7)),
83                    ("1_4", list(range(222,246)), minor_versions("1.4" , 5)),
84                    ("1_5", list(range(246,277)), minor_versions("1.5" , 7)),
85                    ("1_6", list(range(277,346)), minor_versions("1.6" , 10)),
86                    ("2_0", list(range(346,414)), minor_versions("2.0" , 8)),
87                    ("2_1", list(range(414,475)), minor_versions("2.1" , 0)),
88                    ("2_2", list(range(475,502)), minor_versions("2.2" , 0))
89                   ]
90
91 ####################################################################
92 # This is useful just for development versions                     #
93 # if the list of supported formats is empty get it from last step  #
94 if not format_relation[-1][1]:
95     step, mode = format_relation[-1][0], "convert"
96     convert = getattr(__import__("lyx_" + step), mode)
97     format_relation[-1] = (step,
98                            [conv[0] for conv in convert],
99                            format_relation[-1][2])
100 #                                                                  #
101 ####################################################################
102
103 def formats_list():
104     " Returns a list with supported file formats."
105     formats = []
106     for version in format_relation:
107         for format in version[1]:
108             if format not in formats:
109                 formats.append(format)
110     return formats
111
112
113 def format_info():
114     " Returns a list with supported file formats."
115     out = """Major version:
116         minor versions
117         formats
118 """
119     for version in format_relation:
120         major = str(version[2][0])
121         versions = str(version[2][1:])
122         if len(version[1]) == 1:
123             formats = str(version[1][0])
124         else:
125             formats = "%s - %s" % (version[1][-1], version[1][0])
126         out += "%s\n\t%s\n\t%s\n\n" % (major, versions, formats)
127     return out + '\n'
128
129
130 def get_end_format():
131     " Returns the more recent file format available."
132     # this check will fail only when we have a new version
133     # and there is no format change yet.
134     if format_relation[-1][1]:
135       return format_relation[-1][1][-1]
136     return format_relation[-2][1][-1]
137
138
139 def get_backend(textclass):
140     " For _textclass_ returns its backend."
141     if textclass == "linuxdoc" or textclass == "manpage":
142         return "linuxdoc"
143     if textclass.startswith("docbook") or textclass.startswith("agu-"):
144         return "docbook"
145     return "latex"
146
147
148 def trim_eol(line):
149     " Remove end of line char(s)."
150     if line[-1] != '\n' and line[-1] != '\r':
151         # May happen for the last line of a document
152         return line
153     if line[-2:-1] == '\r':
154         return line[:-2]
155     else:
156         return line[:-1]
157
158
159 def get_encoding(language, inputencoding, format, cjk_encoding):
160     " Returns enconding of the lyx file"
161     if format > 248:
162         return "utf8"
163     # CJK-LyX encodes files using the current locale encoding.
164     # This means that files created by CJK-LyX can only be converted using
165     # the correct locale settings unless the encoding is given as commandline
166     # argument.
167     if cjk_encoding == 'auto':
168         return locale.getpreferredencoding()
169     elif cjk_encoding:
170         return cjk_encoding
171     from lyx2lyx_lang import lang
172     if inputencoding == "auto" or inputencoding == "default":
173         return lang[language][3]
174     if inputencoding == "":
175         return "latin1"
176     if inputencoding == "utf8x":
177         return "utf8"
178     # python does not know the alias latin9
179     if inputencoding == "latin9":
180         return "iso-8859-15"
181     return inputencoding
182
183 ##
184 # Class
185 #
186 class LyX_base:
187     """This class carries all the information of the LyX file."""
188
189     def __init__(self, end_format = 0, input = "", output = "", error = "",
190                  debug = default_debug__, try_hard = 0, cjk_encoding = '',
191                  final_version = "", systemlyxdir = '', language = "english",
192                  encoding = "auto"):
193
194         """Arguments:
195         end_format: final format that the file should be converted. (integer)
196         input: the name of the input source, if empty resort to standard input.
197         output: the name of the output file, if empty use the standard output.
198         error: the name of the error file, if empty use the standard error.
199         debug: debug level, O means no debug, as its value increases be more verbose.
200         """
201         self.choose_io(input, output)
202
203         if error:
204             self.err = open(error, "w")
205         else:
206             self.err = sys.stderr
207
208         self.debug = debug
209         self.try_hard = try_hard
210         self.cjk_encoding = cjk_encoding
211
212         if end_format:
213             self.end_format = self.lyxformat(end_format)
214
215             # In case the target version and format are both specified
216             # verify that they are compatible. If not send a warning
217             # and ignore the version.
218             if final_version:
219                 message = "Incompatible version %s for specified format %d" % (
220                     final_version, self.end_format)
221                 for version in format_relation:
222                     if self.end_format in version[1]:
223                         if final_version not in version[2]:
224                             self.warning(message)
225                             final_version = ""
226         elif final_version:
227             for version in format_relation:
228                 if final_version in version[2]:
229                     # set the last format for that version
230                     self.end_format = version[1][-1]
231                     break
232             else:
233                 final_version = ""
234         else:
235             self.end_format = get_end_format()
236
237         if not final_version:
238             for step in format_relation:
239                 if self.end_format in step[1]:
240                     final_version = step[2][1]
241         self.final_version = final_version
242         self.warning("Final version: %s" % self.final_version, 10)
243         self.warning("Final format: %d" % self.end_format, 10)
244
245         self.backend = "latex"
246         self.textclass = "article"
247         # This is a hack: We use '' since we don't know the default
248         # layout of the text class. LyX will parse it as default layout.
249         # FIXME: Read the layout file and use the real default layout
250         self.default_layout = ''
251         self.header = []
252         self.preamble = []
253         self.body = []
254         self.status = 0
255         self.encoding = encoding
256         self.language = language
257         self.systemlyxdir = systemlyxdir
258
259
260     def warning(self, message, debug_level= default_debug__):
261         """ Emits warning to self.error, if the debug_level is less
262         than the self.debug."""
263         if debug_level <= self.debug:
264             self.err.write("Warning: " + message + "\n")
265
266
267     def error(self, message):
268         " Emits a warning and exits if not in try_hard mode."
269         self.warning(message)
270         if not self.try_hard:
271             self.warning("Quitting.")
272             sys.exit(1)
273
274         self.status = 2
275
276
277     def read(self):
278         """Reads a file into the self.header and
279         self.body parts, from self.input."""
280
281         while True:
282             line = self.input.readline()
283             if not line:
284                 self.error("Invalid LyX file.")
285
286             line = trim_eol(line)
287             if check_token(line, '\\begin_preamble'):
288                 while 1:
289                     line = self.input.readline()
290                     if not line:
291                         self.error("Invalid LyX file.")
292
293                     line = trim_eol(line)
294                     if check_token(line, '\\end_preamble'):
295                         break
296
297                     if line.split()[:0] in ("\\layout",
298                                             "\\begin_layout", "\\begin_body"):
299
300                         self.warning("Malformed LyX file:"
301                                      "Missing '\\end_preamble'."
302                                      "\nAdding it now and hoping"
303                                      "for the best.")
304
305                     self.preamble.append(line)
306
307             if check_token(line, '\\end_preamble'):
308                 continue
309
310             line = line.strip()
311             if not line:
312                 continue
313
314             if line.split()[0] in ("\\layout", "\\begin_layout",
315                                    "\\begin_body", "\\begin_deeper"):
316                 self.body.append(line)
317                 break
318
319             self.header.append(line)
320
321         i = find_token(self.header, '\\textclass', 0)
322         if i == -1:
323             self.warning("Malformed LyX file: Missing '\\textclass'.")
324             i = find_token(self.header, '\\lyxformat', 0) + 1
325             self.header[i:i] = ['\\textclass article']
326
327         self.textclass = get_value(self.header, "\\textclass", 0)
328         self.backend = get_backend(self.textclass)
329         self.format  = self.read_format()
330         self.language = get_value(self.header, "\\language", 0,
331                                   default = "english")
332         self.inputencoding = get_value(self.header, "\\inputencoding",
333                                        0, default = "auto")
334         self.encoding = get_encoding(self.language,
335                                      self.inputencoding, self.format,
336                                      self.cjk_encoding)
337         self.initial_version = self.read_version()
338
339         # Second pass over header and preamble, now we know the file encoding
340         # Do not forget the textclass (Debian bug #700828)
341         self.textclass = self.textclass.decode(self.encoding)
342         for i in range(len(self.header)):
343             self.header[i] = self.header[i].decode(self.encoding)
344         for i in range(len(self.preamble)):
345             self.preamble[i] = self.preamble[i].decode(self.encoding)
346
347         # Read document body
348         while 1:
349             line = self.input.readline().decode(self.encoding)
350             if not line:
351                 break
352             self.body.append(trim_eol(line))
353
354
355     def write(self):
356         " Writes the LyX file to self.output."
357         self.set_version()
358         self.set_format()
359         self.set_textclass()
360         if self.encoding == "auto":
361             self.encoding = get_encoding(self.language, self.encoding,
362                                          self.format, self.cjk_encoding)
363         if self.preamble:
364             i = find_token(self.header, '\\textclass', 0) + 1
365             preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
366             header = self.header[:i] + preamble + self.header[i:]
367         else:
368             header = self.header
369
370         for line in header + [''] + self.body:
371             self.output.write(line.encode(self.encoding)+"\n")
372
373
374     def choose_io(self, input, output):
375         """Choose input and output streams, dealing transparently with
376         compressed files."""
377
378         if output:
379             self.output = open(output, "wb")
380         else:
381             self.output = sys.stdout
382
383         if input and input != '-':
384             self.dir = os.path.dirname(os.path.abspath(input))
385             try:
386                 gzip.open(input).readline()
387                 self.input = gzip.open(input)
388                 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
389             except:
390                 self.input = open(input)
391         else:
392             self.dir = ''
393             self.input = sys.stdin
394
395
396     def lyxformat(self, format):
397         " Returns the file format representation, an integer."
398         result = format_re.match(format)
399         if result:
400             format = int(result.group(1) + result.group(2))
401         elif format == '2':
402             format = 200
403         else:
404             self.error(str(format) + ": " + "Invalid LyX file.")
405
406         if format in formats_list():
407             return format
408
409         self.error(str(format) + ": " + "Format not supported.")
410         return None
411
412
413     def read_version(self):
414         """ Searchs for clues of the LyX version used to write the
415         file, returns the most likely value, or None otherwise."""
416
417         for line in self.header:
418             if line[0] != "#":
419                 return None
420
421             line = line.replace("fix",".")
422             # need to test original_tex2lyx_version first because tex2lyx
423             # writes "#LyX file created by tex2lyx 2.2"
424             result = original_tex2lyx_version.match(line)
425             if not result:
426                 result = original_version.match(line)
427                 if result:
428                     # Special know cases: reLyX and KLyX
429                     if line.find("reLyX") != -1 or line.find("KLyX") != -1:
430                         return "0.12"
431             if result:
432                 res = result.group(1)
433                 if not res:
434                     self.warning(line)
435                 #self.warning("Version %s" % result.group(1))
436                 return res
437         self.warning(str(self.header[:2]))
438         return None
439
440
441     def set_version(self):
442         " Set the header with the version used."
443
444         initial_comment = " ".join(["#LyX %s created this file." % version__,
445                                     "For more info see http://www.lyx.org/"])
446
447         # Simple heuristic to determine the comment that always starts
448         # a lyx file
449         if self.header[0].startswith("#"):
450             self.header[0] = initial_comment
451         else:
452             self.header.insert(0, initial_comment)
453
454         # Old lyx files had a two lines comment header:
455         # 1) the first line had the user who had created it
456         # 2) the second line had the lyx version used
457         # later we decided that 1) was a privacy risk for no gain
458         # here we remove the second line effectively erasing 1)
459         if self.header[1][0] == '#':
460             del self.header[1]
461
462
463     def read_format(self):
464         " Read from the header the fileformat of the present LyX file."
465         for line in self.header:
466             result = fileformat.match(line)
467             if result:
468                 return self.lyxformat(result.group(1))
469         else:
470             self.error("Invalid LyX File.")
471         return None
472
473
474     def set_format(self):
475         " Set the file format of the file, in the header."
476         if self.format <= 217:
477             format = str(float(self.format)/100)
478         else:
479             format = str(self.format)
480         i = find_token(self.header, "\\lyxformat", 0)
481         self.header[i] = "\\lyxformat %s" % format
482
483
484     def set_textclass(self):
485         i = find_token(self.header, "\\textclass", 0)
486         self.header[i] = "\\textclass %s" % self.textclass
487
488
489     #Note that the module will be added at the END of the extant ones
490     def add_module(self, module):
491       i = find_token(self.header, "\\begin_modules", 0)
492       if i == -1:
493         #No modules yet included
494         i = find_token(self.header, "\\textclass", 0)
495         if i == -1:
496           self.warning("Malformed LyX document: No \\textclass!!")
497           return
498         modinfo = ["\\begin_modules", module, "\\end_modules"]
499         self.header[i + 1: i + 1] = modinfo
500         return
501       j = find_token(self.header, "\\end_modules", i)
502       if j == -1:
503         self.warning("(add_module)Malformed LyX document: No \\end_modules.")
504         return
505       k = find_token(self.header, module, i)
506       if k != -1 and k < j:
507         return
508       self.header.insert(j, module)
509
510
511     def get_module_list(self):
512       i = find_token(self.header, "\\begin_modules", 0)
513       if (i == -1):
514         return []
515       j = find_token(self.header, "\\end_modules", i)
516       return self.header[i + 1 : j]
517
518
519     def set_module_list(self, mlist):
520       modbegin = find_token(self.header, "\\begin_modules", 0)
521       newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
522       if (modbegin == -1):
523         #No modules yet included
524         tclass = find_token(self.header, "\\textclass", 0)
525         if tclass == -1:
526           self.warning("Malformed LyX document: No \\textclass!!")
527           return
528         modbegin = tclass + 1
529         self.header[modbegin:modbegin] = newmodlist
530         return
531       modend = find_token(self.header, "\\end_modules", modbegin)
532       if modend == -1:
533         self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
534         return
535       newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
536       self.header[modbegin:modend + 1] = newmodlist
537
538
539     def set_parameter(self, param, value):
540         " Set the value of the header parameter."
541         i = find_token(self.header, '\\' + param, 0)
542         if i == -1:
543             self.warning('Parameter not found in the header: %s' % param, 3)
544             return
545         self.header[i] = '\\%s %s' % (param, str(value))
546
547
548     def is_default_layout(self, layout):
549         " Check whether a layout is the default layout of this class."
550         # FIXME: Check against the real text class default layout
551         if layout == 'Standard' or layout == self.default_layout:
552             return 1
553         return 0
554
555
556     def convert(self):
557         "Convert from current (self.format) to self.end_format."
558         if self.format == self.end_format:
559             self.warning("No conversion needed: Target format %s "
560                 "same as current format!" % self.format, default_debug__)
561             return
562
563         mode, conversion_chain = self.chain()
564         self.warning("conversion chain: " + str(conversion_chain), 3)
565
566         for step in conversion_chain:
567             steps = getattr(__import__("lyx_" + step), mode)
568
569             self.warning("Convertion step: %s - %s" % (step, mode),
570                          default_debug__ + 1)
571             if not steps:
572                 self.error("The conversion to an older "
573                 "format (%s) is not implemented." % self.format)
574
575             multi_conv = len(steps) != 1
576             for version, table in steps:
577                 if multi_conv and \
578                    (self.format >= version and mode == "convert") or\
579                    (self.format <= version and mode == "revert"):
580                     continue
581
582                 for conv in table:
583                     init_t = time.time()
584                     try:
585                         conv(self)
586                     except:
587                         self.warning("An error ocurred in %s, %s" %
588                                      (version, str(conv)),
589                                      default_debug__)
590                         if not self.try_hard:
591                             raise
592                         self.status = 2
593                     else:
594                         self.warning("%lf: Elapsed time on %s" %
595                                      (time.time() - init_t,
596                                       str(conv)), default_debug__ +
597                                      1)
598                 self.format = version
599                 if self.end_format == self.format:
600                     return
601
602
603     def chain(self):
604         """ This is where all the decisions related with the
605         conversion are taken.  It returns a list of modules needed to
606         convert the LyX file from self.format to self.end_format"""
607
608         self.start =  self.format
609         format = self.format
610         correct_version = 0
611
612         for rel in format_relation:
613             if self.initial_version in rel[2]:
614                 if format in rel[1]:
615                     initial_step = rel[0]
616                     correct_version = 1
617                     break
618
619         if not correct_version:
620             if format <= 215:
621                 self.warning("Version does not match file format, "
622                              "discarding it. (Version %s, format %d)" %
623                              (self.initial_version, self.format))
624             for rel in format_relation:
625                 if format in rel[1]:
626                     initial_step = rel[0]
627                     break
628             else:
629                 # This should not happen, really.
630                 self.error("Format not supported.")
631
632         # Find the final step
633         for rel in format_relation:
634             if self.end_format in rel[1]:
635                 final_step = rel[0]
636                 break
637         else:
638             self.error("Format not supported.")
639
640         # Convertion mode, back or forth
641         steps = []
642         if (initial_step, self.start) < (final_step, self.end_format):
643             mode = "convert"
644             full_steps = []
645             for step in format_relation:
646                 if  initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
647                     full_steps.append(step)
648             if full_steps[0][1][-1] == self.format:
649                 full_steps = full_steps[1:]
650             for step in full_steps:
651                 steps.append(step[0])
652         else:
653             mode = "revert"
654             relation_format = format_relation[:]
655             relation_format.reverse()
656             last_step = None
657
658             for step in relation_format:
659                 if  final_step <= step[0] <= initial_step:
660                     steps.append(step[0])
661                     last_step = step
662
663             if last_step[1][-1] == self.end_format:
664                 steps.pop()
665
666         self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
667         return mode, steps
668
669
670 # Part of an unfinished attempt to make lyx2lyx gave a more
671 # structured view of the document.
672 #    def get_toc(self, depth = 4):
673 #        " Returns the TOC of this LyX document."
674 #        paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
675 #                             'Subsection' : 3, 'Subsubsection': 4}
676 #        allowed_insets = ['Quotes']
677 #        allowed_parameters = ('\\paragraph_spacing', '\\noindent',
678 #                              '\\align', '\\labelwidthstring',
679 #                              "\\start_of_appendix", "\\leftindent")
680 #        sections = []
681 #        for section in paragraphs_filter.keys():
682 #            sections.append('\\begin_layout %s' % section)
683
684 #        toc_par = []
685 #        i = 0
686 #        while 1:
687 #            i = find_tokens(self.body, sections, i)
688 #            if i == -1:
689 #                break
690
691 #            j = find_end_of(self.body,  i + 1, '\\begin_layout', '\\end_layout')
692 #            if j == -1:
693 #                self.warning('Incomplete file.', 0)
694 #                break
695
696 #            section = self.body[i].split()[1]
697 #            if section[-1] == '*':
698 #                section = section[:-1]
699
700 #            par = []
701
702 #            k = i + 1
703 #            # skip paragraph parameters
704 #            while not self.body[k].strip() or self.body[k].split()[0] \
705 #                      in allowed_parameters:
706 #                k += 1
707
708 #            while k < j:
709 #                if check_token(self.body[k], '\\begin_inset'):
710 #                    inset = self.body[k].split()[1]
711 #                    end = find_end_of_inset(self.body, k)
712 #                    if end == -1 or end > j:
713 #                        self.warning('Malformed file.', 0)
714
715 #                    if inset in allowed_insets:
716 #                        par.extend(self.body[k: end+1])
717 #                    k = end + 1
718 #                else:
719 #                    par.append(self.body[k])
720 #                    k += 1
721
722 #            # trim empty lines in the end.
723 #            while par and par[-1].strip() == '':
724 #                par.pop()
725
726 #            toc_par.append(Paragraph(section, par))
727
728 #            i = j + 1
729
730 #        return toc_par
731
732
733 class File(LyX_base):
734     " This class reads existing LyX files."
735
736     def __init__(self, end_format = 0, input = "", output = "", error = "",
737                  debug = default_debug__, try_hard = 0, cjk_encoding = '',
738                  final_version = '', systemlyxdir = ''):
739         LyX_base.__init__(self, end_format, input, output, error,
740                           debug, try_hard, cjk_encoding, final_version,
741                           systemlyxdir)
742         self.read()
743
744
745 # FIXME: header settings are completely outdated, don't use like this
746 #class NewFile(LyX_base):
747 #    " This class is to create new LyX files."
748 #    def set_header(self, **params):
749 #        # set default values
750 #        self.header.extend([
751 #            "#LyX xxxx created this file."
752 #            "For more info see http://www.lyx.org/",
753 #            "\\lyxformat xxx",
754 #            "\\begin_document",
755 #            "\\begin_header",
756 #            "\\textclass article",
757 #            "\\language english",
758 #            "\\inputencoding auto",
759 #            "\\font_roman default",
760 #            "\\font_sans default",
761 #            "\\font_typewriter default",
762 #            "\\font_default_family default",
763 #            "\\font_sc false",
764 #            "\\font_osf false",
765 #            "\\font_sf_scale 100",
766 #            "\\font_tt_scale 100",
767 #            "\\graphics default",
768 #            "\\paperfontsize default",
769 #            "\\papersize default",
770 #            "\\use_geometry false",
771 #            "\\use_amsmath 1",
772 #            "\\cite_engine basic",
773 #            "\\use_bibtopic false",
774 #            "\\use_indices false",
775 #            "\\paperorientation portrait",
776 #            "\\secnumdepth 3",
777 #            "\\tocdepth 3",
778 #            "\\paragraph_separation indent",
779 #            "\\defskip medskip",
780 #            "\\quotes_language english",
781 #            "\\papercolumns 1",
782 #            "\\papersides 1",
783 #            "\\paperpagestyle default",
784 #            "\\tracking_changes false",
785 #            "\\end_header"])
786
787 #        self.format = get_end_format()
788 #        for param in params:
789 #            self.set_parameter(param, params[param])
790
791
792 #    def set_body(self, paragraphs):
793 #        self.body.extend(['\\begin_body',''])
794
795 #        for par in paragraphs:
796 #            self.body.extend(par.asLines())
797
798 #        self.body.extend(['','\\end_body', '\\end_document'])
799
800
801 # Part of an unfinished attempt to make lyx2lyx gave a more
802 # structured view of the document.
803 #class Paragraph:
804 #    # unfinished implementation, it is missing the Text and Insets
805 #    # representation.
806 #    " This class represents the LyX paragraphs."
807 #    def __init__(self, name, body=[], settings = [], child = []):
808 #        """ Parameters:
809 #        name: paragraph name.
810 #        body: list of lines of body text.
811 #        child: list of paragraphs that descend from this paragraph.
812 #        """
813 #        self.name = name
814 #        self.body = body
815 #        self.settings = settings
816 #        self.child = child
817
818 #    def asLines(self):
819 #        """ Converts the paragraph to a list of strings, representing
820 #        it in the LyX file."""
821
822 #        result = ['','\\begin_layout %s' % self.name]
823 #        result.extend(self.settings)
824 #        result.append('')
825 #        result.extend(self.body)
826 #        result.append('\\end_layout')
827
828 #        if not self.child:
829 #            return result
830
831 #        result.append('\\begin_deeper')
832 #        for node in self.child:
833 #            result.extend(node.asLines())
834 #        result.append('\\end_deeper')
835
836 #        return result