]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_2_1.py
Fix lyx2lyx revertion for natbib.
[lyx.git] / lib / lyx2lyx / lyx_2_1.py
1 # -*- coding: utf-8 -*-
2 # This file is part of lyx2lyx
3 # -*- coding: utf-8 -*-
4 # Copyright (C) 2011 The LyX team
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19
20 """ Convert files to the file format generated by lyx 2.1"""
21
22 import re, string
23 import unicodedata
24 import sys, os
25
26 # Uncomment only what you need to import, please.
27
28 from parser_tools import del_token, find_token, find_end_of, find_end_of_inset, \
29     find_end_of_layout, find_re, get_option_value, get_value, get_quoted_value, \
30     set_option_value
31
32 #from parser_tools import find_token, find_end_of, find_tokens, \
33   #find_token_exact, find_end_of_inset, find_end_of_layout, \
34   #find_token_backwards, is_in_inset, get_value, get_quoted_value, \
35   #del_token, check_token
36
37 from lyx2lyx_tools import add_to_preamble, put_cmd_in_ert
38
39 #from lyx2lyx_tools import insert_to_preamble, \
40 #  put_cmd_in_ert, lyx2latex, latex_length, revert_flex_inset, \
41 #  revert_font_attrs, hex2ratio, str2bool
42
43 ####################################################################
44 # Private helper functions
45
46 #def remove_option(lines, m, option):
47     #''' removes option from line m. returns whether we did anything '''
48     #l = lines[m].find(option)
49     #if l == -1:
50         #return False
51     #val = lines[m][l:].split('"')[1]
52     #lines[m] = lines[m][:l - 1] + lines[m][l+len(option + '="' + val + '"'):]
53     #return True
54
55
56 ###############################################################################
57 ###
58 ### Conversion and reversion routines
59 ###
60 ###############################################################################
61
62 def revert_visible_space(document):
63     "Revert InsetSpace visible into its ERT counterpart"
64     i = 0
65     while True:
66       i = find_token(document.body, "\\begin_inset space \\textvisiblespace{}", i)
67       if i == -1:
68         return
69       end = find_end_of_inset(document.body, i)
70       subst = put_cmd_in_ert("\\textvisiblespace{}")
71       document.body[i:end + 1] = subst
72
73
74 def convert_undertilde(document):
75     " Load undertilde automatically "
76     i = find_token(document.header, "\\use_mathdots" , 0)
77     if i == -1:
78         i = find_token(document.header, "\\use_mhchem" , 0)
79     if i == -1:
80         i = find_token(document.header, "\\use_esint" , 0)
81     if i == -1:
82         document.warning("Malformed LyX document: Can't find \\use_mathdots.")
83         return;
84     j = find_token(document.preamble, "\\usepackage{undertilde}", 0)
85     if j == -1:
86         document.header.insert(i + 1, "\\use_undertilde 0")
87     else:
88         document.header.insert(i + 1, "\\use_undertilde 2")
89         del document.preamble[j]
90
91
92 def revert_undertilde(document):
93     " Load undertilde if used in the document "
94     undertilde = find_token(document.header, "\\use_undertilde" , 0)
95     if undertilde == -1:
96       document.warning("No \\use_undertilde line. Assuming auto.")
97     else:
98       val = get_value(document.header, "\\use_undertilde", undertilde)
99       del document.header[undertilde]
100       try:
101         usetilde = int(val)
102       except:
103         document.warning("Invalid \\use_undertilde value: " + val + ". Assuming auto.")
104         # probably usedots has not been changed, but be safe.
105         usetilde = 1
106
107       if usetilde == 0:
108         # do not load case
109         return
110       if usetilde == 2:
111         # force load case
112         add_to_preamble(document, ["\\usepackage{undertilde}"])
113         return
114
115     # so we are in the auto case. we want to load undertilde if \utilde is used.
116     i = 0
117     while True:
118       i = find_token(document.body, '\\begin_inset Formula', i)
119       if i == -1:
120         return
121       j = find_end_of_inset(document.body, i)
122       if j == -1:
123         document.warning("Malformed LyX document: Can't find end of Formula inset at line " + str(i))
124         i += 1
125         continue
126       code = "\n".join(document.body[i:j])
127       if code.find("\\utilde") != -1:
128         add_to_preamble(document, ["\\@ifundefined{utilde}{\\usepackage{undertilde}}"])
129         return
130       i = j
131
132
133 def revert_negative_space(document):
134     "Revert InsetSpace negmedspace and negthickspace into its TeX-code counterpart"
135     i = 0
136     j = 0
137     reverted = False
138     while True:
139       i = find_token(document.body, "\\begin_inset space \\negmedspace{}", i)
140       if i == -1:
141         j = find_token(document.body, "\\begin_inset space \\negthickspace{}", j)
142         if j == -1:
143           # load amsmath in the preamble if not already loaded if we are at the end of checking
144           if reverted == True:
145             i = find_token(document.header, "\\use_amsmath 2", 0)
146             if i == -1:
147               add_to_preamble(document, ["\\@ifundefined{negthickspace}{\\usepackage{amsmath}}"])
148           return
149       if i == -1:
150         return
151       end = find_end_of_inset(document.body, i)
152       subst = put_cmd_in_ert("\\negmedspace{}")
153       document.body[i:end + 1] = subst
154       j = find_token(document.body, "\\begin_inset space \\negthickspace{}", j)
155       if j == -1:
156         return
157       end = find_end_of_inset(document.body, j)
158       subst = put_cmd_in_ert("\\negthickspace{}")
159       document.body[j:end + 1] = subst
160       reverted = True
161
162
163 def revert_math_spaces(document):
164     "Revert formulas with protected custom space and protected hfills to TeX-code"
165     i = 0
166     while True:
167       i = find_token(document.body, "\\begin_inset Formula", i)
168       if i == -1:
169         return
170       j = document.body[i].find("\\hspace*")
171       if j != -1:
172         end = find_end_of_inset(document.body, i)
173         subst = put_cmd_in_ert(document.body[i][21:])
174         document.body[i:end + 1] = subst
175       i = i + 1
176
177
178 def convert_japanese_encodings(document):
179     " Rename the japanese encodings to names understood by platex "
180     jap_enc_dict = {
181         "EUC-JP-pLaTeX": "euc",
182         "JIS-pLaTeX":    "jis",
183         "SJIS-pLaTeX":   "sjis"
184     }
185     i = find_token(document.header, "\\inputencoding" , 0)
186     if i == -1:
187         return
188     val = get_value(document.header, "\\inputencoding", i)
189     if val in jap_enc_dict.keys():
190         document.header[i] = "\\inputencoding %s" % jap_enc_dict[val]
191
192
193 def revert_japanese_encodings(document):
194     " Revert the japanese encodings name changes "
195     jap_enc_dict = {
196         "euc":  "EUC-JP-pLaTeX",
197         "jis":  "JIS-pLaTeX",
198         "sjis": "SJIS-pLaTeX"
199     }
200     i = find_token(document.header, "\\inputencoding" , 0)
201     if i == -1:
202         return
203     val = get_value(document.header, "\\inputencoding", i)
204     if val in jap_enc_dict.keys():
205         document.header[i] = "\\inputencoding %s" % jap_enc_dict[val]
206
207
208 def revert_justification(document):
209     " Revert the \\justification buffer param"
210     if not del_token(document.header, '\\justification', 0):
211         document.warning("Malformed LyX document: Missing \\justification.")
212
213
214 def revert_australian(document):
215     "Set English language variants Australian and Newzealand to English" 
216
217     if document.language == "australian" or document.language == "newzealand": 
218         document.language = "english" 
219         i = find_token(document.header, "\\language", 0) 
220         if i != -1: 
221             document.header[i] = "\\language english" 
222
223     j = 0 
224     while True: 
225         j = find_token(document.body, "\\lang australian", j) 
226         if j == -1: 
227             j = find_token(document.body, "\\lang newzealand", 0)
228             if j == -1:
229                 return
230             else:
231                 document.body[j] = document.body[j].replace("\\lang newzealand", "\\lang english")
232         else:
233             document.body[j] = document.body[j].replace("\\lang australian", "\\lang english") 
234         j += 1
235
236
237 def convert_biblio_style(document):
238     "Add a sensible default for \\biblio_style based on the citation engine."
239     i = find_token(document.header, "\\cite_engine", 0)
240     if i != -1:
241         engine = get_value(document.header, "\\cite_engine", i).split("_")[0]
242         style = {"basic": "plain", "natbib": "plainnat", "jurabib": "jurabib"}
243         document.header.insert(i + 1, "\\biblio_style " + style[engine])
244
245
246 def revert_biblio_style(document):
247     "BibTeX insets with default option use the style defined by \\biblio_style."
248     i = find_token(document.header, "\\biblio_style" , 0)
249     if i == -1:
250         document.warning("No \\biblio_style line. Nothing to do.")
251         return
252
253     default_style = get_value(document.header, "\\biblio_style", i)
254     del document.header[i]
255
256     # We are looking for bibtex insets having the default option
257     i = 0
258     while True:
259         i = find_token(document.body, "\\begin_inset CommandInset bibtex", i)
260         if i == -1:
261             return
262         j = find_end_of_inset(document.body, i)
263         if j == -1:
264             document.warning("Malformed LyX document: Can't find end of bibtex inset at line " + str(i))
265             i += 1
266             return
267         k = find_token(document.body, "options", i, j)
268         if k != -1:
269             options = get_quoted_value(document.body, "options", k)
270             if "default" in options.split(","):
271                 document.body[k] = 'options "%s"' \
272                     % options.replace("default", default_style)
273         i = j
274
275
276 def handle_longtable_captions(document, forward):
277     begin_table = 0
278     while True:
279         begin_table = find_token(document.body, '<lyxtabular version=', begin_table)
280         if begin_table == -1:
281             break
282         end_table = find_end_of(document.body, begin_table, '<lyxtabular', '</lyxtabular>')
283         if end_table == -1:
284             document.warning("Malformed LyX document: Could not find end of table.")
285             begin_table += 1
286             continue
287         fline = find_token(document.body, "<features", begin_table, end_table)
288         if fline == -1:
289             document.warning("Can't find features for inset at line " + str(begin_table))
290             begin_table += 1
291             continue
292         p = document.body[fline].find("islongtable")
293         if p == -1:
294             # no longtable
295             begin_table += 1
296             continue
297         numrows = get_option_value(document.body[begin_table], "rows")
298         try:
299             numrows = int(numrows)
300         except:
301             document.warning(document.body[begin_table])
302             document.warning("Unable to determine rows!")
303             begin_table = end_table
304             continue
305         begin_row = begin_table
306         for row in range(numrows):
307             begin_row = find_token(document.body, '<row', begin_row, end_table)
308             if begin_row == -1:
309                 document.warning("Can't find row " + str(row + 1))
310                 break
311             end_row = find_end_of(document.body, begin_row, '<row', '</row>')
312             if end_row == -1:
313                 document.warning("Can't find end of row " + str(row + 1))
314                 break
315             if forward:
316                 if (get_option_value(document.body[begin_row], 'caption') == 'true' and
317                     get_option_value(document.body[begin_row], 'endfirsthead') != 'true' and
318                     get_option_value(document.body[begin_row], 'endhead') != 'true' and
319                     get_option_value(document.body[begin_row], 'endfoot') != 'true' and
320                     get_option_value(document.body[begin_row], 'endlastfoot') != 'true'):
321                     document.body[begin_row] = set_option_value(document.body[begin_row], 'caption', 'true", endfirsthead="true')
322             elif get_option_value(document.body[begin_row], 'caption') == 'true':
323                 if get_option_value(document.body[begin_row], 'endfirsthead') == 'true':
324                     document.body[begin_row] = set_option_value(document.body[begin_row], 'endfirsthead', 'false')
325                 if get_option_value(document.body[begin_row], 'endhead') == 'true':
326                     document.body[begin_row] = set_option_value(document.body[begin_row], 'endhead', 'false')
327                 if get_option_value(document.body[begin_row], 'endfoot') == 'true':
328                     document.body[begin_row] = set_option_value(document.body[begin_row], 'endfoot', 'false')
329                 if get_option_value(document.body[begin_row], 'endlastfoot') == 'true':
330                     document.body[begin_row] = set_option_value(document.body[begin_row], 'endlastfoot', 'false')
331             begin_row = end_row
332         # since there could be a tabular inside this one, we 
333         # cannot jump to end.
334         begin_table += 1
335
336
337 def convert_longtable_captions(document):
338     "Add a firsthead flag to caption rows"
339     handle_longtable_captions(document, True)
340
341
342 def revert_longtable_captions(document):
343     "remove head/foot flag from caption rows"
344     handle_longtable_captions(document, False)
345
346
347 def convert_use_packages(document):
348     "use_xxx yyy => use_package xxx yyy"
349     packages = ["amsmath", "esint", "mathdots", "mhchem", "undertilde"]
350     for p in packages:
351         i = find_token(document.header, "\\use_%s" % p , 0)
352         if i != -1:
353             value = get_value(document.header, "\\use_%s" % p , i)
354             document.header[i] = "\\use_package %s %s" % (p, value)
355
356
357 def revert_use_packages(document):
358     "use_package xxx yyy => use_xxx yyy"
359     packages = {"amsmath":"1", "esint":"1", "mathdots":"1", "mhchem":"1", "undertilde":"1"}
360     # the order is arbitrary for the use_package version, and not all packages need to be given.
361     # Ensure a complete list and correct order (important for older LyX versions and especially lyx2lyx)
362     j = -1
363     for p in packages.keys():
364         regexp = re.compile(r'(\\use_package\s+%s)' % p)
365         i = find_re(document.header, regexp, 0)
366         if i != -1:
367             value = get_value(document.header, "\\use_package" , i).split()[1]
368             del document.header[i]
369             j = i
370     for (p, v) in packages.items():
371         document.header.insert(j, "\\use_%s %s"  % (p, value))
372         j = j + 1
373
374
375 def convert_use_mathtools(document):
376     "insert use_package mathtools"
377     i = find_token(document.header, "\\use_package", 0)
378     if i == -1:
379         document.warning("Malformed LyX document: Can't find \\use_package.")
380         return;
381     j = find_token(document.preamble, "\\usepackage{mathtools}", 0)
382     if j == -1:
383         document.header.insert(i + 1, "\\use_package mathtools 0")
384     else:
385         document.header.insert(i + 1, "\\use_package mathtools 2")
386         del document.preamble[j]
387
388
389 def revert_use_mathtools(document):
390     "remove use_package mathtools"
391     regexp = re.compile(r'(\\use_package\s+mathtools)')
392     i = find_re(document.header, regexp, 0)
393     value = "1" # default is auto
394     if i != -1:
395         value = get_value(document.header, "\\use_package" , i).split()[1]
396         del document.header[i]
397     if value == "2": # on
398         add_to_preamble(document, ["\\usepackage{mathtools}"])
399     elif value == "1": # auto
400         commands = ["mathclap", "mathllap", "mathrlap", \
401                     "lgathered", "rgathered", "vcentcolon", "dblcolon", \
402                     "coloneqq", "Coloneqq", "coloneq", "Coloneq", "eqqcolon", \
403                     "Eqqcolon", "eqcolon", "Eqcolon", "colonapprox", \
404                     "Colonapprox", "colonsim", "Colonsim"]
405         i = 0
406         while True:
407             i = find_token(document.body, '\\begin_inset Formula', i)
408             if i == -1:
409                 return
410             j = find_end_of_inset(document.body, i)
411             if j == -1:
412                 document.warning("Malformed LyX document: Can't find end of Formula inset at line " + str(i))
413                 i += 1
414                 continue
415             code = "\n".join(document.body[i:j])
416             for c in commands:
417                 if code.find("\\%s" % c) != -1:
418                     add_to_preamble(document, ["\\usepackage{mathtools}"])
419                     return
420             i = j
421
422
423 def convert_cite_engine_type(document):
424     "Determine the \\cite_engine_type from the citation engine."
425     i = find_token(document.header, "\\cite_engine", 0)
426     if i == -1:
427         return
428     engine = get_value(document.header, "\\cite_engine", i)
429     if "_" in engine:
430         engine, type = engine.split("_")
431     else:
432         type = {"basic": "numerical", "jurabib": "authoryear"}[engine]
433     document.header[i] = "\\cite_engine " + engine
434     document.header.insert(i + 1, "\\cite_engine_type " + type)
435
436
437 def revert_cite_engine_type(document):
438     "Natbib had the type appended with an underscore."
439     engine_type = "numerical"
440     i = find_token(document.header, "\\cite_engine_type" , 0)
441     if i == -1:
442         document.warning("No \\cite_engine_type line. Assuming numerical.")
443     else:
444         engine_type = get_value(document.header, "\\cite_engine_type", i)
445         del document.header[i]
446
447     # We are looking for the natbib citation engine
448     i = find_token(document.header, "\\cite_engine natbib", 0)
449     if i == -1:
450         return
451     document.header[i] = "\\cite_engine natbib_" + engine_type
452
453
454 def revert_cancel(document):
455     "add cancel to the preamble if necessary"
456     commands = ["cancelto", "cancel", "bcancel", "xcancel"]
457     i = 0
458     while True:
459         i = find_token(document.body, '\\begin_inset Formula', i)
460         if i == -1:
461             return
462         j = find_end_of_inset(document.body, i)
463         if j == -1:
464             document.warning("Malformed LyX document: Can't find end of Formula inset at line " + str(i))
465             i += 1
466             continue
467         code = "\n".join(document.body[i:j])
468         for c in commands:
469             if code.find("\\%s" % c) != -1:
470                 add_to_preamble(document, ["\\usepackage{cancel}"])
471                 return
472         i = j
473
474
475 def revert_verbatim(document):
476     " Revert verbatim einvironments completely to TeX-code. "
477     i = 0
478     consecutive = False
479     subst_end = ['\end_layout', '', '\\begin_layout Plain Layout',
480                  '\end_layout', '',
481                  '\\begin_layout Plain Layout', '', '',
482                  '\\backslash', '',
483                  'end{verbatim}',
484                  '\\end_layout', '', '\\end_inset',
485                  '', '', '\\end_layout']
486     subst_begin = ['\\begin_layout Standard', '\\noindent',
487                    '\\begin_inset ERT', 'status collapsed', '',
488                    '\\begin_layout Plain Layout', '', '', '\\backslash',
489                    'begin{verbatim}',
490                    '\\end_layout', '', '\\begin_layout Plain Layout', '']
491     while 1:
492         i = find_token(document.body, "\\begin_layout Verbatim", i)
493         if i == -1:
494             return
495         j = find_end_of_layout(document.body, i)
496         if j == -1:
497             document.warning("Malformed lyx document: Can't find end of Verbatim layout")
498             i += 1
499             continue
500         # delete all line breaks insets (there are no other insets)
501         l = i
502         while 1:
503             n = find_token(document.body, "\\begin_inset Newline newline", l)
504             if n == -1:
505                 n = find_token(document.body, "\\begin_inset Newline linebreak", l)
506                 if n == -1:
507                     break
508             m = find_end_of_inset(document.body, n)
509             del(document.body[m:m+1])
510             document.body[n:n+1] = ['\end_layout', '', '\\begin_layout Plain Layout']
511             l += 1
512             j += 1
513         # consecutive verbatim environments need to be connected
514         k = find_token(document.body, "\\begin_layout Verbatim", j)
515         if k == j + 2 and consecutive == False:
516             consecutive = True
517             document.body[j:j+1] = ['\end_layout', '', '\\begin_layout Plain Layout']
518             document.body[i:i+1] = subst_begin
519             continue
520         if k == j + 2 and consecutive == True:
521             document.body[j:j+1] = ['\end_layout', '', '\\begin_layout Plain Layout']
522             del(document.body[i:i+1])
523             continue
524         if k != j + 2 and consecutive == True:
525             document.body[j:j+1] = subst_end
526             # the next paragraph must not be indented
527             document.body[j+19:j+19] = ['\\noindent']
528             del(document.body[i:i+1])
529             consecutive = False
530             continue
531         else:
532             document.body[j:j+1] = subst_end
533             # the next paragraph must not be indented
534             document.body[j+19:j+19] = ['\\noindent']
535             document.body[i:i+1] = subst_begin
536
537
538 def revert_tipa(document):
539     " Revert native TIPA insets to mathed or ERT. "
540     i = 0
541     while 1:
542         i = find_token(document.body, "\\begin_inset IPA", i)
543         if i == -1:
544             return
545         j = find_end_of_inset(document.body, i)
546         if j == -1:
547             document.warning("Malformed lyx document: Can't find end of IPA inset")
548             i += 1
549             continue
550         Multipar = False
551         n = find_token(document.body, "\\begin_layout", i, j)
552         if n == -1:
553             document.warning("Malformed lyx document: IPA inset has no embedded layout")
554             i += 1
555             continue
556         m = find_end_of_layout(document.body, n)
557         if m == -1:
558             document.warning("Malformed lyx document: Can't find end of embedded layout")
559             i += 1
560             continue
561         content = document.body[n+1:m]
562         p = find_token(document.body, "\\begin_layout", m, j)
563         if p != -1 or len(content) > 1:
564             Multipar = True
565             content = document.body[i+1:j]
566         if Multipar:
567             # IPA insets with multiple pars need to be wrapped by \begin{IPA}...\end{IPA}
568             document.body[i:j+1] = ['\\end_layout', '', '\\begin_layout Standard'] + put_cmd_in_ert("\\begin{IPA}") + ['\\end_layout'] + content + ['\\begin_layout Standard'] + put_cmd_in_ert("\\end{IPA}")
569             add_to_preamble(document, ["\\usepackage{tipa,tipx}"])
570         else:
571             # single-par IPA insets can be reverted to mathed
572             document.body[i:j+1] = ["\\begin_inset Formula $\\text{\\textipa{" + content[0] + "}}$", "\\end_inset"]
573         i = j
574
575
576 ##
577 # Conversion hub
578 #
579
580 supported_versions = ["2.1.0","2.1"]
581 convert = [
582            [414, []],
583            [415, [convert_undertilde]],
584            [416, []],
585            [417, [convert_japanese_encodings]],
586            [418, []],
587            [419, []],
588            [420, [convert_biblio_style]],
589            [421, [convert_longtable_captions]],
590            [422, [convert_use_packages]],
591            [423, [convert_use_mathtools]],
592            [424, [convert_cite_engine_type]],
593            [425, []],
594            [426, []],
595            [427, []]
596           ]
597
598 revert =  [
599            [426, [revert_tipa]],
600            [425, [revert_verbatim]],
601            [424, [revert_cancel]],
602            [423, [revert_cite_engine_type]],
603            [422, [revert_use_mathtools]],
604            [421, [revert_use_packages]],
605            [420, [revert_longtable_captions]],
606            [419, [revert_biblio_style]],
607            [418, [revert_australian]],
608            [417, [revert_justification]],
609            [416, [revert_japanese_encodings]],
610            [415, [revert_negative_space, revert_math_spaces]],
611            [414, [revert_undertilde]],
612            [413, [revert_visible_space]]
613           ]
614
615
616 if __name__ == "__main__":
617     pass