]> git.lyx.org Git - features.git/blob - lib/lyx2lyx/lyx_2_1.py
lyx2lyx/lyx_2_1.py: fix #8172
[features.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, del_token, check_token
35
36 from lyx2lyx_tools import add_to_preamble, put_cmd_in_ert, get_ert
37
38 #from lyx2lyx_tools import insert_to_preamble, \
39 #  lyx2latex, latex_length, revert_flex_inset, \
40 #  revert_font_attrs, hex2ratio, str2bool
41
42 ####################################################################
43 # Private helper functions
44
45 #def remove_option(lines, m, option):
46     #''' removes option from line m. returns whether we did anything '''
47     #l = lines[m].find(option)
48     #if l == -1:
49         #return False
50     #val = lines[m][l:].split('"')[1]
51     #lines[m] = lines[m][:l - 1] + lines[m][l+len(option + '="' + val + '"'):]
52     #return True
53
54
55 ###############################################################################
56 ###
57 ### Conversion and reversion routines
58 ###
59 ###############################################################################
60
61 def revert_visible_space(document):
62     "Revert InsetSpace visible into its ERT counterpart"
63     i = 0
64     while True:
65       i = find_token(document.body, "\\begin_inset space \\textvisiblespace{}", i)
66       if i == -1:
67         return
68       end = find_end_of_inset(document.body, i)
69       subst = put_cmd_in_ert("\\textvisiblespace{}")
70       document.body[i:end + 1] = subst
71
72
73 def convert_undertilde(document):
74     " Load undertilde automatically "
75     i = find_token(document.header, "\\use_mathdots" , 0)
76     if i == -1:
77         i = find_token(document.header, "\\use_mhchem" , 0)
78     if i == -1:
79         i = find_token(document.header, "\\use_esint" , 0)
80     if i == -1:
81         document.warning("Malformed LyX document: Can't find \\use_mathdots.")
82         return;
83     j = find_token(document.preamble, "\\usepackage{undertilde}", 0)
84     if j == -1:
85         document.header.insert(i + 1, "\\use_undertilde 0")
86     else:
87         document.header.insert(i + 1, "\\use_undertilde 2")
88         del document.preamble[j]
89
90
91 def revert_undertilde(document):
92     " Load undertilde if used in the document "
93     undertilde = find_token(document.header, "\\use_undertilde" , 0)
94     if undertilde == -1:
95       document.warning("No \\use_undertilde line. Assuming auto.")
96     else:
97       val = get_value(document.header, "\\use_undertilde", undertilde)
98       del document.header[undertilde]
99       try:
100         usetilde = int(val)
101       except:
102         document.warning("Invalid \\use_undertilde value: " + val + ". Assuming auto.")
103         # probably usedots has not been changed, but be safe.
104         usetilde = 1
105
106       if usetilde == 0:
107         # do not load case
108         return
109       if usetilde == 2:
110         # force load case
111         add_to_preamble(document, ["\\usepackage{undertilde}"])
112         return
113
114     # so we are in the auto case. we want to load undertilde if \utilde is used.
115     i = 0
116     while True:
117       i = find_token(document.body, '\\begin_inset Formula', i)
118       if i == -1:
119         return
120       j = find_end_of_inset(document.body, i)
121       if j == -1:
122         document.warning("Malformed LyX document: Can't find end of Formula inset at line " + str(i))
123         i += 1
124         continue
125       code = "\n".join(document.body[i:j])
126       if code.find("\\utilde") != -1:
127         add_to_preamble(document, ["\\@ifundefined{utilde}{\\usepackage{undertilde}}"])
128         return
129       i = j
130
131
132 def revert_negative_space(document):
133     "Revert InsetSpace negmedspace and negthickspace into its TeX-code counterpart"
134     i = 0
135     j = 0
136     reverted = False
137     while True:
138       i = find_token(document.body, "\\begin_inset space \\negmedspace{}", i)
139       if i == -1:
140         j = find_token(document.body, "\\begin_inset space \\negthickspace{}", j)
141         if j == -1:
142           # load amsmath in the preamble if not already loaded if we are at the end of checking
143           if reverted == True:
144             i = find_token(document.header, "\\use_amsmath 2", 0)
145             if i == -1:
146               add_to_preamble(document, ["\\@ifundefined{negthickspace}{\\usepackage{amsmath}}"])
147           return
148       if i == -1:
149         return
150       end = find_end_of_inset(document.body, i)
151       subst = put_cmd_in_ert("\\negmedspace{}")
152       document.body[i:end + 1] = subst
153       j = find_token(document.body, "\\begin_inset space \\negthickspace{}", j)
154       if j == -1:
155         return
156       end = find_end_of_inset(document.body, j)
157       subst = put_cmd_in_ert("\\negthickspace{}")
158       document.body[j:end + 1] = subst
159       reverted = True
160
161
162 def revert_math_spaces(document):
163     "Revert formulas with protected custom space and protected hfills to TeX-code"
164     i = 0
165     while True:
166       i = find_token(document.body, "\\begin_inset Formula", i)
167       if i == -1:
168         return
169       j = document.body[i].find("\\hspace*")
170       if j != -1:
171         end = find_end_of_inset(document.body, i)
172         subst = put_cmd_in_ert(document.body[i][21:])
173         document.body[i:end + 1] = subst
174       i = i + 1
175
176
177 def convert_japanese_encodings(document):
178     " Rename the japanese encodings to names understood by platex "
179     jap_enc_dict = {
180         "EUC-JP-pLaTeX": "euc",
181         "JIS-pLaTeX":    "jis",
182         "SJIS-pLaTeX":   "sjis"
183     }
184     i = find_token(document.header, "\\inputencoding" , 0)
185     if i == -1:
186         return
187     val = get_value(document.header, "\\inputencoding", i)
188     if val in jap_enc_dict.keys():
189         document.header[i] = "\\inputencoding %s" % jap_enc_dict[val]
190
191
192 def revert_japanese_encodings(document):
193     " Revert the japanese encodings name changes "
194     jap_enc_dict = {
195         "euc":  "EUC-JP-pLaTeX",
196         "jis":  "JIS-pLaTeX",
197         "sjis": "SJIS-pLaTeX"
198     }
199     i = find_token(document.header, "\\inputencoding" , 0)
200     if i == -1:
201         return
202     val = get_value(document.header, "\\inputencoding", i)
203     if val in jap_enc_dict.keys():
204         document.header[i] = "\\inputencoding %s" % jap_enc_dict[val]
205
206
207 def revert_justification(document):
208     " Revert the \\justification buffer param"
209     if not del_token(document.header, '\\justification', 0):
210         document.warning("Malformed LyX document: Missing \\justification.")
211
212
213 def revert_australian(document):
214     "Set English language variants Australian and Newzealand to English" 
215
216     if document.language == "australian" or document.language == "newzealand": 
217         document.language = "english" 
218         i = find_token(document.header, "\\language", 0) 
219         if i != -1: 
220             document.header[i] = "\\language english" 
221
222     j = 0 
223     while True: 
224         j = find_token(document.body, "\\lang australian", j) 
225         if j == -1: 
226             j = find_token(document.body, "\\lang newzealand", 0)
227             if j == -1:
228                 return
229             else:
230                 document.body[j] = document.body[j].replace("\\lang newzealand", "\\lang english")
231         else:
232             document.body[j] = document.body[j].replace("\\lang australian", "\\lang english") 
233         j += 1
234
235
236 def convert_biblio_style(document):
237     "Add a sensible default for \\biblio_style based on the citation engine."
238     i = find_token(document.header, "\\cite_engine", 0)
239     if i != -1:
240         engine = get_value(document.header, "\\cite_engine", i).split("_")[0]
241         style = {"basic": "plain", "natbib": "plainnat", "jurabib": "jurabib"}
242         document.header.insert(i + 1, "\\biblio_style " + style[engine])
243
244
245 def revert_biblio_style(document):
246     "BibTeX insets with default option use the style defined by \\biblio_style."
247     i = find_token(document.header, "\\biblio_style" , 0)
248     if i == -1:
249         document.warning("No \\biblio_style line. Nothing to do.")
250         return
251
252     default_style = get_value(document.header, "\\biblio_style", i)
253     del document.header[i]
254
255     # We are looking for bibtex insets having the default option
256     i = 0
257     while True:
258         i = find_token(document.body, "\\begin_inset CommandInset bibtex", i)
259         if i == -1:
260             return
261         j = find_end_of_inset(document.body, i)
262         if j == -1:
263             document.warning("Malformed LyX document: Can't find end of bibtex inset at line " + str(i))
264             i += 1
265             return
266         k = find_token(document.body, "options", i, j)
267         if k != -1:
268             options = get_quoted_value(document.body, "options", k)
269             if "default" in options.split(","):
270                 document.body[k] = 'options "%s"' \
271                     % options.replace("default", default_style)
272         i = j
273
274
275 def handle_longtable_captions(document, forward):
276     begin_table = 0
277     while True:
278         begin_table = find_token(document.body, '<lyxtabular version=', begin_table)
279         if begin_table == -1:
280             break
281         end_table = find_end_of(document.body, begin_table, '<lyxtabular', '</lyxtabular>')
282         if end_table == -1:
283             document.warning("Malformed LyX document: Could not find end of table.")
284             begin_table += 1
285             continue
286         fline = find_token(document.body, "<features", begin_table, end_table)
287         if fline == -1:
288             document.warning("Can't find features for inset at line " + str(begin_table))
289             begin_table += 1
290             continue
291         p = document.body[fline].find("islongtable")
292         if p == -1:
293             # no longtable
294             begin_table += 1
295             continue
296         numrows = get_option_value(document.body[begin_table], "rows")
297         try:
298             numrows = int(numrows)
299         except:
300             document.warning(document.body[begin_table])
301             document.warning("Unable to determine rows!")
302             begin_table = end_table
303             continue
304         begin_row = begin_table
305         for row in range(numrows):
306             begin_row = find_token(document.body, '<row', begin_row, end_table)
307             if begin_row == -1:
308                 document.warning("Can't find row " + str(row + 1))
309                 break
310             end_row = find_end_of(document.body, begin_row, '<row', '</row>')
311             if end_row == -1:
312                 document.warning("Can't find end of row " + str(row + 1))
313                 break
314             if forward:
315                 if (get_option_value(document.body[begin_row], 'caption') == 'true' and
316                     get_option_value(document.body[begin_row], 'endfirsthead') != 'true' and
317                     get_option_value(document.body[begin_row], 'endhead') != 'true' and
318                     get_option_value(document.body[begin_row], 'endfoot') != 'true' and
319                     get_option_value(document.body[begin_row], 'endlastfoot') != 'true'):
320                     document.body[begin_row] = set_option_value(document.body[begin_row], 'caption', 'true", endfirsthead="true')
321             elif get_option_value(document.body[begin_row], 'caption') == 'true':
322                 if get_option_value(document.body[begin_row], 'endfirsthead') == 'true':
323                     document.body[begin_row] = set_option_value(document.body[begin_row], 'endfirsthead', 'false')
324                 if get_option_value(document.body[begin_row], 'endhead') == 'true':
325                     document.body[begin_row] = set_option_value(document.body[begin_row], 'endhead', 'false')
326                 if get_option_value(document.body[begin_row], 'endfoot') == 'true':
327                     document.body[begin_row] = set_option_value(document.body[begin_row], 'endfoot', 'false')
328                 if get_option_value(document.body[begin_row], 'endlastfoot') == 'true':
329                     document.body[begin_row] = set_option_value(document.body[begin_row], 'endlastfoot', 'false')
330             begin_row = end_row
331         # since there could be a tabular inside this one, we 
332         # cannot jump to end.
333         begin_table += 1
334
335
336 def convert_longtable_captions(document):
337     "Add a firsthead flag to caption rows"
338     handle_longtable_captions(document, True)
339
340
341 def revert_longtable_captions(document):
342     "remove head/foot flag from caption rows"
343     handle_longtable_captions(document, False)
344
345
346 def convert_use_packages(document):
347     "use_xxx yyy => use_package xxx yyy"
348     packages = ["amsmath", "esint", "mathdots", "mhchem", "undertilde"]
349     for p in packages:
350         i = find_token(document.header, "\\use_%s" % p, 0)
351         if i != -1:
352             value = get_value(document.header, "\\use_%s" % p, i)
353             document.header[i] = "\\use_package %s %s" % (p, value)
354
355
356 def revert_use_packages(document):
357     "use_package xxx yyy => use_xxx yyy"
358     packages = ["amsmath", "esint", "mathdots", "mhchem", "undertilde"]
359     # the order is arbitrary for the use_package version, and not all packages need to be given.
360     # Ensure a complete list and correct order (important for older LyX versions and especially lyx2lyx)
361     j = 0
362     for p in packages:
363         regexp = re.compile(r'(\\use_package\s+%s)' % p)
364         i = find_re(document.header, regexp, j)
365         if i != -1:
366             value = get_value(document.header, "\\use_package %s" % p, i).split()[1]
367             document.warning(str(value))
368             del document.header[i]
369             j = i
370             document.header.insert(j, "\\use_%s %s"  % (p, value))
371             document.warning(str(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 def revert_cell_rotation(document):
577   "Revert cell rotations to TeX-code"
578
579   load_rotating = False
580   i = 0
581   try:
582     while True:
583       # first, let's find out if we need to do anything
584       i = find_token(document.body, '<cell ', i)
585       if i == -1:
586         return
587       j = document.body[i].find('rotate="')
588       if j != -1:
589         k = document.body[i].find('"', j + 8)
590         value = document.body[i][j + 8 : k]
591         if value == "0":
592           rgx = re.compile(r' rotate="[^"]+?"')
593           # remove rotate option
594           document.body[i] = rgx.sub('', document.body[i])
595         elif value == "90":
596           rgx = re.compile(r' rotate="[^"]+?"')
597           document.body[i] = rgx.sub('rotate="true"', document.body[i])
598         else:
599           rgx = re.compile(r' rotate="[^"]+?"')
600           load_rotating = True
601           # remove rotate option
602           document.body[i] = rgx.sub('', document.body[i])
603           # write ERT
604           document.body[i + 5 : i + 5] = \
605             put_cmd_in_ert("\\end{turn}")
606           document.body[i + 4 : i + 4] = \
607             put_cmd_in_ert("\\begin{turn}{" + value + "}")
608         
609       i += 1
610         
611   finally:
612     if load_rotating:
613       add_to_preamble(document, ["\\@ifundefined{turnbox}{\usepackage{rotating}}{}"])
614
615
616 def convert_cell_rotation(document):
617     'Convert cell rotation statements from "true" to "90"'
618
619     i = 0
620     while True:
621       # first, let's find out if we need to do anything
622       i = find_token(document.body, '<cell ', i)
623       if i == -1:
624         return
625       j = document.body[i].find('rotate="true"')
626       if j != -1:
627         rgx = re.compile(r'rotate="[^"]+?"')
628         # convert "true" to "90"
629         document.body[i] = rgx.sub('rotate="90"', document.body[i])
630         
631       i += 1
632
633
634 def revert_table_rotation(document):
635   "Revert table rotations to TeX-code"
636
637   load_rotating = False
638   i = 0
639   try:
640     while True:
641       # first, let's find out if we need to do anything
642       i = find_token(document.body, '<features ', i)
643       if i == -1:
644         return
645       j = document.body[i].find('rotate="')
646       if j != -1:
647         end_table = find_token(document.body, '</lyxtabular>', j)
648         k = document.body[i].find('"', j + 8)
649         value = document.body[i][j + 8 : k]
650         if value == "0":
651           rgx = re.compile(r' rotate="[^"]+?"')
652           # remove rotate option
653           document.body[i] = rgx.sub('', document.body[i])
654         elif value == "90":
655           rgx = re.compile(r'rotate="[^"]+?"')
656           document.body[i] = rgx.sub('rotate="true"', document.body[i])
657         else:
658           rgx = re.compile(r' rotate="[^"]+?"')
659           load_rotating = True
660           # remove rotate option
661           document.body[i] = rgx.sub('', document.body[i])
662           # write ERT
663           document.body[end_table + 3 : end_table + 3] = \
664             put_cmd_in_ert("\\end{turn}")
665           document.body[i - 2 : i - 2] = \
666             put_cmd_in_ert("\\begin{turn}{" + value + "}")
667         
668       i += 1
669         
670   finally:
671     if load_rotating:
672       add_to_preamble(document, ["\\@ifundefined{turnbox}{\usepackage{rotating}}{}"])
673
674
675 def convert_table_rotation(document):
676     'Convert table rotation statements from "true" to "90"'
677
678     i = 0
679     while True:
680       # first, let's find out if we need to do anything
681       i = find_token(document.body, '<features ', i)
682       if i == -1:
683         return
684       j = document.body[i].find('rotate="true"')
685       if j != -1:
686         rgx = re.compile(r'rotate="[^"]+?"')
687         # convert "true" to "90"
688         document.body[i] = rgx.sub('rotate="90"', document.body[i])
689         
690       i += 1
691
692
693 def convert_listoflistings(document):
694     'Convert ERT \lstlistoflistings to TOC lstlistoflistings inset'
695     # We can support roundtrip because the command is so simple
696     i = 0
697     while True:
698         i = find_token(document.body, "\\begin_inset ERT", i)
699         if i == -1:
700             return
701         j = find_end_of_inset(document.body, i)
702         if j == -1:
703             document.warning("Malformed lyx document: Can't find end of ERT inset")
704             i += 1
705             continue
706         ert = get_ert(document.body, i)
707         if ert == "\\lstlistoflistings{}":
708             document.body[i:j] = ["\\begin_inset CommandInset toc", "LatexCommand lstlistoflistings", ""]
709             i = i + 4
710         else:
711             i = j + 1
712
713
714 def revert_listoflistings(document):
715     'Convert TOC lstlistoflistings inset to ERT lstlistoflistings'
716     i = 0
717     while True:
718         i = find_token(document.body, "\\begin_inset CommandInset toc", i)
719         if i == -1:
720             return
721         if document.body[i+1] == "LatexCommand lstlistoflistings":
722             j = find_end_of_inset(document.body, i)
723             if j == -1:
724                 document.warning("Malformed lyx document: Can't find end of TOC inset")
725                 i += 1
726                 continue
727             subst = put_cmd_in_ert("\\lstlistoflistings{}")
728             document.body[i:j+1] = subst
729             add_to_preamble(document, ["\\usepackage{listings}"])
730         i = i + 1
731
732
733 def convert_use_amssymb(document):
734     "insert use_package amssymb"
735     regexp = re.compile(r'(\\use_package\s+amsmath)')
736     i = find_re(document.header, regexp, 0)
737     if i == -1:
738         document.warning("Malformed LyX document: Can't find \\use_package amsmath.")
739         return;
740     value = get_value(document.header, "\\use_package" , i).split()[1]
741     useamsmath = 0
742     try:
743         useamsmath = int(value)
744     except:
745         document.warning("Invalid \\use_package amsmath: " + value + ". Assuming auto.")
746         useamsmath = 1
747     j = find_token(document.preamble, "\\usepackage{amssymb}", 0)
748     if j == -1:
749         document.header.insert(i + 1, "\\use_package amssymb %d" % useamsmath)
750     else:
751         document.header.insert(i + 1, "\\use_package amssymb 2")
752         del document.preamble[j]
753
754
755 def revert_use_amssymb(document):
756     "remove use_package amssymb"
757     regexp1 = re.compile(r'(\\use_package\s+amsmath)')
758     regexp2 = re.compile(r'(\\use_package\s+amssymb)')
759     i = find_re(document.header, regexp1, 0)
760     j = find_re(document.header, regexp2, 0)
761     value1 = "1" # default is auto
762     value2 = "1" # default is auto
763     if i != -1:
764         value1 = get_value(document.header, "\\use_package" , i).split()[1]
765     if j != -1:
766         value2 = get_value(document.header, "\\use_package" , j).split()[1]
767         del document.header[j]
768     if value1 != value2 and value2 == "2": # on
769         add_to_preamble(document, ["\\usepackage{amssymb}"])
770
771
772 ##
773 # Conversion hub
774 #
775
776 supported_versions = ["2.1.0","2.1"]
777 convert = [
778            [414, []],
779            [415, [convert_undertilde]],
780            [416, []],
781            [417, [convert_japanese_encodings]],
782            [418, []],
783            [419, []],
784            [420, [convert_biblio_style]],
785            [421, [convert_longtable_captions]],
786            [422, [convert_use_packages]],
787            [423, [convert_use_mathtools]],
788            [424, [convert_cite_engine_type]],
789            [425, []],
790            [426, []],
791            [427, []],
792            [428, [convert_cell_rotation]],
793            [429, [convert_table_rotation]],
794            [430, [convert_listoflistings]],
795            [431, [convert_use_amssymb]],
796           ]
797
798 revert =  [
799            [430, [revert_use_amssymb]],
800            [429, [revert_listoflistings]],
801            [428, [revert_table_rotation]],
802            [427, [revert_cell_rotation]],
803            [426, [revert_tipa]],
804            [425, [revert_verbatim]],
805            [424, [revert_cancel]],
806            [423, [revert_cite_engine_type]],
807            [422, [revert_use_mathtools]],
808            [421, [revert_use_packages]],
809            [420, [revert_longtable_captions]],
810            [419, [revert_biblio_style]],
811            [418, [revert_australian]],
812            [417, [revert_justification]],
813            [416, [revert_japanese_encodings]],
814            [415, [revert_negative_space, revert_math_spaces]],
815            [414, [revert_undertilde]],
816            [413, [revert_visible_space]]
817           ]
818
819
820 if __name__ == "__main__":
821     pass