]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/LyX.py
e37691f273d11969af9bcea2828ad031f5396f7f
[lyx.git] / lib / lyx2lyx / LyX.py
1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2002-2011 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", range(222,246), minor_versions("1.4" , 5)),
84                    ("1_5", range(246,277), minor_versions("1.5" , 7)),
85                    ("1_6", range(277,346), minor_versions("1.6" , 10)),
86                    ("2_0", range(346,414), minor_versions("2.0", 8)),
87                    ("2_1", range(414,475), minor_versions("2.1", 0)),
88                    ("2_2", range(475,477), 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[-2:-1] == '\r':
151         return line[:-2]
152     else:
153         return line[:-1]
154
155
156 def get_encoding(language, inputencoding, format, cjk_encoding):
157     " Returns enconding of the lyx file"
158     if format > 248:
159         return "utf8"
160     # CJK-LyX encodes files using the current locale encoding.
161     # This means that files created by CJK-LyX can only be converted using
162     # the correct locale settings unless the encoding is given as commandline
163     # argument.
164     if cjk_encoding == 'auto':
165         return locale.getpreferredencoding()
166     elif cjk_encoding:
167         return cjk_encoding
168     from lyx2lyx_lang import lang
169     if inputencoding == "auto" or inputencoding == "default":
170         return lang[language][3]
171     if inputencoding == "":
172         return "latin1"
173     if inputencoding == "utf8x":
174         return "utf8"
175     # python does not know the alias latin9
176     if inputencoding == "latin9":
177         return "iso-8859-15"
178     return inputencoding
179
180 ##
181 # Class
182 #
183 class LyX_base:
184     """This class carries all the information of the LyX file."""
185
186     def __init__(self, end_format = 0, input = "", output = "", error = "",
187                  debug = default_debug__, try_hard = 0, cjk_encoding = '',
188                  final_version = "", language = "english", encoding = "auto"):
189
190         """Arguments:
191         end_format: final format that the file should be converted. (integer)
192         input: the name of the input source, if empty resort to standard input.
193         output: the name of the output file, if empty use the standard output.
194         error: the name of the error file, if empty use the standard error.
195         debug: debug level, O means no debug, as its value increases be more verbose.
196         """
197         self.choose_io(input, output)
198
199         if error:
200             self.err = open(error, "w")
201         else:
202             self.err = sys.stderr
203
204         self.debug = debug
205         self.try_hard = try_hard
206         self.cjk_encoding = cjk_encoding
207
208         if end_format:
209             self.end_format = self.lyxformat(end_format)
210
211             # In case the target version and format are both specified
212             # verify that they are compatible. If not send a warning
213             # and ignore the version.
214             if final_version:
215                 message = "Incompatible version %s for specified format %d" % (
216                     final_version, self.end_format)
217                 for version in format_relation:
218                     if self.end_format in version[1]:
219                         if final_version not in version[2]:
220                             self.warning(message)
221                             final_version = ""
222         elif final_version:
223             for version in format_relation:
224                 if final_version in version[2]:
225                     # set the last format for that version
226                     self.end_format = version[1][-1]
227                     break
228             else:
229                 final_version = ""
230         else:
231             self.end_format = get_end_format()
232
233         if not final_version:
234             for step in format_relation:
235                 if self.end_format in step[1]:
236                     final_version = step[2][1]
237         self.final_version = final_version
238         self.warning("Final version: %s" % self.final_version, 10)
239         self.warning("Final format: %d" % self.end_format, 10)
240
241         self.backend = "latex"
242         self.textclass = "article"
243         # This is a hack: We use '' since we don't know the default
244         # layout of the text class. LyX will parse it as default layout.
245         # FIXME: Read the layout file and use the real default layout
246         self.default_layout = ''
247         self.header = []
248         self.preamble = []
249         self.body = []
250         self.status = 0
251         self.encoding = encoding
252         self.language = language
253
254
255     def warning(self, message, debug_level= default_debug__):
256         """ Emits warning to self.error, if the debug_level is less
257         than the self.debug."""
258         if debug_level <= self.debug:
259             self.err.write("Warning: " + message + "\n")
260
261
262     def error(self, message):
263         " Emits a warning and exits if not in try_hard mode."
264         self.warning(message)
265         if not self.try_hard:
266             self.warning("Quitting.")
267             sys.exit(1)
268
269         self.status = 2
270
271
272     def read(self):
273         """Reads a file into the self.header and
274         self.body parts, from self.input."""
275
276         while True:
277             line = self.input.readline()
278             if not line:
279                 self.error("Invalid LyX file.")
280
281             line = trim_eol(line)
282             if check_token(line, '\\begin_preamble'):
283                 while 1:
284                     line = self.input.readline()
285                     if not line:
286                         self.error("Invalid LyX file.")
287
288                     line = trim_eol(line)
289                     if check_token(line, '\\end_preamble'):
290                         break
291
292                     if line.split()[:0] in ("\\layout",
293                                             "\\begin_layout", "\\begin_body"):
294
295                         self.warning("Malformed LyX file:"
296                                      "Missing '\\end_preamble'."
297                                      "\nAdding it now and hoping"
298                                      "for the best.")
299
300                     self.preamble.append(line)
301
302             if check_token(line, '\\end_preamble'):
303                 continue
304
305             line = line.strip()
306             if not line:
307                 continue
308
309             if line.split()[0] in ("\\layout", "\\begin_layout",
310                                    "\\begin_body", "\\begin_deeper"):
311                 self.body.append(line)
312                 break
313
314             self.header.append(line)
315
316         i = find_token(self.header, '\\textclass', 0)
317         if i == -1:
318             self.warning("Malformed LyX file: Missing '\\textclass'.")
319             i = find_token(self.header, '\\lyxformat', 0) + 1
320             self.header[i:i] = ['\\textclass article']
321
322         self.textclass = get_value(self.header, "\\textclass", 0)
323         self.backend = get_backend(self.textclass)
324         self.format  = self.read_format()
325         self.language = get_value(self.header, "\\language", 0,
326                                   default = "english")
327         self.inputencoding = get_value(self.header, "\\inputencoding",
328                                        0, default = "auto")
329         self.encoding = get_encoding(self.language,
330                                      self.inputencoding, self.format,
331                                      self.cjk_encoding)
332         self.initial_version = self.read_version()
333
334         # Second pass over header and preamble, now we know the file encoding
335         # Do not forget the textclass (Debian bug #700828)
336         self.textclass = self.textclass.decode(self.encoding)
337         for i in range(len(self.header)):
338             self.header[i] = self.header[i].decode(self.encoding)
339         for i in range(len(self.preamble)):
340             self.preamble[i] = self.preamble[i].decode(self.encoding)
341
342         # Read document body
343         while 1:
344             line = self.input.readline().decode(self.encoding)
345             if not line:
346                 break
347             self.body.append(trim_eol(line))
348
349
350     def write(self):
351         " Writes the LyX file to self.output."
352         self.set_version()
353         self.set_format()
354         self.set_textclass()
355         if self.encoding == "auto":
356             self.encoding = get_encoding(self.language, self.encoding,
357                                          self.format, self.cjk_encoding)
358         if self.preamble:
359             i = find_token(self.header, '\\textclass', 0) + 1
360             preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
361             header = self.header[:i] + preamble + self.header[i:]
362         else:
363             header = self.header
364
365         for line in header + [''] + self.body:
366             self.output.write(line.encode(self.encoding)+"\n")
367
368
369     def choose_io(self, input, output):
370         """Choose input and output streams, dealing transparently with
371         compressed files."""
372
373         if output:
374             self.output = open(output, "wb")
375         else:
376             self.output = sys.stdout
377
378         if input and input != '-':
379             self.dir = os.path.dirname(os.path.abspath(input))
380             try:
381                 gzip.open(input).readline()
382                 self.input = gzip.open(input)
383                 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
384             except:
385                 self.input = open(input)
386         else:
387             self.dir = ''
388             self.input = sys.stdin
389
390
391     def lyxformat(self, format):
392         " Returns the file format representation, an integer."
393         result = format_re.match(format)
394         if result:
395             format = int(result.group(1) + result.group(2))
396         elif format == '2':
397             format = 200
398         else:
399             self.error(str(format) + ": " + "Invalid LyX file.")
400
401         if format in formats_list():
402             return format
403
404         self.error(str(format) + ": " + "Format not supported.")
405         return None
406
407
408     def read_version(self):
409         """ Searchs for clues of the LyX version used to write the
410         file, returns the most likely value, or None otherwise."""
411
412         for line in self.header:
413             if line[0] != "#":
414                 return None
415
416             line = line.replace("fix",".")
417             # need to test original_tex2lyx_version first because tex2lyx
418             # writes "#LyX file created by tex2lyx 2.2"
419             result = original_tex2lyx_version.match(line)
420             if not result:
421                 result = original_version.match(line)
422                 if result:
423                     # Special know cases: reLyX and KLyX
424                     if line.find("reLyX") != -1 or line.find("KLyX") != -1:
425                         return "0.12"
426             if result:
427                 res = result.group(1)
428                 if not res:
429                     self.warning(line)
430                 #self.warning("Version %s" % result.group(1))
431                 return res
432         self.warning(str(self.header[:2]))
433         return None
434
435
436     def set_version(self):
437         " Set the header with the version used."
438         self.header[0] = " ".join(["#LyX %s created this file." % version__,
439                                   "For more info see http://www.lyx.org/"])
440         if self.header[1][0] == '#':
441             del self.header[1]
442
443
444     def read_format(self):
445         " Read from the header the fileformat of the present LyX file."
446         for line in self.header:
447             result = fileformat.match(line)
448             if result:
449                 return self.lyxformat(result.group(1))
450         else:
451             self.error("Invalid LyX File.")
452         return None
453
454
455     def set_format(self):
456         " Set the file format of the file, in the header."
457         if self.format <= 217:
458             format = str(float(self.format)/100)
459         else:
460             format = str(self.format)
461         i = find_token(self.header, "\\lyxformat", 0)
462         self.header[i] = "\\lyxformat %s" % format
463
464
465     def set_textclass(self):
466         i = find_token(self.header, "\\textclass", 0)
467         self.header[i] = "\\textclass %s" % self.textclass
468
469
470     #Note that the module will be added at the END of the extant ones
471     def add_module(self, module):
472       i = find_token(self.header, "\\begin_modules", 0)
473       if i == -1:
474         #No modules yet included
475         i = find_token(self.header, "\\textclass", 0)
476         if i == -1:
477           self.warning("Malformed LyX document: No \\textclass!!")
478           return
479         modinfo = ["\\begin_modules", module, "\\end_modules"]
480         self.header[i + 1: i + 1] = modinfo
481         return
482       j = find_token(self.header, "\\end_modules", i)
483       if j == -1:
484         self.warning("(add_module)Malformed LyX document: No \\end_modules.")
485         return
486       k = find_token(self.header, module, i)
487       if k != -1 and k < j:
488         return
489       self.header.insert(j, module)
490
491
492     def get_module_list(self):
493       i = find_token(self.header, "\\begin_modules", 0)
494       if (i == -1):
495         return []
496       j = find_token(self.header, "\\end_modules", i)
497       return self.header[i + 1 : j]
498
499
500     def set_module_list(self, mlist):
501       modbegin = find_token(self.header, "\\begin_modules", 0)
502       newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
503       if (modbegin == -1):
504         #No modules yet included
505         tclass = find_token(self.header, "\\textclass", 0)
506         if tclass == -1:
507           self.warning("Malformed LyX document: No \\textclass!!")
508           return
509         modbegin = tclass + 1
510         self.header[modbegin:modbegin] = newmodlist
511         return
512       modend = find_token(self.header, "\\end_modules", modbegin)
513       if modend == -1:
514         self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
515         return
516       newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
517       self.header[modbegin:modend + 1] = newmodlist
518
519
520     def set_parameter(self, param, value):
521         " Set the value of the header parameter."
522         i = find_token(self.header, '\\' + param, 0)
523         if i == -1:
524             self.warning('Parameter not found in the header: %s' % param, 3)
525             return
526         self.header[i] = '\\%s %s' % (param, str(value))
527
528
529     def is_default_layout(self, layout):
530         " Check whether a layout is the default layout of this class."
531         # FIXME: Check against the real text class default layout
532         if layout == 'Standard' or layout == self.default_layout:
533             return 1
534         return 0
535
536
537     def convert(self):
538         "Convert from current (self.format) to self.end_format."
539         mode, conversion_chain = self.chain()
540         self.warning("conversion chain: " + str(conversion_chain), 3)
541
542         for step in conversion_chain:
543             steps = getattr(__import__("lyx_" + step), mode)
544
545             self.warning("Convertion step: %s - %s" % (step, mode),
546                          default_debug__ + 1)
547             if not steps:
548                 self.error("The conversion to an older "
549                 "format (%s) is not implemented." % self.format)
550
551             multi_conv = len(steps) != 1
552             for version, table in steps:
553                 if multi_conv and \
554                    (self.format >= version and mode == "convert") or\
555                    (self.format <= version and mode == "revert"):
556                     continue
557
558                 for conv in table:
559                     init_t = time.time()
560                     try:
561                         conv(self)
562                     except:
563                         self.warning("An error ocurred in %s, %s" %
564                                      (version, str(conv)),
565                                      default_debug__)
566                         if not self.try_hard:
567                             raise
568                         self.status = 2
569                     else:
570                         self.warning("%lf: Elapsed time on %s" %
571                                      (time.time() - init_t,
572                                       str(conv)), default_debug__ +
573                                      1)
574                 self.format = version
575                 if self.end_format == self.format:
576                     return
577
578
579     def chain(self):
580         """ This is where all the decisions related with the
581         conversion are taken.  It returns a list of modules needed to
582         convert the LyX file from self.format to self.end_format"""
583
584         self.start =  self.format
585         format = self.format
586         correct_version = 0
587
588         for rel in format_relation:
589             if self.initial_version in rel[2]:
590                 if format in rel[1]:
591                     initial_step = rel[0]
592                     correct_version = 1
593                     break
594
595         if not correct_version:
596             if format <= 215:
597                 self.warning("Version does not match file format, "
598                              "discarding it. (Version %s, format %d)" %
599                              (self.initial_version, self.format))
600             for rel in format_relation:
601                 if format in rel[1]:
602                     initial_step = rel[0]
603                     break
604             else:
605                 # This should not happen, really.
606                 self.error("Format not supported.")
607
608         # Find the final step
609         for rel in format_relation:
610             if self.end_format in rel[1]:
611                 final_step = rel[0]
612                 break
613         else:
614             self.error("Format not supported.")
615
616         # Convertion mode, back or forth
617         steps = []
618         if (initial_step, self.start) < (final_step, self.end_format):
619             mode = "convert"
620             full_steps = []
621             for step in format_relation:
622                 if  initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
623                     full_steps.append(step)
624             if full_steps[0][1][-1] == self.format:
625                 full_steps = full_steps[1:]
626             for step in full_steps:
627                 steps.append(step[0])
628         else:
629             mode = "revert"
630             relation_format = format_relation[:]
631             relation_format.reverse()
632             last_step = None
633
634             for step in relation_format:
635                 if  final_step <= step[0] <= initial_step:
636                     steps.append(step[0])
637                     last_step = step
638
639             if last_step[1][-1] == self.end_format:
640                 steps.pop()
641
642         self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
643         return mode, steps
644
645
646 # Part of an unfinished attempt to make lyx2lyx gave a more
647 # structured view of the document.
648 #    def get_toc(self, depth = 4):
649 #        " Returns the TOC of this LyX document."
650 #        paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
651 #                             'Subsection' : 3, 'Subsubsection': 4}
652 #        allowed_insets = ['Quotes']
653 #        allowed_parameters = ('\\paragraph_spacing', '\\noindent',
654 #                              '\\align', '\\labelwidthstring',
655 #                              "\\start_of_appendix", "\\leftindent")
656 #        sections = []
657 #        for section in paragraphs_filter.keys():
658 #            sections.append('\\begin_layout %s' % section)
659
660 #        toc_par = []
661 #        i = 0
662 #        while 1:
663 #            i = find_tokens(self.body, sections, i)
664 #            if i == -1:
665 #                break
666
667 #            j = find_end_of(self.body,  i + 1, '\\begin_layout', '\\end_layout')
668 #            if j == -1:
669 #                self.warning('Incomplete file.', 0)
670 #                break
671
672 #            section = self.body[i].split()[1]
673 #            if section[-1] == '*':
674 #                section = section[:-1]
675
676 #            par = []
677
678 #            k = i + 1
679 #            # skip paragraph parameters
680 #            while not self.body[k].strip() or self.body[k].split()[0] \
681 #                      in allowed_parameters:
682 #                k += 1
683
684 #            while k < j:
685 #                if check_token(self.body[k], '\\begin_inset'):
686 #                    inset = self.body[k].split()[1]
687 #                    end = find_end_of_inset(self.body, k)
688 #                    if end == -1 or end > j:
689 #                        self.warning('Malformed file.', 0)
690
691 #                    if inset in allowed_insets:
692 #                        par.extend(self.body[k: end+1])
693 #                    k = end + 1
694 #                else:
695 #                    par.append(self.body[k])
696 #                    k += 1
697
698 #            # trim empty lines in the end.
699 #            while par and par[-1].strip() == '':
700 #                par.pop()
701
702 #            toc_par.append(Paragraph(section, par))
703
704 #            i = j + 1
705
706 #        return toc_par
707
708
709 class File(LyX_base):
710     " This class reads existing LyX files."
711
712     def __init__(self, end_format = 0, input = "", output = "", error = "",
713                  debug = default_debug__, try_hard = 0, cjk_encoding = '',
714                  final_version = ''):
715         LyX_base.__init__(self, end_format, input, output, error,
716                           debug, try_hard, cjk_encoding, final_version)
717         self.read()
718
719
720 #class NewFile(LyX_base):
721 #    " This class is to create new LyX files."
722 #    def set_header(self, **params):
723 #        # set default values
724 #        self.header.extend([
725 #            "#LyX xxxx created this file."
726 #            "For more info see http://www.lyx.org/",
727 #            "\\lyxformat xxx",
728 #            "\\begin_document",
729 #            "\\begin_header",
730 #            "\\textclass article",
731 #            "\\language english",
732 #            "\\inputencoding auto",
733 #            "\\font_roman default",
734 #            "\\font_sans default",
735 #            "\\font_typewriter default",
736 #            "\\font_default_family default",
737 #            "\\font_sc false",
738 #            "\\font_osf false",
739 #            "\\font_sf_scale 100",
740 #            "\\font_tt_scale 100",
741 #            "\\graphics default",
742 #            "\\paperfontsize default",
743 #            "\\papersize default",
744 #            "\\use_geometry false",
745 #            "\\use_amsmath 1",
746 #            "\\cite_engine basic",
747 #            "\\use_bibtopic false",
748 #            "\\paperorientation portrait",
749 #            "\\secnumdepth 3",
750 #            "\\tocdepth 3",
751 #            "\\paragraph_separation indent",
752 #            "\\defskip medskip",
753 #            "\\quotes_language english",
754 #            "\\papercolumns 1",
755 #            "\\papersides 1",
756 #            "\\paperpagestyle default",
757 #            "\\tracking_changes false",
758 #            "\\end_header"])
759
760 #        self.format = get_end_format()
761 #        for param in params:
762 #            self.set_parameter(param, params[param])
763
764
765 #    def set_body(self, paragraphs):
766 #        self.body.extend(['\\begin_body',''])
767
768 #        for par in paragraphs:
769 #            self.body.extend(par.asLines())
770
771 #        self.body.extend(['','\\end_body', '\\end_document'])
772
773
774 # Part of an unfinished attempt to make lyx2lyx gave a more
775 # structured view of the document.
776 #class Paragraph:
777 #    # unfinished implementation, it is missing the Text and Insets
778 #    # representation.
779 #    " This class represents the LyX paragraphs."
780 #    def __init__(self, name, body=[], settings = [], child = []):
781 #        """ Parameters:
782 #        name: paragraph name.
783 #        body: list of lines of body text.
784 #        child: list of paragraphs that descend from this paragraph.
785 #        """
786 #        self.name = name
787 #        self.body = body
788 #        self.settings = settings
789 #        self.child = child
790
791 #    def asLines(self):
792 #        """ Converts the paragraph to a list of strings, representing
793 #        it in the LyX file."""
794
795 #        result = ['','\\begin_layout %s' % self.name]
796 #        result.extend(self.settings)
797 #        result.append('')
798 #        result.extend(self.body)
799 #        result.append('\\end_layout')
800
801 #        if not self.child:
802 #            return result
803
804 #        result.append('\\begin_deeper')
805 #        for node in self.child:
806 #            result.extend(node.asLines())
807 #        result.append('\\end_deeper')
808
809 #        return result