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