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