]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_1_6.py
0f17557d5b515d8ba3f469dcdd551078d2447c93
[lyx.git] / lib / lyx2lyx / lyx_1_6.py
1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2007-2008 The LyX Team <lyx-devel@lists.lyx.org>
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 """ Convert files to the file format generated by lyx 1.6"""
20
21 import re
22 import unicodedata
23 import sys, os
24
25 from parser_tools import find_token, find_end_of, find_tokens, get_value, get_value_string
26
27 ####################################################################
28 # Private helper functions
29
30 def find_end_of_inset(lines, i):
31     " Find end of inset, where lines[i] is included."
32     return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
33
34 def wrap_into_ert(string, src, dst):
35     " Wrap a something into an ERT"
36     return string.replace(src, '\n\\begin_inset ERT\nstatus collapsed\n\\begin_layout Standard\n'
37       + dst + '\n\\end_layout\n\\end_inset\n')
38
39 def add_to_preamble(document, text):
40     """ Add text to the preamble if it is not already there.
41     Only the first line is checked!"""
42
43     if find_token(document.preamble, text[0], 0) != -1:
44         return
45
46     document.preamble.extend(text)
47
48 # Convert a LyX length into a LaTeX length
49 def convert_len(len):
50     units = {"text%":"\\backslash\ntextwidth", "col%":"\\backslash\ncolumnwidth",
51              "page%":"\\backslash\npagewidth", "line%":"\\backslash\nlinewidth",
52              "theight%":"\\backslash\ntextheight", "pheight%":"\\backslash\npageheight"}
53
54     # Convert LyX units to LaTeX units
55     for unit in units.keys():
56         if len.find(unit) != -1:
57             len = '%f' % (len2value(len) / 100)
58             len = len.strip('0') + units[unit]
59             break
60
61     return len
62
63 # Return the value of len without the unit in numerical form.
64 def len2value(len):
65     result = re.search('([+-]?[0-9.]+)', len)
66     if result:
67         return float(result.group(1))
68     # No number means 1.0
69     return 1.0
70
71 # Unfortunately, this doesn't really work, since Standard isn't always default.
72 # But it's as good as we can do right now.
73 def find_default_layout(document, start, end):
74     l = find_token(document.body, "\\begin_layout Standard", start, end)
75     if l == -1:
76         l = find_token(document.body, "\\begin_layout PlainLayout", start, end)
77     if l == -1:
78         l = find_token(document.body, "\\begin_layout Plain Layout", start, end)
79     return l
80
81 def get_option(document, m, option, default):
82     l = document.body[m].find(option)
83     val = default
84     if l != -1:
85         val = document.body[m][l:].split('"')[1]
86     return val
87
88 def remove_option(document, m, option):
89     l = document.body[m].find(option)
90     if l != -1:
91         val = document.body[m][l:].split('"')[1]
92         document.body[m] = document.body[m][:l-1] + document.body[m][l+len(option + '="' + val + '"'):]
93     return l
94
95 def set_option(document, m, option, value):
96     l = document.body[m].find(option)
97     if l != -1:
98         oldval = document.body[m][l:].split('"')[1]
99         l = l + len(option + '="')
100         document.body[m] = document.body[m][:l] + value + document.body[m][l+len(oldval):]
101     else:
102         document.body[m] = document.body[m][:-1] + ' ' + option + '="' + value + '">'
103     return l
104
105
106 ####################################################################
107
108 def convert_ltcaption(document):
109     i = 0
110     while True:
111         i = find_token(document.body, "\\begin_inset Tabular", i)
112         if i == -1:
113             return
114         j = find_end_of_inset(document.body, i + 1)
115         if j == -1:
116             document.warning("Malformed LyX document: Could not find end of tabular.")
117             continue
118
119         nrows = int(document.body[i+1].split('"')[3])
120         ncols = int(document.body[i+1].split('"')[5])
121
122         m = i + 1
123         for k in range(nrows):
124             m = find_token(document.body, "<row", m)
125             r = m
126             caption = 'false'
127             for k in range(ncols):
128                 m = find_token(document.body, "<cell", m)
129                 if (k == 0):
130                     mend = find_token(document.body, "</cell>", m + 1)
131                     # first look for caption insets
132                     mcap = find_token(document.body, "\\begin_inset Caption", m + 1, mend)
133                     # then look for ERT captions
134                     if mcap == -1:
135                         mcap = find_token(document.body, "caption", m + 1, mend)
136                         if mcap > -1:
137                             mcap = find_token(document.body, "\\backslash", mcap - 1, mcap)
138                     if mcap > -1:
139                         caption = 'true'
140                 if caption == 'true':
141                     if (k == 0):
142                         set_option(document, r, 'caption', 'true')
143                         set_option(document, m, 'multicolumn', '1')
144                         set_option(document, m, 'bottomline', 'false')
145                         set_option(document, m, 'topline', 'false')
146                         set_option(document, m, 'rightline', 'false')
147                         set_option(document, m, 'leftline', 'false')
148                         #j = find_end_of_inset(document.body, j + 1)
149                     else:
150                         set_option(document, m, 'multicolumn', '2')
151                 m = m + 1
152             m = m + 1
153
154         i = j + 1
155
156 def revert_ltcaption(document):
157     i = 0
158     while True:
159         i = find_token(document.body, "\\begin_inset Tabular", i)
160         if i == -1:
161             return
162         j = find_end_of_inset(document.body, i + 1)
163         if j == -1:
164             document.warning("Malformed LyX document: Could not find end of tabular.")
165             continue
166
167         m = i + 1
168         nrows = int(document.body[i+1].split('"')[3])
169         ncols = int(document.body[i+1].split('"')[5])
170
171         for k in range(nrows):
172             m = find_token(document.body, "<row", m)
173             caption = get_option(document, m, 'caption', 'false')
174             if caption == 'true':
175                 remove_option(document, m, 'caption')
176                 for k in range(ncols):
177                     m = find_token(document.body, "<cell", m)
178                     remove_option(document, m, 'multicolumn')
179                     if k == 0:
180                         m = find_token(document.body, "\\begin_inset Caption", m)
181                         if m == -1:
182                             return
183                         m = find_end_of_inset(document.body, m + 1)
184                         document.body[m] += wrap_into_ert("","","\\backslash\n\\backslash\n%")
185                     m = m + 1
186             m = m + 1
187         i = j + 1
188
189
190 def convert_tablines(document):
191     i = 0
192     while True:
193         i = find_token(document.body, "\\begin_inset Tabular", i)
194         if i == -1:
195             # LyX 1.3 inserted an extra space between \begin_inset
196             # and Tabular so let us try if this is the case and fix it.
197             i = find_token(document.body, "\\begin_inset  Tabular", i)
198             if i == -1:
199                 return
200             else:
201                 document.body[i] = "\\begin_inset Tabular"
202         j = find_end_of_inset(document.body, i + 1)
203         if j == -1:
204             document.warning("Malformed LyX document: Could not find end of tabular.")
205             continue
206
207         m = i + 1
208         nrows = int(document.body[i+1].split('"')[3])
209         ncols = int(document.body[i+1].split('"')[5])
210
211         col_info = []
212         for k in range(ncols):
213             m = find_token(document.body, "<column", m)
214             left = get_option(document, m, 'leftline', 'false')
215             right = get_option(document, m, 'rightline', 'false')
216             col_info.append([left, right])
217             remove_option(document, m, 'leftline')
218             remove_option(document, m, 'rightline')
219             m = m + 1
220
221         row_info = []
222         for k in range(nrows):
223             m = find_token(document.body, "<row", m)
224             top = get_option(document, m, 'topline', 'false')
225             bottom = get_option(document, m, 'bottomline', 'false')
226             row_info.append([top, bottom])
227             remove_option(document, m, 'topline')
228             remove_option(document, m, 'bottomline')
229             m = m + 1
230
231         m = i + 1
232         mc_info = []
233         for k in range(nrows*ncols):
234             m = find_token(document.body, "<cell", m)
235             mc_info.append(get_option(document, m, 'multicolumn', '0'))
236             m = m + 1
237         m = i + 1
238         for l in range(nrows):
239             for k in range(ncols):
240                 m = find_token(document.body, '<cell', m)
241                 if mc_info[l*ncols + k] == '0':
242                     r = set_option(document, m, 'topline', row_info[l][0])
243                     r = set_option(document, m, 'bottomline', row_info[l][1])
244                     r = set_option(document, m, 'leftline', col_info[k][0])
245                     r = set_option(document, m, 'rightline', col_info[k][1])
246                 elif mc_info[l*ncols + k] == '1':
247                     s = k + 1
248                     while s < ncols and mc_info[l*ncols + s] == '2':
249                         s = s + 1
250                     if s < ncols and mc_info[l*ncols + s] != '1':
251                         r = set_option(document, m, 'rightline', col_info[k][1])
252                     if k > 0 and mc_info[l*ncols + k - 1] == '0':
253                         r = set_option(document, m, 'leftline', col_info[k][0])
254                 m = m + 1
255         i = j + 1
256
257
258 def revert_tablines(document):
259     i = 0
260     while True:
261         i = find_token(document.body, "\\begin_inset Tabular", i)
262         if i == -1:
263             return
264         j = find_end_of_inset(document.body, i + 1)
265         if j == -1:
266             document.warning("Malformed LyX document: Could not find end of tabular.")
267             continue
268
269         m = i + 1
270         nrows = int(document.body[i+1].split('"')[3])
271         ncols = int(document.body[i+1].split('"')[5])
272
273         lines = []
274         for k in range(nrows*ncols):
275             m = find_token(document.body, "<cell", m)
276             top = get_option(document, m, 'topline', 'false')
277             bottom = get_option(document, m, 'bottomline', 'false')
278             left = get_option(document, m, 'leftline', 'false')
279             right = get_option(document, m, 'rightline', 'false')
280             lines.append([top, bottom, left, right])
281             m = m + 1
282
283         # we will want to ignore longtable captions
284         m = i + 1
285         caption_info = []
286         for k in range(nrows):
287             m = find_token(document.body, "<row", m)
288             caption = get_option(document, m, 'caption', 'false')
289             caption_info.append([caption])
290             m = m + 1
291
292         m = i + 1
293         col_info = []
294         for k in range(ncols):
295             m = find_token(document.body, "<column", m)
296             left = 'true'
297             for l in range(nrows):
298                 left = lines[l*ncols + k][2]
299                 if left == 'false' and caption_info[l] == 'false':
300                     break
301             set_option(document, m, 'leftline', left)
302             right = 'true'
303             for l in range(nrows):
304                 right = lines[l*ncols + k][3]
305                 if right == 'false' and caption_info[l] == 'false':
306                     break
307             set_option(document, m, 'rightline', right)
308             m = m + 1
309
310         row_info = []
311         for k in range(nrows):
312             m = find_token(document.body, "<row", m)
313             top = 'true'
314             for l in range(ncols):
315                 top = lines[k*ncols + l][0]
316                 if top == 'false':
317                     break
318             if caption_info[k] == 'false':
319                 top = 'false'
320             set_option(document, m, 'topline', top)
321             bottom = 'true'
322             for l in range(ncols):
323                 bottom = lines[k*ncols + l][1]
324                 if bottom == 'false':
325                     break
326             if caption_info[k] == 'false':
327                 bottom = 'false'
328             set_option(document, m, 'bottomline', bottom)
329             m = m + 1
330
331         i = j + 1
332
333
334 def fix_wrong_tables(document):
335     i = 0
336     while True:
337         i = find_token(document.body, "\\begin_inset Tabular", i)
338         if i == -1:
339             return
340         j = find_end_of_inset(document.body, i + 1)
341         if j == -1:
342             document.warning("Malformed LyX document: Could not find end of tabular.")
343             continue
344
345         m = i + 1
346         nrows = int(document.body[i+1].split('"')[3])
347         ncols = int(document.body[i+1].split('"')[5])
348
349         for l in range(nrows):
350             prev_multicolumn = 0
351             for k in range(ncols):
352                 m = find_token(document.body, '<cell', m)
353
354                 if document.body[m].find('multicolumn') != -1:
355                     multicol_cont = int(document.body[m].split('"')[1])
356
357                     if multicol_cont == 2 and (k == 0 or prev_multicolumn == 0):
358                         document.body[m] = document.body[m][:5] + document.body[m][21:]
359                         prev_multicolumn = 0
360                     else:
361                         prev_multicolumn = multicol_cont
362                 else:
363                     prev_multicolumn = 0
364
365         i = j + 1
366
367
368 def close_begin_deeper(document):
369     i = 0
370     depth = 0
371     while True:
372         i = find_tokens(document.body, ["\\begin_deeper", "\\end_deeper"], i)
373
374         if i == -1:
375             break
376
377         if document.body[i][:13] == "\\begin_deeper":
378             depth += 1
379         else:
380             depth -= 1
381
382         i += 1
383
384     document.body[-2:-2] = ['\\end_deeper' for i in range(depth)]
385
386
387 def long_charstyle_names(document):
388     i = 0
389     while True:
390         i = find_token(document.body, "\\begin_inset CharStyle", i)
391         if i == -1:
392             return
393         document.body[i] = document.body[i].replace("CharStyle ", "CharStyle CharStyle:")
394         i += 1
395
396 def revert_long_charstyle_names(document):
397     i = 0
398     while True:
399         i = find_token(document.body, "\\begin_inset CharStyle", i)
400         if i == -1:
401             return
402         document.body[i] = document.body[i].replace("CharStyle CharStyle:", "CharStyle")
403         i += 1
404
405
406 def axe_show_label(document):
407     i = 0
408     while True:
409         i = find_token(document.body, "\\begin_inset CharStyle", i)
410         if i == -1:
411             return
412         if document.body[i + 1].find("show_label") != -1:
413             if document.body[i + 1].find("true") != -1:
414                 document.body[i + 1] = "status open"
415                 del document.body[ i + 2]
416             else:
417                 if document.body[i + 1].find("false") != -1:
418                     document.body[i + 1] = "status collapsed"
419                     del document.body[ i + 2]
420                 else:
421                     document.warning("Malformed LyX document: show_label neither false nor true.")
422         else:
423             document.warning("Malformed LyX document: show_label missing in CharStyle.")
424
425         i += 1
426
427
428 def revert_show_label(document):
429     i = 0
430     while True:
431         i = find_token(document.body, "\\begin_inset CharStyle", i)
432         if i == -1:
433             return
434         if document.body[i + 1].find("status open") != -1:
435             document.body.insert(i + 1, "show_label true")
436         else:
437             if document.body[i + 1].find("status collapsed") != -1:
438                 document.body.insert(i + 1, "show_label false")
439             else:
440                 document.warning("Malformed LyX document: no legal status line in CharStyle.")
441         i += 1
442
443 def revert_begin_modules(document):
444     i = 0
445     while True:
446         i = find_token(document.header, "\\begin_modules", i)
447         if i == -1:
448             return
449         j = find_end_of(document.header, i, "\\begin_modules", "\\end_modules")
450         if j == -1:
451             # this should not happen
452             break
453         document.header[i : j + 1] = []
454
455 def convert_flex(document):
456     "Convert CharStyle to Flex"
457     i = 0
458     while True:
459         i = find_token(document.body, "\\begin_inset CharStyle", i)
460         if i == -1:
461             return
462         document.body[i] = document.body[i].replace('\\begin_inset CharStyle', '\\begin_inset Flex')
463
464 def revert_flex(document):
465     "Convert Flex to CharStyle"
466     i = 0
467     while True:
468         i = find_token(document.body, "\\begin_inset Flex", i)
469         if i == -1:
470             return
471         document.body[i] = document.body[i].replace('\\begin_inset Flex', '\\begin_inset CharStyle')
472
473
474 #  Discard PDF options for hyperref
475 def revert_pdf_options(document):
476         "Revert PDF options for hyperref."
477         # store the PDF options and delete the entries from the Lyx file
478         i = 0
479         hyperref = False
480         title = ""
481         author = ""
482         subject = ""
483         keywords = ""
484         bookmarks = ""
485         bookmarksnumbered = ""
486         bookmarksopen = ""
487         bookmarksopenlevel = ""
488         breaklinks = ""
489         pdfborder = ""
490         colorlinks = ""
491         backref = ""
492         pagebackref = ""
493         pagemode = ""
494         otheroptions = ""
495         i = find_token(document.header, "\\use_hyperref", i)
496         if i != -1:
497             hyperref = get_value(document.header, "\\use_hyperref", i) == 'true'
498             del document.header[i]
499         i = find_token(document.header, "\\pdf_store_options", i)
500         if i != -1:
501             del document.header[i]
502         i = find_token(document.header, "\\pdf_title", 0)
503         if i != -1:
504             title = get_value_string(document.header, '\\pdf_title', 0, 0, True)
505             title = ' pdftitle={' + title + '}'
506             del document.header[i]
507         i = find_token(document.header, "\\pdf_author", 0)
508         if i != -1:
509             author = get_value_string(document.header, '\\pdf_author', 0, 0, True)
510             if title == "":
511                 author = ' pdfauthor={' + author + '}'
512             else:
513                 author = ',\n pdfauthor={' + author + '}'
514             del document.header[i]
515         i = find_token(document.header, "\\pdf_subject", 0)
516         if i != -1:
517             subject = get_value_string(document.header, '\\pdf_subject', 0, 0, True)
518             if title == "" and author == "":
519                 subject = ' pdfsubject={' + subject + '}'
520             else:
521                 subject = ',\n pdfsubject={' + subject + '}'
522             del document.header[i]
523         i = find_token(document.header, "\\pdf_keywords", 0)
524         if i != -1:
525             keywords = get_value_string(document.header, '\\pdf_keywords', 0, 0, True)
526             if title == "" and author == "" and subject == "":
527                 keywords = ' pdfkeywords={' + keywords + '}'
528             else:
529                 keywords = ',\n pdfkeywords={' + keywords + '}'
530             del document.header[i]
531         i = find_token(document.header, "\\pdf_bookmarks", 0)
532         if i != -1:
533             bookmarks = get_value_string(document.header, '\\pdf_bookmarks', 0)
534             bookmarks = ',\n bookmarks=' + bookmarks
535             del document.header[i]
536         i = find_token(document.header, "\\pdf_bookmarksnumbered", i)
537         if i != -1:
538             bookmarksnumbered = get_value_string(document.header, '\\pdf_bookmarksnumbered', 0)
539             bookmarksnumbered = ',\n bookmarksnumbered=' + bookmarksnumbered
540             del document.header[i]
541         i = find_token(document.header, "\\pdf_bookmarksopen", i)
542         if i != -1:
543             bookmarksopen = get_value_string(document.header, '\\pdf_bookmarksopen', 0)
544             bookmarksopen = ',\n bookmarksopen=' + bookmarksopen
545             del document.header[i]
546         i = find_token(document.header, "\\pdf_bookmarksopenlevel", i)
547         if i != -1:
548             bookmarksopenlevel = get_value_string(document.header, '\\pdf_bookmarksopenlevel', 0, 0, True)
549             bookmarksopenlevel = ',\n bookmarksopenlevel=' + bookmarksopenlevel
550             del document.header[i]
551         i = find_token(document.header, "\\pdf_breaklinks", i)
552         if i != -1:
553             breaklinks = get_value_string(document.header, '\\pdf_breaklinks', 0)
554             breaklinks = ',\n breaklinks=' + breaklinks
555             del document.header[i]
556         i = find_token(document.header, "\\pdf_pdfborder", i)
557         if i != -1:
558             pdfborder = get_value_string(document.header, '\\pdf_pdfborder', 0)
559             if pdfborder == 'true':
560                 pdfborder = ',\n pdfborder={0 0 0}'
561             else:
562                 pdfborder = ',\n pdfborder={0 0 1}'
563             del document.header[i]
564         i = find_token(document.header, "\\pdf_colorlinks", i)
565         if i != -1:
566             colorlinks = get_value_string(document.header, '\\pdf_colorlinks', 0)
567             colorlinks = ',\n colorlinks=' + colorlinks
568             del document.header[i]
569         i = find_token(document.header, "\\pdf_backref", i)
570         if i != -1:
571             backref = get_value_string(document.header, '\\pdf_backref', 0)
572             backref = ',\n backref=' + backref
573             del document.header[i]
574         i = find_token(document.header, "\\pdf_pagebackref", i)
575         if i != -1:
576             pagebackref = get_value_string(document.header, '\\pdf_pagebackref', 0)
577             pagebackref = ',\n pagebackref=' + pagebackref
578             del document.header[i]
579         i = find_token(document.header, "\\pdf_pagemode", 0)
580         if i != -1:
581             pagemode = get_value_string(document.header, '\\pdf_pagemode', 0)
582             pagemode = ',\n pdfpagemode=' + pagemode
583             del document.header[i]
584         i = find_token(document.header, "\\pdf_quoted_options", 0)
585         if i != -1:
586             otheroptions = get_value_string(document.header, '\\pdf_quoted_options', 0, 0, True)
587             if title == "" and author == "" and subject == "" and keywords == "":
588                 otheroptions = ' ' + otheroptions
589             else:
590                 otheroptions = ',\n ' + otheroptions
591             del document.header[i]
592
593         # write to the preamble when hyperref was used
594         if hyperref == True:
595             # preamble write preparations
596             # bookmark numbers are only output when they are turned on
597             if bookmarksopen == ',\n bookmarksopen=true':
598                 bookmarksopen = bookmarksopen + bookmarksopenlevel
599             if bookmarks == ',\n bookmarks=true':
600                 bookmarks = bookmarks + bookmarksnumbered + bookmarksopen
601             else:
602                 bookmarks = bookmarks
603             # hypersetup is only output when there are things to be set up
604             setupstart = '\\hypersetup{%\n'
605             setupend = ' }\n'
606             if otheroptions == "" and title == "" and  author == ""\
607                and  subject == "" and keywords == "":
608                 setupstart = ""
609                 setupend = ""
610             # write the preamble
611             add_to_preamble(document,
612                                 ['% Commands inserted by lyx2lyx for PDF properties',
613                                  '\\usepackage[unicode=true'
614                                  + bookmarks
615                                  + breaklinks
616                                  + pdfborder
617                                  + backref
618                                  + pagebackref
619                                  + colorlinks
620                                  + pagemode
621                                  + ']\n'
622                                  ' {hyperref}\n'
623                                  + setupstart
624                                  + title
625                                  + author
626                                  + subject
627                                  + keywords
628                                  + otheroptions
629                                  + setupend])
630
631
632 def remove_inzip_options(document):
633     "Remove inzipName and embed options from the Graphics inset"
634     i = 0
635     while 1:
636         i = find_token(document.body, "\\begin_inset Graphics", i)
637         if i == -1:
638             return
639         j = find_end_of_inset(document.body, i + 1)
640         if j == -1:
641             # should not happen
642             document.warning("Malformed LyX document: Could not find end of graphics inset.")
643         # If there's a inzip param, just remove that
644         k = find_token(document.body, "\tinzipName", i + 1, j)
645         if k != -1:
646             del document.body[k]
647             # embed option must follow the inzipName option
648             del document.body[k+1]
649         i = i + 1
650
651
652 def convert_inset_command(document):
653     """
654         Convert:
655             \begin_inset LatexCommand cmd
656         to
657             \begin_inset CommandInset InsetType
658             LatexCommand cmd
659     """
660     i = 0
661     while 1:
662         i = find_token(document.body, "\\begin_inset LatexCommand", i)
663         if i == -1:
664             return
665         line = document.body[i]
666         r = re.compile(r'\\begin_inset LatexCommand (.*)$')
667         m = r.match(line)
668         cmdName = m.group(1)
669         insetName = ""
670         #this is adapted from factory.cpp
671         if cmdName[0:4].lower() == "cite":
672             insetName = "citation"
673         elif cmdName == "url" or cmdName == "htmlurl":
674             insetName = "url"
675         elif cmdName[-3:] == "ref":
676             insetName = "ref"
677         elif cmdName == "tableofcontents":
678             insetName = "toc"
679         elif cmdName == "printnomenclature":
680             insetName = "nomencl_print"
681         elif cmdName == "printindex":
682             insetName = "index_print"
683         else:
684             insetName = cmdName
685         insertion = ["\\begin_inset CommandInset " + insetName, "LatexCommand " + cmdName]
686         document.body[i : i+1] = insertion
687
688
689 def revert_inset_command(document):
690     """
691         Convert:
692             \begin_inset CommandInset InsetType
693             LatexCommand cmd
694         to
695             \begin_inset LatexCommand cmd
696         Some insets may end up being converted to insets earlier versions of LyX
697         will not be able to recognize. Not sure what to do about that.
698     """
699     i = 0
700     while 1:
701         i = find_token(document.body, "\\begin_inset CommandInset", i)
702         if i == -1:
703             return
704         nextline = document.body[i+1]
705         r = re.compile(r'LatexCommand\s+(.*)$')
706         m = r.match(nextline)
707         if not m:
708             document.warning("Malformed LyX document: Missing LatexCommand in " + document.body[i] + ".")
709             continue
710         cmdName = m.group(1)
711         insertion = ["\\begin_inset LatexCommand " + cmdName]
712         document.body[i : i+2] = insertion
713
714
715 def convert_wrapfig_options(document):
716     "Convert optional options for wrap floats (wrapfig)."
717     # adds the tokens "lines", "placement", and "overhang"
718     i = 0
719     while True:
720         i = find_token(document.body, "\\begin_inset Wrap figure", i)
721         if i == -1:
722             return
723         document.body.insert(i + 1, "lines 0")
724         j = find_token(document.body, "placement", i)
725         # placement can be already set or not; if not, set it
726         if j == i+2:
727             document.body.insert(i + 3, "overhang 0col%")
728         else:
729            document.body.insert(i + 2, "placement o")
730            document.body.insert(i + 3, "overhang 0col%")
731         i = i + 1
732
733
734 def revert_wrapfig_options(document):
735     "Revert optional options for wrap floats (wrapfig)."
736     i = 0
737     while True:
738         i = find_token(document.body, "lines", i)
739         if i == -1:
740             return
741         j = find_token(document.body, "overhang", i+1)
742         if j != i + 2 and j != -1:
743             document.warning("Malformed LyX document: Couldn't find overhang parameter of wrap float.")
744         if j == -1:
745             return
746         del document.body[i]
747         del document.body[j-1]
748         i = i + 1
749
750
751 def convert_latexcommand_index(document):
752     "Convert from LatexCommand form to collapsable form."
753     i = 0
754     while True:
755         i = find_token(document.body, "\\begin_inset CommandInset index", i)
756         if i == -1:
757             return
758         if document.body[i + 1] != "LatexCommand index": # Might also be index_print
759             return
760         fullcontent = document.body[i + 2][6:].strip('"')
761         document.body[i:i + 2] = ["\\begin_inset Index",
762           "status collapsed",
763           "\\begin_layout Standard"]
764         # Put here the conversions needed from LaTeX string to LyXText.
765         # Here we do a minimal conversion to prevent crashes and data loss.
766         # Manual patch-up may be needed.
767         # Umlauted characters (most common ones, can be extended):
768         fullcontent = fullcontent.replace(r'\\\"a', u'ä').replace(r'\\\"o', u'ö').replace(r'\\\"u', u'ü')
769         # Generic, \" -> ":
770         fullcontent = wrap_into_ert(fullcontent, r'\"', '"')
771         #fullcontent = fullcontent.replace(r'\"', '\n\\begin_inset ERT\nstatus collapsed\n\\begin_layout standard\n"\n\\end_layout\n\\end_inset\n')
772         # Math:
773         r = re.compile('^(.*?)(\$.*?\$)(.*)')
774         g = fullcontent
775         while r.match(g):
776           m = r.match(g)
777           s = m.group(1)
778           f = m.group(2).replace('\\\\', '\\')
779           g = m.group(3)
780           if s:
781             # this is non-math!
782             s = wrap_into_ert(s, r'\\', '\\backslash')
783             s = wrap_into_ert(s, '{', '{')
784             s = wrap_into_ert(s, '}', '}')
785             document.body.insert(i + 3, s)
786             i += 1
787           document.body.insert(i + 3, "\\begin_inset Formula " + f)
788           document.body.insert(i + 4, "\\end_inset")
789           i += 2
790         # Generic, \\ -> \backslash:
791         g = wrap_into_ert(g, r'\\', '\\backslash')
792         g = wrap_into_ert(g, '{', '{')
793         g = wrap_into_ert(g, '}', '}')
794         document.body.insert(i + 3, g)
795         document.body[i + 4] = "\\end_layout"
796         i = i + 5
797
798
799 def revert_latexcommand_index(document):
800     "Revert from collapsable form to LatexCommand form."
801     i = 0
802     while True:
803         i = find_token(document.body, "\\begin_inset Index", i)
804         if i == -1:
805           return
806         j = find_end_of_inset(document.body, i + 1)
807         if j == -1:
808           return
809         del document.body[j - 1]
810         del document.body[j - 2] # \end_layout
811         document.body[i] =  "\\begin_inset CommandInset index"
812         document.body[i + 1] =  "LatexCommand index"
813         # clean up multiline stuff
814         content = ""
815         ert_end = 0
816         for k in range(i + 3, j - 2):
817           line = document.body[k]
818           if line.startswith("\\begin_inset ERT"):
819               ert_end = find_end_of_inset(document.body, k + 1)
820               line = line[16:]
821           if line.startswith("\\begin_inset Formula"):
822             line = line[20:]
823           if line.startswith("\\begin_layout Standard"):
824             line = line[22:]
825           if line.startswith("\\begin_layout Plain Layout"):
826             line = line[26:]
827           if line.startswith("\\end_layout"):
828             line = line[11:]
829           if line.startswith("\\end_inset"):
830             line = line[10:]
831           if line.startswith("status collapsed"):
832             line = line[16:]
833           if line.startswith("status open"):
834             line = line[11:]
835           # a lossless reversion is not possible
836           # try at least to handle some common insets and settings
837           # do not replace inside ERTs
838           if ert_end < k:
839               line = line.replace(u'ä', r'\\\"a').replace(u'ö', r'\\\"o').replace(u'ü', r'\\\"u')
840               line = line.replace(r'\\backslash', r'\\textbackslash{}')
841               line = line.replace(r'\\series bold', r'\\bfseries{}').replace(r'\\series default', r'\\mdseries{}')
842               line = line.replace(r'\\shape italic', r'\\itshape{}').replace(r'\\shape smallcaps', r'\\scshape{}')
843               line = line.replace(r'\\shape slanted', r'\\slshape{}').replace(r'\\shape default', r'\\upshape{}')
844               line = line.replace(r'\\emph on', r'\\em{}').replace(r'\\emph default', r'\\em{}')
845               line = line.replace(r'\\noun on', r'\\scshape{}').replace(r'\\noun default', r'\\upshape{}')
846               line = line.replace(r'\\bar under', r'\\underbar{').replace(r'\\bar default', r'}')
847               line = line.replace(r'\\family sans', r'\\sffamily{}').replace(r'\\family default', r'\\normalfont{}')
848               line = line.replace(r'\\family typewriter', r'\\ttfamily{}').replace(r'\\family roman', r'\\rmfamily{}')
849               line = line.replace(r'\\InsetSpace ', r'').replace(r'\\SpecialChar ', r'')
850           else:
851               line = line.replace(r'\\backslash', r'\\')
852           content = content + line;
853         document.body[i + 3] = "name " + '"' + content + '"'
854         for k in range(i + 4, j - 2):
855           del document.body[i + 4]
856         document.body.insert(i + 4, "")
857         del document.body[i + 2] # \begin_layout standard
858         i = i + 5
859
860
861 def revert_wraptable(document):
862     "Revert wrap table to wrap figure."
863     i = 0
864     while True:
865         i = find_token(document.body, "\\begin_inset Wrap table", i)
866         if i == -1:
867             return
868         document.body[i] = document.body[i].replace('\\begin_inset Wrap table', '\\begin_inset Wrap figure')
869         i = i + 1
870
871
872 def revert_vietnamese(document):
873     "Set language Vietnamese to English"
874     # Set document language from Vietnamese to English
875     i = 0
876     if document.language == "vietnamese":
877         document.language = "english"
878         i = find_token(document.header, "\\language", 0)
879         if i != -1:
880             document.header[i] = "\\language english"
881     j = 0
882     while True:
883         j = find_token(document.body, "\\lang vietnamese", j)
884         if j == -1:
885             return
886         document.body[j] = document.body[j].replace("\\lang vietnamese", "\\lang english")
887         j = j + 1
888
889
890 def revert_japanese(document):
891     "Set language japanese-plain to japanese"
892     # Set document language from japanese-plain to japanese
893     i = 0
894     if document.language == "japanese-plain":
895         document.language = "japanese"
896         i = find_token(document.header, "\\language", 0)
897         if i != -1:
898             document.header[i] = "\\language japanese"
899     j = 0
900     while True:
901         j = find_token(document.body, "\\lang japanese-plain", j)
902         if j == -1:
903             return
904         document.body[j] = document.body[j].replace("\\lang japanese-plain", "\\lang japanese")
905         j = j + 1
906
907
908 def revert_japanese_encoding(document):
909     "Set input encoding form EUC-JP-plain to EUC-JP etc."
910     # Set input encoding form EUC-JP-plain to EUC-JP etc.
911     i = 0
912     i = find_token(document.header, "\\inputencoding EUC-JP-plain", 0)
913     if i != -1:
914         document.header[i] = "\\inputencoding EUC-JP"
915     j = 0
916     j = find_token(document.header, "\\inputencoding JIS-plain", 0)
917     if j != -1:
918         document.header[j] = "\\inputencoding JIS"
919     k = 0
920     k = find_token(document.header, "\\inputencoding SJIS-plain", 0)
921     if k != -1: # convert to UTF8 since there is currently no SJIS encoding
922         document.header[k] = "\\inputencoding UTF8"
923
924
925 def revert_inset_info(document):
926     'Replace info inset with its content'
927     i = 0
928     while 1:
929         i = find_token(document.body, '\\begin_inset Info', i)
930         if i == -1:
931             return
932         j = find_end_of_inset(document.body, i + 1)
933         if j == -1:
934             # should not happen
935             document.warning("Malformed LyX document: Could not find end of Info inset.")
936         type = 'unknown'
937         arg = ''
938         for k in range(i, j+1):
939             if document.body[k].startswith("arg"):
940                 arg = document.body[k][3:].strip().strip('"')
941             if document.body[k].startswith("type"):
942                 type = document.body[k][4:].strip().strip('"')
943         # I think there is a newline after \\end_inset, which should be removed.
944         if document.body[j + 1].strip() == "":
945             document.body[i : (j + 2)] = [type + ':' + arg]
946         else:
947             document.body[i : (j + 1)] = [type + ':' + arg]
948
949
950 def convert_pdf_options(document):
951     # Set the pdfusetitle tag, delete the pdf_store_options,
952     # set quotes for bookmarksopenlevel"
953     has_hr = get_value(document.header, "\\use_hyperref", 0, default = "0")
954     if has_hr == "1":
955         k = find_token(document.header, "\\use_hyperref", 0)
956         document.header.insert(k + 1, "\\pdf_pdfusetitle true")
957     k = find_token(document.header, "\\pdf_store_options", 0)
958     if k != -1:
959         del document.header[k]
960     i = find_token(document.header, "\\pdf_bookmarksopenlevel", k)
961     if i == -1: return
962     document.header[i] = document.header[i].replace('"', '')
963
964
965 def revert_pdf_options_2(document):
966     # reset the pdfusetitle tag, set quotes for bookmarksopenlevel"
967     k = find_token(document.header, "\\use_hyperref", 0)
968     i = find_token(document.header, "\\pdf_pdfusetitle", k)
969     if i != -1:
970         del document.header[i]
971     i = find_token(document.header, "\\pdf_bookmarksopenlevel", k)
972     if i == -1: return
973     values = document.header[i].split()
974     values[1] = ' "' + values[1] + '"'
975     document.header[i] = ''.join(values)
976
977
978 def convert_htmlurl(document):
979     'Convert "htmlurl" to "href" insets for docbook'
980     if document.backend != "docbook":
981       return
982     i = 0
983     while True:
984       i = find_token(document.body, "\\begin_inset CommandInset url", i)
985       if i == -1:
986         return
987       document.body[i] = "\\begin_inset CommandInset href"
988       document.body[i + 1] = "LatexCommand href"
989       i = i + 1
990
991
992 def convert_url(document):
993     'Convert url insets to url charstyles'
994     if document.backend == "docbook":
995       return
996     i = 0
997     while True:
998       i = find_token(document.body, "\\begin_inset CommandInset url", i)
999       if i == -1:
1000         break
1001       n = find_token(document.body, "name", i)
1002       if n == i + 2:
1003         # place the URL name in typewriter before the new URL insert
1004         # grab the name 'bla' from the e.g. the line 'name "bla"',
1005         # therefore start with the 6th character
1006         name = document.body[n][6:-1]
1007         newname = [name + " "]
1008         document.body[i:i] = newname
1009         i = i + 1
1010       j = find_token(document.body, "target", i)
1011       if j == -1:
1012         document.warning("Malformed LyX document: Can't find target for url inset")
1013         i = j
1014         continue
1015       target = document.body[j][8:-1]
1016       k = find_token(document.body, "\\end_inset", j)
1017       if k == -1:
1018         document.warning("Malformed LyX document: Can't find end of url inset")
1019         i = k
1020         continue
1021       newstuff = ["\\begin_inset Flex URL",
1022         "status collapsed", "",
1023         "\\begin_layout Standard",
1024         "",
1025         target,
1026         "\\end_layout",
1027         ""]
1028       document.body[i:k] = newstuff
1029       i = k
1030
1031 def convert_ams_classes(document):
1032   tc = document.textclass
1033   if (tc != "amsart" and tc != "amsart-plain" and
1034       tc != "amsart-seq" and tc != "amsbook"):
1035     return
1036   if tc == "amsart-plain":
1037     document.textclass = "amsart"
1038     document.set_textclass()
1039     document.add_module("Theorems (Starred)")
1040     return
1041   if tc == "amsart-seq":
1042     document.textclass = "amsart"
1043     document.set_textclass()
1044   document.add_module("Theorems (AMS)")
1045
1046   #Now we want to see if any of the environments in the extended theorems
1047   #module were used in this document. If so, we'll add that module, too.
1048   layouts = ["Criterion", "Algorithm", "Axiom", "Condition", "Note",  \
1049     "Notation", "Summary", "Acknowledgement", "Conclusion", "Fact", \
1050     "Assumption"]
1051
1052   r = re.compile(r'^\\begin_layout (.*?)\*?\s*$')
1053   i = 0
1054   while True:
1055     i = find_token(document.body, "\\begin_layout", i)
1056     if i == -1:
1057       return
1058     m = r.match(document.body[i])
1059     if m == None:
1060       document.warning("Weirdly formed \\begin_layout at line %d of body!" % i)
1061       i += 1
1062       continue
1063     m = m.group(1)
1064     if layouts.count(m) != 0:
1065       document.add_module("Theorems (AMS-Extended)")
1066       return
1067     i += 1
1068
1069 def revert_href(document):
1070     'Reverts hyperlink insets (href) to url insets (url)'
1071     i = 0
1072     while True:
1073       i = find_token(document.body, "\\begin_inset CommandInset href", i)
1074       if i == -1:
1075           return
1076       document.body[i : i + 2] = \
1077         ["\\begin_inset CommandInset url", "LatexCommand url"]
1078       i = i + 2
1079
1080
1081 def convert_include(document):
1082   'Converts include insets to new format.'
1083   i = 0
1084   r = re.compile(r'\\begin_inset Include\s+\\([^{]+){([^}]*)}(?:\[(.*)\])?')
1085   while True:
1086     i = find_token(document.body, "\\begin_inset Include", i)
1087     if i == -1:
1088       return
1089     line = document.body[i]
1090     previewline = document.body[i + 1]
1091     m = r.match(line)
1092     if m == None:
1093       document.warning("Unable to match line " + str(i) + " of body!")
1094       i += 1
1095       continue
1096     cmd = m.group(1)
1097     fn  = m.group(2)
1098     opt = m.group(3)
1099     insertion = ["\\begin_inset CommandInset include",
1100        "LatexCommand " + cmd, previewline,
1101        "filename \"" + fn + "\""]
1102     newlines = 2
1103     if opt:
1104       insertion.append("lstparams " + '"' + opt + '"')
1105       newlines += 1
1106     document.body[i : i + 2] = insertion
1107     i += newlines
1108
1109
1110 def revert_include(document):
1111   'Reverts include insets to old format.'
1112   i = 0
1113   r1 = re.compile('LatexCommand (.+)')
1114   r2 = re.compile('filename (.+)')
1115   r3 = re.compile('options (.*)')
1116   while True:
1117     i = find_token(document.body, "\\begin_inset CommandInset include", i)
1118     if i == -1:
1119       return
1120     previewline = document.body[i + 1]
1121     m = r1.match(document.body[i + 2])
1122     if m == None:
1123       document.warning("Malformed LyX document: No LatexCommand line for `" +
1124         document.body[i] + "' on line " + str(i) + ".")
1125       i += 1
1126       continue
1127     cmd = m.group(1)
1128     m = r2.match(document.body[i + 3])
1129     if m == None:
1130       document.warning("Malformed LyX document: No filename line for `" + \
1131         document.body[i] + "' on line " + str(i) + ".")
1132       i += 2
1133       continue
1134     fn = m.group(1)
1135     options = ""
1136     numlines = 4
1137     if (cmd == "lstinputlisting"):
1138       m = r3.match(document.body[i + 4])
1139       if m != None:
1140         options = m.group(1)
1141         numlines = 5
1142     newline = "\\begin_inset Include \\" + cmd + "{" + fn + "}"
1143     if options:
1144       newline += ("[" + options + "]")
1145     insertion = [newline, previewline]
1146     document.body[i : i + numlines] = insertion
1147     i += 2
1148
1149
1150 def revert_albanian(document):
1151     "Set language Albanian to English"
1152     i = 0
1153     if document.language == "albanian":
1154         document.language = "english"
1155         i = find_token(document.header, "\\language", 0)
1156         if i != -1:
1157             document.header[i] = "\\language english"
1158     j = 0
1159     while True:
1160         j = find_token(document.body, "\\lang albanian", j)
1161         if j == -1:
1162             return
1163         document.body[j] = document.body[j].replace("\\lang albanian", "\\lang english")
1164         j = j + 1
1165
1166
1167 def revert_lowersorbian(document):
1168     "Set language lower Sorbian to English"
1169     i = 0
1170     if document.language == "lowersorbian":
1171         document.language = "english"
1172         i = find_token(document.header, "\\language", 0)
1173         if i != -1:
1174             document.header[i] = "\\language english"
1175     j = 0
1176     while True:
1177         j = find_token(document.body, "\\lang lowersorbian", j)
1178         if j == -1:
1179             return
1180         document.body[j] = document.body[j].replace("\\lang lowersorbian", "\\lang english")
1181         j = j + 1
1182
1183
1184 def revert_uppersorbian(document):
1185     "Set language uppersorbian to usorbian as this was used in LyX 1.5"
1186     i = 0
1187     if document.language == "uppersorbian":
1188         document.language = "usorbian"
1189         i = find_token(document.header, "\\language", 0)
1190         if i != -1:
1191             document.header[i] = "\\language usorbian"
1192     j = 0
1193     while True:
1194         j = find_token(document.body, "\\lang uppersorbian", j)
1195         if j == -1:
1196             return
1197         document.body[j] = document.body[j].replace("\\lang uppersorbian", "\\lang usorbian")
1198         j = j + 1
1199
1200
1201 def convert_usorbian(document):
1202     "Set language usorbian to uppersorbian"
1203     i = 0
1204     if document.language == "usorbian":
1205         document.language = "uppersorbian"
1206         i = find_token(document.header, "\\language", 0)
1207         if i != -1:
1208             document.header[i] = "\\language uppersorbian"
1209     j = 0
1210     while True:
1211         j = find_token(document.body, "\\lang usorbian", j)
1212         if j == -1:
1213             return
1214         document.body[j] = document.body[j].replace("\\lang usorbian", "\\lang uppersorbian")
1215         j = j + 1
1216
1217
1218 def revert_macro_optional_params(document):
1219     "Convert macro definitions with optional parameters into ERTs"
1220     # Stub to convert macro definitions with one or more optional parameters
1221     # into uninterpreted ERT insets
1222
1223
1224 def revert_hyperlinktype(document):
1225     'Reverts hyperlink type'
1226     i = 0
1227     j = 0
1228     while True:
1229       i = find_token(document.body, "target", i)
1230       if i == -1:
1231           return
1232       j = find_token(document.body, "type", i)
1233       if j == -1:
1234           return
1235       if j == i + 1:
1236           del document.body[j]
1237       i = i + 1
1238
1239
1240 def revert_pagebreak(document):
1241     'Reverts pagebreak to ERT'
1242     i = 0
1243     while True:
1244       i = find_token(document.body, "\\pagebreak", i)
1245       if i == -1:
1246           return
1247       document.body[i] = '\\begin_inset ERT\nstatus collapsed\n\n' \
1248       '\\begin_layout Standard\n\n\n\\backslash\n' \
1249       'pagebreak{}\n\\end_layout\n\n\\end_inset\n\n'
1250       i = i + 1
1251
1252
1253 def revert_linebreak(document):
1254     'Reverts linebreak to ERT'
1255     i = 0
1256     while True:
1257       i = find_token(document.body, "\\linebreak", i)
1258       if i == -1:
1259           return
1260       document.body[i] = '\\begin_inset ERT\nstatus collapsed\n\n' \
1261       '\\begin_layout Standard\n\n\n\\backslash\n' \
1262       'linebreak{}\n\\end_layout\n\n\\end_inset\n\n'
1263       i = i + 1
1264
1265
1266 def revert_latin(document):
1267     "Set language Latin to English"
1268     i = 0
1269     if document.language == "latin":
1270         document.language = "english"
1271         i = find_token(document.header, "\\language", 0)
1272         if i != -1:
1273             document.header[i] = "\\language english"
1274     j = 0
1275     while True:
1276         j = find_token(document.body, "\\lang latin", j)
1277         if j == -1:
1278             return
1279         document.body[j] = document.body[j].replace("\\lang latin", "\\lang english")
1280         j = j + 1
1281
1282
1283 def revert_samin(document):
1284     "Set language North Sami to English"
1285     i = 0
1286     if document.language == "samin":
1287         document.language = "english"
1288         i = find_token(document.header, "\\language", 0)
1289         if i != -1:
1290             document.header[i] = "\\language english"
1291     j = 0
1292     while True:
1293         j = find_token(document.body, "\\lang samin", j)
1294         if j == -1:
1295             return
1296         document.body[j] = document.body[j].replace("\\lang samin", "\\lang english")
1297         j = j + 1
1298
1299
1300 def convert_serbocroatian(document):
1301     "Set language Serbocroatian to Croatian as this was really Croatian in LyX 1.5"
1302     i = 0
1303     if document.language == "serbocroatian":
1304         document.language = "croatian"
1305         i = find_token(document.header, "\\language", 0)
1306         if i != -1:
1307             document.header[i] = "\\language croatian"
1308     j = 0
1309     while True:
1310         j = find_token(document.body, "\\lang serbocroatian", j)
1311         if j == -1:
1312             return
1313         document.body[j] = document.body[j].replace("\\lang serbocroatian", "\\lang croatian")
1314         j = j + 1
1315
1316
1317 def convert_framed_notes(document):
1318     "Convert framed notes to boxes. "
1319     i = 0
1320     while 1:
1321         i = find_tokens(document.body, ["\\begin_inset Note Framed", "\\begin_inset Note Shaded"], i)
1322         if i == -1:
1323             return
1324         subst = [document.body[i].replace("\\begin_inset Note", "\\begin_inset Box"),
1325                  'position "t"',
1326                  'hor_pos "c"',
1327                  'has_inner_box 0'
1328                  'inner_pos "t"', 
1329                  'use_parbox 0',
1330                  'width "100col%"',
1331                  'special "none"',
1332                  'height "1in"',
1333                  'height_special "totalheight"']
1334         document.body[i:i+1] = subst
1335         i = i + 9
1336
1337
1338 def convert_module_names(document):
1339   modulemap = { 'Braille' : 'braille', 'Endnote' : 'endnotes', 'Foot to End' : 'foottoend',\
1340     'Hanging' : 'hanging', 'Linguistics' : 'linguistics', 'Logical Markup' : 'logicalmkup', \
1341     'Theorems (AMS-Extended)' : 'theorems-ams-extended', 'Theorems (AMS)' : 'theorems-ams', \
1342     'Theorems (Order By Chapter)' : 'theorems-chap', 'Theorems (Order By Section)' : 'theorems-sec', \
1343     'Theorems (Starred)' : 'theorems-starred', 'Theorems' : 'theorems-std' }
1344   modlist = document.get_module_list()
1345   if len(modlist) == 0:
1346     return
1347   newmodlist = []
1348   for mod in modlist:
1349     if modulemap.has_key(mod):
1350       newmodlist.append(modulemap[mod])
1351     else:
1352       document.warning("Can't find module %s in the module map!" % mod)
1353       newmodlist.append(mod)
1354   document.set_module_list(newmodlist)
1355
1356
1357 def revert_module_names(document):
1358   modulemap = { 'braille' : 'Braille', 'endnotes' : 'Endnote', 'foottoend' : 'Foot to End',\
1359     'hanging' : 'Hanging', 'linguistics' : 'Linguistics', 'logicalmkup' : 'Logical Markup', \
1360     'theorems-ams-extended' : 'Theorems (AMS-Extended)', 'theorems-ams' : 'Theorems (AMS)', \
1361     'theorems-chap' : 'Theorems (Order By Chapter)', 'theorems-sec' : 'Theorems (Order By Section)', \
1362     'theorems-starred' : 'Theorems (Starred)', 'theorems-std' : 'Theorems'}
1363   modlist = document.get_module_list()
1364   if len(modlist) == 0:
1365     return
1366   newmodlist = []
1367   for mod in modlist:
1368     if modulemap.has_key(mod):
1369       newmodlist.append(modulemap[mod])
1370     else:
1371       document.warning("Can't find module %s in the module map!" % mod)
1372       newmodlist.append(mod)
1373   document.set_module_list(newmodlist)
1374
1375
1376 def revert_colsep(document):
1377     i = find_token(document.header, "\\columnsep", 0)
1378     if i == -1:
1379         return
1380     colsepline = document.header[i]
1381     r = re.compile(r'\\columnsep (.*)')
1382     m = r.match(colsepline)
1383     if not m:
1384         document.warning("Malformed column separation line!")
1385         return
1386     colsep = m.group(1)
1387     del document.header[i]
1388     #it seems to be safe to add the package even if it is already used
1389     pretext = ["\\usepackage{geometry}", "\\geometry{columnsep=" + colsep + "}"]
1390
1391     add_to_preamble(document, pretext)
1392
1393
1394 def revert_framed_notes(document):
1395     "Revert framed boxes to notes. "
1396     i = 0
1397     while 1:
1398         i = find_tokens(document.body, ["\\begin_inset Box Framed", "\\begin_inset Box Shaded"], i)
1399
1400         if i == -1:
1401             return
1402         j = find_end_of_inset(document.body, i + 1)
1403         if j == -1:
1404             # should not happen
1405             document.warning("Malformed LyX document: Could not find end of Box inset.")
1406         k = find_token(document.body, "status", i + 1, j)
1407         if k == -1:
1408             document.warning("Malformed LyX document: Missing `status' tag in Box inset.")
1409             return
1410         status = document.body[k]
1411         l = find_default_layout(document, i + 1, j)
1412         if l == -1:
1413             document.warning("Malformed LyX document: Missing `\\begin_layout' in Box inset.")
1414             return
1415         m = find_token(document.body, "\\end_layout", i + 1, j)
1416         if m == -1:
1417             document.warning("Malformed LyX document: Missing `\\end_layout' in Box inset.")
1418             return
1419         ibox = find_token(document.body, "has_inner_box 1", i + 1, k)
1420         pbox = find_token(document.body, "use_parbox 1", i + 1, k)
1421         if ibox == -1 and pbox == -1:
1422             document.body[i] = document.body[i].replace("\\begin_inset Box", "\\begin_inset Note")
1423             del document.body[i+1:k]
1424         else:
1425             document.body[i] = document.body[i].replace("\\begin_inset Box Shaded", "\\begin_inset Box Frameless")
1426             subst1 = [document.body[l],
1427                       "\\begin_inset Note Shaded",
1428                       status,
1429                       '\\begin_layout Standard']
1430             document.body[l:l + 1] = subst1
1431             subst2 = [document.body[m], "\\end_layout", "\\end_inset"]
1432             document.body[m:m + 1] = subst2
1433         i = i + 1
1434
1435
1436 def revert_slash(document):
1437     'Revert \\SpecialChar \\slash{} to ERT'
1438     r = re.compile(r'\\SpecialChar \\slash{}')
1439     for i in range(len(document.body)):
1440         m = r.match(document.body[i])
1441         if m:
1442           subst = ['\\begin_inset ERT',
1443                    'status collapsed', '',
1444                    '\\begin_layout Standard',
1445                    '', '', '\\backslash',
1446                    'slash{}',
1447                    '\\end_layout', '',
1448                    '\\end_inset', '']
1449           document.body[i: i+1] = subst
1450
1451
1452 def revert_nobreakdash(document):
1453     'Revert \\SpecialChar \\nobreakdash- to ERT'
1454     found = 0
1455     for i in range(len(document.body)):
1456         line = document.body[i]
1457         r = re.compile(r'\\SpecialChar \\nobreakdash-')
1458         m = r.match(line)
1459         if m:
1460             found = 1
1461         subst = ['\\begin_inset ERT',
1462                  'status collapsed', '',
1463                  '\\begin_layout Standard', '', '',
1464                  '\\backslash',
1465                  'nobreakdash-',
1466                  '\\end_layout', '',
1467                  '\\end_inset', '']
1468         document.body[i:i+1] = subst
1469     if not found:
1470         return
1471     j = find_token(document.header, "\\use_amsmath", 0)
1472     if j == -1:
1473         document.warning("Malformed LyX document: Missing '\\use_amsmath'.")
1474         return
1475     document.header[j] = "\\use_amsmath 2"
1476
1477
1478 def revert_nocite_key(body, start, end):
1479     'key "..." -> \nocite{...}'
1480     for i in range(start, end):
1481         if (body[i][0:5] == 'key "'):
1482             body[i] = body[i].replace('key "', "\\backslash\nnocite{")
1483             body[i] = body[i].replace('"', "}")
1484         else:
1485             body[i] = ""
1486
1487
1488 def revert_nocite(document):
1489     "Revert LatexCommand nocite to ERT"
1490     i = 0
1491     while 1:
1492         i = find_token(document.body, "\\begin_inset CommandInset citation", i)
1493         if i == -1:
1494             return
1495         i = i + 1
1496         if (document.body[i] == "LatexCommand nocite"):
1497             j = find_end_of_inset(document.body, i + 1)
1498             if j == -1:
1499                 #this should not happen
1500                 document.warning("End of CommandInset citation not found in revert_nocite!")
1501                 revert_nocite_key(document.body, i + 1, len(document.body))
1502                 return
1503             revert_nocite_key(document.body, i + 1, j)
1504             document.body[i-1] = "\\begin_inset ERT"
1505             document.body[i:i+1] = ["status collapsed", "", "\\begin_layout Standard"]
1506             document.body[j+1:j+1] = ["\\end_layout", ""]
1507             i = j
1508
1509
1510 def revert_btprintall(document):
1511     "Revert (non-bibtopic) btPrintAll option to ERT \nocite{*}"
1512     i = find_token(document.header, '\\use_bibtopic', 0)
1513     if i == -1:
1514         document.warning("Malformed lyx document: Missing '\\use_bibtopic'.")
1515         return
1516     if get_value(document.header, '\\use_bibtopic', 0) == "false":
1517         i = 0
1518         while i < len(document.body):
1519             i = find_token(document.body, "\\begin_inset CommandInset bibtex", i)
1520             if i == -1:
1521                 return
1522             j = find_end_of_inset(document.body, i + 1)
1523             if j == -1:
1524                 #this should not happen
1525                 document.warning("End of CommandInset bibtex not found in revert_btprintall!")
1526                 j = len(document.body)
1527             for k in range(i, j):
1528                 if (document.body[k] == 'btprint "btPrintAll"'):
1529                     del document.body[k]
1530                     document.body.insert(i, "\\begin_inset ERT\n" \
1531                     "status collapsed\n\n\\begin_layout Standard\n\n" \
1532                     "\\backslash\nnocite{*}\n" \
1533                     "\\end_layout\n\\end_inset\n")
1534             i = j
1535
1536
1537 def revert_bahasam(document):
1538     "Set language Bahasa Malaysia to Bahasa Indonesia"
1539     i = 0
1540     if document.language == "bahasam":
1541         document.language = "bahasa"
1542         i = find_token(document.header, "\\language", 0)
1543         if i != -1:
1544             document.header[i] = "\\language bahasa"
1545     j = 0
1546     while True:
1547         j = find_token(document.body, "\\lang bahasam", j)
1548         if j == -1:
1549             return
1550         document.body[j] = document.body[j].replace("\\lang bahasam", "\\lang bahasa")
1551         j = j + 1
1552
1553
1554 def revert_interlingua(document):
1555     "Set language Interlingua to English"
1556     i = 0
1557     if document.language == "interlingua":
1558         document.language = "english"
1559         i = find_token(document.header, "\\language", 0)
1560         if i != -1:
1561             document.header[i] = "\\language english"
1562     j = 0
1563     while True:
1564         j = find_token(document.body, "\\lang interlingua", j)
1565         if j == -1:
1566             return
1567         document.body[j] = document.body[j].replace("\\lang interlingua", "\\lang english")
1568         j = j + 1
1569
1570
1571 def revert_serbianlatin(document):
1572     "Set language Serbian-Latin to Croatian"
1573     i = 0
1574     if document.language == "serbian-latin":
1575         document.language = "croatian"
1576         i = find_token(document.header, "\\language", 0)
1577         if i != -1:
1578             document.header[i] = "\\language croatian"
1579     j = 0
1580     while True:
1581         j = find_token(document.body, "\\lang serbian-latin", j)
1582         if j == -1:
1583             return
1584         document.body[j] = document.body[j].replace("\\lang serbian-latin", "\\lang croatian")
1585         j = j + 1
1586
1587
1588 def revert_rotfloat(document):
1589     " Revert sideways custom floats. "
1590     i = 0
1591     while 1:
1592         # whitespace intended (exclude \\begin_inset FloatList)
1593         i = find_token(document.body, "\\begin_inset Float ", i)
1594         if i == -1:
1595             return
1596         line = document.body[i]
1597         r = re.compile(r'\\begin_inset Float (.*)$')
1598         m = r.match(line)
1599         if m == None:
1600             document.warning("Unable to match line " + str(i) + " of body!")
1601             i += 1
1602             continue
1603         floattype = m.group(1)
1604         if floattype == "figure" or floattype == "table":
1605             i = i + 1
1606             continue
1607         j = find_end_of_inset(document.body, i)
1608         if j == -1:
1609             document.warning("Malformed lyx document: Missing '\\end_inset'.")
1610             i = i + 1
1611             continue
1612         if get_value(document.body, 'sideways', i, j) != "false":
1613             l = find_default_layout(document, i + 1, j)
1614             if l == -1:
1615                 document.warning("Malformed LyX document: Missing `\\begin_layout' in Float inset.")
1616                 return
1617             document.body[j] = '\\begin_layout Standard\n\\begin_inset ERT\nstatus collapsed\n\n' \
1618             '\\begin_layout Standard\n\n\n\\backslash\n' \
1619             'end{sideways' + floattype + '}\n\\end_layout\n\n\\end_inset\n'
1620             del document.body[i+1:l-1]
1621             document.body[i] = '\\begin_inset ERT\nstatus collapsed\n\n' \
1622             '\\begin_layout Standard\n\n\n\\backslash\n' \
1623             'begin{sideways' + floattype + '}\n\\end_layout\n\n\\end_inset\n\n\\end_layout\n\n'
1624             if floattype == "algorithm":
1625                 add_to_preamble(document,
1626                                 ['% Commands inserted by lyx2lyx for sideways algorithm float',
1627                                  '\\usepackage{rotfloat}\n'
1628                                  '\\floatstyle{ruled}\n'
1629                                  '\\newfloat{algorithm}{tbp}{loa}\n'
1630                                  '\\floatname{algorithm}{Algorithm}\n'])
1631             else:
1632                 document.warning("Cannot create preamble definition for custom float" + floattype + ".")
1633             i = i + 1
1634             continue
1635         i = i + 1
1636
1637
1638 def revert_widesideways(document):
1639     " Revert wide sideways floats. "
1640     i = 0
1641     while 1:
1642         # whitespace intended (exclude \\begin_inset FloatList)
1643         i = find_token(document.body, '\\begin_inset Float ', i)
1644         if i == -1:
1645             return
1646         line = document.body[i]
1647         r = re.compile(r'\\begin_inset Float (.*)$')
1648         m = r.match(line)
1649         if m == None:
1650             document.warning("Unable to match line " + str(i) + " of body!")
1651             i += 1
1652             continue
1653         floattype = m.group(1)
1654         if floattype != "figure" and floattype != "table":
1655             i = i + 1
1656             continue
1657         j = find_end_of_inset(document.body, i)
1658         if j == -1:
1659             document.warning("Malformed lyx document: Missing '\\end_inset'.")
1660             i = i + 1
1661             continue
1662         if get_value(document.body, 'sideways', i, j) != "false":
1663             if get_value(document.body, 'wide', i, j) != "false":
1664                 l = find_default_layout(document, i + 1, j)
1665                 if l == -1:
1666                     document.warning("Malformed LyX document: Missing `\\begin_layout' in Float inset.")
1667                     return
1668                 document.body[j] = '\\begin_layout Standard\n\\begin_inset ERT\nstatus collapsed\n\n' \
1669                 '\\begin_layout Standard\n\n\n\\backslash\n' \
1670                 'end{sideways' + floattype + '*}\n\\end_layout\n\n\\end_inset\n'
1671                 del document.body[i+1:l-1]
1672                 document.body[i] = '\\begin_inset ERT\nstatus collapsed\n\n' \
1673                 '\\begin_layout Standard\n\n\n\\backslash\n' \
1674                 'begin{sideways' + floattype + '*}\n\\end_layout\n\n\\end_inset\n\n\\end_layout\n\n'
1675                 add_to_preamble(document,
1676                                 ['\\usepackage{rotfloat}\n'])
1677                 i = i + 1
1678                 continue
1679         i = i + 1
1680
1681
1682 def revert_inset_embedding(document, type):
1683     ' Remove embed tag from certain type of insets'
1684     i = 0
1685     while 1:
1686         i = find_token(document.body, "\\begin_inset %s" % type, i)
1687         if i == -1:
1688             return
1689         j = find_end_of_inset(document.body, i)
1690         if j == -1:
1691             document.warning("Malformed lyx document: Missing '\\end_inset'.")
1692             i = i + 1
1693             continue
1694         k = find_token(document.body, "\tembed", i, j)
1695         if k == -1:
1696             k = find_token(document.body, "embed", i, j)
1697         if k != -1:
1698             del document.body[k]
1699         i = i + 1
1700
1701
1702 def revert_external_embedding(document):
1703     ' Remove embed tag from external inset '
1704     revert_inset_embedding(document, 'External')
1705
1706
1707 def convert_subfig(document):
1708     " Convert subfigures to subfloats. "
1709     i = 0
1710     while 1:
1711         i = find_token(document.body, '\\begin_inset Graphics', i)
1712         if i == -1:
1713             return
1714         j = find_end_of_inset(document.body, i)
1715         if j == -1:
1716             document.warning("Malformed lyx document: Missing '\\end_inset'.")
1717             i = i + 1
1718             continue
1719         k = find_token(document.body, '\tsubcaption', i, j)
1720         if k == -1:
1721             i = i + 1
1722             continue
1723         l = find_token(document.body, '\tsubcaptionText', i, j)
1724         caption = document.body[l][16:].strip('"')
1725         savestr = document.body[i]
1726         del document.body[l]
1727         del document.body[k]
1728         document.body[i] = '\\begin_inset Float figure\nwide false\nsideways false\n' \
1729         'status open\n\n\\begin_layout Plain Layout\n\\begin_inset Caption\n\n\\begin_layout Plain Layout\n' \
1730         + caption + '\n\\end_layout\n\n\\end_inset\n\n\\end_layout\n\n\\begin_layout Plain Layout\n' + savestr
1731         savestr = document.body[j]
1732         document.body[j] = '\n\\end_layout\n\n\\end_inset\n' + savestr
1733
1734
1735 def revert_subfig(document):
1736     " Revert subfloats. "
1737     i = 0
1738     while 1:
1739         # whitespace intended (exclude \\begin_inset FloatList)
1740         i = find_token(document.body, '\\begin_inset Float ', i)
1741         if i == -1:
1742             return
1743         while 1:
1744             j = find_end_of_inset(document.body, i)
1745             if j == -1:
1746                 document.warning("Malformed lyx document: Missing '\\end_inset' (float).")
1747                 i = i + 1
1748                 continue
1749             # look for embedded float (= subfloat)
1750             # whitespace intended (exclude \\begin_inset FloatList)
1751             k = find_token(document.body, '\\begin_inset Float ', i + 1, j)
1752             if k == -1:
1753                 break
1754             l = find_end_of_inset(document.body, k)
1755             if l == -1:
1756                 document.warning("Malformed lyx document: Missing '\\end_inset' (embedded float).")
1757                 i = i + 1
1758                 continue
1759             m = find_default_layout(document, k + 1, l)
1760             # caption?
1761             cap = find_token(document.body, '\\begin_inset Caption', k + 1, l)
1762             caption = ''
1763             shortcap = ''
1764             if cap != -1:
1765                 capend = find_end_of_inset(document.body, cap)
1766                 if capend == -1:
1767                     document.warning("Malformed lyx document: Missing '\\end_inset' (caption).")
1768                     return
1769                 # label?
1770                 label = ''
1771                 lbl = find_token(document.body, '\\begin_inset CommandInset label', cap, capend)
1772                 if lbl != -1:
1773                     lblend = find_end_of_inset(document.body, lbl + 1)
1774                     if lblend == -1:
1775                         document.warning("Malformed lyx document: Missing '\\end_inset' (label).")
1776                         return
1777                     for line in document.body[lbl:lblend + 1]:
1778                         if line.startswith('name '):
1779                             label = line.split()[1].strip('"')
1780                             break
1781                 else:
1782                     lbl = capend
1783                     lblend = capend
1784                     label = ''
1785                 # opt arg?
1786                 opt = find_token(document.body, '\\begin_inset OptArg', cap, capend)
1787                 if opt != -1:
1788                     optend = find_end_of_inset(document.body, opt)
1789                     if optend == -1:
1790                         document.warning("Malformed lyx document: Missing '\\end_inset' (OptArg).")
1791                         return
1792                     optc = find_default_layout(document, opt, optend)
1793                     if optc == -1:
1794                         document.warning("Malformed LyX document: Missing `\\begin_layout' in Float inset.")
1795                         return
1796                     optcend = find_end_of(document.body, optc, "\\begin_layout", "\\end_layout")
1797                     for line in document.body[optc:optcend]:
1798                         if not line.startswith('\\'):
1799                             shortcap += line.strip()
1800                 else:
1801                     opt = capend
1802                     optend = capend
1803                 for line in document.body[cap:capend]:
1804                     if line in document.body[lbl:lblend]:
1805                         continue
1806                     elif line in document.body[opt:optend]:
1807                         continue
1808                     elif not line.startswith('\\'):
1809                         caption += line.strip()
1810                 if len(label) > 0:
1811                     caption += "\\backslash\nlabel{" + label + "}"
1812             document.body[l] = '\\begin_layout Plain Layout\n\\begin_inset ERT\nstatus collapsed\n\n' \
1813             '\\begin_layout Plain Layout\n\n}\n\\end_layout\n\n\\end_inset\n\n\\end_layout\n\n\\begin_layout Plain Layout\n'
1814             del document.body[cap:capend+1]
1815             del document.body[k+1:m-1]
1816             insertion = '\\begin_inset ERT\nstatus collapsed\n\n' \
1817             '\\begin_layout Plain Layout\n\n\\backslash\n' \
1818             'subfloat'
1819             if len(shortcap) > 0:
1820                 insertion = insertion + "[" + shortcap + "]"
1821             if len(caption) > 0:
1822                 insertion = insertion + "[" + caption + "]"
1823             insertion = insertion + '{%\n\\end_layout\n\n\\end_inset\n\n\\end_layout\n'
1824             document.body[k] = insertion
1825             add_to_preamble(document,
1826                             ['\\usepackage{subfig}\n'])
1827         i = i + 1
1828
1829
1830 def revert_wrapplacement(document):
1831     " Revert placement options wrap floats (wrapfig). "
1832     i = 0
1833     while True:
1834         i = find_token(document.body, "lines", i)
1835         if i == -1:
1836             return
1837         j = find_token(document.body, "placement", i+1)
1838         if j != i + 1:
1839             document.warning("Malformed LyX document: Couldn't find placement parameter of wrap float.")
1840             return
1841         document.body[j] = document.body[j].replace("placement O", "placement o")
1842         document.body[j] = document.body[j].replace("placement I", "placement i")
1843         document.body[j] = document.body[j].replace("placement L", "placement l")
1844         document.body[j] = document.body[j].replace("placement R", "placement r")
1845         i = i + 1
1846
1847
1848 def remove_extra_embedded_files(document):
1849     " Remove \extra_embedded_files from buffer params "
1850     i = find_token(document.header, '\\extra_embedded_files', 0)
1851     if i == -1:
1852         return
1853     document.header.pop(i)
1854
1855
1856 def convert_spaceinset(document):
1857    " Convert '\\InsetSpace foo' to '\\begin_inset Space foo\n\\end_inset' "
1858    for i in range(len(document.body)):
1859        m = re.match(r'(.*)\\InsetSpace (.*)', document.body[i])
1860        if m:
1861            before = m.group(1)
1862            after = m.group(2)
1863            subst = [before, "\\begin_inset Space " + after, "\\end_inset"]
1864            document.body[i: i+1] = subst
1865
1866
1867 def revert_spaceinset(document):
1868     " Revert '\\begin_inset Space foo\n\\end_inset' to '\\InsetSpace foo' "
1869     i = 0
1870     while True:
1871         i = find_token(document.body, "\\begin_inset Space", i)
1872         if i == -1:
1873             return
1874         j = find_end_of_inset(document.body, i)
1875         if j == -1:
1876             document.warning("Malformed LyX document: Could not find end of space inset.")
1877             continue
1878         document.body[i] = document.body[i].replace('\\begin_inset Space', '\\InsetSpace')
1879         del document.body[j]
1880
1881
1882 def convert_hfill(document):
1883     " Convert hfill to space inset "
1884     i = 0
1885     while True:
1886         i = find_token(document.body, "\\hfill", i)
1887         if i == -1:
1888             return
1889         document.body[i] = document.body[i].replace('\\hfill', '\n\\begin_inset Space \\hfill{}\n\\end_inset')
1890
1891
1892 def revert_hfills(document):
1893     ' Revert \\hfill commands '
1894     for i in range(len(document.body)):
1895         document.body[i] = document.body[i].replace('\\InsetSpace \\hfill{}', '\\hfill')
1896         document.body[i] = document.body[i].replace('\\InsetSpace \\dotfill{}', \
1897         '\\begin_inset ERT\nstatus collapsed\n\n' \
1898         '\\begin_layout Standard\n\n\n\\backslash\n' \
1899         'dotfill{}\n\\end_layout\n\n\\end_inset\n\n')
1900         document.body[i] = document.body[i].replace('\\InsetSpace \\hrulefill{}', \
1901         '\\begin_inset ERT\nstatus collapsed\n\n' \
1902         '\\begin_layout Standard\n\n\n\\backslash\n' \
1903         'hrulefill{}\n\\end_layout\n\n\\end_inset\n\n')
1904
1905
1906 def revert_hspace(document):
1907     ' Revert \\InsetSpace \\hspace{} to ERT '
1908     i = 0
1909     while True:
1910         i = find_token(document.body, "\\InsetSpace \\hspace", i)
1911         if i == -1:
1912             return
1913         length = get_value(document.body, '\\length', i+1)
1914         if length == '':
1915             document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1916             return
1917         del document.body[i+1]
1918         document.body[i] = document.body[i].replace('\\InsetSpace \\hspace*{}', \
1919         '\\begin_inset ERT\nstatus collapsed\n\n' \
1920         '\\begin_layout Standard\n\n\n\\backslash\n' \
1921         'hspace*{' + length + '}\n\\end_layout\n\n\\end_inset\n\n')
1922         document.body[i] = document.body[i].replace('\\InsetSpace \\hspace{}', \
1923         '\\begin_inset ERT\nstatus collapsed\n\n' \
1924         '\\begin_layout Standard\n\n\n\\backslash\n' \
1925         'hspace{' + length + '}\n\\end_layout\n\n\\end_inset\n\n')
1926
1927
1928 def revert_protected_hfill(document):
1929     ' Revert \\begin_inset Space \\hspace*{\\fill} to ERT '
1930     i = 0
1931     while True:
1932         i = find_token(document.body, '\\begin_inset Space \\hspace*{\\fill}', i)
1933         if i == -1:
1934             return
1935         j = find_end_of_inset(document.body, i)
1936         if j == -1:
1937             document.warning("Malformed LyX document: Could not find end of space inset.")
1938             continue
1939         del document.body[j]
1940         document.body[i] = document.body[i].replace('\\begin_inset Space \\hspace*{\\fill}', \
1941         '\\begin_inset ERT\nstatus collapsed\n\n' \
1942         '\\begin_layout Standard\n\n\n\\backslash\n' \
1943         'hspace*{\n\\backslash\nfill}\n\\end_layout\n\n\\end_inset\n\n')
1944
1945
1946 def revert_leftarrowfill(document):
1947     ' Revert \\begin_inset Space \\leftarrowfill{} to ERT '
1948     i = 0
1949     while True:
1950         i = find_token(document.body, '\\begin_inset Space \\leftarrowfill{}', i)
1951         if i == -1:
1952             return
1953         j = find_end_of_inset(document.body, i)
1954         if j == -1:
1955             document.warning("Malformed LyX document: Could not find end of space inset.")
1956             continue
1957         del document.body[j]
1958         document.body[i] = document.body[i].replace('\\begin_inset Space \\leftarrowfill{}', \
1959         '\\begin_inset ERT\nstatus collapsed\n\n' \
1960         '\\begin_layout Standard\n\n\n\\backslash\n' \
1961         'leftarrowfill{}\n\\end_layout\n\n\\end_inset\n\n')
1962
1963
1964 def revert_rightarrowfill(document):
1965     ' Revert \\begin_inset Space \\rightarrowfill{} to ERT '
1966     i = 0
1967     while True:
1968         i = find_token(document.body, '\\begin_inset Space \\rightarrowfill{}', i)
1969         if i == -1:
1970             return
1971         j = find_end_of_inset(document.body, i)
1972         if j == -1:
1973             document.warning("Malformed LyX document: Could not find end of space inset.")
1974             continue
1975         del document.body[j]
1976         document.body[i] = document.body[i].replace('\\begin_inset Space \\rightarrowfill{}', \
1977         '\\begin_inset ERT\nstatus collapsed\n\n' \
1978         '\\begin_layout Standard\n\n\n\\backslash\n' \
1979         'rightarrowfill{}\n\\end_layout\n\n\\end_inset\n\n')
1980
1981
1982 def revert_upbracefill(document):
1983     ' Revert \\begin_inset Space \\upbracefill{} to ERT '
1984     i = 0
1985     while True:
1986         i = find_token(document.body, '\\begin_inset Space \\upbracefill{}', i)
1987         if i == -1:
1988             return
1989         j = find_end_of_inset(document.body, i)
1990         if j == -1:
1991             document.warning("Malformed LyX document: Could not find end of space inset.")
1992             continue
1993         del document.body[j]
1994         document.body[i] = document.body[i].replace('\\begin_inset Space \\upbracefill{}', \
1995         '\\begin_inset ERT\nstatus collapsed\n\n' \
1996         '\\begin_layout Standard\n\n\n\\backslash\n' \
1997         'upbracefill{}\n\\end_layout\n\n\\end_inset\n\n')
1998
1999
2000 def revert_downbracefill(document):
2001     ' Revert \\begin_inset Space \\downbracefill{} to ERT '
2002     i = 0
2003     while True:
2004         i = find_token(document.body, '\\begin_inset Space \\downbracefill{}', i)
2005         if i == -1:
2006             return
2007         j = find_end_of_inset(document.body, i)
2008         if j == -1:
2009             document.warning("Malformed LyX document: Could not find end of space inset.")
2010             continue
2011         del document.body[j]
2012         document.body[i] = document.body[i].replace('\\begin_inset Space \\downbracefill{}', \
2013         '\\begin_inset ERT\nstatus collapsed\n\n' \
2014         '\\begin_layout Standard\n\n\n\\backslash\n' \
2015         'downbracefill{}\n\\end_layout\n\n\\end_inset\n\n')
2016
2017
2018 def revert_local_layout(document):
2019     ' Revert local layout headers.'
2020     i = 0
2021     while True:
2022         i = find_token(document.header, "\\begin_local_layout", i)
2023         if i == -1:
2024             return
2025         j = find_end_of(document.header, i, "\\begin_local_layout", "\\end_local_layout")
2026         if j == -1:
2027             # this should not happen
2028             break
2029         document.header[i : j + 1] = []
2030
2031
2032 def convert_pagebreaks(document):
2033     ' Convert inline Newpage insets to new format '
2034     i = 0
2035     while True:
2036         i = find_token(document.body, '\\newpage', i)
2037         if i == -1:
2038             break
2039         document.body[i:i+1] = ['\\begin_inset Newpage newpage',
2040                              '\\end_inset']
2041     i = 0
2042     while True:
2043         i = find_token(document.body, '\\pagebreak', i)
2044         if i == -1:
2045             break
2046         document.body[i:i+1] = ['\\begin_inset Newpage pagebreak',
2047                              '\\end_inset']
2048     i = 0
2049     while True:
2050         i = find_token(document.body, '\\clearpage', i)
2051         if i == -1:
2052             break
2053         document.body[i:i+1] = ['\\begin_inset Newpage clearpage',
2054                              '\\end_inset']
2055     i = 0
2056     while True:
2057         i = find_token(document.body, '\\cleardoublepage', i)
2058         if i == -1:
2059             break
2060         document.body[i:i+1] = ['\\begin_inset Newpage cleardoublepage',
2061                              '\\end_inset']
2062
2063
2064 def revert_pagebreaks(document):
2065     ' Revert \\begin_inset Newpage to previous inline format '
2066     i = 0
2067     while True:
2068         i = find_token(document.body, '\\begin_inset Newpage', i)
2069         if i == -1:
2070             return
2071         j = find_end_of_inset(document.body, i)
2072         if j == -1:
2073             document.warning("Malformed LyX document: Could not find end of Newpage inset.")
2074             continue
2075         del document.body[j]
2076         document.body[i] = document.body[i].replace('\\begin_inset Newpage newpage', '\\newpage')
2077         document.body[i] = document.body[i].replace('\\begin_inset Newpage pagebreak', '\\pagebreak')
2078         document.body[i] = document.body[i].replace('\\begin_inset Newpage clearpage', '\\clearpage')
2079         document.body[i] = document.body[i].replace('\\begin_inset Newpage cleardoublepage', '\\cleardoublepage')
2080
2081
2082 def convert_linebreaks(document):
2083     ' Convert inline Newline insets to new format '
2084     i = 0
2085     while True:
2086         i = find_token(document.body, '\\newline', i)
2087         if i == -1:
2088             break
2089         document.body[i:i+1] = ['\\begin_inset Newline newline',
2090                              '\\end_inset']
2091     i = 0
2092     while True:
2093         i = find_token(document.body, '\\linebreak', i)
2094         if i == -1:
2095             break
2096         document.body[i:i+1] = ['\\begin_inset Newline linebreak',
2097                              '\\end_inset']
2098
2099
2100 def revert_linebreaks(document):
2101     ' Revert \\begin_inset Newline to previous inline format '
2102     i = 0
2103     while True:
2104         i = find_token(document.body, '\\begin_inset Newline', i)
2105         if i == -1:
2106             return
2107         j = find_end_of_inset(document.body, i)
2108         if j == -1:
2109             document.warning("Malformed LyX document: Could not find end of Newline inset.")
2110             continue
2111         del document.body[j]
2112         document.body[i] = document.body[i].replace('\\begin_inset Newline newline', '\\newline')
2113         document.body[i] = document.body[i].replace('\\begin_inset Newline linebreak', '\\linebreak')
2114
2115
2116 def convert_japanese_plain(document):
2117     ' Set language japanese-plain to japanese '
2118     i = 0
2119     if document.language == "japanese-plain":
2120         document.language = "japanese"
2121         i = find_token(document.header, "\\language", 0)
2122         if i != -1:
2123             document.header[i] = "\\language japanese"
2124     j = 0
2125     while True:
2126         j = find_token(document.body, "\\lang japanese-plain", j)
2127         if j == -1:
2128             return
2129         document.body[j] = document.body[j].replace("\\lang japanese-plain", "\\lang japanese")
2130         j = j + 1
2131
2132
2133 def revert_pdfpages(document):
2134     ' Revert pdfpages external inset to ERT '
2135     i = 0
2136     while 1:
2137         i = find_token(document.body, "\\begin_inset External", i)
2138         if i == -1:
2139             return
2140         j = find_end_of_inset(document.body, i)
2141         if j == -1:
2142             document.warning("Malformed lyx document: Missing '\\end_inset'.")
2143             i = i + 1
2144             continue
2145         if get_value(document.body, 'template', i, j) == "PDFPages":
2146             filename = get_value(document.body, 'filename', i, j)
2147             extra = ''
2148             r = re.compile(r'\textra PDFLaTeX \"(.*)\"$')
2149             for k in range(i, j):
2150                 m = r.match(document.body[k])
2151                 if m:
2152                     extra = m.group(1)
2153             angle = get_value(document.body, 'rotateAngle', i, j)
2154             width = get_value(document.body, 'width', i, j)
2155             height = get_value(document.body, 'height', i, j)
2156             scale = get_value(document.body, 'scale', i, j)
2157             keepAspectRatio = find_token(document.body, "\tkeepAspectRatio", i, j)
2158             options = extra
2159             if angle != '':
2160                  if options != '':
2161                      options += ",angle=" + angle
2162                  else:
2163                      options += "angle=" + angle
2164             if width != '':
2165                  if options != '':
2166                      options += ",width=" + convert_len(width)
2167                  else:
2168                      options += "width=" + convert_len(width)
2169             if height != '':
2170                  if options != '':
2171                      options += ",height=" + convert_len(height)
2172                  else:
2173                      options += "height=" + convert_len(height)
2174             if scale != '':
2175                  if options != '':
2176                      options += ",scale=" + scale
2177                  else:
2178                      options += "scale=" + scale
2179             if keepAspectRatio != '':
2180                  if options != '':
2181                      options += ",keepaspectratio"
2182                  else:
2183                      options += "keepaspectratio"
2184             if options != '':
2185                      options = '[' + options + ']'
2186             del document.body[i+1:j+1]
2187             document.body[i:i+1] = ['\\begin_inset ERT',
2188                                 'status collapsed',
2189                                 '',
2190                                 '\\begin_layout Standard',
2191                                 '',
2192                                 '\\backslash',
2193                                 'includepdf' + options + '{' + filename + '}',
2194                                 '\\end_layout',
2195                                 '',
2196                                 '\\end_inset']
2197             add_to_preamble(document, ['\\usepackage{pdfpages}\n'])
2198             i = i + 1
2199             continue
2200         i = i + 1
2201
2202
2203 def revert_mexican(document):
2204     ' Set language Spanish(Mexico) to Spanish '
2205     i = 0
2206     if document.language == "spanish-mexico":
2207         document.language = "spanish"
2208         i = find_token(document.header, "\\language", 0)
2209         if i != -1:
2210             document.header[i] = "\\language spanish"
2211     j = 0
2212     while True:
2213         j = find_token(document.body, "\\lang spanish-mexico", j)
2214         if j == -1:
2215             return
2216         document.body[j] = document.body[j].replace("\\lang spanish-mexico", "\\lang spanish")
2217         j = j + 1
2218
2219
2220 def remove_embedding(document):
2221     ' Remove embed tag from all insets '
2222     revert_inset_embedding(document, 'Graphics')
2223     revert_inset_embedding(document, 'External')
2224     revert_inset_embedding(document, 'CommandInset include')
2225     revert_inset_embedding(document, 'CommandInset bibtex')
2226
2227
2228 def revert_master(document):
2229     ' Remove master param '
2230     i = find_token(document.header, "\\master", 0)
2231     if i != -1:
2232         del document.header[i]
2233
2234
2235 def revert_graphics_group(document):
2236     ' Revert group information from graphics insets '
2237     i = 0
2238     while 1:
2239         i = find_token(document.body, "\\begin_inset Graphics", i)
2240         if i == -1:
2241             return
2242         j = find_end_of_inset(document.body, i)
2243         if j == -1:
2244             document.warning("Malformed lyx document: Missing '\\end_inset'.")
2245             i = i + 1
2246             continue
2247         k = find_token(document.body, " groupId", i, j)
2248         if k == -1:
2249             i = i + 1
2250             continue
2251         del document.body[k]
2252         i = i + 1
2253
2254
2255 def update_apa_styles(document):
2256     ' Replace obsolete styles '
2257
2258     if document.textclass != "apa":
2259         return
2260
2261     obsoletedby = { "Acknowledgments": "Acknowledgements",
2262                     "Section*":        "Section",
2263                     "Subsection*":     "Subsection",
2264                     "Subsubsection*":  "Subsubsection",
2265                     "Paragraph*":      "Paragraph",
2266                     "Subparagraph*":   "Subparagraph"}
2267     i = 0
2268     while 1:
2269         i = find_token(document.body, "\\begin_layout", i)
2270         if i == -1:
2271             return
2272
2273         layout = document.body[i][14:]
2274         if layout in obsoletedby:
2275             document.body[i] = "\\begin_layout " + obsoletedby[layout]
2276
2277         i += 1
2278
2279
2280 def convert_paper_sizes(document):
2281     ' exchange size options legalpaper and executivepaper to correct order '
2282     # routine is needed to fix http://bugzilla.lyx.org/show_bug.cgi?id=4868
2283     i = 0
2284     j = 0
2285     i = find_token(document.header, "\\papersize executivepaper", 0)
2286     if i != -1:
2287         document.header[i] = "\\papersize legalpaper"
2288         return
2289     j = find_token(document.header, "\\papersize legalpaper", 0)
2290     if j != -1:
2291         document.header[j] = "\\papersize executivepaper"
2292
2293
2294 def revert_paper_sizes(document):
2295     ' exchange size options legalpaper and executivepaper to correct order '
2296     i = 0
2297     j = 0
2298     i = find_token(document.header, "\\papersize executivepaper", 0)
2299     if i != -1:
2300         document.header[i] = "\\papersize legalpaper"
2301         return
2302     j = find_token(document.header, "\\papersize legalpaper", 0)
2303     if j != -1:
2304         document.header[j] = "\\papersize executivepaper"
2305
2306
2307 def convert_InsetSpace(document):
2308     " Convert '\\begin_inset Space foo' to '\\begin_inset space foo'"
2309     i = 0
2310     while True:
2311         i = find_token(document.body, "\\begin_inset Space", i)
2312         if i == -1:
2313             return
2314         document.body[i] = document.body[i].replace('\\begin_inset Space', '\\begin_inset space')
2315
2316
2317 def revert_InsetSpace(document):
2318     " Revert '\\begin_inset space foo' to '\\begin_inset Space foo'"
2319     i = 0
2320     while True:
2321         i = find_token(document.body, "\\begin_inset space", i)
2322         if i == -1:
2323             return
2324         document.body[i] = document.body[i].replace('\\begin_inset space', '\\begin_inset Space')
2325
2326
2327 ##
2328 # Conversion hub
2329 #
2330
2331 supported_versions = ["1.6.0","1.6"]
2332 convert = [[277, [fix_wrong_tables]],
2333            [278, [close_begin_deeper]],
2334            [279, [long_charstyle_names]],
2335            [280, [axe_show_label]],
2336            [281, []],
2337            [282, []],
2338            [283, [convert_flex]],
2339            [284, []],
2340            [285, []],
2341            [286, []],
2342            [287, [convert_wrapfig_options]],
2343            [288, [convert_inset_command]],
2344            [289, [convert_latexcommand_index]],
2345            [290, []],
2346            [291, []],
2347            [292, []],
2348            [293, []],
2349            [294, [convert_pdf_options]],
2350            [295, [convert_htmlurl, convert_url]],
2351            [296, [convert_include]],
2352            [297, [convert_usorbian]],
2353            [298, []],
2354            [299, []],
2355            [300, []],
2356            [301, []],
2357            [302, []],
2358            [303, [convert_serbocroatian]],
2359            [304, [convert_framed_notes]],
2360            [305, []],
2361            [306, []],
2362            [307, []],
2363            [308, []],
2364            [309, []],
2365            [310, []],
2366            [311, [convert_ams_classes]],
2367            [312, []],
2368            [313, [convert_module_names]],
2369            [314, []],
2370            [315, []],
2371            [316, [convert_subfig]],
2372            [317, []],
2373            [318, []],
2374            [319, [convert_spaceinset, convert_hfill]],
2375            [320, []],
2376            [321, [convert_tablines]],
2377            [322, []],
2378            [323, [convert_pagebreaks]],
2379            [324, [convert_linebreaks]],
2380            [325, [convert_japanese_plain]],
2381            [326, []],
2382            [327, []],
2383            [328, [remove_embedding, remove_extra_embedded_files, remove_inzip_options]],
2384            [329, []],
2385            [330, []],
2386            [331, [convert_ltcaption]],
2387            [332, []],
2388            [333, [update_apa_styles]],
2389            [334, [convert_paper_sizes]],
2390            [335, [convert_InsetSpace]],
2391           ]
2392
2393 revert =  [[334, [revert_InsetSpace]],
2394            [333, [revert_paper_sizes]],
2395            [332, []],
2396            [331, [revert_graphics_group]],
2397            [330, [revert_ltcaption]],
2398            [329, [revert_leftarrowfill, revert_rightarrowfill, revert_upbracefill, revert_downbracefill]],
2399            [328, [revert_master]],
2400            [327, []],
2401            [326, [revert_mexican]],
2402            [325, [revert_pdfpages]],
2403            [324, []],
2404            [323, [revert_linebreaks]],
2405            [322, [revert_pagebreaks]],
2406            [321, [revert_local_layout]],
2407            [320, [revert_tablines]],
2408            [319, [revert_protected_hfill]],
2409            [318, [revert_spaceinset, revert_hfills, revert_hspace]],
2410            [317, [remove_extra_embedded_files]],
2411            [316, [revert_wrapplacement]],
2412            [315, [revert_subfig]],
2413            [314, [revert_colsep]],
2414            [313, []],
2415            [312, [revert_module_names]],
2416            [311, [revert_rotfloat, revert_widesideways]],
2417            [310, [revert_external_embedding]],
2418            [309, [revert_btprintall]],
2419            [308, [revert_nocite]],
2420            [307, [revert_serbianlatin]],
2421            [306, [revert_slash, revert_nobreakdash]],
2422            [305, [revert_interlingua]],
2423            [304, [revert_bahasam]],
2424            [303, [revert_framed_notes]],
2425            [302, []],
2426            [301, [revert_latin, revert_samin]],
2427            [300, [revert_linebreak]],
2428            [299, [revert_pagebreak]],
2429            [298, [revert_hyperlinktype]],
2430            [297, [revert_macro_optional_params]],
2431            [296, [revert_albanian, revert_lowersorbian, revert_uppersorbian]],
2432            [295, [revert_include]],
2433            [294, [revert_href]],
2434            [293, [revert_pdf_options_2]],
2435            [292, [revert_inset_info]],
2436            [291, [revert_japanese, revert_japanese_encoding]],
2437            [290, [revert_vietnamese]],
2438            [289, [revert_wraptable]],
2439            [288, [revert_latexcommand_index]],
2440            [287, [revert_inset_command]],
2441            [286, [revert_wrapfig_options]],
2442            [285, [revert_pdf_options]],
2443            [284, [remove_inzip_options]],
2444            [283, []],
2445            [282, [revert_flex]],
2446            [281, []],
2447            [280, [revert_begin_modules]],
2448            [279, [revert_show_label]],
2449            [278, [revert_long_charstyle_names]],
2450            [277, []],
2451            [276, []]
2452           ]
2453
2454
2455 if __name__ == "__main__":
2456     pass