]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/LyX.py
add pure ASCII encoding for LaTeX export
[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 from parser_tools import get_value, check_token, find_token,\
21      find_tokens, find_end_of
22 import os.path
23 import gzip
24 import locale
25 import sys
26 import re
27 import time
28
29 import lyx2lyx_version
30 version_lyx2lyx = lyx2lyx_version.version
31
32 default_debug_level = 2
33
34 ####################################################################
35 # Private helper functions
36
37 def find_end_of_inset(lines, i):
38     " Find beginning of inset, where lines[i] is included."
39     return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
40
41 def generate_minor_versions(major, last_minor_version):
42     """ Generate minor versions, using major as prefix and minor
43     versions from 0 until last_minor_version, plus the generic version.
44
45     Example:
46
47       generate_minor_versions("1.2", 4) ->
48       [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
49     """
50     return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
51
52
53 # End of helper functions
54 ####################################################################
55
56
57 # Regular expressions used
58 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
59 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
60 original_version = re.compile(r".*?LyX ([\d.]*)")
61
62 ##
63 # file format information:
64 #  file, supported formats, stable release versions
65 format_relation = [("0_06",    [200], generate_minor_versions("0.6" , 4)),
66                    ("0_08",    [210], generate_minor_versions("0.8" , 6) + ["0.7"]),
67                    ("0_10",    [210], generate_minor_versions("0.10", 7) + ["0.9"]),
68                    ("0_12",    [215], generate_minor_versions("0.12", 1) + ["0.11"]),
69                    ("1_0",     [215], generate_minor_versions("1.0" , 4)),
70                    ("1_1",     [215], generate_minor_versions("1.1" , 4)),
71                    ("1_1_5",   [216], ["1.1.5","1.1.5.1","1.1.5.2","1.1"]),
72                    ("1_1_6_0", [217], ["1.1.6","1.1.6.1","1.1.6.2","1.1"]),
73                    ("1_1_6_3", [218], ["1.1.6.3","1.1.6.4","1.1"]),
74                    ("1_2",     [220], generate_minor_versions("1.2" , 4)),
75                    ("1_3",     [221], generate_minor_versions("1.3" , 7)),
76                    ("1_4", range(222,246), generate_minor_versions("1.4" , 3)),
77                    ("1_5", range(246,263), generate_minor_versions("1.5" , 0))]
78
79
80 def formats_list():
81     " Returns a list with supported file formats."
82     formats = []
83     for version in format_relation:
84         for format in version[1]:
85             if format not in formats:
86                 formats.append(format)
87     return formats
88
89
90 def get_end_format():
91     " Returns the more recent file format available."
92     return format_relation[-1][1][-1]
93
94
95 def get_backend(textclass):
96     " For _textclass_ returns its backend."
97     if textclass == "linuxdoc" or textclass == "manpage":
98         return "linuxdoc"
99     if textclass[:7] == "docbook":
100         return "docbook"
101     return "latex"
102
103
104 def trim_eol(line):
105     " Remove end of line char(s)."
106     if line[-2:-1] == '\r':
107         return line[:-2]
108     else:
109         return line[:-1]
110
111
112 def get_encoding(language, inputencoding, format, cjk_encoding):
113     if format > 248:
114         return "utf8"
115     # CJK-LyX encodes files using the current locale encoding.
116     # This means that files created by CJK-LyX can only be converted using
117     # the correct locale settings unless the encoding is given as commandline
118     # argument.
119     if cjk_encoding == 'auto':
120         return locale.getpreferredencoding()
121     elif cjk_encoding != '':
122         return cjk_encoding
123     from lyx2lyx_lang import lang
124     if inputencoding == "auto" or inputencoding == "default":
125         return lang[language][3]
126     if inputencoding == "":
127         return "latin1"
128     # python does not know the alias latin9
129     if inputencoding == "latin9":
130         return "iso-8859-15"
131     return inputencoding
132
133 ##
134 # Class
135 #
136 class LyX_Base:
137     """This class carries all the information of the LyX file."""
138     
139     def __init__(self, end_format = 0, input = "", output = "", error
140                  = "", debug = default_debug_level, try_hard = 0, cjk_encoding = '',
141                  language = "english", encoding = "auto"):
142
143         """Arguments:
144         end_format: final format that the file should be converted. (integer)
145         input: the name of the input source, if empty resort to standard input.
146         output: the name of the output file, if empty use the standard output.
147         error: the name of the error file, if empty use the standard error.
148         debug: debug level, O means no debug, as its value increases be more verbose.
149         """
150         self.choose_io(input, output)
151
152         if error:
153             self.err = open(error, "w")
154         else:
155             self.err = sys.stderr
156
157         self.debug = debug
158         self.try_hard = try_hard
159         self.cjk_encoding = cjk_encoding
160
161         if end_format:
162             self.end_format = self.lyxformat(end_format)
163         else:
164             self.end_format = get_end_format()
165
166         self.backend = "latex"
167         self.textclass = "article"
168         # This is a hack: We use '' since we don't know the default
169         # layout of the text class. LyX will parse it as default layout.
170         # FIXME: Read the layout file and use the real default layout
171         self.default_layout = ''
172         self.header = []
173         self.preamble = []
174         self.body = []
175         self.status = 0
176         self.encoding = encoding
177         self.language = language
178
179
180     def warning(self, message, debug_level= default_debug_level):
181         " Emits warning to self.error, if the debug_level is less than the self.debug."
182         if debug_level <= self.debug:
183             self.err.write("Warning: " + message + "\n")
184
185
186     def error(self, message):
187         " Emits a warning and exits if not in try_hard mode."
188         self.warning(message)
189         if not self.try_hard:
190             self.warning("Quiting.")
191             sys.exit(1)
192
193         self.status = 2
194
195
196     def read(self):
197         """Reads a file into the self.header and self.body parts, from self.input."""
198
199         while 1:
200             line = self.input.readline()
201             if not line:
202                 self.error("Invalid LyX file.")
203
204             line = trim_eol(line)
205             if check_token(line, '\\begin_preamble'):
206                 while 1:
207                     line = self.input.readline()
208                     if not line:
209                         self.error("Invalid LyX file.")
210
211                     line = trim_eol(line)
212                     if check_token(line, '\\end_preamble'):
213                         break
214                     
215                     if line.split()[:0] in ("\\layout", "\\begin_layout", "\\begin_body"):
216                         self.warning("Malformed LyX file: Missing '\\end_preamble'.")
217                         self.warning("Adding it now and hoping for the best.")
218
219                     self.preamble.append(line)
220
221             if check_token(line, '\\end_preamble'):
222                 continue
223
224             line = line.strip()
225             if not line:
226                 continue
227
228             if line.split()[0] in ("\\layout", "\\begin_layout", "\\begin_body"):
229                 self.body.append(line)
230                 break
231
232             self.header.append(line)
233
234         self.textclass = get_value(self.header, "\\textclass", 0)
235         self.backend = get_backend(self.textclass)
236         self.format  = self.read_format()
237         self.language = get_value(self.header, "\\language", 0, default = "english")
238         self.inputencoding = get_value(self.header, "\\inputencoding", 0, default = "auto")
239         self.encoding = get_encoding(self.language, self.inputencoding, self.format, self.cjk_encoding)
240         self.initial_version = self.read_version()
241
242         # Second pass over header and preamble, now we know the file encoding
243         for i in range(len(self.header)):
244             self.header[i] = self.header[i].decode(self.encoding)
245         for i in range(len(self.preamble)):
246             self.preamble[i] = self.preamble[i].decode(self.encoding)
247
248         # Read document body
249         while 1:
250             line = self.input.readline().decode(self.encoding)
251             if not line:
252                 break
253             self.body.append(trim_eol(line))
254
255
256     def write(self):
257         " Writes the LyX file to self.output."
258         self.set_version()
259         self.set_format()
260         if self.encoding == "auto":
261             self.encoding = get_encoding(self.language, self.encoding, self.format, self.cjk_encoding)
262
263         if self.preamble:
264             i = find_token(self.header, '\\textclass', 0) + 1
265             preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
266             if i == 0:
267                 self.error("Malformed LyX file: Missing '\\textclass'.")
268             else:
269                 header = self.header[:i] + preamble + self.header[i:]
270         else:
271             header = self.header
272
273         for line in header + [''] + self.body:
274             self.output.write(line.encode(self.encoding)+"\n")
275
276
277     def choose_io(self, input, output):
278         """Choose input and output streams, dealing transparently with
279         compressed files."""
280
281         if output:
282             self.output = open(output, "wb")
283         else:
284             self.output = sys.stdout
285
286         if input and input != '-':
287             self.dir = os.path.dirname(os.path.abspath(input))
288             try:
289                 gzip.open(input).readline()
290                 self.input = gzip.open(input)
291                 self.output = gzip.GzipFile(mode="wb", fileobj=self.output) 
292             except:
293                 self.input = open(input)
294         else:
295             self.dir = ''
296             self.input = sys.stdin
297
298
299     def lyxformat(self, format):
300         " Returns the file format representation, an integer."
301         result = format_re.match(format)
302         if result:
303             format = int(result.group(1) + result.group(2))
304         elif format == '2':
305             format = 200
306         else:
307             self.error(str(format) + ": " + "Invalid LyX file.")
308
309         if format in formats_list():
310             return format
311
312         self.error(str(format) + ": " + "Format not supported.")
313         return None
314
315
316     def read_version(self):
317         """ Searchs for clues of the LyX version used to write the file, returns the
318         most likely value, or None otherwise."""
319         for line in self.header:
320             if line[0] != "#":
321                 return None
322
323             line = line.replace("fix",".")
324             result = original_version.match(line)
325             if result:
326                 # Special know cases: reLyX and KLyX
327                 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
328                     return "0.12"
329
330                 res = result.group(1)
331                 if not res:
332                     self.warning(line)
333                 #self.warning("Version %s" % result.group(1))
334                 return res
335         self.warning(str(self.header[:2]))
336         return None
337
338
339     def set_version(self):
340         " Set the header with the version used."
341         self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version_lyx2lyx
342         if self.header[1][0] == '#':
343             del self.header[1]
344
345
346     def read_format(self):
347         " Read from the header the fileformat of the present LyX file."
348         for line in self.header:
349             result = fileformat.match(line)
350             if result:
351                 return self.lyxformat(result.group(1))
352         else:
353             self.error("Invalid LyX File.")
354         return None
355
356
357     def set_format(self):
358         " Set the file format of the file, in the header."
359         if self.format <= 217:
360             format = str(float(self.format)/100)
361         else:
362             format = str(self.format)
363         i = find_token(self.header, "\\lyxformat", 0)
364         self.header[i] = "\\lyxformat %s" % format
365
366
367     def set_parameter(self, param, value):
368         " Set the value of the header parameter."
369         i = find_token(self.header, '\\' + param, 0)
370         if i == -1:
371             self.warning('Parameter not found in the header: %s' % param, 3)
372             return
373         self.header[i] = '\\%s %s' % (param, str(value))
374
375
376     def is_default_layout(self, layout):
377         " Check whether a layout is the default layout of this class."
378         # FIXME: Check against the real text class default layout
379         if layout == 'Standard' or layout == self.default_layout:
380             return 1
381         return 0
382
383
384     def convert(self):
385         "Convert from current (self.format) to self.end_format."
386         mode, convertion_chain = self.chain()
387         self.warning("convertion chain: " + str(convertion_chain), 3)
388
389         for step in convertion_chain:
390             steps = getattr(__import__("lyx_" + step), mode)
391
392             self.warning("Convertion step: %s - %s" % (step, mode), default_debug_level + 1)
393             if not steps:
394                     self.error("The convertion to an older format (%s) is not implemented." % self.format)
395
396             multi_conv = len(steps) != 1
397             for version, table in steps:
398                 if multi_conv and \
399                    (self.format >= version and mode == "convert") or\
400                    (self.format <= version and mode == "revert"):
401                     continue
402
403                 for conv in table:
404                     init_t = time.time()
405                     try:
406                         conv(self)
407                     except:
408                         self.warning("An error ocurred in %s, %s" % (version, str(conv)),
409                                      default_debug_level)
410                         if not self.try_hard:
411                             raise
412                         self.status = 2
413                     else:
414                         self.warning("%lf: Elapsed time on %s"  % (time.time() - init_t, str(conv)),
415                                      default_debug_level + 1)
416
417                 self.format = version
418                 if self.end_format == self.format:
419                     return
420
421
422     def chain(self):
423         """ This is where all the decisions related with the convertion are taken.
424         It returns a list of modules needed to convert the LyX file from
425         self.format to self.end_format"""
426
427         self.start =  self.format
428         format = self.format
429         correct_version = 0
430
431         for rel in format_relation:
432             if self.initial_version in rel[2]:
433                 if format in rel[1]:
434                     initial_step = rel[0]
435                     correct_version = 1
436                     break
437
438         if not correct_version:
439             if format <= 215:
440                 self.warning("Version does not match file format, discarding it. (Version %s, format %d)" %(self.initial_version, self.format))
441             for rel in format_relation:
442                 if format in rel[1]:
443                     initial_step = rel[0]
444                     break
445             else:
446                 # This should not happen, really.
447                 self.error("Format not supported.")
448
449         # Find the final step
450         for rel in format_relation:
451             if self.end_format in rel[1]:
452                 final_step = rel[0]
453                 break
454         else:
455             self.error("Format not supported.")
456
457         # Convertion mode, back or forth
458         steps = []
459         if (initial_step, self.start) < (final_step, self.end_format):
460             mode = "convert"
461             first_step = 1
462             for step in format_relation:
463                 if  initial_step <= step[0] <= final_step:
464                     if first_step and len(step[1]) == 1:
465                         first_step = 0
466                         continue
467                     steps.append(step[0])
468         else:
469             mode = "revert"
470             relation_format = format_relation[:]
471             relation_format.reverse()
472             last_step = None
473
474             for step in relation_format:
475                 if  final_step <= step[0] <= initial_step:
476                     steps.append(step[0])
477                     last_step = step
478
479             if last_step[1][-1] == self.end_format:
480                 steps.pop()
481
482         return mode, steps
483
484
485     def get_toc(self, depth = 4):
486         " Returns the TOC of this LyX document."
487         paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, 'Subsection' : 3, 'Subsubsection': 4}
488         allowed_insets = ['Quotes']
489         allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix", "\\leftindent"
490
491         sections = []
492         for section in paragraphs_filter.keys():
493             sections.append('\\begin_layout %s' % section)
494
495         toc_par = []
496         i = 0
497         while 1:
498             i = find_tokens(self.body, sections, i)
499             if i == -1:
500                 break
501
502             j = find_end_of(self.body,  i + 1, '\\begin_layout', '\\end_layout')
503             if j == -1:
504                 self.warning('Incomplete file.', 0)
505                 break
506
507             section = self.body[i].split()[1]
508             if section[-1] == '*':
509                 section = section[:-1]
510
511             par = []
512
513             k = i + 1
514             # skip paragraph parameters
515             while not self.body[k].strip() or self.body[k].split()[0] in allowed_parameters:
516                 k = k +1
517
518             while k < j:
519                 if check_token(self.body[k], '\\begin_inset'):
520                     inset = self.body[k].split()[1]
521                     end = find_end_of_inset(self.body, k)
522                     if end == -1 or end > j:
523                         self.warning('Malformed file.', 0)
524
525                     if inset in allowed_insets:
526                         par.extend(self.body[k: end+1])
527                     k = end + 1
528                 else:
529                     par.append(self.body[k])
530                     k = k + 1
531
532             # trim empty lines in the end.
533             while par[-1].strip() == '' and par:
534                 par.pop()
535
536             toc_par.append(Paragraph(section, par))
537
538             i = j + 1
539
540         return toc_par
541
542
543 class File(LyX_Base):
544     " This class reads existing LyX files."
545     def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0, cjk_encoding = ''):
546         LyX_Base.__init__(self, end_format, input, output, error, debug, try_hard, cjk_encoding)
547         self.read()
548
549
550 class NewFile(LyX_Base):
551     " This class is to create new LyX files."
552     def set_header(self, **params):
553         # set default values
554         self.header.extend([
555             "#LyX xxxx created this file. For more info see http://www.lyx.org/",
556             "\\lyxformat xxx",
557             "\\begin_document",
558             "\\begin_header",
559             "\\textclass article",
560             "\\language english",
561             "\\inputencoding auto",
562             "\\font_roman default",
563             "\\font_sans default",
564             "\\font_typewriter default",
565             "\\font_default_family default",
566             "\\font_sc false",
567             "\\font_osf false",
568             "\\font_sf_scale 100",
569             "\\font_tt_scale 100",
570             "\\graphics default",
571             "\\paperfontsize default",
572             "\\papersize default",
573             "\\use_geometry false",
574             "\\use_amsmath 1",
575             "\\cite_engine basic",
576             "\\use_bibtopic false",
577             "\\paperorientation portrait",
578             "\\secnumdepth 3",
579             "\\tocdepth 3",
580             "\\paragraph_separation indent",
581             "\\defskip medskip",
582             "\\quotes_language english",
583             "\\papercolumns 1",
584             "\\papersides 1",
585             "\\paperpagestyle default",
586             "\\tracking_changes false",
587             "\\end_header"])
588
589         self.format = get_end_format()
590         for param in params:
591             self.set_parameter(param, params[param])
592
593
594     def set_body(self, paragraphs):
595         self.body.extend(['\\begin_body',''])
596
597         for par in paragraphs:
598             self.body.extend(par.asLines())
599
600         self.body.extend(['','\\end_body', '\\end_document'])
601
602
603 class Paragraph:
604     # unfinished implementation, it is missing the Text and Insets representation.
605     " This class represents the LyX paragraphs."
606     def __init__(self, name, body=[], settings = [], child = []):
607         """ Parameters:
608         name: paragraph name.
609         body: list of lines of body text.
610         child: list of paragraphs that descend from this paragraph.
611         """
612         self.name = name
613         self.body = body
614         self.settings = settings
615         self.child = child
616
617     def asLines(self):
618         " Converts the paragraph to a list of strings, representing it in the LyX file."
619         result = ['','\\begin_layout %s' % self.name]
620         result.extend(self.settings)
621         result.append('')
622         result.extend(self.body)
623         result.append('\\end_layout')
624
625         if not self.child:
626             return result
627
628         result.append('\\begin_deeper')
629         for node in self.child:
630             result.extend(node.asLines())
631         result.append('\\end_deeper')
632
633         return result
634
635
636 class Inset:
637     " This class represents the LyX insets."
638     pass
639
640
641 class Text:
642     " This class represents simple chuncks of text."
643     pass