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