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, str2bool
34 ####################################################################
35 # Private helper functions
37 def remove_option(lines, m, option):
38 ''' removes option from line m. returns whether we did anything '''
39 l = lines[m].find(option)
42 val = lines[m][l:].split('"')[1]
43 lines[m] = lines[m][:l - 1] + lines[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 "
198 i = find_token(document.header, '\\use_xetex', 0)
200 document.warning("Malformed LyX document: Missing \\use_xetex.")
202 if not str2bool(get_value(document.header, "\\use_xetex", i)):
203 del document.header[i]
205 del document.header[i]
207 # 1.) set doc encoding to utf8-plain
208 i = find_token(document.header, "\\inputencoding", 0)
210 document.warning("Malformed LyX document: Missing \\inputencoding.")
212 document.header[i] = "\\inputencoding utf8-plain"
214 # 2.) check font settings
216 roman = sans = typew = default
218 sf_scale = tt_scale = 100.0
220 i = find_token(document.header, "\\font_roman", 0)
222 document.warning("Malformed LyX document: Missing \\font_roman.")
224 roman = get_value(document.header, "\\font_roman", i)
225 document.header[i] = "\\font_roman default"
227 i = find_token(document.header, "\\font_sans", 0)
229 document.warning("Malformed LyX document: Missing \\font_sans.")
231 sans = get_value(document.header, "\\font_sans", i)
232 document.header[i] = "\\font_sans default"
234 i = find_token(document.header, "\\font_typewriter", 0)
236 document.warning("Malformed LyX document: Missing \\font_typewriter.")
238 typew = get_value(document.header, "\\font_typewriter", i)
239 document.header[i] = "\\font_typewriter default"
241 i = find_token(document.header, "\\font_osf", 0)
243 document.warning("Malformed LyX document: Missing \\font_osf.")
245 osf = str2bool(get_value(document.header, "\\font_osf", i))
246 document.header[i] = "\\font_osf false"
248 i = find_token(document.header, "\\font_sc", 0)
250 document.warning("Malformed LyX document: Missing \\font_sc.")
252 # FIXME Do we want this value? and want to do something with it?
253 document.header[i] = "\\font_sc false"
255 i = find_token(document.header, "\\font_sf_scale", 0)
257 document.warning("Malformed LyX document: Missing \\font_sf_scale.")
259 val = get_value(document.header, '\\font_sf_scale', i)
262 sf_scale = float(val)
264 document.warning("Invalid font_sf_scale value: " + val)
265 document.header[i] = "\\font_sf_scale 100"
267 i = find_token(document.header, "\\font_tt_scale", 0)
269 document.warning("Malformed LyX document: Missing \\font_tt_scale.")
271 val = get_value(document.header, '\\font_tt_scale', i)
274 tt_scale = float(val)
276 document.warning("Invalid font_tt_scale value: " + val)
277 document.header[i] = "\\font_tt_scale 100"
279 # 3.) set preamble stuff
280 pretext = ['%% This document must be processed with xelatex!']
281 pretext.append('\\usepackage{fontspec}')
282 if roman != "default":
283 pretext.append('\\setmainfont[Mapping=tex-text]{' + roman + '}')
284 if sans != "default":
285 sf = '\\setsansfont['
286 if sf_scale != 100.0:
287 sf += 'Scale=' + str(sf_scale / 100.0) + ','
288 sf += 'Mapping=tex-text]{' + sans + '}'
290 if typewriter != "default":
292 if tt_scale != 100.0:
293 tw += '[Scale=' + str(tt_scale / 100.0) + ']'
294 tw += '{' + typewriter + '}'
297 pretext.append('\\defaultfontfeatures{Numbers=OldStyle}')
298 pretext.append('\usepackage{xunicode}')
299 pretext.append('\usepackage{xltxtra}')
300 insert_to_preamble(0, document, pretext)
303 def revert_outputformat(document):
304 " Remove default output format param "
305 i = find_token(document.header, '\\default_output_format', 0)
307 document.warning("Malformed LyX document: Missing \\default_output_format.")
309 del document.header[i]
312 def revert_backgroundcolor(document):
313 " Reverts background color to preamble code "
314 i = find_token(document.header, "\\backgroundcolor", 0)
317 colorcode = get_value(document.header, '\\backgroundcolor', i)
318 del document.header[i]
319 # don't clutter the preamble if backgroundcolor is not set
320 if colorcode == "#ffffff":
322 red = hex2ratio(colorcode[1:3])
323 green = hex2ratio(colorcode[3:5])
324 blue = hex2ratio(colorcode[5:7])
325 insert_to_preamble(0, document,
326 '% Commands inserted by lyx2lyx to set the background color\n'
327 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
328 + '\\definecolor{page_backgroundcolor}{rgb}{'
329 + red + ',' + green + ',' + blue + '}\n'
330 + '\\pagecolor{page_backgroundcolor}\n')
333 def revert_splitindex(document):
334 " Reverts splitindex-aware documents "
335 i = find_token(document.header, '\\use_indices', 0)
337 document.warning("Malformed LyX document: Missing \\use_indices.")
339 indices = get_value(document.header, "\\use_indices", i)
341 useindices = (indices == "true")
343 preamble += "\\usepackage{splitidx}\n"
344 del document.header[i]
346 # deal with index declarations in the preamble
349 i = find_token(document.header, "\\index", i)
352 k = find_token(document.header, "\\end_index", i)
354 document.warning("Malformed LyX document: Missing \\end_index.")
357 line = document.header[i]
358 l = re.compile(r'\\index (.*)$')
361 ishortcut = get_value(document.header, '\\shortcut', i, k)
363 preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
364 del document.header[i:k + 1]
366 insert_to_preamble(0, document, preamble)
368 # deal with index insets
369 # these need to have the argument removed
372 i = find_token(document.body, "\\begin_inset Index", i)
375 line = document.body[i]
376 l = re.compile(r'\\begin_inset Index (.*)$')
379 if itype == "idx" or indices == "false":
380 document.body[i] = "\\begin_inset Index"
382 k = find_end_of_inset(document.body, i)
384 document.warning("Can't find end of index inset!")
387 content = lyx2latex(document, document.body[i:k])
389 content = content.replace('"', r'\"')
390 subst = put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")
391 document.body[i:k + 1] = subst
394 # deal with index_print insets
397 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
400 k = find_end_of_inset(document.body, i)
401 ptype = get_value(document.body, 'type', i, k).strip('"')
403 j = find_token(document.body, "type", i, k)
406 del document.body[i:k + 1]
408 subst = put_cmd_in_ert("\\printindex[" + ptype + "]{}")
409 document.body[i:k + 1] = subst
413 def convert_splitindex(document):
414 " Converts index and printindex insets to splitindex-aware format "
417 i = find_token(document.body, "\\begin_inset Index", i)
420 document.body[i] = document.body[i].replace("\\begin_inset Index",
421 "\\begin_inset Index idx")
425 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
428 if document.body[i + 1].find('LatexCommand printindex') == -1:
429 document.warning("Malformed LyX document: Incomplete printindex inset.")
431 subst = ["LatexCommand printindex",
433 document.body[i + 1:i + 2] = subst
437 def revert_subindex(document):
438 " Reverts \\printsubindex CommandInset types "
439 i = find_token(document.header, '\\use_indices', 0)
441 document.warning("Malformed LyX document: Missing \\use_indices.")
443 indices = get_value(document.header, "\\use_indices", i)
444 useindices = (indices == "true")
447 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
450 k = find_end_of_inset(document.body, i)
451 ctype = get_value(document.body, 'LatexCommand', i, k)
452 if ctype != "printsubindex":
455 ptype = get_value(document.body, 'type', i, k).strip('"')
457 del document.body[i:k + 1]
459 subst = put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")
460 document.body[i:k + 1] = subst
464 def revert_printindexall(document):
465 " Reverts \\print[sub]index* CommandInset types "
466 i = find_token(document.header, '\\use_indices', 0)
468 document.warning("Malformed LyX document: Missing \\use_indices.")
470 indices = get_value(document.header, "\\use_indices", i)
471 useindices = (indices == "true")
474 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
477 k = find_end_of_inset(document.body, i)
478 ctype = get_value(document.body, 'LatexCommand', i, k)
479 if ctype != "printindex*" and ctype != "printsubindex*":
483 del document.body[i:k + 1]
485 subst = put_cmd_in_ert("\\" + ctype + "{}")
486 document.body[i:k + 1] = subst
490 def revert_strikeout(document):
491 " Reverts \\strikeout font attribute "
492 changed = revert_font_attrs(document, "\\uuline", "\\uuline")
493 changed = revert_font_attrs(document, "\\uwave", "\\uwave") or changed
494 changed = revert_font_attrs(document, "\\strikeout", "\\sout") or changed
496 insert_to_preamble(0, document,
497 '% Commands inserted by lyx2lyx for proper underlining\n'
498 + '\\PassOptionsToPackage{normalem}{ulem}\n'
499 + '\\usepackage{ulem}\n')
502 def revert_ulinelatex(document):
503 " Reverts \\uline font attribute "
504 i = find_token(document.body, '\\bar under', 0)
507 insert_to_preamble(0, document,
508 '% Commands inserted by lyx2lyx for proper underlining\n'
509 + '\\PassOptionsToPackage{normalem}{ulem}\n'
510 + '\\usepackage{ulem}\n'
511 + '\\let\\cite@rig\\cite\n'
512 + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
513 + ' \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
514 + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
517 def revert_custom_processors(document):
518 " Remove bibtex_command and index_command params "
519 i = find_token(document.header, '\\bibtex_command', 0)
521 document.warning("Malformed LyX document: Missing \\bibtex_command.")
523 del document.header[i]
524 i = find_token(document.header, '\\index_command', 0)
526 document.warning("Malformed LyX document: Missing \\index_command.")
528 del document.header[i]
531 def convert_nomencl_width(document):
532 " Add set_width param to nomencl_print "
535 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
538 document.body.insert(i + 2, "set_width \"none\"")
542 def revert_nomencl_width(document):
543 " Remove set_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, "set_width", i, j)
552 document.warning("Can't find set_width option for nomencl_print!")
559 def revert_nomencl_cwidth(document):
560 " Remove width param from nomencl_print "
563 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
566 j = find_end_of_inset(document.body, i)
567 l = find_token(document.body, "width", i, j)
569 document.warning("Can't find width option for nomencl_print!")
572 width = get_value(document.body, "width", i, j).strip('"')
574 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
575 add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
579 def revert_applemac(document):
580 " Revert applemac encoding to auto "
581 if document.encoding != "applemac":
583 document.encoding = "auto"
584 i = find_token(document.header, "\\encoding", 0)
586 document.header[i] = "\\encoding auto"
589 def revert_longtable_align(document):
590 " Remove longtable alignment setting "
593 i = find_token(document.body, "\\begin_inset Tabular", i)
596 end = find_end_of_inset(document.body, i)
598 document.warning("Can't find end of inset at line " + str(i))
601 fline = find_token(document.body, "<features", i, end)
603 document.warning("Can't find features for inset at line " + str(i))
606 j = document.body[fline].find("longtabularalignment")
610 # FIXME Is this correct? It wipes out everything after the
612 document.body[fline] = document.body[fline][:j - 1] + '>'
613 # since there could be a tabular inside this one, we
614 # cannot jump to end.
618 def revert_branch_filename(document):
619 " Remove \\filename_suffix parameter from branches "
622 i = find_token(document.header, "\\filename_suffix", i)
625 del document.header[i]
628 def revert_paragraph_indentation(document):
629 " Revert custom paragraph indentation to preamble code "
630 i = find_token(document.header, "\\paragraph_indentation", 0)
633 length = get_value(document.header, "\\paragraph_indentation", i)
634 # we need only remove the line if indentation is default
635 if length != "default":
636 # handle percent lengths
637 length = latex_length(length)[1]
638 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
639 add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
640 del document.header[i]
643 def revert_percent_skip_lengths(document):
644 " Revert relative lengths for paragraph skip separation to preamble code "
645 i = find_token(document.header, "\\defskip", 0)
648 length = get_value(document.header, "\\defskip", i)
649 # only revert when a custom length was set and when
650 # it used a percent length
651 if length in ('smallskip', 'medskip', 'bigskip'):
653 # handle percent lengths
654 percent, length = latex_length(length)
656 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
657 add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
658 # set defskip to medskip as default
659 document.header[i] = "\\defskip medskip"
662 def revert_percent_vspace_lengths(document):
663 " Revert relative VSpace lengths to ERT "
666 i = find_token(document.body, "\\begin_inset VSpace", i)
669 # only revert if a custom length was set and if
670 # it used a percent length
671 r = re.compile(r'\\begin_inset VSpace (.*)$')
672 m = r.match(document.body[i])
674 if length in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
677 # check if the space has a star (protected space)
678 protected = (document.body[i].rfind("*") != -1)
680 length = length.rstrip('*')
681 # handle percent lengths
682 percent, length = latex_length(length)
683 # revert the VSpace inset to ERT
686 subst = put_cmd_in_ert("\\vspace*{" + length + "}")
688 subst = put_cmd_in_ert("\\vspace{" + length + "}")
689 document.body[i:i + 2] = subst
693 def revert_percent_hspace_lengths(document):
694 " Revert relative HSpace lengths to ERT "
697 i = find_token(document.body, "\\begin_inset space \\hspace", i)
700 j = find_end_of_inset(document.body, i)
702 document.warning("Can't find end of inset at line " + str(i))
705 # only revert if a custom length was set...
706 length = get_value(document.body, '\\length', i + 1, j)
708 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
712 if document.body[i].find("\\hspace*{}") != -1:
714 # ...and if it used a percent length
715 percent, length = latex_length(length)
716 # revert the HSpace inset to ERT
718 subst = put_cmd_in_ert("\\hspace" + protected + "{" + length + "}")
719 document.body[i:j + 1] = subst
720 # if we did a substitution, this will still be ok
724 def revert_hspace_glue_lengths(document):
725 " Revert HSpace glue lengths to ERT "
728 i = find_token(document.body, "\\begin_inset space \\hspace", i)
731 j = find_end_of_inset(document.body, i)
733 document.warning("Can't find end of inset at line " + str(i))
736 length = get_value(document.body, '\\length', i + 1, j)
738 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
742 if document.body[i].find("\\hspace*{}") != -1:
744 # only revert if the length contains a plus or minus at pos != 0
745 if length.find('-',1) != -1 or length.find('+',1) != -1:
746 # handle percent lengths
747 length = latex_length(length)[1]
748 # revert the HSpace inset to ERT
749 subst = put_cmd_in_ert("\\hspace" + protected + "{" + length + "}")
750 document.body[i:j+1] = subst
754 def convert_author_id(document):
755 " Add the author_id to the \\author definition and make sure 0 is not used"
758 re_author = re.compile(r'(\\author) (\".*\")\s*(.*)$')
761 i = find_token(document.header, "\\author", i)
764 m = re_author.match(document.header[i])
768 document.header[i] = "\\author %i %s %s" % (anum, name, email)
769 # FIXME Should this really be incremented if we didn't match?
775 i = find_token(document.body, "\\change_", i)
778 change = document.body[i].split(' ');
781 author_id = int(change[1])
783 document.body[i] = "%s %i %s" % (type, author_id + 1, time)
787 def revert_author_id(document):
788 " Remove the author_id from the \\author definition "
791 rx = re.compile(r'(\\author)\s+(\d+)\s+(\".*\")\s*(.*)$')
795 i = find_token(document.header, "\\author", i)
798 m = rx.match(document.header[i])
800 author_id = int(m.group(2))
801 idmap[author_id] = anum
804 document.header[i] = "\\author %s %s" % (name, email)
806 # FIXME Should this be incremented if we didn't match?
811 i = find_token(document.body, "\\change_", i)
814 change = document.body[i].split(' ');
817 author_id = int(change[1])
819 document.body[i] = "%s %i %s" % (type, idmap[author_id], time)
823 def revert_suppress_date(document):
824 " Revert suppressing of default document date to preamble code "
825 i = find_token(document.header, "\\suppress_date", 0)
828 # remove the preamble line and write to the preamble
829 # when suppress_date was true
830 date = get_value(document.header, "\\suppress_date", i)
832 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
833 add_to_preamble(document, ["\\date{}"])
834 del document.header[i]
837 def revert_mhchem(document):
838 "Revert mhchem loading to preamble code"
841 i = find_token(document.header, "\\use_mhchem", 0)
843 document.warning("Malformed LyX document: Could not find mhchem setting.")
846 val = get_value(document.header, "\\use_mhchem", i)
851 del document.header[i]
860 i = find_token(document.body, "\\begin_inset Formula", i)
863 line = document.body[i]
864 if line.find("\\ce{") != -1 or line.find("\\cf{") != -1:
870 pre = ["% lyx2lyx mhchem commands",
871 "\\PassOptionsToPackage{version=3}{mhchem}",
872 "\\usepackage{mhchem}"]
873 add_to_preamble(document, pre)
876 def revert_fontenc(document):
877 " Remove fontencoding param "
878 i = find_token(document.header, '\\fontencoding', 0)
880 document.warning("Malformed LyX document: Missing \\fontencoding.")
882 del document.header[i]
885 def merge_gbrief(document):
886 " Merge g-brief-en and g-brief-de to one class "
888 if document.textclass != "g-brief-de":
889 if document.textclass == "g-brief-en":
890 document.textclass = "g-brief"
891 document.set_textclass()
894 obsoletedby = { "Brieftext": "Letter",
895 "Unterschrift": "Signature",
897 "Zusatz": "Addition",
900 "RetourAdresse": "ReturnAddress",
901 "MeinZeichen": "MyRef",
902 "IhrZeichen": "YourRef",
903 "IhrSchreiben": "YourMail",
906 "Konto": "BankAccount",
907 "Postvermerk": "PostalComment",
908 "Adresse": "Address",
910 "Betreff": "Reference",
917 i = find_token(document.body, "\\begin_layout", i)
921 layout = document.body[i][14:]
922 if layout in obsoletedby:
923 document.body[i] = "\\begin_layout " + obsoletedby[layout]
927 document.textclass = "g-brief"
928 document.set_textclass()
931 def revert_gbrief(document):
932 " Revert g-brief to g-brief-en "
933 if document.textclass == "g-brief":
934 document.textclass = "g-brief-en"
935 document.set_textclass()
938 def revert_html_options(document):
939 " Remove html options "
940 i = find_token(document.header, '\\html_use_mathml', 0)
942 del document.header[i]
943 i = find_token(document.header, '\\html_be_strict', 0)
945 del document.header[i]
948 def revert_includeonly(document):
951 i = find_token(document.header, "\\begin_includeonly", i)
954 j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
956 document.warning("Unable to find end of includeonly section!!")
958 document.header[i : j + 1] = []
961 def revert_includeall(document):
962 " Remove maintain_unincluded_children param "
963 i = find_token(document.header, '\\maintain_unincluded_children', 0)
965 del document.header[i]
968 def revert_multirow(document):
969 " Revert multirow cells in tables to TeX-code"
973 # cell type 3 is multirow begin cell
974 i = find_token(document.body, '<cell multirow="3"', i)
977 # a multirow cell was found
979 # remove the multirow tag, set the valignment to top
980 # and remove the bottom line
981 # FIXME Are we sure these always have space around them?
982 document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
983 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
984 document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
985 # write ERT to create the multirow cell
986 # use 2 rows and 2cm as default with because the multirow span
987 # and the column width is only hardly accessible
988 cend = find_token(document.body, "</cell>", i)
990 document.warning("Malformed LyX document: Could not find end of tabular cell.")
993 blay = find_token(document.body, "\\begin_layout", i, cend)
995 document.warning("Can't find layout for cell!")
998 bend = find_end_of_layout(document.body, blay)
1000 document.warning("Can't find end of layout for cell!")
1004 # do the later one first, so as not to mess up the numbering
1005 # we are wrapping the whole cell in this ert
1006 # so before the end of the layout...
1007 document.body[bend:bend] = put_cmd_in_ert("}")
1008 # ...and after the beginning
1009 document.body[blay+1:blay+1] = put_cmd_in_ert("\\multirow{2}{2cm}{")
1012 # cell type 4 is multirow part cell
1013 k = find_token(document.body, '<cell multirow="4"', cend)
1016 # remove the multirow tag, set the valignment to top
1017 # and remove the top line
1018 # FIXME Are we sure these always have space around them?
1019 document.body[k] = document.body[k].replace(' multirow="4" ', ' ')
1020 document.body[k] = document.body[k].replace('valignment="middle"', 'valignment="top"')
1021 document.body[k] = document.body[k].replace(' topline="true" ', ' ')
1023 # this will always be ok
1026 if multirow == True:
1027 add_to_preamble(document,
1028 ["% lyx2lyx multirow additions ", "\\usepackage{multirow}"])
1031 def convert_math_output(document):
1032 " Convert \html_use_mathml to \html_math_output "
1033 i = find_token(document.header, "\\html_use_mathml", 0)
1036 rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1037 m = rgx.match(document.header[i])
1038 newval = "0" # MathML
1042 newval = "2" # Images
1044 document.warning("Can't match " + document.header[i])
1045 document.header[i] = "\\html_math_output " + newval
1048 def revert_math_output(document):
1049 " Revert \html_math_output to \html_use_mathml "
1050 i = find_token(document.header, "\\html_math_output", 0)
1053 rgx = re.compile(r'\\html_math_output\s+(\d)')
1054 m = rgx.match(document.header[i])
1058 if val == "1" or val == "2":
1061 document.warning("Unable to match " + document.header[i])
1062 document.header[i] = "\\html_use_mathml " + newval
1066 def revert_inset_preview(document):
1067 " Dissolves the preview inset "
1070 i = find_token(document.body, "\\begin_inset Preview", i)
1073 iend = find_end_of_inset(document.body, i)
1075 document.warning("Malformed LyX document: Could not find end of Preview inset.")
1079 # This has several issues.
1080 # We need to do something about the layouts inside InsetPreview.
1081 # If we just leave the first one, then we have something like:
1082 # \begin_layout Standard
1084 # \begin_layout Standard
1085 # and we get a "no \end_layout" error. So something has to be done.
1086 # Ideally, we would check if it is the same as the layout we are in.
1087 # If so, we just remove it; if not, we end the active one. But it is
1088 # not easy to know what layout we are in, due to depth changes, etc,
1089 # and it is not clear to me how much work it is worth doing. In most
1090 # cases, the layout will probably be the same.
1092 # For the same reason, we have to remove the \end_layout tag at the
1093 # end of the last layout in the inset. Again, that will sometimes be
1094 # wrong, but it will usually be right. To know what to do, we would
1095 # again have to know what layout the inset is in.
1097 blay = find_token(document.body, "\\begin_layout", i, iend)
1099 document.warning("Can't find layout for preview inset!")
1100 # always do the later one first...
1101 del document.body[iend]
1102 del document.body[i]
1103 # deletions mean we do not need to reset i
1106 # This is where we would check what layout we are in.
1107 # The check for Standard is definitely wrong.
1109 # lay = document.body[blay].split(None, 1)[1]
1110 # if lay != oldlayout:
1111 # # record a boolean to tell us what to do later....
1112 # # better to do it later, since (a) it won't mess up
1113 # # the numbering and (b) we only modify at the end.
1115 # we want to delete the last \\end_layout in this inset, too.
1116 # note that this may not be the \\end_layout that goes with blay!!
1117 bend = find_end_of_layout(document.body, blay)
1119 tmp = find_token(document.body, "\\end_layout", bend + 1, iend)
1124 document.warning("Unable to find last layout in preview inset!")
1125 del document.body[iend]
1126 del document.body[i]
1127 # deletions mean we do not need to reset i
1129 # always do the later one first...
1130 del document.body[iend]
1131 del document.body[bend]
1132 del document.body[i:blay + 1]
1133 # we do not need to reset i
1136 def revert_equalspacing_xymatrix(document):
1137 " Revert a Formula with xymatrix@! to an ERT inset "
1139 has_preamble = False
1140 has_equal_spacing = False
1143 i = find_token(document.body, "\\begin_inset Formula", i)
1146 j = find_end_of_inset(document.body, i)
1148 document.warning("Malformed LyX document: Could not find end of Formula inset.")
1152 for curline in range(i,j):
1153 found = document.body[curline].find("\\xymatrix@!")
1158 has_equal_spacing = True
1159 content = [document.body[i][21:]]
1160 content += document.body[i + 1:j]
1161 subst = put_cmd_in_ert(content)
1162 document.body[i:j + 1] = subst
1163 i += len(subst) - (j - i) + 1
1165 for curline in range(i,j):
1166 l = document.body[curline].find("\\xymatrix")
1168 has_preamble = True;
1172 if has_equal_spacing and not has_preamble:
1173 add_to_preamble(document, ['% lyx2lyx xymatrix addition', '\\usepackage[all]{xy}'])
1176 def revert_notefontcolor(document):
1177 " Reverts greyed-out note font color to preamble code "
1179 i = find_token(document.header, "\\notefontcolor", 0)
1183 # are there any grey notes?
1184 if find_token(document.body, "\\begin_inset Note Greyedout", 0) == -1:
1185 # no need to do anything, and \renewcommand will throw an error
1186 # since lyxgreyedout will not exist.
1189 colorcode = get_value(document.header, '\\notefontcolor', i)
1190 del document.header[i]
1191 # the color code is in the form #rrggbb where every character denotes a hex number
1192 red = hex2ratio(colorcode[1:3])
1193 green = hex2ratio(colorcode[3:5])
1194 blue = hex2ratio(colorcode[5:7])
1195 # write the preamble
1196 insert_to_preamble(0, document,
1197 ['% Commands inserted by lyx2lyx to set the font color',
1198 '% for greyed-out notes',
1199 '\\@ifundefined{definecolor}{\\usepackage{color}}{}'
1200 '\\definecolor{note_fontcolor}{rgb}{%s,%s,%s}' % (red, green, blue),
1201 '\\renewenvironment{lyxgreyedout}',
1202 ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}'])
1205 def revert_turkmen(document):
1206 "Set language Turkmen to English"
1208 if document.language == "turkmen":
1209 document.language = "english"
1210 i = find_token(document.header, "\\language", 0)
1212 document.header[i] = "\\language english"
1216 j = find_token(document.body, "\\lang turkmen", j)
1219 document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english")
1223 def revert_fontcolor(document):
1224 " Reverts font color to preamble code "
1225 i = find_token(document.header, "\\fontcolor", 0)
1228 colorcode = get_value(document.header, '\\fontcolor', i)
1229 del document.header[i]
1230 # don't clutter the preamble if font color is not set
1231 if colorcode == "#000000":
1233 # the color code is in the form #rrggbb where every character denotes a hex number
1234 red = hex2ratio(colorcode[1:3])
1235 green = hex2ratio(colorcode[3:5])
1236 blue = hex2ratio(colorcode[5:7])
1237 # write the preamble
1238 insert_to_preamble(0, document,
1239 ['% Commands inserted by lyx2lyx to set the font color',
1240 '\\@ifundefined{definecolor}{\\usepackage{color}}{}',
1241 '\\definecolor{document_fontcolor}{rgb}{%s,%s,%s}' % (red, green, blue),
1242 '\\color{document_fontcolor}'])
1245 def revert_shadedboxcolor(document):
1246 " Reverts shaded box color to preamble code "
1247 i = find_token(document.header, "\\boxbgcolor", 0)
1250 colorcode = get_value(document.header, '\\boxbgcolor', i)
1251 del document.header[i]
1252 # the color code is in the form #rrggbb
1253 red = hex2ratio(colorcode[1:3])
1254 green = hex2ratio(colorcode[3:5])
1255 blue = hex2ratio(colorcode[5:7])
1256 # write the preamble
1257 insert_to_preamble(0, document,
1258 ['% Commands inserted by lyx2lyx to set the color of boxes with shaded background',
1259 '\\@ifundefined{definecolor}{\\usepackage{color}}{}',
1260 "\\definecolor{shadecolor}{rgb}{%s,%s,%s}" % (red, green, blue)])
1263 def revert_lyx_version(document):
1264 " Reverts LyX Version information from Inset Info "
1265 version = "LyX version"
1267 import lyx2lyx_version
1268 version = lyx2lyx_version.version
1274 i = find_token(document.body, '\\begin_inset Info', i)
1277 j = find_end_of_inset(document.body, i + 1)
1279 document.warning("Malformed LyX document: Could not find end of Info inset.")
1288 # but we shall try to be forgiving.
1290 for k in range(i, j):
1291 if document.body[k].startswith("arg"):
1292 arg = document.body[k][3:].strip().strip('"')
1293 if document.body[k].startswith("type"):
1294 typ = document.body[k][4:].strip().strip('"')
1295 if arg != "version" or typ != "lyxinfo":
1299 # We do not actually know the version of LyX used to produce the document.
1300 # But we can use our version, since we are reverting.
1302 # Now we want to check if the line after "\end_inset" is empty. It normally
1303 # is, so we want to remove it, too.
1305 if document.body[j + 1].strip() == "":
1307 document.body[i: lastline] = s
1311 def revert_math_scale(document):
1312 " Remove math scaling and LaTeX options "
1313 i = find_token(document.header, '\\html_math_img_scale', 0)
1315 del document.header[i]
1316 i = find_token(document.header, '\\html_latex_start', 0)
1318 del document.header[i]
1319 i = find_token(document.header, '\\html_latex_end', 0)
1321 del document.header[i]
1324 def revert_pagesizes(document):
1325 " Revert page sizes to default "
1326 i = find_token(document.header, '\\papersize', 0)
1328 size = document.header[i][11:]
1329 if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1330 or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1331 or size == "b2paper" or size == "b6paper" or size == "b0j" \
1332 or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1333 or size == "b5j" or size == "b6j":
1334 del document.header[i]
1337 def revert_DIN_C_pagesizes(document):
1338 " Revert DIN C page sizes to default "
1339 i = find_token(document.header, '\\papersize', 0)
1341 size = document.header[i][11:]
1342 if size == "c0paper" or size == "c1paper" or size == "c2paper" \
1343 or size == "c3paper" or size == "c4paper" or size == "c5paper" \
1344 or size == "c6paper":
1345 del document.header[i]
1348 def convert_html_quotes(document):
1349 " Remove quotes around html_latex_start and html_latex_end "
1351 i = find_token(document.header, '\\html_latex_start', 0)
1353 line = document.header[i]
1354 l = re.compile(r'\\html_latex_start\s+"(.*)"')
1357 document.header[i] = "\\html_latex_start " + m.group(1)
1359 i = find_token(document.header, '\\html_latex_end', 0)
1361 line = document.header[i]
1362 l = re.compile(r'\\html_latex_end\s+"(.*)"')
1365 document.header[i] = "\\html_latex_end " + m.group(1)
1368 def revert_html_quotes(document):
1369 " Remove quotes around html_latex_start and html_latex_end "
1371 i = find_token(document.header, '\\html_latex_start', 0)
1373 line = document.header[i]
1374 l = re.compile(r'\\html_latex_start\s+(.*)')
1377 document.warning("Weird html_latex_start line: " + line)
1378 del document.header[i]
1380 document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1382 i = find_token(document.header, '\\html_latex_end', 0)
1384 line = document.header[i]
1385 l = re.compile(r'\\html_latex_end\s+(.*)')
1388 document.warning("Weird html_latex_end line: " + line)
1389 del document.header[i]
1391 document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1394 def revert_output_sync(document):
1395 " Remove forward search options "
1396 i = find_token(document.header, '\\output_sync_macro', 0)
1398 del document.header[i]
1399 i = find_token(document.header, '\\output_sync', 0)
1401 del document.header[i]
1404 def revert_align_decimal(document):
1407 i = find_token(document.body, "\\begin_inset Tabular", i)
1410 j = find_end_of_inset(document.body, i)
1412 document.warning("Unable to find end of Tabular inset at line " + str(i))
1415 cell = find_token(document.body, "<cell", i, j)
1417 document.warning("Can't find any cells in Tabular inset at line " + str(i))
1422 k = find_token(document.body, "<column", k, cell)
1425 if document.body[k].find('alignment="decimal"') == -1:
1428 remove_option(document.body, k, 'decimal_point')
1429 document.body[k] = \
1430 document.body[k].replace('alignment="decimal"', 'alignment="center"')
1434 def convert_optarg(document):
1435 " Convert \\begin_inset OptArg to \\begin_inset Argument "
1438 i = find_token(document.body, '\\begin_inset OptArg', i)
1441 document.body[i] = "\\begin_inset Argument"
1445 def revert_argument(document):
1446 " Convert \\begin_inset Argument to \\begin_inset OptArg "
1449 i = find_token(document.body, '\\begin_inset Argument', i)
1452 document.body[i] = "\\begin_inset OptArg"
1456 def revert_makebox(document):
1457 " Convert \\makebox to TeX code "
1460 # only revert frameless boxes without an inner box
1461 i = find_token(document.body, '\\begin_inset Box Frameless', i)
1464 z = find_end_of_inset(document.body, i)
1466 document.warning("Malformed LyX document: Can't find end of box inset.")
1469 blay = find_token(document.body, "\\begin_layout", i, z)
1471 document.warning("Malformed LyX document: Can't find layout in box.")
1474 # by looking before the layout we make sure we're actually finding
1475 # an option, not text.
1476 j = find_token(document.body, 'use_makebox', i, blay)
1480 val = get_value(document.body, 'use_makebox', j)
1482 del document.body[j]
1485 bend = find_end_of_layout(document.body, blay)
1486 if bend == -1 or bend > z:
1487 document.warning("Malformed LyX document: Can't find end of layout in box.")
1490 # determine the alignment
1491 align = get_value(document.body, 'hor_pos', i, blay, "c").strip('"')
1492 # determine the width
1493 length = get_value(document.body, 'width', i, blay, "50col%").strip('"')
1494 length = latex_length(length)[1]
1495 # remove the \end_layout \end_inset pair
1496 document.body[bend:z + 1] = put_cmd_in_ert("}")
1497 subst = "\\makebox[" + length + "][" \
1499 document.body[i:blay + 1] = put_cmd_in_ert(subst)
1503 def convert_use_makebox(document):
1504 " Adds use_makebox option for boxes "
1507 i = find_token(document.body, '\\begin_inset Box', i)
1510 # all of this is to make sure we actually find the use_parbox
1511 # that is an option for this box, not some text elsewhere.
1512 z = find_end_of_inset(document.body, i)
1514 document.warning("Can't find end of box inset!!")
1517 blay = find_token(document.body, "\\begin_layout", i, z)
1519 document.warning("Can't find layout in box inset!!")
1522 # so now we are looking for use_parbox before the box's layout
1523 k = find_token(document.body, 'use_parbox', i, blay)
1525 document.warning("Malformed LyX document: Can't find use_parbox statement in box.")
1528 document.body.insert(k + 1, "use_makebox 0")
1532 def revert_IEEEtran(document):
1533 " Convert IEEEtran layouts and styles to TeX code "
1534 if document.textclass != "IEEEtran":
1536 revert_flex_inset(document, "IEEE membership", "\\IEEEmembership", 0)
1537 revert_flex_inset(document, "Lowercase", "\\MakeLowercase", 0)
1538 layouts = ("Special Paper Notice", "After Title Text", "Publication ID",
1539 "Page headings", "Biography without photo")
1540 latexcmd = {"Special Paper Notice": "\\IEEEspecialpapernotice",
1541 "After Title Text": "\\IEEEaftertitletext",
1542 "Publication ID": "\\IEEEpubid"}
1543 obsoletedby = {"Page headings": "MarkBoth",
1544 "Biography without photo": "BiographyNoPhoto"}
1545 for layout in layouts:
1548 i = find_token(document.body, '\\begin_layout ' + layout, i)
1551 j = find_end_of_layout(document.body, i)
1553 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1556 if layout in obsoletedby:
1557 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1560 content = lyx2latex(document, document.body[i:j + 1])
1561 add_to_preamble(document, [latexcmd[layout] + "{" + content + "}"])
1562 del document.body[i:j + 1]
1563 # no need to reset i
1566 def convert_prettyref(document):
1567 " Converts prettyref references to neutral formatted refs "
1568 re_ref = re.compile("^\s*reference\s+\"(\w+):(\S+)\"")
1569 nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
1573 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
1576 j = find_end_of_inset(document.body, i)
1578 document.warning("Malformed LyX document: No end of InsetRef!")
1581 k = find_token(document.body, "LatexCommand prettyref", i, j)
1583 document.body[k] = "LatexCommand formatted"
1585 document.header.insert(-1, "\\use_refstyle 0")
1588 def revert_refstyle(document):
1589 " Reverts neutral formatted refs to prettyref "
1590 re_ref = re.compile("^reference\s+\"(\w+):(\S+)\"")
1591 nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
1595 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
1598 j = find_end_of_inset(document.body, i)
1600 document.warning("Malformed LyX document: No end of InsetRef")
1603 k = find_token(document.body, "LatexCommand formatted", i, j)
1605 document.body[k] = "LatexCommand prettyref"
1607 i = find_token(document.header, "\\use_refstyle", 0)
1609 document.header.pop(i)
1612 def revert_nameref(document):
1613 " Convert namerefs to regular references "
1614 cmds = ["Nameref", "nameref"]
1616 rx = re.compile(r'reference "(.*)"')
1619 oldcmd = "LatexCommand " + cmd
1621 # It seems better to look for this, as most of the reference
1622 # insets won't be ones we care about.
1623 i = find_token(document.body, oldcmd, i)
1628 # Make sure it is actually in an inset!
1629 # A normal line could begin with "LatexCommand nameref"!
1630 stins, endins = get_containing_inset(document.body, cmdloc, \
1631 "\\begin_inset CommandInset ref")
1635 # ok, so it is in an InsetRef
1636 refline = find_token(document.body, "reference", stins, endins)
1638 document.warning("Can't find reference for inset at line " + stinst + "!!")
1640 m = rx.match(document.body[refline])
1642 document.warning("Can't match reference line: " + document.body[ref])
1646 newcontent = put_cmd_in_ert('\\' + cmd + '{' + ref + '}')
1647 document.body[stins:endins + 1] = newcontent
1650 add_to_preamble(document, "\usepackage{nameref}")
1653 def remove_Nameref(document):
1654 " Convert Nameref commands to nameref commands "
1657 # It seems better to look for this, as most of the reference
1658 # insets won't be ones we care about.
1659 i = find_token(document.body, "LatexCommand Nameref" , i)
1665 # Make sure it is actually in an inset!
1666 stins, endins = get_containing_inset(document.body, \
1667 cmdloc, "\\begin_inset CommandInset ref")
1670 document.body[cmdloc] = "LatexCommand nameref"
1673 def revert_mathrsfs(document):
1674 " Load mathrsfs if \mathrsfs us use in the document "
1676 for line in document.body:
1677 if line.find("\\mathscr{") != -1:
1678 add_to_preamble(document, ["% lyx2lyx mathrsfs addition", "\\usepackage{mathrsfs}"])
1682 def convert_flexnames(document):
1683 "Convert \\begin_inset Flex Custom:Style to \\begin_inset Flex Style and similarly for CharStyle and Element."
1686 rx = re.compile(r'^\\begin_inset Flex (?:Custom|CharStyle|Element):(.+)$')
1688 i = find_token(document.body, "\\begin_inset Flex", i)
1691 m = rx.match(document.body[i])
1693 document.body[i] = "\\begin_inset Flex " + m.group(1)
1698 "Alert" : "CharStyle:Alert",
1699 "Code" : "CharStyle:Code",
1700 "Concepts" : "CharStyle:Concepts",
1701 "E-Mail" : "CharStyle:E-Mail",
1702 "Emph" : "CharStyle:Emph",
1703 "Expression" : "CharStyle:Expression",
1704 "Initial" : "CharStyle:Initial",
1705 "Institute" : "CharStyle:Institute",
1706 "Meaning" : "CharStyle:Meaning",
1707 "Noun" : "CharStyle:Noun",
1708 "Strong" : "CharStyle:Strong",
1709 "Structure" : "CharStyle:Structure",
1710 "ArticleMode" : "Custom:ArticleMode",
1711 "Endnote" : "Custom:Endnote",
1712 "Glosse" : "Custom:Glosse",
1713 "PresentationMode" : "Custom:PresentationMode",
1714 "Tri-Glosse" : "Custom:Tri-Glosse"
1718 "Abbrev" : "Element:Abbrev",
1719 "CCC-Code" : "Element:CCC-Code",
1720 "Citation-number" : "Element:Citation-number",
1721 "City" : "Element:City",
1722 "Code" : "Element:Code",
1723 "CODEN" : "Element:CODEN",
1724 "Country" : "Element:Country",
1725 "Day" : "Element:Day",
1726 "Directory" : "Element:Directory",
1727 "Dscr" : "Element:Dscr",
1728 "Email" : "Element:Email",
1729 "Emph" : "Element:Emph",
1730 "Filename" : "Element:Filename",
1731 "Firstname" : "Element:Firstname",
1732 "Fname" : "Element:Fname",
1733 "GuiButton" : "Element:GuiButton",
1734 "GuiMenu" : "Element:GuiMenu",
1735 "GuiMenuItem" : "Element:GuiMenuItem",
1736 "ISSN" : "Element:ISSN",
1737 "Issue-day" : "Element:Issue-day",
1738 "Issue-months" : "Element:Issue-months",
1739 "Issue-number" : "Element:Issue-number",
1740 "KeyCap" : "Element:KeyCap",
1741 "KeyCombo" : "Element:KeyCombo",
1742 "Keyword" : "Element:Keyword",
1743 "Literal" : "Element:Literal",
1744 "MenuChoice" : "Element:MenuChoice",
1745 "Month" : "Element:Month",
1746 "Orgdiv" : "Element:Orgdiv",
1747 "Orgname" : "Element:Orgname",
1748 "Postcode" : "Element:Postcode",
1749 "SS-Code" : "Element:SS-Code",
1750 "SS-Title" : "Element:SS-Title",
1751 "State" : "Element:State",
1752 "Street" : "Element:Street",
1753 "Surname" : "Element:Surname",
1754 "Volume" : "Element:Volume",
1755 "Year" : "Element:Year"
1759 def revert_flexnames(document):
1760 if document.backend == "latex":
1761 flexlist = flex_insets
1763 flexlist = flex_elements
1765 rx = re.compile(r'^\\begin_inset Flex\s+(.+)$')
1768 i = find_token(document.body, "\\begin_inset Flex", i)
1771 m = rx.match(document.body[i])
1773 document.warning("Illegal flex inset: " + document.body[i])
1777 if style in flexlist:
1778 document.body[i] = "\\begin_inset Flex " + flexlist[style]
1782 def convert_mathdots(document):
1783 " Load mathdots automatically "
1784 i = find_token(document.header, "\\use_esint" , 0)
1786 document.header.insert(i + 1, "\\use_mathdots 1")
1789 def revert_mathdots(document):
1790 " Load mathdots if used in the document "
1792 mathdots = find_token(document.header, "\\use_mathdots" , 0)
1794 document.warning("No \\usemathdots line. Assuming auto.")
1796 val = get_value(document.header, "\\use_mathdots", mathdots)
1797 del document.header[mathdots]
1801 document.warning("Invalid \\use_mathdots value: " + val + ". Assuming auto.")
1802 # probably usedots has not been changed, but be safe.
1810 add_to_preamble(["% lyx2lyx mathdots addition", "\\usepackage{mathdots}"])
1813 # so we are in the auto case. we want to load mathdots if \iddots is used.
1816 i = find_token(document.body, '\\begin_inset Formula', i)
1819 j = find_end_of_inset(document.body, i)
1821 document.warning("Malformed LyX document: Can't find end of Formula inset at line " + str(i))
1824 code = "\n".join(document.body[i:j])
1825 if code.find("\\iddots") != -1:
1826 add_to_preamble(document, ["% lyx2lyx mathdots addition",
1827 "\\@ifundefined{iddots}{\\usepackage{mathdots}}"])
1832 def convert_rule(document):
1833 " Convert \\lyxline to CommandInset line. "
1836 inset = ['\\begin_inset CommandInset line',
1837 'LatexCommand rule',
1841 '\\end_inset', '', '']
1843 # if paragraphs are indented, we may have to unindent to get the
1844 # line to be full-width.
1845 indent = get_value(document.header, "\\paragraph_separation", 0)
1846 have_indent = (indent == "indent")
1849 i = find_token(document.body, "\\lyxline" , i)
1853 # we need to find out if this line follows other content
1854 # in its paragraph. find its layout....
1855 lastlay = find_token_backwards(document.body, "\\begin_layout", i)
1857 document.warning("Can't find layout for line at " + str(i))
1858 # do the best we can.
1859 document.body[i:i+1] = inset
1863 # ...and look for other content before it.
1865 for line in document.body[lastlay + 1:i]:
1866 # is it empty or a paragraph option?
1867 if not line or line[0] == '\\':
1873 document.body[i:i+1] = inset
1875 # we need to unindent, lest the line be too long
1876 document.body.insert(lastlay + 1, "\\noindent")
1879 # so our line is in the middle of a paragraph
1880 # we need to add a new line, lest this line follow the
1881 # other content on that line and run off the side of the page
1882 document.body[i:i+1] = inset
1883 document.body[i:i] = ["\\begin_inset Newline newline", "\\end_inset", ""]
1887 def revert_rule(document):
1888 " Revert line insets to Tex code "
1891 i = find_token(document.body, "\\begin_inset CommandInset line" , i)
1895 j = find_token(document.body, "\\end_inset" , i)
1897 document.warning("Malformed LyX document: Can't find end of line inset.")
1899 # determine the optional offset
1900 offset = get_value(document.body, 'offset', i, j).strip('"')
1902 offset = '[' + offset + ']'
1903 # determine the width
1904 width = get_value(document.body, 'width', i, j, "100col%").strip('"')
1905 width = latex_length(width)[1]
1906 # determine the height
1907 height = get_value(document.body, 'height', i, j, "1pt").strip('"')
1908 height = latex_length(height)[1]
1909 # output the \rule command
1910 subst = "\\rule[" + offset + "]{" + width + "}{" + height + "}"
1911 document.body[i:j + 1] = put_cmd_in_ert(subst)
1912 i += len(subst) - (j - i)
1915 def revert_diagram(document):
1916 " Add the feyn package if \\Diagram is used in math "
1919 i = find_token(document.body, '\\begin_inset Formula', i)
1922 j = find_end_of_inset(document.body, i)
1924 document.warning("Malformed LyX document: Can't find end of Formula inset.")
1926 lines = "\n".join(document.body[i:j])
1927 if lines.find("\\Diagram") == -1:
1930 add_to_preamble(document, ["% lyx2lyx feyn package insertion ", "\\usepackage{feyn}"])
1931 # only need to do it once!
1935 def convert_bibtex_clearpage(document):
1936 " insert a clear(double)page bibliographystyle if bibtotoc option is used "
1938 i = find_token(document.header, '\\papersides', 0)
1941 document.warning("Malformed LyX document: Can't find papersides definition.")
1942 document.warning("Assuming single sided.")
1945 val = get_value(document.header, "\\papersides", i)
1950 if sides != 1 and sides != 2:
1951 document.warning("Invalid papersides value: " + val)
1952 document.warning("Assuming single sided.")
1957 j = find_token(document.body, "\\begin_inset CommandInset bibtex", j)
1961 k = find_end_of_inset(document.body, j)
1963 document.warning("Can't find end of Bibliography inset at line " + str(j))
1967 # only act if there is the option "bibtotoc"
1968 val = get_value(document.body, 'options', j, k)
1970 document.warning("Can't find options for bibliography inset at line " + str(j))
1974 if val.find("bibtotoc") == -1:
1978 # so we want to insert a new page right before the paragraph that
1979 # this bibliography thing is in.
1980 lay = find_token_backwards(document.body, "\\begin_layout", j)
1982 document.warning("Can't find layout containing bibliography inset at line " + str(j))
1989 cmd = "cleardoublepage"
1990 subst = ['\\begin_layout Standard',
1991 '\\begin_inset Newpage ' + cmd,
1992 '\\end_inset', '', '',
1994 document.body[lay:lay] = subst
2002 supported_versions = ["2.0.0","2.0"]
2003 convert = [[346, []],
2009 [352, [convert_splitindex]],
2016 [359, [convert_nomencl_width]],
2026 [369, [convert_author_id]],
2030 [373, [merge_gbrief]],
2036 [379, [convert_math_output]],
2046 [389, [convert_html_quotes]],
2050 [393, [convert_optarg]],
2051 [394, [convert_use_makebox]],
2054 [397, [remove_Nameref]],
2056 [399, [convert_mathdots]],
2057 [400, [convert_rule]],
2059 [402, [convert_bibtex_clearpage]],
2060 [403, [convert_flexnames]],
2061 [404, [convert_prettyref]]
2064 revert = [[403, [revert_refstyle]],
2065 [402, [revert_flexnames]],
2067 [400, [revert_diagram]],
2068 [399, [revert_rule]],
2069 [398, [revert_mathdots]],
2070 [397, [revert_mathrsfs]],
2072 [395, [revert_nameref]],
2073 [394, [revert_DIN_C_pagesizes]],
2074 [393, [revert_makebox]],
2075 [392, [revert_argument]],
2077 [390, [revert_align_decimal, revert_IEEEtran]],
2078 [389, [revert_output_sync]],
2079 [388, [revert_html_quotes]],
2080 [387, [revert_pagesizes]],
2081 [386, [revert_math_scale]],
2082 [385, [revert_lyx_version]],
2083 [384, [revert_shadedboxcolor]],
2084 [383, [revert_fontcolor]],
2085 [382, [revert_turkmen]],
2086 [381, [revert_notefontcolor]],
2087 [380, [revert_equalspacing_xymatrix]],
2088 [379, [revert_inset_preview]],
2089 [378, [revert_math_output]],
2091 [376, [revert_multirow]],
2092 [375, [revert_includeall]],
2093 [374, [revert_includeonly]],
2094 [373, [revert_html_options]],
2095 [372, [revert_gbrief]],
2096 [371, [revert_fontenc]],
2097 [370, [revert_mhchem]],
2098 [369, [revert_suppress_date]],
2099 [368, [revert_author_id]],
2100 [367, [revert_hspace_glue_lengths]],
2101 [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
2102 [365, [revert_percent_skip_lengths]],
2103 [364, [revert_paragraph_indentation]],
2104 [363, [revert_branch_filename]],
2105 [362, [revert_longtable_align]],
2106 [361, [revert_applemac]],
2108 [359, [revert_nomencl_cwidth]],
2109 [358, [revert_nomencl_width]],
2110 [357, [revert_custom_processors]],
2111 [356, [revert_ulinelatex]],
2113 [354, [revert_strikeout]],
2114 [353, [revert_printindexall]],
2115 [352, [revert_subindex]],
2116 [351, [revert_splitindex]],
2117 [350, [revert_backgroundcolor]],
2118 [349, [revert_outputformat]],
2119 [348, [revert_xetex]],
2120 [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2121 [346, [revert_tabularvalign]],
2122 [345, [revert_swiss]]
2126 if __name__ == "__main__":