1 # -*- coding: utf-8 -*-
2 # This file is part of lyx2lyx
3 # -*- coding: utf-8 -*-
4 # Copyright (C) 2010 The LyX team
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 """ Convert files to the file format generated by lyx 2.0"""
26 from parser_tools import find_token, find_end_of, find_tokens, \
27 find_end_of_inset, find_end_of_layout, find_token_backwards, \
28 get_containing_inset, get_value, get_value_string
30 from lyx2lyx_tools import add_to_preamble, insert_to_preamble, \
31 put_cmd_in_ert, lyx2latex, latex_length, revert_flex_inset, \
32 revert_font_attrs, revert_layout_command, hex2ratio
34 ####################################################################
35 # Private helper functions
37 def remove_option(document, m, option):
38 ''' removes option from line m. returns whether we did anything '''
39 l = document.body[m].find(option)
42 val = document.body[m][l:].split('"')[1]
43 document.body[m] = document.body[m][:l - 1] + document.body[m][l+len(option + '="' + val + '"'):]
47 # DO NOT USE THIS ROUTINE ANY MORE. Better yet, replace the uses that
48 # have been made of it with uses of put_cmd_in_ert.
49 def old_put_cmd_in_ert(string):
50 for rep in unicode_reps:
51 string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
52 string = string.replace('\\', "\\backslash\n")
53 string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
54 + string + "\n\\end_layout\n\\end_inset"
58 ###############################################################################
60 ### Conversion and reversion routines
62 ###############################################################################
64 def revert_swiss(document):
65 " Set language german-ch to ngerman "
67 if document.language == "german-ch":
68 document.language = "ngerman"
69 i = find_token(document.header, "\\language", 0)
71 document.header[i] = "\\language ngerman"
74 j = find_token(document.body, "\\lang german-ch", j)
77 document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
81 def revert_tabularvalign(document):
82 " Revert the tabular valign option "
85 i = find_token(document.body, "\\begin_inset Tabular", i)
88 end = find_end_of_inset(document.body, i)
90 document.warning("Can't find end of inset at line " + str(i))
93 fline = find_token(document.body, "<features", i, end)
95 document.warning("Can't find features for inset at line " + str(i))
98 p = document.body[fline].find("islongtable")
100 q = document.body[fline].find("tabularvalignment")
103 # This seems wrong: It removes everything after
104 # tabularvalignment, too.
105 document.body[fline] = document.body[fline][:q - 1] + '>'
110 tabularvalignment = 'c'
111 # which valignment is specified?
112 m = document.body[fline].find('tabularvalignment="top"')
114 tabularvalignment = 't'
115 m = document.body[fline].find('tabularvalignment="bottom"')
117 tabularvalignment = 'b'
118 # delete tabularvalignment
119 q = document.body[fline].find("tabularvalignment")
122 # This seems wrong: It removes everything after
123 # tabularvalignment, too.
124 document.body[fline] = document.body[fline][:q - 1] + '>'
126 # don't add a box when centered
127 if tabularvalignment == 'c':
130 subst = ['\\end_layout', '\\end_inset']
131 document.body[end:end] = subst # just inserts those lines
132 subst = ['\\begin_inset Box Frameless',
133 'position "' + tabularvalignment +'"',
138 # we don't know the width, assume 50%
142 'height_special "totalheight"',
145 '\\begin_layout Plain Layout']
146 document.body[i:i] = subst # this just inserts the array at i
147 # since there could be a tabular inside a tabular, we cannot
152 def revert_phantom_types(document, ptype, cmd):
153 " Reverts phantom to ERT "
156 i = find_token(document.body, "\\begin_inset Phantom " + ptype, i)
159 end = find_end_of_inset(document.body, i)
161 document.warning("Can't find end of inset at line " + str(i))
164 blay = find_token(document.body, "\\begin_layout Plain Layout", i, end)
166 document.warning("Can't find layout for inset at line " + str(i))
169 bend = find_token(document.body, "\\end_layout", blay, end)
171 document.warning("Malformed LyX document: Could not find end of Phantom inset's layout.")
174 substi = ["\\begin_inset ERT", "status collapsed", "",
175 "\\begin_layout Plain Layout", "", "", "\\backslash",
176 cmd + "{", "\\end_layout", "", "\\end_inset"]
177 substj = ["\\size default", "", "\\begin_inset ERT", "status collapsed", "",
178 "\\begin_layout Plain Layout", "", "}", "\\end_layout", "", "\\end_inset"]
179 # do the later one first so as not to mess up the numbering
180 document.body[bend:end + 1] = substj
181 document.body[i:blay + 1] = substi
182 i = end + len(substi) + len(substj) - (end - bend) - (blay - i) - 2
185 def revert_phantom(document):
186 revert_phantom_types(document, "Phantom", "phantom")
188 def revert_hphantom(document):
189 revert_phantom_types(document, "HPhantom", "hphantom")
191 def revert_vphantom(document):
192 revert_phantom_types(document, "VPhantom", "vphantom")
195 def revert_xetex(document):
196 " Reverts documents that use XeTeX "
197 i = find_token(document.header, '\\use_xetex', 0)
199 document.warning("Malformed LyX document: Missing \\use_xetex.")
201 if get_value(document.header, "\\use_xetex", i) == 'false':
202 del document.header[i]
204 del document.header[i]
205 # 1.) set doc encoding to utf8-plain
206 i = find_token(document.header, "\\inputencoding", 0)
208 document.warning("Malformed LyX document: Missing \\inputencoding.")
209 document.header[i] = "\\inputencoding utf8-plain"
210 # 2.) check font settings
211 l = find_token(document.header, "\\font_roman", 0)
213 document.warning("Malformed LyX document: Missing \\font_roman.")
214 line = document.header[l]
215 l = re.compile(r'\\font_roman (.*)$')
218 l = find_token(document.header, "\\font_sans", 0)
220 document.warning("Malformed LyX document: Missing \\font_sans.")
221 line = document.header[l]
222 l = re.compile(r'\\font_sans (.*)$')
225 l = find_token(document.header, "\\font_typewriter", 0)
227 document.warning("Malformed LyX document: Missing \\font_typewriter.")
228 line = document.header[l]
229 l = re.compile(r'\\font_typewriter (.*)$')
231 typewriter = m.group(1)
232 osf = get_value(document.header, '\\font_osf', 0) == "true"
233 sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
234 tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
235 # 3.) set preamble stuff
236 pretext = '%% This document must be processed with xelatex!\n'
237 pretext += '\\usepackage{fontspec}\n'
238 if roman != "default":
239 pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
240 if sans != "default":
241 pretext += '\\setsansfont['
243 pretext += 'Scale=' + str(sf_scale / 100) + ','
244 pretext += 'Mapping=tex-text]{' + sans + '}\n'
245 if typewriter != "default":
246 pretext += '\\setmonofont'
248 pretext += '[Scale=' + str(tt_scale / 100) + ']'
249 pretext += '{' + typewriter + '}\n'
251 pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
252 pretext += '\usepackage{xunicode}\n'
253 pretext += '\usepackage{xltxtra}\n'
254 insert_to_preamble(0, document, pretext)
255 # 4.) reset font settings
256 i = find_token(document.header, "\\font_roman", 0)
258 document.warning("Malformed LyX document: Missing \\font_roman.")
259 document.header[i] = "\\font_roman default"
260 i = find_token(document.header, "\\font_sans", 0)
262 document.warning("Malformed LyX document: Missing \\font_sans.")
263 document.header[i] = "\\font_sans default"
264 i = find_token(document.header, "\\font_typewriter", 0)
266 document.warning("Malformed LyX document: Missing \\font_typewriter.")
267 document.header[i] = "\\font_typewriter default"
268 i = find_token(document.header, "\\font_osf", 0)
270 document.warning("Malformed LyX document: Missing \\font_osf.")
271 document.header[i] = "\\font_osf false"
272 i = find_token(document.header, "\\font_sc", 0)
274 document.warning("Malformed LyX document: Missing \\font_sc.")
275 document.header[i] = "\\font_sc false"
276 i = find_token(document.header, "\\font_sf_scale", 0)
278 document.warning("Malformed LyX document: Missing \\font_sf_scale.")
279 document.header[i] = "\\font_sf_scale 100"
280 i = find_token(document.header, "\\font_tt_scale", 0)
282 document.warning("Malformed LyX document: Missing \\font_tt_scale.")
283 document.header[i] = "\\font_tt_scale 100"
286 def revert_outputformat(document):
287 " Remove default output format param "
288 i = find_token(document.header, '\\default_output_format', 0)
290 document.warning("Malformed LyX document: Missing \\default_output_format.")
292 del document.header[i]
295 def revert_backgroundcolor(document):
296 " Reverts background color to preamble code "
297 i = find_token(document.header, "\\backgroundcolor", 0)
300 colorcode = get_value(document.header, '\\backgroundcolor', i)
301 del document.header[i]
302 # don't clutter the preamble if backgroundcolor is not set
303 if colorcode == "#ffffff":
305 red = hex2ratio(colorcode[1:3])
306 green = hex2ratio(colorcode[3:5])
307 blue = hex2ratio(colorcode[5:7])
308 insert_to_preamble(0, document,
309 '% Commands inserted by lyx2lyx to set the background color\n'
310 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
311 + '\\definecolor{page_backgroundcolor}{rgb}{'
312 + red + ',' + green + ',' + blue + '}\n'
313 + '\\pagecolor{page_backgroundcolor}\n')
316 def revert_splitindex(document):
317 " Reverts splitindex-aware documents "
318 i = find_token(document.header, '\\use_indices', 0)
320 document.warning("Malformed LyX document: Missing \\use_indices.")
322 indices = get_value(document.header, "\\use_indices", i)
324 useindices = (indices == "true")
326 preamble += "\\usepackage{splitidx}\n"
327 del document.header[i]
329 # deal with index declarations in the preamble
332 i = find_token(document.header, "\\index", i)
335 k = find_token(document.header, "\\end_index", i)
337 document.warning("Malformed LyX document: Missing \\end_index.")
340 line = document.header[i]
341 l = re.compile(r'\\index (.*)$')
344 ishortcut = get_value(document.header, '\\shortcut', i, k)
346 preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
347 del document.header[i:k + 1]
349 insert_to_preamble(0, document, preamble)
351 # deal with index insets
352 # these need to have the argument removed
355 i = find_token(document.body, "\\begin_inset Index", i)
358 line = document.body[i]
359 l = re.compile(r'\\begin_inset Index (.*)$')
362 if itype == "idx" or indices == "false":
363 document.body[i] = "\\begin_inset Index"
365 k = find_end_of_inset(document.body, i)
367 document.warning("Can't find end of index inset!")
370 content = lyx2latex(document, document.body[i:k])
372 content = content.replace('"', r'\"')
373 subst = put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")
374 document.body[i:k + 1] = subst
377 # deal with index_print insets
380 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
383 k = find_end_of_inset(document.body, i)
384 ptype = get_value(document.body, 'type', i, k).strip('"')
386 j = find_token(document.body, "type", i, k)
389 del document.body[i:k + 1]
391 subst = put_cmd_in_ert("\\printindex[" + ptype + "]{}")
392 document.body[i:k + 1] = subst
396 def convert_splitindex(document):
397 " Converts index and printindex insets to splitindex-aware format "
400 i = find_token(document.body, "\\begin_inset Index", i)
403 document.body[i] = document.body[i].replace("\\begin_inset Index",
404 "\\begin_inset Index idx")
408 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
411 if document.body[i + 1].find('LatexCommand printindex') == -1:
412 document.warning("Malformed LyX document: Incomplete printindex inset.")
414 subst = ["LatexCommand printindex",
416 document.body[i + 1:i + 2] = subst
420 def revert_subindex(document):
421 " Reverts \\printsubindex CommandInset types "
422 i = find_token(document.header, '\\use_indices', 0)
424 document.warning("Malformed LyX document: Missing \\use_indices.")
426 indices = get_value(document.header, "\\use_indices", i)
427 useindices = (indices == "true")
430 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
433 k = find_end_of_inset(document.body, i)
434 ctype = get_value(document.body, 'LatexCommand', i, k)
435 if ctype != "printsubindex":
438 ptype = get_value(document.body, 'type', i, k).strip('"')
440 del document.body[i:k + 1]
442 subst = put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")
443 document.body[i:k + 1] = subst
447 def revert_printindexall(document):
448 " Reverts \\print[sub]index* CommandInset types "
449 i = find_token(document.header, '\\use_indices', 0)
451 document.warning("Malformed LyX document: Missing \\use_indices.")
453 indices = get_value(document.header, "\\use_indices", i)
454 useindices = (indices == "true")
457 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
460 k = find_end_of_inset(document.body, i)
461 ctype = get_value(document.body, 'LatexCommand', i, k)
462 if ctype != "printindex*" and ctype != "printsubindex*":
466 del document.body[i:k + 1]
468 subst = put_cmd_in_ert("\\" + ctype + "{}")
469 document.body[i:k + 1] = subst
473 def revert_strikeout(document):
474 " Reverts \\strikeout font attribute "
475 changed = revert_font_attrs(document, "\\uuline", "\\uuline")
476 changed = revert_font_attrs(document, "\\uwave", "\\uwave") or changed
477 changed = revert_font_attrs(document, "\\strikeout", "\\sout") or changed
479 insert_to_preamble(0, document,
480 '% Commands inserted by lyx2lyx for proper underlining\n'
481 + '\\PassOptionsToPackage{normalem}{ulem}\n'
482 + '\\usepackage{ulem}\n')
485 def revert_ulinelatex(document):
486 " Reverts \\uline font attribute "
487 i = find_token(document.body, '\\bar under', 0)
490 insert_to_preamble(0, document,
491 '% Commands inserted by lyx2lyx for proper underlining\n'
492 + '\\PassOptionsToPackage{normalem}{ulem}\n'
493 + '\\usepackage{ulem}\n'
494 + '\\let\\cite@rig\\cite\n'
495 + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
496 + ' \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
497 + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
500 def revert_custom_processors(document):
501 " Remove bibtex_command and index_command params "
502 i = find_token(document.header, '\\bibtex_command', 0)
504 document.warning("Malformed LyX document: Missing \\bibtex_command.")
506 del document.header[i]
507 i = find_token(document.header, '\\index_command', 0)
509 document.warning("Malformed LyX document: Missing \\index_command.")
511 del document.header[i]
514 def convert_nomencl_width(document):
515 " Add set_width param to nomencl_print "
518 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
521 document.body.insert(i + 2, "set_width \"none\"")
525 def revert_nomencl_width(document):
526 " Remove set_width param from nomencl_print "
529 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
532 j = find_end_of_inset(document.body, i)
533 l = find_token(document.body, "set_width", i, j)
535 document.warning("Can't find set_width option for nomencl_print!")
542 def revert_nomencl_cwidth(document):
543 " Remove width param from nomencl_print "
546 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
549 j = find_end_of_inset(document.body, i)
550 l = find_token(document.body, "width", i, j)
552 document.warning("Can't find width option for nomencl_print!")
555 width = get_value(document.body, "width", i, j).strip('"')
557 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
558 add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
562 def revert_applemac(document):
563 " Revert applemac encoding to auto "
564 if document.encoding != "applemac":
566 document.encoding = "auto"
567 i = find_token(document.header, "\\encoding", 0)
569 document.header[i] = "\\encoding auto"
572 def revert_longtable_align(document):
573 " Remove longtable alignment setting "
576 i = find_token(document.body, "\\begin_inset Tabular", i)
579 end = find_end_of_inset(document.body, i)
581 document.warning("Can't find end of inset at line " + str(i))
584 fline = find_token(document.body, "<features", i, end)
586 document.warning("Can't find features for inset at line " + str(i))
589 j = document.body[fline].find("longtabularalignment")
593 # FIXME Is this correct? It wipes out everything after the
595 document.body[fline] = document.body[fline][:j - 1] + '>'
596 # since there could be a tabular inside this one, we
597 # cannot jump to end.
601 def revert_branch_filename(document):
602 " Remove \\filename_suffix parameter from branches "
605 i = find_token(document.header, "\\filename_suffix", i)
608 del document.header[i]
611 def revert_paragraph_indentation(document):
612 " Revert custom paragraph indentation to preamble code "
613 i = find_token(document.header, "\\paragraph_indentation", 0)
616 length = get_value(document.header, "\\paragraph_indentation", i)
617 # we need only remove the line if indentation is default
618 if length != "default":
619 # handle percent lengths
620 length = latex_length(length)[1]
621 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
622 add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
623 del document.header[i]
626 def revert_percent_skip_lengths(document):
627 " Revert relative lengths for paragraph skip separation to preamble code "
628 i = find_token(document.header, "\\defskip", 0)
631 length = get_value(document.header, "\\defskip", i)
632 # only revert when a custom length was set and when
633 # it used a percent length
634 if length in ('smallskip', 'medskip', 'bigskip'):
636 # handle percent lengths
637 percent, length = latex_length(length)
639 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
640 add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
641 # set defskip to medskip as default
642 document.header[i] = "\\defskip medskip"
645 def revert_percent_vspace_lengths(document):
646 " Revert relative VSpace lengths to ERT "
649 i = find_token(document.body, "\\begin_inset VSpace", i)
652 # only revert if a custom length was set and if
653 # it used a percent length
654 r = re.compile(r'\\begin_inset VSpace (.*)$')
655 m = r.match(document.body[i])
657 if length in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
660 # check if the space has a star (protected space)
661 protected = (document.body[i].rfind("*") != -1)
663 length = length.rstrip('*')
664 # handle percent lengths
665 percent, length = latex_length(length)
666 # revert the VSpace inset to ERT
669 subst = put_cmd_in_ert("\\vspace*{" + length + "}")
671 subst = put_cmd_in_ert("\\vspace{" + length + "}")
672 document.body[i:i + 2] = subst
676 def revert_percent_hspace_lengths(document):
677 " Revert relative HSpace lengths to ERT "
680 i = find_token(document.body, "\\begin_inset space \\hspace", i)
683 j = find_end_of_inset(document.body, i)
685 document.warning("Can't find end of inset at line " + str(i))
688 # only revert if a custom length was set...
689 length = get_value(document.body, '\\length', i + 1, j)
691 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
695 if document.body[i].find("\\hspace*{}") != -1:
697 # ...and if it used a percent length
698 percent, length = latex_length(length)
699 # revert the HSpace inset to ERT
701 subst = put_cmd_in_ert("\\hspace" + protected + "{" + length + "}")
702 document.body[i:j + 1] = subst
703 # if we did a substitution, this will still be ok
707 def revert_hspace_glue_lengths(document):
708 " Revert HSpace glue lengths to ERT "
711 i = find_token(document.body, "\\begin_inset space \\hspace", i)
714 j = find_end_of_inset(document.body, i)
716 document.warning("Can't find end of inset at line " + str(i))
719 length = get_value(document.body, '\\length', i + 1, j)
721 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
725 if document.body[i].find("\\hspace*{}") != -1:
727 # only revert if the length contains a plus or minus at pos != 0
728 if length.find('-',1) != -1 or length.find('+',1) != -1:
729 # handle percent lengths
730 length = latex_length(length)[1]
731 # revert the HSpace inset to ERT
732 subst = put_cmd_in_ert("\\hspace" + protected + "{" + length + "}")
733 document.body[i:j+1] = subst
737 def convert_author_id(document):
738 " Add the author_id to the \\author definition and make sure 0 is not used"
741 re_author = re.compile(r'(\\author) (\".*\")\s*(.*)$')
744 i = find_token(document.header, "\\author", i)
747 m = re_author.match(document.header[i])
751 document.header[i] = "\\author %i %s %s" % (anum, name, email)
752 # FIXME Should this really be incremented if we didn't match?
758 i = find_token(document.body, "\\change_", i)
761 change = document.body[i].split(' ');
764 author_id = int(change[1])
766 document.body[i] = "%s %i %s" % (type, author_id + 1, time)
770 def revert_author_id(document):
771 " Remove the author_id from the \\author definition "
774 rx = re.compile(r'(\\author)\s+(\d+)\s+(\".*\")\s*(.*)$')
778 i = find_token(document.header, "\\author", i)
781 m = rx.match(document.header[i])
783 author_id = int(m.group(2))
784 idmap[author_id] = anum
787 document.header[i] = "\\author %s %s" % (name, email)
789 # FIXME Should this be incremented if we didn't match?
794 i = find_token(document.body, "\\change_", i)
797 change = document.body[i].split(' ');
800 author_id = int(change[1])
802 document.body[i] = "%s %i %s" % (type, idmap[author_id], time)
806 def revert_suppress_date(document):
807 " Revert suppressing of default document date to preamble code "
808 i = find_token(document.header, "\\suppress_date", 0)
811 # remove the preamble line and write to the preamble
812 # when suppress_date was true
813 date = get_value(document.header, "\\suppress_date", i)
815 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
816 add_to_preamble(document, ["\\date{}"])
817 del document.header[i]
820 def revert_mhchem(document):
821 "Revert mhchem loading to preamble code"
824 i = find_token(document.header, "\\use_mhchem", 0)
826 document.warning("Malformed LyX document: Could not find mhchem setting.")
829 val = get_value(document.header, "\\use_mhchem", i)
834 del document.header[i]
839 i = find_token(document.body, "\\begin_inset Formula", i)
842 line = document.body[i]
843 if line.find("\\ce{") != -1 or line.find("\\cf{") != 1:
849 pre = ["% lyx2lyx mhchem commands",
850 "\\PassOptionsToPackage{version=3}{mhchem}",
851 "\\usepackage{mhchem}"]
852 add_to_preamble(document, pre)
855 def revert_fontenc(document):
856 " Remove fontencoding param "
857 i = find_token(document.header, '\\fontencoding', 0)
859 document.warning("Malformed LyX document: Missing \\fontencoding.")
861 del document.header[i]
864 def merge_gbrief(document):
865 " Merge g-brief-en and g-brief-de to one class "
867 if document.textclass != "g-brief-de":
868 if document.textclass == "g-brief-en":
869 document.textclass = "g-brief"
870 document.set_textclass()
873 obsoletedby = { "Brieftext": "Letter",
874 "Unterschrift": "Signature",
876 "Zusatz": "Addition",
879 "RetourAdresse": "ReturnAddress",
880 "MeinZeichen": "MyRef",
881 "IhrZeichen": "YourRef",
882 "IhrSchreiben": "YourMail",
885 "Konto": "BankAccount",
886 "Postvermerk": "PostalComment",
887 "Adresse": "Address",
889 "Betreff": "Reference",
896 i = find_token(document.body, "\\begin_layout", i)
900 layout = document.body[i][14:]
901 if layout in obsoletedby:
902 document.body[i] = "\\begin_layout " + obsoletedby[layout]
906 document.textclass = "g-brief"
907 document.set_textclass()
910 def revert_gbrief(document):
911 " Revert g-brief to g-brief-en "
912 if document.textclass == "g-brief":
913 document.textclass = "g-brief-en"
914 document.set_textclass()
917 def revert_html_options(document):
918 " Remove html options "
919 i = find_token(document.header, '\\html_use_mathml', 0)
921 del document.header[i]
922 i = find_token(document.header, '\\html_be_strict', 0)
924 del document.header[i]
927 def revert_includeonly(document):
930 i = find_token(document.header, "\\begin_includeonly", i)
933 j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
935 document.warning("Unable to find end of includeonly section!!")
937 document.header[i : j + 1] = []
940 def revert_includeall(document):
941 " Remove maintain_unincluded_children param "
942 i = find_token(document.header, '\\maintain_unincluded_children', 0)
944 del document.header[i]
947 def revert_multirow(document):
948 " Revert multirow cells in tables to TeX-code"
952 # cell type 3 is multirow begin cell
953 i = find_token(document.body, '<cell multirow="3"', i)
956 # a multirow cell was found
958 # remove the multirow tag, set the valignment to top
959 # and remove the bottom line
960 # FIXME Are we sure these always have space around them?
961 document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
962 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
963 document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
964 # write ERT to create the multirow cell
965 # use 2 rows and 2cm as default with because the multirow span
966 # and the column width is only hardly accessible
967 cend = find_token(document.body, "</cell>", i)
969 document.warning("Malformed LyX document: Could not find end of tabular cell.")
972 blay = find_token(document.body, "\\begin_layout", i, cend)
974 document.warning("Can't find layout for cell!")
977 bend = find_end_of_layout(document.body, blay)
979 document.warning("Can't find end of layout for cell!")
983 # do the later one first, so as not to mess up the numbering
984 # we are wrapping the whole cell in this ert
985 # so before the end of the layout...
986 document.body[bend:bend] = put_cmd_in_ert("}")
987 # ...and after the beginning
988 document.body[blay+1:blay+1] = put_cmd_in_ert("\\multirow{2}{2cm}{")
991 # cell type 4 is multirow part cell
992 k = find_token(document.body, '<cell multirow="4"', cend)
995 # remove the multirow tag, set the valignment to top
996 # and remove the top line
997 # FIXME Are we sure these always have space around them?
998 document.body[k] = document.body[k].replace(' multirow="4" ', ' ')
999 document.body[k] = document.body[k].replace('valignment="middle"', 'valignment="top"')
1000 document.body[k] = document.body[k].replace(' topline="true" ', ' ')
1002 # this will always be ok
1005 if multirow == True:
1006 add_to_preamble(document,
1007 ["% lyx2lyx multirow additions ", "\\usepackage{multirow}"])
1010 def convert_math_output(document):
1011 " Convert \html_use_mathml to \html_math_output "
1012 i = find_token(document.header, "\\html_use_mathml", 0)
1015 rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1016 m = rgx.match(document.header[i])
1017 newval = "0" # MathML
1021 newval = "2" # Images
1023 document.warning("Can't match " + document.header[i])
1024 document.header[i] = "\\html_math_output " + newval
1027 def revert_math_output(document):
1028 " Revert \html_math_output to \html_use_mathml "
1029 i = find_token(document.header, "\\html_math_output", 0)
1032 rgx = re.compile(r'\\html_math_output\s+(\d)')
1033 m = rgx.match(document.header[i])
1037 if val == "1" or val == "2":
1040 document.warning("Unable to match " + document.header[i])
1041 document.header[i] = "\\html_use_mathml " + newval
1045 def revert_inset_preview(document):
1046 " Dissolves the preview inset "
1049 i = find_token(document.body, "\\begin_inset Preview", i)
1052 iend = find_end_of_inset(document.body, i)
1054 document.warning("Malformed LyX document: Could not find end of Preview inset.")
1058 # This has several issues.
1059 # We need to do something about the layouts inside InsetPreview.
1060 # If we just leave the first one, then we have something like:
1061 # \begin_layout Standard
1063 # \begin_layout Standard
1064 # and we get a "no \end_layout" error. So something has to be done.
1065 # Ideally, we would check if it is the same as the layout we are in.
1066 # If so, we just remove it; if not, we end the active one. But it is
1067 # not easy to know what layout we are in, due to depth changes, etc,
1068 # and it is not clear to me how much work it is worth doing. In most
1069 # cases, the layout will probably be the same.
1071 # For the same reason, we have to remove the \end_layout tag at the
1072 # end of the last layout in the inset. Again, that will sometimes be
1073 # wrong, but it will usually be right. To know what to do, we would
1074 # again have to know what layout the inset is in.
1076 blay = find_token(document.body, "\\begin_layout", i, iend)
1078 document.warning("Can't find layout for preview inset!")
1079 # always do the later one first...
1080 del document.body[iend]
1081 del document.body[i]
1082 # deletions mean we do not need to reset i
1085 # This is where we would check what layout we are in.
1086 # The check for Standard is definitely wrong.
1088 # lay = document.body[blay].split(None, 1)[1]
1089 # if lay != oldlayout:
1090 # # record a boolean to tell us what to do later....
1091 # # better to do it later, since (a) it won't mess up
1092 # # the numbering and (b) we only modify at the end.
1094 # we want to delete the last \\end_layout in this inset, too.
1095 # note that this may not be the \\end_layout that goes with blay!!
1096 bend = find_end_of_layout(document.body, blay)
1098 tmp = find_token(document.body, "\\end_layout", bend + 1, iend)
1103 document.warning("Unable to find last layout in preview inset!")
1104 del document.body[iend]
1105 del document.body[i]
1106 # deletions mean we do not need to reset i
1108 # always do the later one first...
1109 del document.body[iend]
1110 del document.body[bend]
1111 del document.body[i:blay + 1]
1112 # we do not need to reset i
1115 def revert_equalspacing_xymatrix(document):
1116 " Revert a Formula with xymatrix@! to an ERT inset "
1118 has_preamble = False
1119 has_equal_spacing = False
1122 i = find_token(document.body, "\\begin_inset Formula", i)
1125 j = find_end_of_inset(document.body, i)
1127 document.warning("Malformed LyX document: Could not find end of Formula inset.")
1131 for curline in range(i,j):
1132 found = document.body[curline].find("\\xymatrix@!")
1137 has_equal_spacing = True
1138 content = [document.body[i][21:]]
1139 content += document.body[i + 1:j]
1140 subst = put_cmd_in_ert(content)
1141 document.body[i:j + 1] = subst
1142 i += len(subst) - (j - i) + 1
1144 for curline in range(i,j):
1145 l = document.body[curline].find("\\xymatrix")
1147 has_preamble = True;
1151 if has_equal_spacing and not has_preamble:
1152 add_to_preamble(document, ['% lyx2lyx xymatrix addition', '\\usepackage[all]{xy}'])
1155 def revert_notefontcolor(document):
1156 " Reverts greyed-out note font color to preamble code "
1158 i = find_token(document.header, "\\notefontcolor", 0)
1162 # are there any grey notes?
1163 if find_token(document.body, "\\begin_inset Note Greyedout", 0) == -1:
1164 # no need to do anything, and \renewcommand will throw an error
1165 # since lyxgreyedout will not exist.
1168 colorcode = get_value(document.header, '\\notefontcolor', i)
1169 del document.header[i]
1170 # the color code is in the form #rrggbb where every character denotes a hex number
1171 red = hex2ratio(colorcode[1:3])
1172 green = hex2ratio(colorcode[3:5])
1173 blue = hex2ratio(colorcode[5:7])
1174 # write the preamble
1175 insert_to_preamble(0, document,
1176 ['% Commands inserted by lyx2lyx to set the font color',
1177 '% for greyed-out notes',
1178 '\\@ifundefined{definecolor}{\\usepackage{color}}{}'
1179 '\\definecolor{note_fontcolor}{rgb}{%s,%s,%s}' % (red, green, blue),
1180 '\\renewenvironment{lyxgreyedout}',
1181 ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}'])
1184 def revert_turkmen(document):
1185 "Set language Turkmen to English"
1187 if document.language == "turkmen":
1188 document.language = "english"
1189 i = find_token(document.header, "\\language", 0)
1191 document.header[i] = "\\language english"
1195 j = find_token(document.body, "\\lang turkmen", j)
1198 document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english")
1202 def revert_fontcolor(document):
1203 " Reverts font color to preamble code "
1204 i = find_token(document.header, "\\fontcolor", 0)
1207 colorcode = get_value(document.header, '\\fontcolor', i)
1208 del document.header[i]
1209 # don't clutter the preamble if font color is not set
1210 if colorcode == "#000000":
1212 # the color code is in the form #rrggbb where every character denotes a hex number
1213 red = hex2ratio(colorcode[1:3])
1214 green = hex2ratio(colorcode[3:5])
1215 blue = hex2ratio(colorcode[5:7])
1216 # write the preamble
1217 insert_to_preamble(0, document,
1218 ['% Commands inserted by lyx2lyx to set the font color',
1219 '\\@ifundefined{definecolor}{\\usepackage{color}}{}',
1220 '\\definecolor{document_fontcolor}{rgb}{%s,%s,%s}' % (red, green, blue),
1221 '\\color{document_fontcolor}'])
1224 def revert_shadedboxcolor(document):
1225 " Reverts shaded box color to preamble code "
1226 i = find_token(document.header, "\\boxbgcolor", 0)
1229 colorcode = get_value(document.header, '\\boxbgcolor', i)
1230 del document.header[i]
1231 # the color code is in the form #rrggbb
1232 red = hex2ratio(colorcode[1:3])
1233 green = hex2ratio(colorcode[3:5])
1234 blue = hex2ratio(colorcode[5:7])
1235 # write the preamble
1236 insert_to_preamble(0, document,
1237 ['% Commands inserted by lyx2lyx to set the color of boxes with shaded background',
1238 '\\@ifundefined{definecolor}{\\usepackage{color}}{}',
1239 "\\definecolor{shadecolor}{rgb}{%s,%s,%s}" % (red, green, blue)])
1242 def revert_lyx_version(document):
1243 " Reverts LyX Version information from Inset Info "
1244 version = "LyX version"
1246 import lyx2lyx_version
1247 version = lyx2lyx_version.version
1253 i = find_token(document.body, '\\begin_inset Info', i)
1256 j = find_end_of_inset(document.body, i + 1)
1258 document.warning("Malformed LyX document: Could not find end of Info inset.")
1267 # but we shall try to be forgiving.
1269 for k in range(i, j):
1270 if document.body[k].startswith("arg"):
1271 arg = document.body[k][3:].strip().strip('"')
1272 if document.body[k].startswith("type"):
1273 typ = document.body[k][4:].strip().strip('"')
1274 if arg != "version" or typ != "lyxinfo":
1278 # We do not actually know the version of LyX used to produce the document.
1279 # But we can use our version, since we are reverting.
1281 # Now we want to check if the line after "\end_inset" is empty. It normally
1282 # is, so we want to remove it, too.
1284 if document.body[j + 1].strip() == "":
1286 document.body[i: lastline] = s
1290 def revert_math_scale(document):
1291 " Remove math scaling and LaTeX options "
1292 i = find_token(document.header, '\\html_math_img_scale', 0)
1294 del document.header[i]
1295 i = find_token(document.header, '\\html_latex_start', 0)
1297 del document.header[i]
1298 i = find_token(document.header, '\\html_latex_end', 0)
1300 del document.header[i]
1303 def revert_pagesizes(document):
1304 " Revert page sizes to default "
1305 i = find_token(document.header, '\\papersize', 0)
1307 size = document.header[i][11:]
1308 if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1309 or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1310 or size == "b2paper" or size == "b6paper" or size == "b0j" \
1311 or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1312 or size == "b5j" or size == "b6j":
1313 del document.header[i]
1316 def revert_DIN_C_pagesizes(document):
1317 " Revert DIN C page sizes to default "
1318 i = find_token(document.header, '\\papersize', 0)
1320 size = document.header[i][11:]
1321 if size == "c0paper" or size == "c1paper" or size == "c2paper" \
1322 or size == "c3paper" or size == "c4paper" or size == "c5paper" \
1323 or size == "c6paper":
1324 del document.header[i]
1327 def convert_html_quotes(document):
1328 " Remove quotes around html_latex_start and html_latex_end "
1330 i = find_token(document.header, '\\html_latex_start', 0)
1332 line = document.header[i]
1333 l = re.compile(r'\\html_latex_start\s+"(.*)"')
1336 document.header[i] = "\\html_latex_start " + m.group(1)
1338 i = find_token(document.header, '\\html_latex_end', 0)
1340 line = document.header[i]
1341 l = re.compile(r'\\html_latex_end\s+"(.*)"')
1344 document.header[i] = "\\html_latex_end " + m.group(1)
1347 def revert_html_quotes(document):
1348 " Remove quotes around html_latex_start and html_latex_end "
1350 i = find_token(document.header, '\\html_latex_start', 0)
1352 line = document.header[i]
1353 l = re.compile(r'\\html_latex_start\s+(.*)')
1356 document.warning("Weird html_latex_start line: " + line)
1357 del document.header[i]
1359 document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1361 i = find_token(document.header, '\\html_latex_end', 0)
1363 line = document.header[i]
1364 l = re.compile(r'\\html_latex_end\s+(.*)')
1367 document.warning("Weird html_latex_end line: " + line)
1368 del document.header[i]
1370 document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1373 def revert_output_sync(document):
1374 " Remove forward search options "
1375 i = find_token(document.header, '\\output_sync_macro', 0)
1377 del document.header[i]
1378 i = find_token(document.header, '\\output_sync', 0)
1380 del document.header[i]
1383 # FIXME This doesn't do anything!!
1384 def revert_align_decimal(document):
1387 l = document.body[l].find('alignment=decimal')
1390 remove_option(document, l, 'decimal_point')
1391 document.body[l].replace('decimal', 'center')
1394 def convert_optarg(document):
1395 " Convert \\begin_inset OptArg to \\begin_inset Argument "
1398 i = find_token(document.body, '\\begin_inset OptArg', i)
1401 document.body[i] = "\\begin_inset Argument"
1405 def revert_argument(document):
1406 " Convert \\begin_inset Argument to \\begin_inset OptArg "
1409 i = find_token(document.body, '\\begin_inset Argument', i)
1412 document.body[i] = "\\begin_inset OptArg"
1416 def revert_makebox(document):
1417 " Convert \\makebox to TeX code "
1420 # only revert frameless boxes without an inner box
1421 i = find_token(document.body, '\\begin_inset Box Frameless', i)
1424 z = find_end_of_inset(document.body, i)
1426 document.warning("Malformed LyX document: Can't find end of box inset.")
1429 blay = find_token(document.body, "\\begin_layout", i, z)
1431 document.warning("Malformed LyX document: Can't find layout in box.")
1434 # by looking before the layout we make sure we're actually finding
1435 # an option, not text.
1436 j = find_token(document.body, 'use_makebox', i, blay)
1440 val = get_value(document.body, 'use_makebox', j)
1442 del document.body[j]
1445 bend = find_end_of_layout(document.body, blay)
1446 if bend == -1 or bend > z:
1447 document.warning("Malformed LyX document: Can't find end of layout in box.")
1450 # determine the alignment
1451 align = get_value(document.body, 'hor_pos', i, blay, "c").strip('"')
1452 # determine the width
1453 length = get_value(document.body, 'width', i, blay, "50col%").strip('"')
1454 length = latex_length(length)[1]
1455 # remove the \end_layout \end_inset pair
1456 document.body[bend:z + 1] = put_cmd_in_ert("}")
1457 subst = "\\makebox[" + length + "][" \
1459 document.body[i:blay + 1] = put_cmd_in_ert(subst)
1463 def convert_use_makebox(document):
1464 " Adds use_makebox option for boxes "
1467 i = find_token(document.body, '\\begin_inset Box', i)
1470 # all of this is to make sure we actually find the use_parbox
1471 # that is an option for this box, not some text elsewhere.
1472 z = find_end_of_inset(document.body, i)
1474 document.warning("Can't find end of box inset!!")
1477 blay = find_token(document.body, "\\begin_layout", i, z)
1479 document.warning("Can't find layout in box inset!!")
1482 # so now we are looking for use_parbox before the box's layout
1483 k = find_token(document.body, 'use_parbox', i, blay)
1485 document.warning("Malformed LyX document: Can't find use_parbox statement in box.")
1488 document.body.insert(k + 1, "use_makebox 0")
1492 def revert_IEEEtran(document):
1493 " Convert IEEEtran layouts and styles to TeX code "
1494 if document.textclass != "IEEEtran":
1496 revert_flex_inset(document, "IEEE membership", "\\IEEEmembership", 0)
1497 revert_flex_inset(document, "Lowercase", "\\MakeLowercase", 0)
1498 layouts = ("Special Paper Notice", "After Title Text", "Publication ID",
1499 "Page headings", "Biography without photo")
1500 latexcmd = {"Special Paper Notice": "\\IEEEspecialpapernotice",
1501 "After Title Text": "\\IEEEaftertitletext",
1502 "Publication ID": "\\IEEEpubid"}
1503 obsoletedby = {"Page headings": "MarkBoth",
1504 "Biography without photo": "BiographyNoPhoto"}
1505 for layout in layouts:
1508 i = find_token(document.body, '\\begin_layout ' + layout, i)
1511 j = find_end_of_layout(document.body, i)
1513 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1516 if layout in obsoletedby:
1517 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1520 content = lyx2latex(document, document.body[i:j + 1])
1521 add_to_preamble(document, [latexcmd[layout] + "{" + content + "}"])
1522 del document.body[i:j + 1]
1523 # no need to reset i
1526 def convert_prettyref(document):
1527 " Converts prettyref references to neutral formatted refs "
1528 re_ref = re.compile("^\s*reference\s+\"(\w+):(\S+)\"")
1529 nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
1533 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
1536 j = find_end_of_inset(document.body, i)
1538 document.warning("Malformed LyX document: No end of InsetRef!")
1541 k = find_token(document.body, "LatexCommand prettyref", i, j)
1543 document.body[k] = "LatexCommand formatted"
1545 document.header.insert(-1, "\\use_refstyle 0")
1548 def revert_refstyle(document):
1549 " Reverts neutral formatted refs to prettyref "
1550 re_ref = re.compile("^reference\s+\"(\w+):(\S+)\"")
1551 nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
1555 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
1558 j = find_end_of_inset(document.body, i)
1560 document.warning("Malformed LyX document: No end of InsetRef")
1563 k = find_token(document.body, "LatexCommand formatted", i, j)
1565 document.body[k] = "LatexCommand prettyref"
1567 i = find_token(document.header, "\\use_refstyle", 0)
1569 document.header.pop(i)
1572 def revert_nameref(document):
1573 " Convert namerefs to regular references "
1574 cmds = ["Nameref", "nameref"]
1576 rx = re.compile(r'reference "(.*)"')
1579 oldcmd = "LatexCommand " + cmd
1581 # It seems better to look for this, as most of the reference
1582 # insets won't be ones we care about.
1583 i = find_token(document.body, oldcmd, i)
1588 # Make sure it is actually in an inset!
1589 # A normal line could begin with "LatexCommand nameref"!
1590 stins, endins = get_containing_inset(document.body, cmdloc, \
1591 "\\begin_inset CommandInset ref")
1595 # ok, so it is in an InsetRef
1596 refline = find_token(document.body, "reference", stins, endins)
1598 document.warning("Can't find reference for inset at line " + stinst + "!!")
1600 m = rx.match(document.body[refline])
1602 document.warning("Can't match reference line: " + document.body[ref])
1606 newcontent = put_cmd_in_ert('\\' + cmd + '{' + ref + '}')
1607 document.body[stins:endins + 1] = newcontent
1610 add_to_preamble(document, "\usepackage{nameref}")
1613 def remove_Nameref(document):
1614 " Convert Nameref commands to nameref commands "
1617 # It seems better to look for this, as most of the reference
1618 # insets won't be ones we care about.
1619 i = find_token(document.body, "LatexCommand Nameref" , i)
1625 # Make sure it is actually in an inset!
1626 stins, endins = get_containing_inset(document.body, \
1627 cmdloc, "\\begin_inset CommandInset ref")
1630 document.body[cmdloc] = "LatexCommand nameref"
1633 def revert_mathrsfs(document):
1634 " Load mathrsfs if \mathrsfs us use in the document "
1636 for line in document.body:
1637 if line.find("\\mathscr{") != -1:
1638 add_to_preamble(document, ["% lyx2lyx mathrsfs addition", "\\usepackage{mathrsfs}"])
1642 def convert_flexnames(document):
1643 "Convert \\begin_inset Flex Custom:Style to \\begin_inset Flex Style and similarly for CharStyle and Element."
1646 rx = re.compile(r'^\\begin_inset Flex (?:Custom|CharStyle|Element):(.+)$')
1648 i = find_token(document.body, "\\begin_inset Flex", i)
1651 m = rx.match(document.body[i])
1653 document.body[i] = "\\begin_inset Flex " + m.group(1)
1658 "Alert" : "CharStyle:Alert",
1659 "Code" : "CharStyle:Code",
1660 "Concepts" : "CharStyle:Concepts",
1661 "E-Mail" : "CharStyle:E-Mail",
1662 "Emph" : "CharStyle:Emph",
1663 "Expression" : "CharStyle:Expression",
1664 "Initial" : "CharStyle:Initial",
1665 "Institute" : "CharStyle:Institute",
1666 "Meaning" : "CharStyle:Meaning",
1667 "Noun" : "CharStyle:Noun",
1668 "Strong" : "CharStyle:Strong",
1669 "Structure" : "CharStyle:Structure",
1670 "ArticleMode" : "Custom:ArticleMode",
1671 "Endnote" : "Custom:Endnote",
1672 "Glosse" : "Custom:Glosse",
1673 "PresentationMode" : "Custom:PresentationMode",
1674 "Tri-Glosse" : "Custom:Tri-Glosse"
1678 "Abbrev" : "Element:Abbrev",
1679 "CCC-Code" : "Element:CCC-Code",
1680 "Citation-number" : "Element:Citation-number",
1681 "City" : "Element:City",
1682 "Code" : "Element:Code",
1683 "CODEN" : "Element:CODEN",
1684 "Country" : "Element:Country",
1685 "Day" : "Element:Day",
1686 "Directory" : "Element:Directory",
1687 "Dscr" : "Element:Dscr",
1688 "Email" : "Element:Email",
1689 "Emph" : "Element:Emph",
1690 "Filename" : "Element:Filename",
1691 "Firstname" : "Element:Firstname",
1692 "Fname" : "Element:Fname",
1693 "GuiButton" : "Element:GuiButton",
1694 "GuiMenu" : "Element:GuiMenu",
1695 "GuiMenuItem" : "Element:GuiMenuItem",
1696 "ISSN" : "Element:ISSN",
1697 "Issue-day" : "Element:Issue-day",
1698 "Issue-months" : "Element:Issue-months",
1699 "Issue-number" : "Element:Issue-number",
1700 "KeyCap" : "Element:KeyCap",
1701 "KeyCombo" : "Element:KeyCombo",
1702 "Keyword" : "Element:Keyword",
1703 "Literal" : "Element:Literal",
1704 "MenuChoice" : "Element:MenuChoice",
1705 "Month" : "Element:Month",
1706 "Orgdiv" : "Element:Orgdiv",
1707 "Orgname" : "Element:Orgname",
1708 "Postcode" : "Element:Postcode",
1709 "SS-Code" : "Element:SS-Code",
1710 "SS-Title" : "Element:SS-Title",
1711 "State" : "Element:State",
1712 "Street" : "Element:Street",
1713 "Surname" : "Element:Surname",
1714 "Volume" : "Element:Volume",
1715 "Year" : "Element:Year"
1719 def revert_flexnames(document):
1720 if document.backend == "latex":
1721 flexlist = flex_insets
1723 flexlist = flex_elements
1725 rx = re.compile(r'^\\begin_inset Flex\s+(.+)$')
1728 i = find_token(document.body, "\\begin_inset Flex", i)
1731 m = rx.match(document.body[i])
1733 document.warning("Illegal flex inset: " + document.body[i])
1737 if style in flexlist:
1738 document.body[i] = "\\begin_inset Flex " + flexlist[style]
1742 def convert_mathdots(document):
1743 " Load mathdots automatically "
1744 i = find_token(document.header, "\\use_esint" , 0)
1746 document.header.insert(i + 1, "\\use_mathdots 1")
1749 def revert_mathdots(document):
1750 " Load mathdots if used in the document "
1752 ddots = re.compile(r'\\begin_inset Formula .*\\ddots', re.DOTALL)
1753 vdots = re.compile(r'\\begin_inset Formula .*\\vdots', re.DOTALL)
1754 iddots = re.compile(r'\\begin_inset Formula .*\\iddots', re.DOTALL)
1755 mathdots = find_token(document.header, "\\use_mathdots" , 0)
1756 no = find_token(document.header, "\\use_mathdots 0" , 0)
1757 auto = find_token(document.header, "\\use_mathdots 1" , 0)
1758 yes = find_token(document.header, "\\use_mathdots 2" , 0)
1760 del document.header[mathdots]
1762 i = find_token(document.body, '\\begin_inset Formula', i)
1765 j = find_end_of_inset(document.body, i)
1767 document.warning("Malformed LyX document: Can't find end of Formula inset.")
1769 k = ddots.search("\n".join(document.body[i:j]))
1770 l = vdots.search("\n".join(document.body[i:j]))
1771 m = iddots.search("\n".join(document.body[i:j]))
1772 if (yes == -1) and ((no != -1) or (not k and not l and not m) or (auto != -1 and not m)):
1775 # use \@ifundefined to catch also the "auto" case
1776 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1777 add_to_preamble(document, ["\\@ifundefined{iddots}{\\usepackage{mathdots}}\n"])
1781 def convert_rule(document):
1782 " Convert \\lyxline to CommandInset line "
1785 i = find_token(document.body, "\\lyxline" , i)
1789 j = find_token(document.body, "\\color" , i - 2)
1791 color = document.body[j] + '\n'
1794 k = find_token(document.body, "\\begin_layout Standard" , i - 4)
1795 # we need to handle the case that \lyxline is in a separate paragraph and that it is colored
1796 # the result is then an extra empty paragraph which we get by adding an empty ERT inset
1797 if k == i - 4 and j == i - 2 and document.body[i - 1] == '':
1798 layout = '\\begin_inset ERT\nstatus collapsed\n\n\\begin_layout Plain Layout\n\n\n\\end_layout\n\n\\end_inset\n' \
1799 + '\\end_layout\n\n' \
1800 + '\\begin_layout Standard\n'
1801 elif k == i - 2 and document.body[i - 1] == '':
1804 layout = '\\end_layout\n\n' \
1805 + '\\begin_layout Standard\n'
1806 l = find_token(document.body, "\\begin_layout Standard" , i + 4)
1807 if l == i + 4 and document.body[i + 1] == '':
1810 layout2 = '\\end_layout\n' \
1811 + '\n\\begin_layout Standard\n'
1813 + '\\noindent\n\n' \
1815 + '\\begin_inset CommandInset line\n' \
1816 + 'LatexCommand rule\n' \
1817 + 'offset "0.5ex"\n' \
1818 + 'width "100line%"\n' \
1819 + 'height "1pt"\n' \
1820 + '\n\\end_inset\n\n\n' \
1822 document.body[i] = subst
1826 def revert_rule(document):
1827 " Revert line insets to Tex code "
1830 i = find_token(document.body, "\\begin_inset CommandInset line" , i)
1834 j = find_token(document.body, "\\end_inset" , i)
1835 # assure we found the end_inset of the current inset
1836 if j > i + 6 or j == -1:
1837 document.warning("Malformed LyX document: Can't find end of line inset.")
1839 # determine the optional offset
1840 k = find_token(document.body, 'offset', i, j)
1842 offset = document.body[k][8:-1]
1845 # determine the width
1846 l = find_token(document.body, 'width', i, j)
1848 width = document.body[l][7:-1]
1851 # determine the height
1852 m = find_token(document.body, 'height', i, j)
1854 height = document.body[m][8:-1]
1857 # output the \rule command
1859 subst = "\\rule[" + offset + "]{" + width + "}{" + height + "}"
1861 subst = "\\rule{" + width + "}{" + height + "}"
1862 document.body[i:j + 1] = put_cmd_in_ert(subst)
1866 def revert_diagram(document):
1867 " Add the feyn package if \\Diagram is used in math "
1869 re_diagram = re.compile(r'\\begin_inset Formula .*\\Diagram', re.DOTALL)
1871 i = find_token(document.body, '\\begin_inset Formula', i)
1874 j = find_end_of_inset(document.body, i)
1876 document.warning("Malformed LyX document: Can't find end of Formula inset.")
1878 m = re_diagram.search("\n".join(document.body[i:j]))
1882 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1883 add_to_preamble(document, "\\usepackage{feyn}")
1884 # only need to do it once!
1888 def convert_bibtex_clearpage(document):
1889 " insert a clear(double)page bibliographystyle if bibtotoc option is used "
1891 i = find_token(document.header, '\\papersides', 0)
1893 document.warning("Malformed LyX document: Can't find papersides definition.")
1895 sides = int(document.header[i][12])
1899 j = find_token(document.body, "\\begin_inset CommandInset bibtex", j)
1903 k = find_end_of_inset(document.body, j)
1905 document.warning("Can't find end of Bibliography inset at line " + str(j))
1909 # only act if there is the option "bibtotoc"
1910 m = find_token(document.body, 'options', j, k)
1912 document.warning("Can't find options for bibliography inset at line " + str(j))
1916 optline = document.body[m]
1917 idx = optline.find("bibtotoc")
1922 # so we want to insert a new page right before the paragraph that
1923 # this bibliography thing is in. we'll look for it backwards.
1926 if document.body[lay].startswith("\\begin_layout"):
1931 document.warning("Can't find layout containing bibliography inset at line " + str(j))
1935 subst1 = '\\begin_layout Standard\n' \
1936 + '\\begin_inset Newpage clearpage\n' \
1937 + '\\end_inset\n\n\n' \
1939 subst2 = '\\begin_layout Standard\n' \
1940 + '\\begin_inset Newpage cleardoublepage\n' \
1941 + '\\end_inset\n\n\n' \
1944 document.body.insert(lay, subst1)
1945 document.warning(subst1)
1947 document.body.insert(lay, subst2)
1948 document.warning(subst2)
1957 supported_versions = ["2.0.0","2.0"]
1958 convert = [[346, []],
1964 [352, [convert_splitindex]],
1971 [359, [convert_nomencl_width]],
1981 [369, [convert_author_id]],
1985 [373, [merge_gbrief]],
1991 [379, [convert_math_output]],
2001 [389, [convert_html_quotes]],
2005 [393, [convert_optarg]],
2006 [394, [convert_use_makebox]],
2009 [397, [remove_Nameref]],
2011 [399, [convert_mathdots]],
2012 [400, [convert_rule]],
2014 [402, [convert_bibtex_clearpage]],
2015 [403, [convert_flexnames]],
2016 [404, [convert_prettyref]]
2019 revert = [[403, [revert_refstyle]],
2020 [402, [revert_flexnames]],
2022 [400, [revert_diagram]],
2023 [399, [revert_rule]],
2024 [398, [revert_mathdots]],
2025 [397, [revert_mathrsfs]],
2027 [395, [revert_nameref]],
2028 [394, [revert_DIN_C_pagesizes]],
2029 [393, [revert_makebox]],
2030 [392, [revert_argument]],
2032 [390, [revert_align_decimal, revert_IEEEtran]],
2033 [389, [revert_output_sync]],
2034 [388, [revert_html_quotes]],
2035 [387, [revert_pagesizes]],
2036 [386, [revert_math_scale]],
2037 [385, [revert_lyx_version]],
2038 [384, [revert_shadedboxcolor]],
2039 [383, [revert_fontcolor]],
2040 [382, [revert_turkmen]],
2041 [381, [revert_notefontcolor]],
2042 [380, [revert_equalspacing_xymatrix]],
2043 [379, [revert_inset_preview]],
2044 [378, [revert_math_output]],
2046 [376, [revert_multirow]],
2047 [375, [revert_includeall]],
2048 [374, [revert_includeonly]],
2049 [373, [revert_html_options]],
2050 [372, [revert_gbrief]],
2051 [371, [revert_fontenc]],
2052 [370, [revert_mhchem]],
2053 [369, [revert_suppress_date]],
2054 [368, [revert_author_id]],
2055 [367, [revert_hspace_glue_lengths]],
2056 [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
2057 [365, [revert_percent_skip_lengths]],
2058 [364, [revert_paragraph_indentation]],
2059 [363, [revert_branch_filename]],
2060 [362, [revert_longtable_align]],
2061 [361, [revert_applemac]],
2063 [359, [revert_nomencl_cwidth]],
2064 [358, [revert_nomencl_width]],
2065 [357, [revert_custom_processors]],
2066 [356, [revert_ulinelatex]],
2068 [354, [revert_strikeout]],
2069 [353, [revert_printindexall]],
2070 [352, [revert_subindex]],
2071 [351, [revert_splitindex]],
2072 [350, [revert_backgroundcolor]],
2073 [349, [revert_outputformat]],
2074 [348, [revert_xetex]],
2075 [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2076 [346, [revert_tabularvalign]],
2077 [345, [revert_swiss]]
2081 if __name__ == "__main__":