1 # -*- coding: utf-8 -*-
2 # This file is part of lyx2lyx
3 # -*- coding: utf-8 -*-
4 # Copyright (C) 2011 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_token_exact, find_end_of_inset, find_end_of_layout, \
28 find_token_backwards, is_in_inset, get_value, get_quoted_value, \
29 del_token, check_token, get_option_value
31 from lyx2lyx_tools import add_to_preamble, insert_to_preamble, \
32 put_cmd_in_ert, lyx2latex, latex_length, revert_flex_inset, \
33 revert_font_attrs, hex2ratio, str2bool
35 ####################################################################
36 # Private helper functions
38 def remove_option(lines, m, option):
39 ''' removes option from line m. returns whether we did anything '''
40 l = lines[m].find(option)
43 val = lines[m][l:].split('"')[1]
44 lines[m] = lines[m][:l - 1] + lines[m][l+len(option + '="' + val + '"'):]
48 ###############################################################################
50 ### Conversion and reversion routines
52 ###############################################################################
54 def revert_swiss(document):
55 " Set language german-ch to ngerman "
57 if document.language == "german-ch":
58 document.language = "ngerman"
59 i = find_token(document.header, "\\language", 0)
61 document.header[i] = "\\language ngerman"
64 j = find_token(document.body, "\\lang german-ch", j)
67 document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
71 def revert_tabularvalign(document):
72 " Revert the tabular valign option "
75 i = find_token(document.body, "\\begin_inset Tabular", i)
78 end = find_end_of_inset(document.body, i)
80 document.warning("Can't find end of inset at line " + str(i))
83 fline = find_token(document.body, "<features", i, end)
85 document.warning("Can't find features for inset at line " + str(i))
88 p = document.body[fline].find("islongtable")
90 q = document.body[fline].find("tabularvalignment")
93 # This seems wrong: It removes everything after
94 # tabularvalignment, too.
95 document.body[fline] = document.body[fline][:q - 1] + '>'
100 tabularvalignment = 'c'
101 # which valignment is specified?
102 m = document.body[fline].find('tabularvalignment="top"')
104 tabularvalignment = 't'
105 m = document.body[fline].find('tabularvalignment="bottom"')
107 tabularvalignment = 'b'
108 # delete tabularvalignment
109 q = document.body[fline].find("tabularvalignment")
112 # This seems wrong: It removes everything after
113 # tabularvalignment, too.
114 document.body[fline] = document.body[fline][:q - 1] + '>'
116 # don't add a box when centered
117 if tabularvalignment == 'c':
120 subst = ['\\end_layout', '\\end_inset']
121 document.body[end:end] = subst # just inserts those lines
122 subst = ['\\begin_inset Box Frameless',
123 'position "' + tabularvalignment +'"',
128 # we don't know the width, assume 50%
132 'height_special "totalheight"',
135 '\\begin_layout Plain Layout']
136 document.body[i:i] = subst # this just inserts the array at i
137 # since there could be a tabular inside a tabular, we cannot
142 def revert_phantom_types(document, ptype, cmd):
143 " Reverts phantom to ERT "
146 i = find_token(document.body, "\\begin_inset Phantom " + ptype, i)
149 end = find_end_of_inset(document.body, i)
151 document.warning("Can't find end of inset at line " + str(i))
154 blay = find_token(document.body, "\\begin_layout Plain Layout", i, end)
156 document.warning("Can't find layout for inset at line " + str(i))
159 bend = find_end_of_layout(document.body, blay)
161 document.warning("Malformed LyX document: Could not find end of Phantom inset's layout.")
164 substi = ["\\begin_inset ERT", "status collapsed", "",
165 "\\begin_layout Plain Layout", "", "", "\\backslash",
166 cmd + "{", "\\end_layout", "", "\\end_inset"]
167 substj = ["\\size default", "", "\\begin_inset ERT", "status collapsed", "",
168 "\\begin_layout Plain Layout", "", "}", "\\end_layout", "", "\\end_inset"]
169 # do the later one first so as not to mess up the numbering
170 document.body[bend:end + 1] = substj
171 document.body[i:blay + 1] = substi
172 i = end + len(substi) + len(substj) - (end - bend) - (blay - i) - 2
175 def revert_phantom(document):
176 revert_phantom_types(document, "Phantom", "phantom")
178 def revert_hphantom(document):
179 revert_phantom_types(document, "HPhantom", "hphantom")
181 def revert_vphantom(document):
182 revert_phantom_types(document, "VPhantom", "vphantom")
185 def revert_xetex(document):
186 " Reverts documents that use XeTeX "
188 i = find_token(document.header, '\\use_xetex', 0)
190 document.warning("Malformed LyX document: Missing \\use_xetex.")
192 if not str2bool(get_value(document.header, "\\use_xetex", i)):
193 del document.header[i]
195 del document.header[i]
197 # 1.) set doc encoding to utf8-plain
198 i = find_token(document.header, "\\inputencoding", 0)
200 document.warning("Malformed LyX document: Missing \\inputencoding.")
202 document.header[i] = "\\inputencoding utf8-plain"
204 # 2.) check font settings
206 roman = sans = typew = "default"
208 sf_scale = tt_scale = 100.0
210 i = find_token(document.header, "\\font_roman", 0)
212 document.warning("Malformed LyX document: Missing \\font_roman.")
214 roman = get_value(document.header, "\\font_roman", i)
215 document.header[i] = "\\font_roman default"
217 i = find_token(document.header, "\\font_sans", 0)
219 document.warning("Malformed LyX document: Missing \\font_sans.")
221 sans = get_value(document.header, "\\font_sans", i)
222 document.header[i] = "\\font_sans default"
224 i = find_token(document.header, "\\font_typewriter", 0)
226 document.warning("Malformed LyX document: Missing \\font_typewriter.")
228 typew = get_value(document.header, "\\font_typewriter", i)
229 document.header[i] = "\\font_typewriter default"
231 i = find_token(document.header, "\\font_osf", 0)
233 document.warning("Malformed LyX document: Missing \\font_osf.")
235 osf = str2bool(get_value(document.header, "\\font_osf", i))
236 document.header[i] = "\\font_osf false"
238 i = find_token(document.header, "\\font_sc", 0)
240 document.warning("Malformed LyX document: Missing \\font_sc.")
242 # we do not need this value.
243 document.header[i] = "\\font_sc false"
245 i = find_token(document.header, "\\font_sf_scale", 0)
247 document.warning("Malformed LyX document: Missing \\font_sf_scale.")
249 val = get_value(document.header, '\\font_sf_scale', i)
252 sf_scale = float(val)
254 document.warning("Invalid font_sf_scale value: " + val)
255 document.header[i] = "\\font_sf_scale 100"
257 i = find_token(document.header, "\\font_tt_scale", 0)
259 document.warning("Malformed LyX document: Missing \\font_tt_scale.")
261 val = get_value(document.header, '\\font_tt_scale', i)
264 tt_scale = float(val)
266 document.warning("Invalid font_tt_scale value: " + val)
267 document.header[i] = "\\font_tt_scale 100"
269 # 3.) set preamble stuff
270 pretext = ['%% This document must be processed with xelatex!']
271 pretext.append('\\usepackage{fontspec}')
272 if roman != "default":
273 pretext.append('\\setmainfont[Mapping=tex-text]{' + roman + '}')
274 if sans != "default":
275 sf = '\\setsansfont['
276 if sf_scale != 100.0:
277 sf += 'Scale=' + str(sf_scale / 100.0) + ','
278 sf += 'Mapping=tex-text]{' + sans + '}'
280 if typew != "default":
282 if tt_scale != 100.0:
283 tw += '[Scale=' + str(tt_scale / 100.0) + ']'
284 tw += '{' + typew + '}'
287 pretext.append('\\defaultfontfeatures{Numbers=OldStyle}')
288 pretext.append('\usepackage{xunicode}')
289 pretext.append('\usepackage{xltxtra}')
290 insert_to_preamble(document, pretext)
293 def revert_outputformat(document):
294 " Remove default output format param "
296 if not del_token(document.header, '\\default_output_format', 0):
297 document.warning("Malformed LyX document: Missing \\default_output_format.")
300 def revert_backgroundcolor(document):
301 " Reverts background color to preamble code "
302 i = find_token(document.header, "\\backgroundcolor", 0)
305 colorcode = get_value(document.header, '\\backgroundcolor', i)
306 del document.header[i]
307 # don't clutter the preamble if backgroundcolor is not set
308 if colorcode == "#ffffff":
310 red = hex2ratio(colorcode[1:3])
311 green = hex2ratio(colorcode[3:5])
312 blue = hex2ratio(colorcode[5:7])
313 insert_to_preamble(document, \
314 ['% To set the background color',
315 '\\@ifundefined{definecolor}{\\usepackage{color}}{}',
316 '\\definecolor{page_backgroundcolor}{rgb}{' + red + ',' + green + ',' + blue + '}',
317 '\\pagecolor{page_backgroundcolor}'])
320 def revert_splitindex(document):
321 " Reverts splitindex-aware documents "
322 i = find_token(document.header, '\\use_indices', 0)
324 document.warning("Malformed LyX document: Missing \\use_indices.")
326 useindices = str2bool(get_value(document.header, "\\use_indices", i))
327 del document.header[i]
330 preamble.append("\\usepackage{splitidx})")
332 # deal with index declarations in the preamble
335 i = find_token(document.header, "\\index", i)
338 k = find_token(document.header, "\\end_index", i)
340 document.warning("Malformed LyX document: Missing \\end_index.")
343 line = document.header[i]
344 l = re.compile(r'\\index (.*)$')
347 ishortcut = get_value(document.header, '\\shortcut', i, k)
349 preamble.append("\\newindex[" + iname + "]{" + ishortcut + "}")
350 del document.header[i:k + 1]
352 insert_to_preamble(document, preamble)
354 # deal with index insets
355 # these need to have the argument removed
358 i = find_token(document.body, "\\begin_inset Index", i)
361 line = document.body[i]
362 l = re.compile(r'\\begin_inset Index (.*)$')
365 if itype == "idx" or indices == "false":
366 document.body[i] = "\\begin_inset Index"
368 k = find_end_of_inset(document.body, i)
370 document.warning("Can't find end of index inset!")
373 content = lyx2latex(document, document.body[i:k])
375 content = content.replace('"', r'\"')
376 subst = put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")
377 document.body[i:k + 1] = subst
380 # deal with index_print insets
383 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
386 k = find_end_of_inset(document.body, i)
387 ptype = get_quoted_value(document.body, 'type', i, k)
389 j = find_token(document.body, "type", i, k)
392 del document.body[i:k + 1]
394 subst = put_cmd_in_ert("\\printindex[" + ptype + "]{}")
395 document.body[i:k + 1] = subst
399 def convert_splitindex(document):
400 " Converts index and printindex insets to splitindex-aware format "
403 i = find_token(document.body, "\\begin_inset Index", i)
406 document.body[i] = document.body[i].replace("\\begin_inset Index",
407 "\\begin_inset Index idx")
411 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
414 if document.body[i + 1].find('LatexCommand printindex') == -1:
415 document.warning("Malformed LyX document: Incomplete printindex inset.")
417 subst = ["LatexCommand printindex",
419 document.body[i + 1:i + 2] = subst
423 def revert_subindex(document):
424 " Reverts \\printsubindex CommandInset types "
425 i = find_token(document.header, '\\use_indices', 0)
427 document.warning("Malformed LyX document: Missing \\use_indices.")
429 useindices = str2bool(get_value(document.header, "\\use_indices", i))
432 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
435 k = find_end_of_inset(document.body, i)
436 ctype = get_value(document.body, 'LatexCommand', i, k)
437 if ctype != "printsubindex":
440 ptype = get_quoted_value(document.body, 'type', i, k)
442 del document.body[i:k + 1]
444 subst = put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")
445 document.body[i:k + 1] = subst
449 def revert_printindexall(document):
450 " Reverts \\print[sub]index* CommandInset types "
451 i = find_token(document.header, '\\use_indices', 0)
453 document.warning("Malformed LyX document: Missing \\use_indices.")
455 useindices = str2bool(get_value(document.header, "\\use_indices", i))
458 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
461 k = find_end_of_inset(document.body, i)
462 ctype = get_value(document.body, 'LatexCommand', i, k)
463 if ctype != "printindex*" and ctype != "printsubindex*":
467 del document.body[i:k + 1]
469 subst = put_cmd_in_ert("\\" + ctype + "{}")
470 document.body[i:k + 1] = subst
474 def revert_strikeout(document):
475 " Reverts \\strikeout font attribute "
476 changed = revert_font_attrs(document.body, "\\uuline", "\\uuline")
477 changed = revert_font_attrs(document.body, "\\uwave", "\\uwave") or changed
478 changed = revert_font_attrs(document.body, "\\strikeout", "\\sout") or changed
480 insert_to_preamble(document, \
481 ['% for proper underlining',
482 '\\PassOptionsToPackage{normalem}{ulem}',
483 '\\usepackage{ulem}'])
486 def revert_ulinelatex(document):
487 " Reverts \\uline font attribute "
488 i = find_token(document.body, '\\bar under', 0)
491 insert_to_preamble(document,\
492 ['% for proper underlining',
493 '\\PassOptionsToPackage{normalem}{ulem}',
494 '\\usepackage{ulem}',
495 '\\let\\cite@rig\\cite',
496 '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}',
497 ' \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}',
498 '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}'])
501 def revert_custom_processors(document):
502 " Remove bibtex_command and index_command params "
504 if not del_token(document.header, '\\bibtex_command', 0):
505 document.warning("Malformed LyX document: Missing \\bibtex_command.")
507 if not del_token(document.header, '\\index_command', 0):
508 document.warning("Malformed LyX document: Missing \\index_command.")
511 def convert_nomencl_width(document):
512 " Add set_width param to nomencl_print "
515 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
518 document.body.insert(i + 2, "set_width \"none\"")
522 def revert_nomencl_width(document):
523 " Remove set_width param from nomencl_print "
526 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
529 j = find_end_of_inset(document.body, i)
530 if not del_token(document.body, "set_width", i, j):
531 document.warning("Can't find set_width option for nomencl_print!")
535 def revert_nomencl_cwidth(document):
536 " Remove width param from nomencl_print "
539 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
542 j = find_end_of_inset(document.body, i)
543 l = find_token(document.body, "width", i, j)
545 document.warning("Can't find width option for nomencl_print!")
548 width = get_quoted_value(document.body, "width", i, j)
550 insert_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
554 def revert_applemac(document):
555 " Revert applemac encoding to auto "
556 if document.encoding != "applemac":
558 document.encoding = "auto"
559 i = find_token(document.header, "\\encoding", 0)
561 document.header[i] = "\\encoding auto"
564 def revert_longtable_align(document):
565 " Remove longtable alignment setting "
568 i = find_token(document.body, "\\begin_inset Tabular", i)
571 end = find_end_of_inset(document.body, i)
573 document.warning("Can't find end of inset at line " + str(i))
576 fline = find_token(document.body, "<features", i, end)
578 document.warning("Can't find features for inset at line " + str(i))
581 j = document.body[fline].find("longtabularalignment")
585 # FIXME Is this correct? It wipes out everything after the
587 document.body[fline] = document.body[fline][:j - 1] + '>'
588 # since there could be a tabular inside this one, we
589 # cannot jump to end.
593 def revert_branch_filename(document):
594 " Remove \\filename_suffix parameter from branches "
597 i = find_token(document.header, "\\filename_suffix", i)
600 del document.header[i]
603 def revert_paragraph_indentation(document):
604 " Revert custom paragraph indentation to preamble code "
605 i = find_token(document.header, "\\paragraph_indentation", 0)
608 length = get_value(document.header, "\\paragraph_indentation", i)
609 # we need only remove the line if indentation is default
610 if length != "default":
611 # handle percent lengths
612 length = latex_length(length)[1]
613 insert_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
614 del document.header[i]
617 def revert_percent_skip_lengths(document):
618 " Revert relative lengths for paragraph skip separation to preamble code "
619 i = find_token(document.header, "\\defskip", 0)
622 length = get_value(document.header, "\\defskip", i)
623 # only revert when a custom length was set and when
624 # it used a percent length
625 if length in ('smallskip', 'medskip', 'bigskip'):
627 # handle percent lengths
628 percent, length = latex_length(length)
630 insert_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
631 # set defskip to medskip as default
632 document.header[i] = "\\defskip medskip"
635 def revert_percent_vspace_lengths(document):
636 " Revert relative VSpace lengths to ERT "
639 i = find_token(document.body, "\\begin_inset VSpace", i)
642 # only revert if a custom length was set and if
643 # it used a percent length
644 r = re.compile(r'\\begin_inset VSpace (.*)$')
645 m = r.match(document.body[i])
647 if length in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
650 # check if the space has a star (protected space)
651 protected = (document.body[i].rfind("*") != -1)
653 length = length.rstrip('*')
654 # handle percent lengths
655 percent, length = latex_length(length)
656 # revert the VSpace inset to ERT
659 subst = put_cmd_in_ert("\\vspace*{" + length + "}")
661 subst = put_cmd_in_ert("\\vspace{" + length + "}")
662 document.body[i:i + 2] = subst
666 def revert_percent_hspace_lengths(document):
667 " Revert relative HSpace lengths to ERT "
670 i = find_token_exact(document.body, "\\begin_inset space \\hspace", i)
673 j = find_end_of_inset(document.body, i)
675 document.warning("Can't find end of inset at line " + str(i))
678 # only revert if a custom length was set...
679 length = get_value(document.body, '\\length', i + 1, j)
681 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
685 if document.body[i].find("\\hspace*{}") != -1:
687 # ...and if it used a percent length
688 percent, length = latex_length(length)
689 # revert the HSpace inset to ERT
691 subst = put_cmd_in_ert("\\hspace" + protected + "{" + length + "}")
692 document.body[i:j + 1] = subst
693 # if we did a substitution, this will still be ok
697 def revert_hspace_glue_lengths(document):
698 " Revert HSpace glue lengths to ERT "
701 i = find_token_exact(document.body, "\\begin_inset space \\hspace", i)
704 j = find_end_of_inset(document.body, i)
706 document.warning("Can't find end of inset at line " + str(i))
709 length = get_value(document.body, '\\length', i + 1, j)
711 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
715 if document.body[i].find("\\hspace*{}") != -1:
717 # only revert if the length contains a plus or minus at pos != 0
718 if length.find('-',1) != -1 or length.find('+',1) != -1:
719 # handle percent lengths
720 length = latex_length(length)[1]
721 # revert the HSpace inset to ERT
722 subst = put_cmd_in_ert("\\hspace" + protected + "{" + length + "}")
723 document.body[i:j+1] = subst
727 def convert_author_id(document):
728 " Add the author_id to the \\author definition and make sure 0 is not used"
731 re_author = re.compile(r'(\\author) (\".*\")\s*(.*)$')
734 i = find_token(document.header, "\\author", i)
737 m = re_author.match(document.header[i])
741 document.header[i] = "\\author %i %s %s" % (anum, name, email)
747 i = find_token(document.body, "\\change_", i)
750 change = document.body[i].split(' ');
753 author_id = int(change[1])
755 document.body[i] = "%s %i %s" % (type, author_id + 1, time)
759 def revert_author_id(document):
760 " Remove the author_id from the \\author definition "
763 rx = re.compile(r'(\\author)\s+(-?\d+)\s+(\".*\")\s*(.*)$')
767 i = find_token(document.header, "\\author", i)
770 m = rx.match(document.header[i])
772 author_id = int(m.group(2))
773 idmap[author_id] = anum
776 document.header[i] = "\\author %s %s" % (name, email)
778 # FIXME Should this be incremented if we didn't match?
783 i = find_token(document.body, "\\change_", i)
786 change = document.body[i].split(' ');
789 author_id = int(change[1])
791 document.body[i] = "%s %i %s" % (type, idmap[author_id], time)
795 def revert_suppress_date(document):
796 " Revert suppressing of default document date to preamble code "
797 i = find_token(document.header, "\\suppress_date", 0)
800 # remove the preamble line and write to the preamble
801 # when suppress_date was true
802 date = str2bool(get_value(document.header, "\\suppress_date", i))
804 add_to_preamble(document, ["\\date{}"])
805 del document.header[i]
808 def convert_mhchem(document):
809 "Set mhchem to off for versions older than 1.6.x"
810 if document.start < 277:
811 # LyX 1.5.x and older did never load mhchem.
812 # Therefore we must switch it off: Documents that use mhchem have
813 # a manual \usepackage anyway, and documents not using mhchem but
814 # custom macros with the same names as mhchem commands might get
815 # corrupted if mhchem is automatically loaded.
818 # LyX 1.6.x did always load mhchem automatically.
820 i = find_token(document.header, "\\use_esint", 0)
823 i = find_token(document.header, "\\use_amsmath", 0)
825 document.warning("Malformed LyX document: Could not find amsmath os esint setting.")
827 document.header.insert(i + 1, "\\use_mhchem %d" % mhchem)
830 def revert_mhchem(document):
831 "Revert mhchem loading to preamble code"
834 i = find_token(document.header, "\\use_mhchem", 0)
836 document.warning("Malformed LyX document: Could not find mhchem setting.")
839 val = get_value(document.header, "\\use_mhchem", i)
844 del document.header[i]
853 i = find_token(document.body, "\\begin_inset Formula", i)
856 line = document.body[i]
857 if line.find("\\ce{") != -1 or line.find("\\cf{") != -1:
863 pre = ["\\PassOptionsToPackage{version=3}{mhchem}",
864 "\\usepackage{mhchem}"]
865 insert_to_preamble(document, pre)
868 def revert_fontenc(document):
869 " Remove fontencoding param "
870 if not del_token(document.header, '\\fontencoding', 0):
871 document.warning("Malformed LyX document: Missing \\fontencoding.")
874 def merge_gbrief(document):
875 " Merge g-brief-en and g-brief-de to one class "
877 if document.textclass != "g-brief-de":
878 if document.textclass == "g-brief-en":
879 document.textclass = "g-brief"
880 document.set_textclass()
883 obsoletedby = { "Brieftext": "Letter",
884 "Unterschrift": "Signature",
886 "Zusatz": "Addition",
889 "RetourAdresse": "ReturnAddress",
890 "MeinZeichen": "MyRef",
891 "IhrZeichen": "YourRef",
892 "IhrSchreiben": "YourMail",
895 "Konto": "BankAccount",
896 "Postvermerk": "PostalComment",
897 "Adresse": "Address",
899 "Betreff": "Reference",
906 i = find_token(document.body, "\\begin_layout", i)
910 layout = document.body[i][14:]
911 if layout in obsoletedby:
912 document.body[i] = "\\begin_layout " + obsoletedby[layout]
916 document.textclass = "g-brief"
917 document.set_textclass()
920 def revert_gbrief(document):
921 " Revert g-brief to g-brief-en "
922 if document.textclass == "g-brief":
923 document.textclass = "g-brief-en"
924 document.set_textclass()
927 def revert_html_options(document):
928 " Remove html options "
929 del_token(document.header, '\\html_use_mathml', 0)
930 del_token(document.header, '\\html_be_strict', 0)
933 def revert_includeonly(document):
936 i = find_token(document.header, "\\begin_includeonly", i)
939 j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
941 document.warning("Unable to find end of includeonly section!!")
943 document.header[i : j + 1] = []
946 def revert_includeall(document):
947 " Remove maintain_unincluded_children param "
948 del_token(document.header, '\\maintain_unincluded_children', 0)
951 def revert_multirow(document):
952 " Revert multirow cells in tables to TeX-code"
954 # first, let's find out if we need to do anything
955 # cell type 3 is multirow begin cell
956 i = find_token(document.body, '<cell multirow="3"', 0)
960 add_to_preamble(document, ["\\usepackage{multirow}"])
964 # find begin/end of table
965 begin_table = find_token(document.body, '<lyxtabular version=', begin_table)
966 if begin_table == -1:
968 end_table = find_end_of(document.body, begin_table, '<lyxtabular', '</lyxtabular>')
970 document.warning("Malformed LyX document: Could not find end of table.")
973 # does this table have multirow?
974 i = find_token(document.body, '<cell multirow="3"', begin_table, end_table)
976 begin_table = end_table
979 # store the number of rows and columns
980 numrows = get_option_value(document.body[begin_table], "rows")
981 numcols = get_option_value(document.body[begin_table], "columns")
983 numrows = int(numrows)
984 numcols = int(numcols)
986 document.warning(numrows)
987 document.warning("Unable to determine rows and columns!")
988 begin_table = end_table
993 # collect info on rows and columns of this table.
994 begin_row = begin_table
995 for row in range(numrows):
996 begin_row = find_token(document.body, '<row>', begin_row, end_table)
998 document.warning("Can't find row " + str(row + 1))
1000 end_row = find_end_of(document.body, begin_row, '<row>', '</row>')
1002 document.warning("Can't find end of row " + str(row + 1))
1004 begin_cell = begin_row
1005 multirows.append([])
1006 for column in range(numcols):
1007 begin_cell = find_token(document.body, '<cell ', begin_cell, end_row)
1008 if begin_cell == -1:
1009 document.warning("Can't find column " + str(column + 1) + \
1010 "in row " + str(row + 1))
1013 # this will fail if someone puts "</cell>" in a cell, but
1014 # that seems fairly unlikely.
1015 end_cell = find_end_of(document.body, begin_cell, '<cell', '</cell>')
1017 document.warning("Can't find end of column " + str(column + 1) + \
1018 "in row " + str(row + 1))
1020 multirows[row].append([begin_cell, end_cell, 0])
1021 if document.body[begin_cell].find('multirow="3"') != -1:
1022 multirows[row][column][2] = 3 # begin multirow
1023 mrstarts.append([row, column])
1024 elif document.body[begin_cell].find('multirow="4"') != -1:
1025 multirows[row][column][2] = 4 # in multirow
1026 begin_cell = end_cell
1028 # end of table info collection
1030 # work from the back to avoid messing up numbering
1036 col_width = get_option_value(document.body[begin_table + 2 + col], "width")
1037 # "0pt" means that no width is specified
1038 if not col_width or col_width == "0pt":
1040 # determine the number of cells that are part of the multirow
1042 for r in range(row + 1, numrows):
1043 if multirows[r][col][2] != 4:
1046 # take the opportunity to revert this line
1047 lineno = multirows[r][col][0]
1048 document.body[lineno] = document.body[lineno].\
1049 replace(' multirow="4" ', ' ').\
1050 replace('valignment="middle"', 'valignment="top"').\
1051 replace(' topline="true" ', ' ')
1052 # remove bottom line of previous multirow-part cell
1053 lineno = multirows[r-1][col][0]
1054 document.body[lineno] = document.body[lineno].replace(' bottomline="true" ', ' ')
1055 # revert beginning cell
1056 bcell = multirows[row][col][0]
1057 ecell = multirows[row][col][1]
1058 document.body[bcell] = document.body[bcell].\
1059 replace(' multirow="3" ', ' ').\
1060 replace('valignment="middle"', 'valignment="top"')
1061 blay = find_token(document.body, "\\begin_layout", bcell, ecell)
1063 document.warning("Can't find layout for cell!")
1065 bend = find_end_of_layout(document.body, blay)
1067 document.warning("Can't find end of layout for cell!")
1069 # do the later one first, so as not to mess up the numbering
1070 # we are wrapping the whole cell in this ert
1071 # so before the end of the layout...
1072 document.body[bend:bend] = put_cmd_in_ert("}")
1073 # ...and after the beginning
1074 document.body[blay + 1:blay + 1] = \
1075 put_cmd_in_ert("\\multirow{" + str(nummrs) + "}{" + col_width + "}{")
1077 begin_table = end_table
1080 def convert_math_output(document):
1081 " Convert \html_use_mathml to \html_math_output "
1082 i = find_token(document.header, "\\html_use_mathml", 0)
1085 rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1086 m = rgx.match(document.header[i])
1087 newval = "0" # MathML
1089 val = str2bool(m.group(1))
1091 newval = "2" # Images
1093 document.warning("Can't match " + document.header[i])
1094 document.header[i] = "\\html_math_output " + newval
1097 def revert_math_output(document):
1098 " Revert \html_math_output to \html_use_mathml "
1099 i = find_token(document.header, "\\html_math_output", 0)
1102 rgx = re.compile(r'\\html_math_output\s+(\d)')
1103 m = rgx.match(document.header[i])
1107 if val == "1" or val == "2":
1110 document.warning("Unable to match " + document.header[i])
1111 document.header[i] = "\\html_use_mathml " + newval
1115 def revert_inset_preview(document):
1116 " Dissolves the preview inset "
1119 i = find_token(document.body, "\\begin_inset Preview", i)
1122 iend = find_end_of_inset(document.body, i)
1124 document.warning("Malformed LyX document: Could not find end of Preview inset.")
1128 # This has several issues.
1129 # We need to do something about the layouts inside InsetPreview.
1130 # If we just leave the first one, then we have something like:
1131 # \begin_layout Standard
1133 # \begin_layout Standard
1134 # and we get a "no \end_layout" error. So something has to be done.
1135 # Ideally, we would check if it is the same as the layout we are in.
1136 # If so, we just remove it; if not, we end the active one. But it is
1137 # not easy to know what layout we are in, due to depth changes, etc,
1138 # and it is not clear to me how much work it is worth doing. In most
1139 # cases, the layout will probably be the same.
1141 # For the same reason, we have to remove the \end_layout tag at the
1142 # end of the last layout in the inset. Again, that will sometimes be
1143 # wrong, but it will usually be right. To know what to do, we would
1144 # again have to know what layout the inset is in.
1146 blay = find_token(document.body, "\\begin_layout", i, iend)
1148 document.warning("Can't find layout for preview inset!")
1149 # always do the later one first...
1150 del document.body[iend]
1151 del document.body[i]
1152 # deletions mean we do not need to reset i
1155 # This is where we would check what layout we are in.
1156 # The check for Standard is definitely wrong.
1158 # lay = document.body[blay].split(None, 1)[1]
1159 # if lay != oldlayout:
1160 # # record a boolean to tell us what to do later....
1161 # # better to do it later, since (a) it won't mess up
1162 # # the numbering and (b) we only modify at the end.
1164 # we want to delete the last \\end_layout in this inset, too.
1165 # note that this may not be the \\end_layout that goes with blay!!
1166 bend = find_end_of_layout(document.body, blay)
1168 tmp = find_token(document.body, "\\end_layout", bend + 1, iend)
1173 document.warning("Unable to find last layout in preview inset!")
1174 del document.body[iend]
1175 del document.body[i]
1176 # deletions mean we do not need to reset i
1178 # always do the later one first...
1179 del document.body[iend]
1180 del document.body[bend]
1181 del document.body[i:blay + 1]
1182 # we do not need to reset i
1185 def revert_equalspacing_xymatrix(document):
1186 " Revert a Formula with xymatrix@! to an ERT inset "
1188 has_preamble = False
1189 has_equal_spacing = False
1192 i = find_token(document.body, "\\begin_inset Formula", i)
1195 j = find_end_of_inset(document.body, i)
1197 document.warning("Malformed LyX document: Could not find end of Formula inset.")
1201 for curline in range(i,j):
1202 found = document.body[curline].find("\\xymatrix@!")
1207 has_equal_spacing = True
1208 content = [document.body[i][21:]]
1209 content += document.body[i + 1:j]
1210 subst = put_cmd_in_ert(content)
1211 document.body[i:j + 1] = subst
1212 i += len(subst) - (j - i) + 1
1214 for curline in range(i,j):
1215 l = document.body[curline].find("\\xymatrix")
1217 has_preamble = True;
1221 if has_equal_spacing and not has_preamble:
1222 add_to_preamble(document, ['\\usepackage[all]{xy}'])
1225 def revert_notefontcolor(document):
1226 " Reverts greyed-out note font color to preamble code "
1228 i = find_token(document.header, "\\notefontcolor", 0)
1232 colorcode = get_value(document.header, '\\notefontcolor', i)
1233 del document.header[i]
1235 # are there any grey notes?
1236 if find_token(document.body, "\\begin_inset Note Greyedout", 0) == -1:
1237 # no need to do anything else, and \renewcommand will throw
1238 # an error since lyxgreyedout will not exist.
1241 # the color code is in the form #rrggbb where every character denotes a hex number
1242 red = hex2ratio(colorcode[1:3])
1243 green = hex2ratio(colorcode[3:5])
1244 blue = hex2ratio(colorcode[5:7])
1245 # write the preamble
1246 insert_to_preamble(document,
1247 [ '% for greyed-out notes',
1248 '\\@ifundefined{definecolor}{\\usepackage{color}}{}'
1249 '\\definecolor{note_fontcolor}{rgb}{%s,%s,%s}' % (red, green, blue),
1250 '\\renewenvironment{lyxgreyedout}',
1251 ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}'])
1254 def revert_turkmen(document):
1255 "Set language Turkmen to English"
1257 if document.language == "turkmen":
1258 document.language = "english"
1259 i = find_token(document.header, "\\language", 0)
1261 document.header[i] = "\\language english"
1265 j = find_token(document.body, "\\lang turkmen", j)
1268 document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english")
1272 def revert_fontcolor(document):
1273 " Reverts font color to preamble code "
1274 i = find_token(document.header, "\\fontcolor", 0)
1277 colorcode = get_value(document.header, '\\fontcolor', i)
1278 del document.header[i]
1279 # don't clutter the preamble if font color is not set
1280 if colorcode == "#000000":
1282 # the color code is in the form #rrggbb where every character denotes a hex number
1283 red = hex2ratio(colorcode[1:3])
1284 green = hex2ratio(colorcode[3:5])
1285 blue = hex2ratio(colorcode[5:7])
1286 # write the preamble
1287 insert_to_preamble(document,
1288 ['% Set the font color',
1289 '\\@ifundefined{definecolor}{\\usepackage{color}}{}',
1290 '\\definecolor{document_fontcolor}{rgb}{%s,%s,%s}' % (red, green, blue),
1291 '\\color{document_fontcolor}'])
1294 def revert_shadedboxcolor(document):
1295 " Reverts shaded box color to preamble code "
1296 i = find_token(document.header, "\\boxbgcolor", 0)
1299 colorcode = get_value(document.header, '\\boxbgcolor', i)
1300 del document.header[i]
1301 # the color code is in the form #rrggbb
1302 red = hex2ratio(colorcode[1:3])
1303 green = hex2ratio(colorcode[3:5])
1304 blue = hex2ratio(colorcode[5:7])
1305 # write the preamble
1306 insert_to_preamble(document,
1307 ['% Set the color of boxes with shaded background',
1308 '\\@ifundefined{definecolor}{\\usepackage{color}}{}',
1309 "\\definecolor{shadecolor}{rgb}{%s,%s,%s}" % (red, green, blue)])
1312 def revert_lyx_version(document):
1313 " Reverts LyX Version information from Inset Info "
1314 version = "LyX version"
1316 import lyx2lyx_version
1317 version = lyx2lyx_version.version
1323 i = find_token(document.body, '\\begin_inset Info', i)
1326 j = find_end_of_inset(document.body, i + 1)
1328 document.warning("Malformed LyX document: Could not find end of Info inset.")
1337 typ = get_quoted_value(document.body, "type", i, j)
1338 arg = get_quoted_value(document.body, "arg", i, j)
1339 if arg != "version" or typ != "lyxinfo":
1343 # We do not actually know the version of LyX used to produce the document.
1344 # But we can use our version, since we are reverting.
1346 # Now we want to check if the line after "\end_inset" is empty. It normally
1347 # is, so we want to remove it, too.
1349 if document.body[j + 1].strip() == "":
1351 document.body[i: lastline] = s
1355 def revert_math_scale(document):
1356 " Remove math scaling and LaTeX options "
1357 del_token(document.header, '\\html_math_img_scale', 0)
1358 del_token(document.header, '\\html_latex_start', 0)
1359 del_token(document.header, '\\html_latex_end', 0)
1362 def revert_pagesizes(document):
1363 " Revert page sizes to default "
1364 i = find_token(document.header, '\\papersize', 0)
1366 size = document.header[i][11:]
1367 if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1368 or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1369 or size == "b2paper" or size == "b6paper" or size == "b0j" \
1370 or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1371 or size == "b5j" or size == "b6j":
1372 del document.header[i]
1375 def revert_DIN_C_pagesizes(document):
1376 " Revert DIN C page sizes to default "
1377 i = find_token(document.header, '\\papersize', 0)
1379 size = document.header[i][11:]
1380 if size == "c0paper" or size == "c1paper" or size == "c2paper" \
1381 or size == "c3paper" or size == "c4paper" or size == "c5paper" \
1382 or size == "c6paper":
1383 del document.header[i]
1386 def convert_html_quotes(document):
1387 " Remove quotes around html_latex_start and html_latex_end "
1389 i = find_token(document.header, '\\html_latex_start', 0)
1391 line = document.header[i]
1392 l = re.compile(r'\\html_latex_start\s+"(.*)"')
1395 document.header[i] = "\\html_latex_start " + m.group(1)
1397 i = find_token(document.header, '\\html_latex_end', 0)
1399 line = document.header[i]
1400 l = re.compile(r'\\html_latex_end\s+"(.*)"')
1403 document.header[i] = "\\html_latex_end " + m.group(1)
1406 def revert_html_quotes(document):
1407 " Remove quotes around html_latex_start and html_latex_end "
1409 i = find_token(document.header, '\\html_latex_start', 0)
1411 line = document.header[i]
1412 l = re.compile(r'\\html_latex_start\s+(.*)')
1415 document.warning("Weird html_latex_start line: " + line)
1416 del document.header[i]
1418 document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1420 i = find_token(document.header, '\\html_latex_end', 0)
1422 line = document.header[i]
1423 l = re.compile(r'\\html_latex_end\s+(.*)')
1426 document.warning("Weird html_latex_end line: " + line)
1427 del document.header[i]
1429 document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1432 def revert_output_sync(document):
1433 " Remove forward search options "
1434 del_token(document.header, '\\output_sync_macro', 0)
1435 del_token(document.header, '\\output_sync', 0)
1438 def revert_align_decimal(document):
1441 i = find_token(document.body, "\\begin_inset Tabular", i)
1444 j = find_end_of_inset(document.body, i)
1446 document.warning("Unable to find end of Tabular inset at line " + str(i))
1449 cell = find_token(document.body, "<cell", i, j)
1451 document.warning("Can't find any cells in Tabular inset at line " + str(i))
1456 k = find_token(document.body, "<column", k, cell)
1459 if document.body[k].find('alignment="decimal"') == -1:
1462 remove_option(document.body, k, 'decimal_point')
1463 document.body[k] = \
1464 document.body[k].replace('alignment="decimal"', 'alignment="center"')
1468 def convert_optarg(document):
1469 " Convert \\begin_inset OptArg to \\begin_inset Argument "
1472 i = find_token(document.body, '\\begin_inset OptArg', i)
1475 document.body[i] = "\\begin_inset Argument"
1479 def revert_argument(document):
1480 " Convert \\begin_inset Argument to \\begin_inset OptArg "
1483 i = find_token(document.body, '\\begin_inset Argument', i)
1486 document.body[i] = "\\begin_inset OptArg"
1490 def revert_makebox(document):
1491 " Convert \\makebox to TeX code "
1494 i = find_token(document.body, '\\begin_inset Box', i)
1497 z = find_end_of_inset(document.body, i)
1499 document.warning("Malformed LyX document: Can't find end of box inset.")
1502 blay = find_token(document.body, "\\begin_layout", i, z)
1504 document.warning("Malformed LyX document: Can't find layout in box.")
1507 # by looking before the layout we make sure we're actually finding
1508 # an option, not text.
1509 j = find_token(document.body, 'use_makebox', i, blay)
1514 if not check_token(document.body[i], "\\begin_inset Box Frameless") \
1515 or get_value(document.body, 'use_makebox', j) != 1:
1516 del document.body[j]
1519 bend = find_end_of_layout(document.body, blay)
1520 if bend == -1 or bend > z:
1521 document.warning("Malformed LyX document: Can't find end of layout in box.")
1524 # determine the alignment
1525 align = get_quoted_value(document.body, 'hor_pos', i, blay, "c")
1526 # determine the width
1527 length = get_quoted_value(document.body, 'width', i, blay, "50col%")
1528 length = latex_length(length)[1]
1529 # remove the \end_layout \end_inset pair
1530 document.body[bend:z + 1] = put_cmd_in_ert("}")
1531 subst = "\\makebox[" + length + "][" \
1533 document.body[i:blay + 1] = put_cmd_in_ert(subst)
1537 def convert_use_makebox(document):
1538 " Adds use_makebox option for boxes "
1541 i = find_token(document.body, '\\begin_inset Box', i)
1544 # all of this is to make sure we actually find the use_parbox
1545 # that is an option for this box, not some text elsewhere.
1546 z = find_end_of_inset(document.body, i)
1548 document.warning("Can't find end of box inset!!")
1551 blay = find_token(document.body, "\\begin_layout", i, z)
1553 document.warning("Can't find layout in box inset!!")
1556 # so now we are looking for use_parbox before the box's layout
1557 k = find_token(document.body, 'use_parbox', i, blay)
1559 document.warning("Malformed LyX document: Can't find use_parbox statement in box.")
1562 document.body.insert(k + 1, "use_makebox 0")
1563 i = blay + 1 # not z + 1 (box insets may be nested)
1566 def revert_IEEEtran(document):
1567 " Convert IEEEtran layouts and styles to TeX code "
1568 if document.textclass != "IEEEtran":
1570 revert_flex_inset(document.body, "IEEE membership", "\\IEEEmembership")
1571 revert_flex_inset(document.body, "Lowercase", "\\MakeLowercase")
1572 layouts = ("Special Paper Notice", "After Title Text", "Publication ID",
1573 "Page headings", "Biography without photo")
1574 latexcmd = {"Special Paper Notice": "\\IEEEspecialpapernotice",
1575 "After Title Text": "\\IEEEaftertitletext",
1576 "Publication ID": "\\IEEEpubid"}
1577 obsoletedby = {"Page headings": "MarkBoth",
1578 "Biography without photo": "BiographyNoPhoto"}
1579 for layout in layouts:
1582 i = find_token(document.body, '\\begin_layout ' + layout, i)
1585 j = find_end_of_layout(document.body, i)
1587 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1590 if layout in obsoletedby:
1591 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1594 content = lyx2latex(document, document.body[i:j + 1])
1595 add_to_preamble(document, [latexcmd[layout] + "{" + content + "}"])
1596 del document.body[i:j + 1]
1597 # no need to reset i
1600 def convert_prettyref(document):
1601 " Converts prettyref references to neutral formatted refs "
1602 re_ref = re.compile("^\s*reference\s+\"(\w+):(\S+)\"")
1603 nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
1607 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
1610 j = find_end_of_inset(document.body, i)
1612 document.warning("Malformed LyX document: No end of InsetRef!")
1615 k = find_token(document.body, "LatexCommand prettyref", i, j)
1617 document.body[k] = "LatexCommand formatted"
1619 document.header.insert(-1, "\\use_refstyle 0")
1622 def revert_refstyle(document):
1623 " Reverts neutral formatted refs to prettyref "
1624 re_ref = re.compile("^reference\s+\"(\w+):(\S+)\"")
1625 nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
1629 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
1632 j = find_end_of_inset(document.body, i)
1634 document.warning("Malformed LyX document: No end of InsetRef")
1637 k = find_token(document.body, "LatexCommand formatted", i, j)
1639 document.body[k] = "LatexCommand prettyref"
1641 i = find_token(document.header, "\\use_refstyle", 0)
1643 document.header.pop(i)
1646 def revert_nameref(document):
1647 " Convert namerefs to regular references "
1648 cmds = ["Nameref", "nameref"]
1650 rx = re.compile(r'reference "(.*)"')
1653 oldcmd = "LatexCommand " + cmd
1655 # It seems better to look for this, as most of the reference
1656 # insets won't be ones we care about.
1657 i = find_token(document.body, oldcmd, i)
1662 # Make sure it is actually in an inset!
1663 # A normal line could begin with "LatexCommand nameref"!
1664 val = is_in_inset(document.body, cmdloc, \
1665 "\\begin_inset CommandInset ref")
1670 # ok, so it is in an InsetRef
1671 refline = find_token(document.body, "reference", stins, endins)
1673 document.warning("Can't find reference for inset at line " + stinst + "!!")
1675 m = rx.match(document.body[refline])
1677 document.warning("Can't match reference line: " + document.body[ref])
1681 newcontent = put_cmd_in_ert('\\' + cmd + '{' + ref + '}')
1682 document.body[stins:endins + 1] = newcontent
1685 add_to_preamble(document, ["\usepackage{nameref}"])
1688 def remove_Nameref(document):
1689 " Convert Nameref commands to nameref commands "
1692 # It seems better to look for this, as most of the reference
1693 # insets won't be ones we care about.
1694 i = find_token(document.body, "LatexCommand Nameref" , i)
1700 # Make sure it is actually in an inset!
1701 val = is_in_inset(document.body, cmdloc, \
1702 "\\begin_inset CommandInset ref")
1705 document.body[cmdloc] = "LatexCommand nameref"
1708 def revert_mathrsfs(document):
1709 " Load mathrsfs if \mathrsfs us use in the document "
1711 for line in document.body:
1712 if line.find("\\mathscr{") != -1:
1713 add_to_preamble(document, ["\\usepackage{mathrsfs}"])
1717 def convert_flexnames(document):
1718 "Convert \\begin_inset Flex Custom:Style to \\begin_inset Flex Style and similarly for CharStyle and Element."
1721 rx = re.compile(r'^\\begin_inset Flex (?:Custom|CharStyle|Element):(.+)$')
1723 i = find_token(document.body, "\\begin_inset Flex", i)
1726 m = rx.match(document.body[i])
1728 document.body[i] = "\\begin_inset Flex " + m.group(1)
1733 "Alert" : "CharStyle:Alert",
1734 "Code" : "CharStyle:Code",
1735 "Concepts" : "CharStyle:Concepts",
1736 "E-Mail" : "CharStyle:E-Mail",
1737 "Emph" : "CharStyle:Emph",
1738 "Expression" : "CharStyle:Expression",
1739 "Initial" : "CharStyle:Initial",
1740 "Institute" : "CharStyle:Institute",
1741 "Meaning" : "CharStyle:Meaning",
1742 "Noun" : "CharStyle:Noun",
1743 "Strong" : "CharStyle:Strong",
1744 "Structure" : "CharStyle:Structure",
1745 "ArticleMode" : "Custom:ArticleMode",
1746 "Endnote" : "Custom:Endnote",
1747 "Glosse" : "Custom:Glosse",
1748 "PresentationMode" : "Custom:PresentationMode",
1749 "Tri-Glosse" : "Custom:Tri-Glosse"
1753 "Abbrev" : "Element:Abbrev",
1754 "CCC-Code" : "Element:CCC-Code",
1755 "Citation-number" : "Element:Citation-number",
1756 "City" : "Element:City",
1757 "Code" : "Element:Code",
1758 "CODEN" : "Element:CODEN",
1759 "Country" : "Element:Country",
1760 "Day" : "Element:Day",
1761 "Directory" : "Element:Directory",
1762 "Dscr" : "Element:Dscr",
1763 "Email" : "Element:Email",
1764 "Emph" : "Element:Emph",
1765 "Filename" : "Element:Filename",
1766 "Firstname" : "Element:Firstname",
1767 "Fname" : "Element:Fname",
1768 "GuiButton" : "Element:GuiButton",
1769 "GuiMenu" : "Element:GuiMenu",
1770 "GuiMenuItem" : "Element:GuiMenuItem",
1771 "ISSN" : "Element:ISSN",
1772 "Issue-day" : "Element:Issue-day",
1773 "Issue-months" : "Element:Issue-months",
1774 "Issue-number" : "Element:Issue-number",
1775 "KeyCap" : "Element:KeyCap",
1776 "KeyCombo" : "Element:KeyCombo",
1777 "Keyword" : "Element:Keyword",
1778 "Literal" : "Element:Literal",
1779 "MenuChoice" : "Element:MenuChoice",
1780 "Month" : "Element:Month",
1781 "Orgdiv" : "Element:Orgdiv",
1782 "Orgname" : "Element:Orgname",
1783 "Postcode" : "Element:Postcode",
1784 "SS-Code" : "Element:SS-Code",
1785 "SS-Title" : "Element:SS-Title",
1786 "State" : "Element:State",
1787 "Street" : "Element:Street",
1788 "Surname" : "Element:Surname",
1789 "Volume" : "Element:Volume",
1790 "Year" : "Element:Year"
1794 def revert_flexnames(document):
1795 if document.backend == "latex":
1796 flexlist = flex_insets
1798 flexlist = flex_elements
1800 rx = re.compile(r'^\\begin_inset Flex\s+(.+)$')
1803 i = find_token(document.body, "\\begin_inset Flex", i)
1806 m = rx.match(document.body[i])
1808 document.warning("Illegal flex inset: " + document.body[i])
1812 if style in flexlist:
1813 document.body[i] = "\\begin_inset Flex " + flexlist[style]
1817 def convert_mathdots(document):
1818 " Load mathdots automatically "
1819 i = find_token(document.header, "\\use_mhchem" , 0)
1821 i = find_token(document.header, "\\use_esint" , 0)
1823 document.header.insert(i + 1, "\\use_mathdots 1")
1826 def revert_mathdots(document):
1827 " Load mathdots if used in the document "
1829 mathdots = find_token(document.header, "\\use_mathdots" , 0)
1831 document.warning("No \\usemathdots line. Assuming auto.")
1833 val = get_value(document.header, "\\use_mathdots", mathdots)
1834 del document.header[mathdots]
1838 document.warning("Invalid \\use_mathdots value: " + val + ". Assuming auto.")
1839 # probably usedots has not been changed, but be safe.
1847 add_to_preamble(["\\usepackage{mathdots}"])
1850 # so we are in the auto case. we want to load mathdots if \iddots is used.
1853 i = find_token(document.body, '\\begin_inset Formula', i)
1856 j = find_end_of_inset(document.body, i)
1858 document.warning("Malformed LyX document: Can't find end of Formula inset at line " + str(i))
1861 code = "\n".join(document.body[i:j])
1862 if code.find("\\iddots") != -1:
1863 add_to_preamble(document, ["\\@ifundefined{iddots}{\\usepackage{mathdots}}"])
1868 def convert_rule(document):
1869 " Convert \\lyxline to CommandInset line. "
1872 inset = ['\\begin_inset CommandInset line',
1873 'LatexCommand rule',
1877 '\\end_inset', '', '']
1879 # if paragraphs are indented, we may have to unindent to get the
1880 # line to be full-width.
1881 indent = get_value(document.header, "\\paragraph_separation", 0)
1882 have_indent = (indent == "indent")
1885 i = find_token(document.body, "\\lyxline" , i)
1889 # we need to find out if this line follows other content
1890 # in its paragraph. find its layout....
1891 lastlay = find_token_backwards(document.body, "\\begin_layout", i)
1893 document.warning("Can't find layout for line at " + str(i))
1894 # do the best we can.
1895 document.body[i:i+1] = inset
1899 # ...and look for other content before it.
1901 for line in document.body[lastlay + 1:i]:
1902 # is it empty or a paragraph option?
1903 if not line or line[0] == '\\':
1909 document.body[i:i+1] = inset
1911 # we need to unindent, lest the line be too long
1912 document.body.insert(lastlay + 1, "\\noindent")
1915 # so our line is in the middle of a paragraph
1916 # we need to add a new line, lest this line follow the
1917 # other content on that line and run off the side of the page
1918 document.body[i:i+1] = inset
1919 document.body[i:i] = ["\\begin_inset Newline newline", "\\end_inset", ""]
1923 def revert_rule(document):
1924 " Revert line insets to Tex code "
1927 i = find_token(document.body, "\\begin_inset CommandInset line" , i)
1931 j = find_token(document.body, "\\end_inset" , i)
1933 document.warning("Malformed LyX document: Can't find end of line inset.")
1935 # determine the optional offset
1936 offset = get_quoted_value(document.body, 'offset', i, j)
1938 offset = '[' + offset + ']'
1939 # determine the width
1940 width = get_quoted_value(document.body, 'width', i, j, "100col%")
1941 width = latex_length(width)[1]
1942 # determine the height
1943 height = get_quoted_value(document.body, 'height', i, j, "1pt")
1944 height = latex_length(height)[1]
1945 # output the \rule command
1946 subst = "\\rule[" + offset + "]{" + width + "}{" + height + "}"
1947 document.body[i:j + 1] = put_cmd_in_ert(subst)
1948 i += len(subst) - (j - i)
1951 def revert_diagram(document):
1952 " Add the feyn package if \\Diagram is used in math "
1955 i = find_token(document.body, '\\begin_inset Formula', i)
1958 j = find_end_of_inset(document.body, i)
1960 document.warning("Malformed LyX document: Can't find end of Formula inset.")
1962 lines = "\n".join(document.body[i:j])
1963 if lines.find("\\Diagram") == -1:
1966 add_to_preamble(document, ["\\usepackage{feyn}"])
1967 # only need to do it once!
1970 chapters = ("amsbook", "book", "docbook-book", "elsart", "extbook", "extreport",
1971 "jbook", "jreport", "jsbook", "literate-book", "literate-report", "memoir",
1972 "mwbk", "mwrep", "recipebook", "report", "scrbook", "scrreprt", "svmono",
1973 "svmult", "tbook", "treport", "tufte-book")
1975 def convert_bibtex_clearpage(document):
1976 " insert a clear(double)page bibliographystyle if bibtotoc option is used "
1978 if document.textclass not in chapters:
1981 i = find_token(document.header, '\\papersides', 0)
1984 document.warning("Malformed LyX document: Can't find papersides definition.")
1985 document.warning("Assuming single sided.")
1988 val = get_value(document.header, "\\papersides", i)
1993 if sides != 1 and sides != 2:
1994 document.warning("Invalid papersides value: " + val)
1995 document.warning("Assuming single sided.")
2000 j = find_token(document.body, "\\begin_inset CommandInset bibtex", j)
2004 k = find_end_of_inset(document.body, j)
2006 document.warning("Can't find end of Bibliography inset at line " + str(j))
2010 # only act if there is the option "bibtotoc"
2011 val = get_value(document.body, 'options', j, k)
2013 document.warning("Can't find options for bibliography inset at line " + str(j))
2017 if val.find("bibtotoc") == -1:
2021 # so we want to insert a new page right before the paragraph that
2022 # this bibliography thing is in.
2023 lay = find_token_backwards(document.body, "\\begin_layout", j)
2025 document.warning("Can't find layout containing bibliography inset at line " + str(j))
2032 cmd = "cleardoublepage"
2033 subst = ['\\begin_layout Standard',
2034 '\\begin_inset Newpage ' + cmd,
2035 '\\end_inset', '', '',
2037 document.body[lay:lay] = subst
2041 def check_passthru(document):
2042 tc = document.textclass
2043 ok = (tc == "literate-article" or tc == "literate-book" or tc == "literate-report")
2045 mods = document.get_module_list()
2047 if mod == "sweave" or mod == "noweb":
2053 def convert_passthru(document):
2054 " http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg161298.html "
2055 if not check_passthru:
2058 rx = re.compile("\\\\begin_layout \s*(\w+)")
2060 for lay in ["Chunk", "Scrap"]:
2062 beg = find_token(document.body, "\\begin_layout " + lay, beg)
2065 end = find_end_of_layout(document.body, beg)
2067 document.warning("Can't find end of layout at line " + str(beg))
2071 # we are now going to replace newline insets within this layout
2072 # by new instances of this layout. so we have repeated layouts
2073 # instead of newlines.
2075 # if the paragraph has any customization, however, we do not want to
2076 # do the replacement.
2077 if document.body[beg + 1].startswith("\\"):
2083 ns = find_token(document.body, "\\begin_inset Newline newline", ns, end)
2086 ne = find_end_of_inset(document.body, ns)
2087 if ne == -1 or ne > end:
2088 document.warning("Can't find end of inset at line " + str(nb))
2091 if document.body[ne + 1] == "":
2093 subst = ["\\end_layout", "", "\\begin_layout " + lay]
2094 document.body[ns:ne + 1] = subst
2095 # now we need to adjust end, in particular, but might as well
2096 # do ns properly, too
2097 newlines = (ne - ns) - len(subst)
2101 # ok, we now want to find out if the next layout is the
2102 # same as this one. if so, we will insert an extra copy of it
2104 next = find_token(document.body, "\\begin_layout", end)
2106 m = rx.match(document.body[next])
2108 nextlay = m.group(1)
2110 subst = ["\\begin_layout " + lay, "", "\\end_layout", ""]
2111 document.body[next:next] = subst
2115 beg += 4 # for the extra layout
2118 def revert_passthru(document):
2119 " http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg161298.html "
2120 if not check_passthru:
2122 rx = re.compile("\\\\begin_layout \s*(\w+)")
2124 for lay in ["Chunk", "Scrap"]:
2126 beg = find_token(document.body, "\\begin_layout " + lay, beg)
2129 end = find_end_of_layout(document.body, beg)
2131 document.warning("Can't find end of layout at line " + str(beg))
2135 # we now want to find out if the next layout is the
2136 # same as this one. but we will need to do this over and
2139 next = find_token(document.body, "\\begin_layout", end)
2142 m = rx.match(document.body[next])
2145 nextlay = m.group(1)
2148 # so it is the same layout again. we now want to know if it is empty.
2149 # but first let's check and make sure there is no content between the
2150 # two layouts. i'm not sure if that can happen or not.
2151 for l in range(end + 1, next):
2152 document.warning("c'" + document.body[l] + "'")
2153 if document.body[l] != "":
2154 document.warning("Found content between adjacent " + lay + " layouts!")
2156 nextend = find_end_of_layout(document.body, next)
2158 document.warning("Can't find end of layout at line " + str(next))
2161 for l in range(next + 1, nextend):
2162 document.warning("e'" + document.body[l] + "'")
2163 if document.body[l] != "":
2167 # empty layouts just get removed
2168 # should we check if it's before yet another such layout?
2169 del document.body[next : nextend + 1]
2170 # and we do not want to check again. we know the next layout
2171 # should be another Chunk and should be left as is.
2174 # if it's not empty, then we want to insert a newline in place
2175 # of the layout switch
2176 subst = ["\\begin_inset Newline newline", "\\end_inset", ""]
2177 document.body[end : next + 1] = subst
2178 # and now we have to find the end of the new, larger layout
2179 newend = find_end_of_layout(document.body, beg)
2181 document.warning("Can't find end of new layout at line " + str(beg))
2187 def revert_multirowOffset(document):
2188 " Revert multirow cells with offset in tables to TeX-code"
2189 # this routine is the same as the revert_multirow routine except that
2190 # it checks additionally for the offset
2192 # first, let's find out if we need to do anything
2193 i = find_token(document.body, '<cell multirow="3" mroffset=', 0)
2197 add_to_preamble(document, ["\\usepackage{multirow}"])
2199 rgx = re.compile(r'mroffset="[^"]+?"')
2203 # find begin/end of table
2204 begin_table = find_token(document.body, '<lyxtabular version=', begin_table)
2205 if begin_table == -1:
2207 end_table = find_end_of(document.body, begin_table, '<lyxtabular', '</lyxtabular>')
2209 document.warning("Malformed LyX document: Could not find end of table.")
2212 # does this table have multirow?
2213 i = find_token(document.body, '<cell multirow="3"', begin_table, end_table)
2215 begin_table = end_table
2218 # store the number of rows and columns
2219 numrows = get_option_value(document.body[begin_table], "rows")
2220 numcols = get_option_value(document.body[begin_table], "columns")
2222 numrows = int(numrows)
2223 numcols = int(numcols)
2225 document.warning(numrows)
2226 document.warning("Unable to determine rows and columns!")
2227 begin_table = end_table
2232 # collect info on rows and columns of this table.
2233 begin_row = begin_table
2234 for row in range(numrows):
2235 begin_row = find_token(document.body, '<row>', begin_row, end_table)
2237 document.warning("Can't find row " + str(row + 1))
2239 end_row = find_end_of(document.body, begin_row, '<row>', '</row>')
2241 document.warning("Can't find end of row " + str(row + 1))
2243 begin_cell = begin_row
2244 multirows.append([])
2245 for column in range(numcols):
2246 begin_cell = find_token(document.body, '<cell ', begin_cell, end_row)
2247 if begin_cell == -1:
2248 document.warning("Can't find column " + str(column + 1) + \
2249 "in row " + str(row + 1))
2252 # this will fail if someone puts "</cell>" in a cell, but
2253 # that seems fairly unlikely.
2254 end_cell = find_end_of(document.body, begin_cell, '<cell', '</cell>')
2256 document.warning("Can't find end of column " + str(column + 1) + \
2257 "in row " + str(row + 1))
2259 multirows[row].append([begin_cell, end_cell, 0])
2260 if document.body[begin_cell].find('multirow="3" mroffset=') != -1:
2261 multirows[row][column][2] = 3 # begin multirow
2262 mrstarts.append([row, column])
2263 elif document.body[begin_cell].find('multirow="4"') != -1:
2264 multirows[row][column][2] = 4 # in multirow
2265 begin_cell = end_cell
2267 # end of table info collection
2269 # work from the back to avoid messing up numbering
2275 col_width = get_option_value(document.body[begin_table + 2 + col], "width")
2276 # "0pt" means that no width is specified
2277 if not col_width or col_width == "0pt":
2279 # determine the number of cells that are part of the multirow
2281 for r in range(row + 1, numrows):
2282 if multirows[r][col][2] != 4:
2285 # take the opportunity to revert this line
2286 lineno = multirows[r][col][0]
2287 document.body[lineno] = document.body[lineno].\
2288 replace(' multirow="4" ', ' ').\
2289 replace('valignment="middle"', 'valignment="top"').\
2290 replace(' topline="true" ', ' ')
2291 # remove bottom line of previous multirow-part cell
2292 lineno = multirows[r-1][col][0]
2293 document.body[lineno] = document.body[lineno].replace(' bottomline="true" ', ' ')
2294 # revert beginning cell
2295 bcell = multirows[row][col][0]
2296 ecell = multirows[row][col][1]
2297 offset = get_option_value(document.body[bcell], "mroffset")
2298 document.body[bcell] = document.body[bcell].\
2299 replace(' multirow="3" ', ' ').\
2300 replace('valignment="middle"', 'valignment="top"')
2301 # remove mroffset option
2302 document.body[bcell] = rgx.sub('', document.body[bcell])
2304 blay = find_token(document.body, "\\begin_layout", bcell, ecell)
2306 document.warning("Can't find layout for cell!")
2308 bend = find_end_of_layout(document.body, blay)
2310 document.warning("Can't find end of layout for cell!")
2312 # do the later one first, so as not to mess up the numbering
2313 # we are wrapping the whole cell in this ert
2314 # so before the end of the layout...
2315 document.body[bend:bend] = put_cmd_in_ert("}")
2316 # ...and after the beginning
2317 document.body[blay + 1:blay + 1] = \
2318 put_cmd_in_ert("\\multirow{" + str(nummrs) + "}{" + col_width + "}[" \
2321 # on to the next table
2322 begin_table = end_table
2325 def revert_script(document):
2326 " Convert subscript/superscript inset to TeX code "
2328 foundsubscript = False
2330 i = find_token(document.body, '\\begin_inset script', i)
2333 z = find_end_of_inset(document.body, i)
2335 document.warning("Malformed LyX document: Can't find end of script inset.")
2338 blay = find_token(document.body, "\\begin_layout", i, z)
2340 document.warning("Malformed LyX document: Can't find layout in script inset.")
2344 if check_token(document.body[i], "\\begin_inset script subscript"):
2345 subst = '\\textsubscript{'
2346 foundsubscript = True
2347 elif check_token(document.body[i], "\\begin_inset script superscript"):
2348 subst = '\\textsuperscript{'
2350 document.warning("Malformed LyX document: Unknown type of script inset.")
2353 bend = find_end_of_layout(document.body, blay)
2354 if bend == -1 or bend > z:
2355 document.warning("Malformed LyX document: Can't find end of layout in script inset.")
2358 # remove the \end_layout \end_inset pair
2359 document.body[bend:z + 1] = put_cmd_in_ert("}")
2360 document.body[i:blay + 1] = put_cmd_in_ert(subst)
2362 # these classes provide a \textsubscript command:
2363 # FIXME: Would be nice if we could use the information of the .layout file here
2364 classes = ["memoir", "scrartcl", "scrbook", "scrlttr2", "scrreprt"]
2365 if foundsubscript and find_token_exact(classes, document.textclass, 0) == -1:
2366 add_to_preamble(document, ['\\usepackage{subscript}'])
2369 def convert_use_xetex(document):
2370 " convert \\use_xetex to \\use_non_tex_fonts "
2372 i = find_token(document.header, "\\use_xetex", 0)
2376 val = get_value(document.header, "\\use_xetex", 0)
2377 document.header[i] = "\\use_non_tex_fonts " + val
2380 def revert_use_xetex(document):
2381 " revert \\use_non_tex_fonts to \\use_xetex "
2383 i = find_token(document.header, "\\use_non_tex_fonts", 0)
2385 document.warning("Malformed document. No \\use_non_tex_fonts param!")
2388 val = get_value(document.header, "\\use_non_tex_fonts", 0)
2389 document.header[i] = "\\use_xetex " + val
2392 def revert_labeling(document):
2393 koma = ("scrartcl", "scrarticle-beamer", "scrbook", "scrlettr",
2394 "scrlttr2", "scrreprt")
2395 if document.textclass in koma:
2399 i = find_token_exact(document.body, "\\begin_layout Labeling", i)
2402 document.body[i] = "\\begin_layout List"
2405 def revert_langpack(document):
2406 " revert \\language_package parameter "
2408 i = find_token(document.header, "\\language_package", 0)
2410 document.warning("Malformed document. No \\language_package param!")
2413 del document.header[i]
2416 def convert_langpack(document):
2417 " Add \\language_package parameter "
2418 i = find_token(document.header, "\language" , 0)
2420 document.warning("Malformed document. No \\language defined!")
2423 document.header.insert(i + 1, "\\language_package default")
2426 def revert_tabularwidth(document):
2429 i = find_token(document.body, "\\begin_inset Tabular", i)
2432 j = find_end_of_inset(document.body, i)
2434 document.warning("Unable to find end of Tabular inset at line " + str(i))
2438 features = find_token(document.body, "<features", i, j)
2440 document.warning("Can't find any features in Tabular inset at line " + str(i))
2443 if document.body[features].find('alignment="tabularwidth"') != -1:
2444 remove_option(document.body, features, 'tabularwidth')
2446 def revert_html_css_as_file(document):
2447 if not del_token(document.header, '\\html_css_as_file', 0):
2448 document.warning("Malformed LyX document: Missing \\html_css_as_file.")
2455 supported_versions = ["2.0.0","2.0"]
2456 convert = [[346, []],
2462 [352, [convert_splitindex]],
2469 [359, [convert_nomencl_width]],
2479 [369, [convert_author_id]],
2481 [371, [convert_mhchem]],
2483 [373, [merge_gbrief]],
2489 [379, [convert_math_output]],
2499 [389, [convert_html_quotes]],
2503 [393, [convert_optarg]],
2504 [394, [convert_use_makebox]],
2507 [397, [remove_Nameref]],
2509 [399, [convert_mathdots]],
2510 [400, [convert_rule]],
2512 [402, [convert_bibtex_clearpage]],
2513 [403, [convert_flexnames]],
2514 [404, [convert_prettyref]],
2516 [406, [convert_passthru]],
2519 [409, [convert_use_xetex]],
2521 [411, [convert_langpack]],
2526 revert = [[412, [revert_html_css_as_file]],
2527 [411, [revert_tabularwidth]],
2528 [410, [revert_langpack]],
2529 [409, [revert_labeling]],
2530 [408, [revert_use_xetex]],
2531 [407, [revert_script]],
2532 [406, [revert_multirowOffset]],
2533 [405, [revert_passthru]],
2535 [403, [revert_refstyle]],
2536 [402, [revert_flexnames]],
2538 [400, [revert_diagram]],
2539 [399, [revert_rule]],
2540 [398, [revert_mathdots]],
2541 [397, [revert_mathrsfs]],
2543 [395, [revert_nameref]],
2544 [394, [revert_DIN_C_pagesizes]],
2545 [393, [revert_makebox]],
2546 [392, [revert_argument]],
2548 [390, [revert_align_decimal, revert_IEEEtran]],
2549 [389, [revert_output_sync]],
2550 [388, [revert_html_quotes]],
2551 [387, [revert_pagesizes]],
2552 [386, [revert_math_scale]],
2553 [385, [revert_lyx_version]],
2554 [384, [revert_shadedboxcolor]],
2555 [383, [revert_fontcolor]],
2556 [382, [revert_turkmen]],
2557 [381, [revert_notefontcolor]],
2558 [380, [revert_equalspacing_xymatrix]],
2559 [379, [revert_inset_preview]],
2560 [378, [revert_math_output]],
2562 [376, [revert_multirow]],
2563 [375, [revert_includeall]],
2564 [374, [revert_includeonly]],
2565 [373, [revert_html_options]],
2566 [372, [revert_gbrief]],
2567 [371, [revert_fontenc]],
2568 [370, [revert_mhchem]],
2569 [369, [revert_suppress_date]],
2570 [368, [revert_author_id]],
2571 [367, [revert_hspace_glue_lengths]],
2572 [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
2573 [365, [revert_percent_skip_lengths]],
2574 [364, [revert_paragraph_indentation]],
2575 [363, [revert_branch_filename]],
2576 [362, [revert_longtable_align]],
2577 [361, [revert_applemac]],
2579 [359, [revert_nomencl_cwidth]],
2580 [358, [revert_nomencl_width]],
2581 [357, [revert_custom_processors]],
2582 [356, [revert_ulinelatex]],
2584 [354, [revert_strikeout]],
2585 [353, [revert_printindexall]],
2586 [352, [revert_subindex]],
2587 [351, [revert_splitindex]],
2588 [350, [revert_backgroundcolor]],
2589 [349, [revert_outputformat]],
2590 [348, [revert_xetex]],
2591 [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2592 [346, [revert_tabularvalign]],
2593 [345, [revert_swiss]]
2597 if __name__ == "__main__":