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