1 # -*- coding: utf-8 -*-
2 # This file is part of lyx2lyx
3 # Copyright (C) 2016 The LyX team
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 """ Convert files to the file format generated by lyx 2.3"""
25 # Uncomment only what you need to import, please.
27 from parser_tools import (del_token, del_value, del_complete_lines,
28 find_complete_lines, find_end_of, find_end_of_layout, find_end_of_inset,
29 find_re, find_substring, find_token, find_token_backwards,
30 get_containing_inset, get_containing_layout, get_bool_value, get_value,
31 get_quoted_value, is_in_inset, set_bool_value)
32 # find_tokens, find_token_exact, check_token, get_option_value
34 from lyx2lyx_tools import (add_to_preamble, put_cmd_in_ert, revert_font_attrs,
35 insert_to_preamble, latex_length, revert_language)
37 ####################################################################
38 # Private helper functions
42 ###############################################################################
44 ### Conversion and reversion routines
46 ###############################################################################
48 def convert_microtype(document):
49 " Add microtype settings. "
50 i = find_token(document.header, "\\font_tt_scale")
51 j = find_token(document.preamble, "\\usepackage{microtype}")
53 document.header.insert(i + 1, "\\use_microtype false")
55 document.header.insert(i + 1, "\\use_microtype true")
56 del document.preamble[j]
57 if j and document.preamble[j-1] == "% Added by lyx2lyx":
58 del document.preamble[j-1]
61 def revert_microtype(document):
62 " Remove microtype settings. "
63 use_microtype = get_bool_value(document.header, "\\use_microtype", delete=True)
65 add_to_preamble(document, ["\\usepackage{microtype}"])
68 def convert_dateinset(document):
69 ' Convert date external inset to ERT '
72 i = find_token(document.body, "\\begin_inset External", i+1)
75 j = find_end_of_inset(document.body, i)
77 document.warning("Malformed lyx document: Missing '\\end_inset' in convert_dateinset.")
79 if get_value(document.body, 'template', i, j) == "Date":
80 document.body[i : j + 1] = put_cmd_in_ert("\\today ")
84 def convert_inputenc(document):
85 """Replace no longer supported input encoding setting."""
86 i = find_token(document.header, "\\inputencoding pt254")
88 document.header[i] = "\\inputencoding pt154"
91 def convert_ibranches(document):
92 ' Add "inverted 0" to branch insets'
95 i = find_token(document.body, "\\begin_inset Branch", i+1)
98 document.body.insert(i + 1, "inverted 0")
101 def revert_ibranches(document):
102 ' Convert inverted branches to explicit anti-branches'
103 # Get list of branches
107 i = find_token(document.header, "\\branch", i+1)
110 branch = document.header[i][8:].strip()
111 selected = get_bool_value(document.header, "\\selected", i+1, i+2)
113 document.warning("Malformed LyX document: No selection indicator "
114 "for branch %s." % branch)
116 # the value tells us whether the branch is selected
117 ourbranches[branch] = selected
119 # Find branch insets, remove "inverted" tag and
120 # convert inverted insets to "Anti-OldBranch" insets
124 i = find_token(document.body, "\\begin_inset Branch", i+1)
127 inverted = get_bool_value(document.body, "inverted", i+1, i+2, delete=True)
129 document.warning("Malformed LyX document: Missing 'inverted' tag in branch inset.")
132 branch = document.body[i][20:].strip()
133 if not branch in antibranches:
134 antibranch = "Anti-" + branch
135 while antibranch in antibranches:
136 antibranch = "x" + antibranch
137 antibranches[branch] = antibranch
139 antibranch = antibranches[branch]
140 document.body[i] = "\\begin_inset Branch " + antibranch
142 # now we need to add the new branches to the header
143 for old, new in antibranches.items():
144 i = find_token(document.header, "\\branch " + old, 0)
146 document.warning("Can't find branch %s even though we found it before!" % (old))
148 j = find_token(document.header, "\\end_branch", i)
150 document.warning("Malformed LyX document! Can't find end of branch " + old)
152 # ourbranches[old] - 1 inverts the selection status of the old branch
153 lines = ["\\branch " + new,
154 "\\selected " + str(ourbranches[old] - 1)]
155 # these are the old lines telling us color, etc.
156 lines += document.header[i+2 : j+1]
157 document.header[i:i] = lines
160 def revert_beamer_article_styles(document):
161 " Include (scr)article styles in beamer article "
163 beamer_articles = ["article-beamer", "scrarticle-beamer"]
164 if document.textclass not in beamer_articles:
167 inclusion = "article.layout"
168 if document.textclass == "scrarticle-beamer":
169 inclusion = "scrartcl.layout"
171 i = find_token(document.header, "\\begin_local_layout", 0)
173 k = find_token(document.header, "\\language", 0)
175 # this should not happen
176 document.warning("Malformed LyX document! No \\language header found!")
178 document.header[k-1 : k-1] = ["\\begin_local_layout", "\\end_local_layout"]
181 j = find_end_of(document.header, i, "\\begin_local_layout", "\\end_local_layout")
183 # this should not happen
184 document.warning("Malformed LyX document: Can't find end of local layout!")
187 document.header[i+1 : i+1] = [
188 "### Inserted by lyx2lyx (more [scr]article styles) ###",
189 "Input " + inclusion,
190 "Input beamer.layout",
191 "Provides geometry 0",
192 "Provides hyperref 0",
201 " \\usepackage{beamerarticle,pgf}",
202 " % this default might be overridden by plain title style",
203 " \\newcommand\makebeamertitle{\\frame{\\maketitle}}%",
204 " \\AtBeginDocument{",
205 " \\let\\origtableofcontents=\\tableofcontents",
206 " \\def\\tableofcontents{\\@ifnextchar[{\\origtableofcontents}{\\gobbletableofcontents}}",
207 " \\def\\gobbletableofcontents#1{\\origtableofcontents}",
210 "### End of insertion by lyx2lyx (more [scr]article styles) ###"
214 def convert_beamer_article_styles(document):
215 " Remove included (scr)article styles in beamer article "
217 beamer_articles = ["article-beamer", "scrarticle-beamer"]
218 if document.textclass not in beamer_articles:
221 i = find_token(document.header, "\\begin_local_layout", 0)
225 j = find_end_of(document.header, i, "\\begin_local_layout", "\\end_local_layout")
227 # this should not happen
228 document.warning("Malformed LyX document: Can't find end of local layout!")
231 k = find_token(document.header, "### Inserted by lyx2lyx (more [scr]article styles) ###", i, j)
233 l = find_token(document.header, "### End of insertion by lyx2lyx (more [scr]article styles) ###", i, j)
235 # this should not happen
236 document.warning("End of lyx2lyx local layout insertion not found!")
239 if k == i + 1 and l == j - 1:
240 # that was all the local layout there was
241 document.header[i : j + 1] = []
243 document.header[k : l + 1] = []
246 def revert_new_babel_languages(document):
247 """Revert "bosnian", "friulan", "macedonian", "piedmontese", "romansh".
249 Set the document language to English but use correct babel setting.
252 nblanguages = ["bosnian", "friulan", "macedonian", "piedmontese", "romansh"]
254 for lang in nblanguages:
255 if lang == "bosnian" or lang == "macedonian":
256 # These are only supported by babel
257 revert_language(document, lang, lang, "")
259 # These are supported by babel and polyglossia
260 revert_language(document, lang, lang, lang)
264 # def convert_new_babel_languages(document)
265 # set to native support if get_value(document.header, "\\options") in
266 # ["bosnian", "friulan", "macedonian", "piedmontese", "romansh"]
267 # and "\\language_package babel".
269 def revert_amharic(document):
270 "Set the document language to English but assure Amharic output"
272 revert_language(document, "amharic", "", "amharic")
275 def revert_asturian(document):
276 "Set the document language to English but assure Asturian output"
278 revert_language(document, "asturian", "", "asturian")
281 def revert_kannada(document):
282 "Set the document language to English but assure Kannada output"
284 revert_language(document, "kannada", "", "kannada")
287 def revert_khmer(document):
288 "Set the document language to English but assure Khmer output"
290 revert_language(document, "khmer", "", "khmer")
293 def revert_urdu(document):
294 "Set the document language to English but assure Urdu output"
296 revert_language(document, "urdu", "", "urdu")
299 def revert_syriac(document):
300 "Set the document language to English but assure Syriac output"
302 revert_language(document, "syriac", "", "syriac")
305 def revert_quotes(document):
306 " Revert Quote Insets in verbatim or Hebrew context to plain quotes "
308 # First handle verbatim insets
311 while i < len(document.body):
312 words = document.body[i].split()
313 if len(words) > 1 and words[0] == "\\begin_inset" and \
314 ( words[1] in ["ERT", "listings"] or ( len(words) > 2 and words[2] in ["URL", "Chunk", "Sweave", "S/R"]) ):
315 j = find_end_of_inset(document.body, i)
318 document.warning("Malformed LyX document: Can't find end of " + words[1] + " inset at line " + str(i))
322 k = find_token(document.body, '\\begin_inset Quotes', i, j)
326 l = find_end_of_inset(document.body, k)
328 document.warning("Malformed LyX document: Can't find end of Quote inset at line " + str(k))
332 if document.body[k].endswith("s"):
334 document.body[k:l+2] = [replace]
339 # Now verbatim layouts
342 while i < len(document.body):
343 words = document.body[i].split()
344 if len(words) > 1 and words[0] == "\\begin_layout" and \
345 words[1] in ["Verbatim", "Verbatim*", "Code", "Author_Email", "Author_URL"]:
346 j = find_end_of_layout(document.body, i)
348 document.warning("Malformed LyX document: Can't find end of " + words[1] + " layout at line " + str(i))
352 k = find_token(document.body, '\\begin_inset Quotes', i, j)
356 l = find_end_of_inset(document.body, k)
358 document.warning("Malformed LyX document: Can't find end of Quote inset at line " + str(k))
362 if document.body[k].endswith("s"):
364 document.body[k:l+2] = [replace]
370 if not document.language == "hebrew" and find_token(document.body, '\\lang hebrew', 0) == -1:
376 k = find_token(document.body, '\\begin_inset Quotes', i)
379 l = find_end_of_inset(document.body, k)
381 document.warning("Malformed LyX document: Can't find end of Quote inset at line " + str(k))
385 parent = get_containing_layout(document.body, k)
386 ql = find_token_backwards(document.body, "\\lang", k)
387 if ql == -1 or ql < parent[1]:
388 hebrew = document.language == "hebrew"
389 elif document.body[ql] == "\\lang hebrew":
393 if document.body[k].endswith("s"):
395 document.body[k:l+2] = [replace]
399 def revert_iopart(document):
400 " Input new styles via local layout "
401 if document.textclass != "iopart":
404 i = find_token(document.header, "\\begin_local_layout", 0)
406 k = find_token(document.header, "\\language", 0)
408 # this should not happen
409 document.warning("Malformed LyX document! No \\language header found!")
411 document.header[k-1 : k-1] = ["\\begin_local_layout", "\\end_local_layout"]
414 j = find_end_of(document.header, i, "\\begin_local_layout", "\\end_local_layout")
416 # this should not happen
417 document.warning("Malformed LyX document! Can't find end of local layout!")
420 document.header[i+1 : i+1] = [
421 "### Inserted by lyx2lyx (stdlayouts) ###",
422 "Input stdlayouts.inc",
423 "### End of insertion by lyx2lyx (stdlayouts) ###"
427 def convert_iopart(document):
428 " Remove local layout we added, if it is there "
429 if document.textclass != "iopart":
432 i = find_token(document.header, "\\begin_local_layout", 0)
436 j = find_end_of(document.header, i, "\\begin_local_layout", "\\end_local_layout")
438 # this should not happen
439 document.warning("Malformed LyX document! Can't find end of local layout!")
442 k = find_token(document.header, "### Inserted by lyx2lyx (stdlayouts) ###", i, j)
444 l = find_token(document.header, "### End of insertion by lyx2lyx (stdlayouts) ###", i, j)
446 # this should not happen
447 document.warning("End of lyx2lyx local layout insertion not found!")
449 if k == i + 1 and l == j - 1:
450 # that was all the local layout there was
451 document.header[i : j + 1] = []
453 document.header[k : l + 1] = []
456 def convert_quotestyle(document):
457 " Convert \\quotes_language to \\quotes_style "
458 i = find_token(document.header, "\\quotes_language", 0)
460 document.warning("Malformed LyX document! Can't find \\quotes_language!")
462 val = get_value(document.header, "\\quotes_language", i)
463 document.header[i] = "\\quotes_style " + val
466 def revert_quotestyle(document):
467 " Revert \\quotes_style to \\quotes_language "
468 i = find_token(document.header, "\\quotes_style", 0)
470 document.warning("Malformed LyX document! Can't find \\quotes_style!")
472 val = get_value(document.header, "\\quotes_style", i)
473 document.header[i] = "\\quotes_language " + val
476 def revert_plainquote(document):
477 " Revert plain quote insets "
479 # First, revert style setting
480 i = find_token(document.header, "\\quotes_style plain", 0)
482 document.header[i] = "\\quotes_style english"
488 k = find_token(document.body, '\\begin_inset Quotes q', i)
491 l = find_end_of_inset(document.body, k)
493 document.warning("Malformed LyX document: Can't find end of Quote inset at line " + str(k))
497 if document.body[k].endswith("s"):
499 document.body[k:l+2] = [replace]
503 def convert_frenchquotes(document):
504 " Convert french quote insets to swiss "
506 # First, revert style setting
507 i = find_token(document.header, "\\quotes_style french", 0)
509 document.header[i] = "\\quotes_style swiss"
514 i = find_token(document.body, '\\begin_inset Quotes f', i)
517 val = get_value(document.body, "\\begin_inset Quotes", i)[7:]
518 newval = val.replace("f", "c", 1)
519 document.body[i] = document.body[i].replace(val, newval)
523 def revert_swissquotes(document):
524 " Revert swiss quote insets to french "
526 # First, revert style setting
527 i = find_token(document.header, "\\quotes_style swiss", 0)
529 document.header[i] = "\\quotes_style french"
534 i = find_token(document.body, '\\begin_inset Quotes c', i)
537 val = get_value(document.body, "\\begin_inset Quotes", i)[7:]
538 newval = val.replace("c", "f", 1)
539 document.body[i] = document.body[i].replace(val, newval)
543 def revert_britishquotes(document):
544 " Revert british quote insets to english "
546 # First, revert style setting
547 i = find_token(document.header, "\\quotes_style british", 0)
549 document.header[i] = "\\quotes_style english"
554 i = find_token(document.body, '\\begin_inset Quotes b', i)
557 val = get_value(document.body, "\\begin_inset Quotes", i)[7:]
558 newval = val.replace("b", "e", 1)
561 newval = newval.replace("d", "s")
564 newval = newval.replace("s", "d")
565 document.body[i] = document.body[i].replace(val, newval)
569 def revert_swedishgquotes(document):
570 " Revert swedish quote insets "
572 # First, revert style setting
573 i = find_token(document.header, "\\quotes_style swedishg", 0)
575 document.header[i] = "\\quotes_style danish"
580 i = find_token(document.body, '\\begin_inset Quotes w', i)
583 val = get_value(document.body, "\\begin_inset Quotes", i)[7:]
586 newval = val.replace("w", "a", 1).replace("r", "l")
589 newval = val.replace("w", "s", 1)
590 document.body[i] = document.body[i].replace(val, newval)
594 def revert_frenchquotes(document):
595 " Revert french inner quote insets "
599 i = find_token(document.body, '\\begin_inset Quotes f', i)
602 val = get_value(document.body, "\\begin_inset Quotes", i)[7:]
605 newval = val.replace("f", "e", 1).replace("s", "d")
606 document.body[i] = document.body[i].replace(val, newval)
610 def revert_frenchinquotes(document):
611 " Revert inner frenchin quote insets "
613 # First, revert style setting
614 i = find_token(document.header, "\\quotes_style frenchin", 0)
616 document.header[i] = "\\quotes_style french"
621 i = find_token(document.body, '\\begin_inset Quotes i', i)
624 val = get_value(document.body, "\\begin_inset Quotes", i)[7:]
625 newval = val.replace("i", "f", 1)
628 newval = newval.replace("s", "d")
629 document.body[i] = document.body[i].replace(val, newval)
633 def revert_russianquotes(document):
634 " Revert russian quote insets "
636 # First, revert style setting
637 i = find_token(document.header, "\\quotes_style russian", 0)
639 document.header[i] = "\\quotes_style french"
644 i = find_token(document.body, '\\begin_inset Quotes r', i)
647 val = get_value(document.body, "\\begin_inset Quotes", i)[7:]
651 newval = val.replace("r", "g", 1).replace("s", "d")
654 newval = val.replace("r", "f", 1)
655 document.body[i] = document.body[i].replace(val, newval)
659 def revert_dynamicquotes(document):
660 " Revert dynamic quote insets "
662 # First, revert header
663 i = find_token(document.header, "\\dynamic_quotes", 0)
665 del document.header[i]
669 i = find_token(document.header, "\\quotes_style", 0)
671 document.warning("Malformed document! Missing \\quotes_style")
673 style = get_value(document.header, "\\quotes_style", i)
676 if style == "english":
678 elif style == "swedish":
680 elif style == "german":
682 elif style == "polish":
684 elif style == "swiss":
686 elif style == "danish":
688 elif style == "plain":
690 elif style == "british":
692 elif style == "swedishg":
694 elif style == "french":
696 elif style == "frenchin":
698 elif style == "russian":
701 # now transform the insets
704 i = find_token(document.body, '\\begin_inset Quotes x', i)
707 document.body[i] = document.body[i].replace("x", s)
711 def revert_cjkquotes(document):
712 " Revert cjk quote insets "
716 i = find_token(document.header, "\\quotes_style", 0)
718 document.warning("Malformed document! Missing \\quotes_style")
720 style = get_value(document.header, "\\quotes_style", i)
722 global_cjk = style.find("cjk") != -1
725 document.header[i] = "\\quotes_style english"
726 # transform dynamic insets
728 if style == "cjkangle":
732 i = find_token(document.body, '\\begin_inset Quotes x', i)
735 document.body[i] = document.body[i].replace("x", s)
738 cjk_langs = ["chinese-simplified", "chinese-traditional", "japanese", "japanese-cjk", "korean"]
743 k = find_token(document.body, '\\begin_inset Quotes j', i)
746 l = find_end_of_inset(document.body, k)
748 document.warning("Malformed LyX document: Can't find end of Quote inset at line " + str(k))
752 parent = get_containing_layout(document.body, k)
753 ql = find_token_backwards(document.body, "\\lang", k)
754 if ql == -1 or ql < parent[1]:
755 cjk = document.language in cjk_langs
756 elif document.body[ql].split()[1] in cjk_langs:
758 val = get_value(document.body, "\\begin_inset Quotes", i)[7:]
765 replace = [u"\u300E"]
767 replace = ["\\begin_inset Formula $\\llceil$", "\\end_inset"]
771 replace = [u"\u300F"]
773 replace = ["\\begin_inset Formula $\\rrfloor$", "\\end_inset"]
779 replace = [u"\u300C"]
781 replace = ["\\begin_inset Formula $\\lceil$", "\\end_inset"]
785 replace = [u"\u300D"]
787 replace = ["\\begin_inset Formula $\\rfloor$", "\\end_inset"]
789 document.body[k:l+1] = replace
795 k = find_token(document.body, '\\begin_inset Quotes k', i)
798 l = find_end_of_inset(document.body, k)
800 document.warning("Malformed LyX document: Can't find end of Quote inset at line " + str(k))
804 parent = get_containing_layout(document.body, k)
805 ql = find_token_backwards(document.body, "\\lang", k)
806 if ql == -1 or ql < parent[1]:
807 cjk = document.language in cjk_langs
808 elif document.body[ql].split()[1] in cjk_langs:
810 val = get_value(document.body, "\\begin_inset Quotes", i)[7:]
817 replace = [u"\u3008"]
819 replace = ["\\begin_inset Formula $\\langle$", "\\end_inset"]
823 replace = [u"\u3009"]
825 replace = ["\\begin_inset Formula $\\rangle$", "\\end_inset"]
831 replace = [u"\u300A"]
833 replace = ["\\begin_inset Formula $\\langle\\kern -2.5pt\\langle$", "\\end_inset"]
837 replace = [u"\u300B"]
839 replace = ["\\begin_inset Formula $\\rangle\\kern -2.5pt\\rangle$", "\\end_inset"]
841 document.body[k:l+1] = replace
845 def convert_crimson(document):
846 """Transform preamble code to native font setting."""
848 i = find_substring(document.preamble, "{cochineal}")
851 # Find and delete user-preamble code:
852 if document.preamble[i] == "\\usepackage[proportional,osf]{cochineal}":
854 elif document.preamble[i] == "\\usepackage{cochineal}":
858 del document.preamble[i]
859 if i and document.preamble[i-1] == "% Added by lyx2lyx":
860 del document.preamble[i-1]
862 # Convert to native font setting:
863 j = find_token(document.header, '\\font_roman')
865 romanfont = ['\font_roman', '"cochineal"', '"default"']
867 romanfont = document.header[j].split()
868 romanfont[1] = '"cochineal"'
869 document.header[j] = " ".join(romanfont)
871 set_bool_value(document.header, '\\font_osf', osf)
872 except ValueError: # no \\font_osf setting in document.header
874 document.header.insert(-1, "\\font_osf true")
877 def revert_crimson(document):
878 " Revert native Cochineal/Crimson font definition to LaTeX "
880 i = find_token(document.header, '\\font_roman "cochineal"')
883 # replace unsupported font setting
884 document.header[i] = document.header[i].replace("cochineal", "default")
885 # no need for preamble code with system fonts
886 if get_bool_value(document.header, "\\use_non_tex_fonts"):
888 # transfer old style figures setting to package options
889 j = find_token(document.header, "\\font_osf true")
891 options = "[proportional,osf]"
892 document.header[j] = "\\font_osf false"
895 add_to_preamble(document, ["\\usepackage%s{cochineal}"%options])
898 def revert_cochinealmath(document):
899 " Revert cochineal newtxmath definitions to LaTeX "
901 if find_token(document.header, "\\use_non_tex_fonts false", 0) != -1:
902 i = find_token(document.header, "\\font_math \"cochineal-ntxm\"", 0)
904 add_to_preamble(document, "\\usepackage[cochineal]{newtxmath}")
905 document.header[i] = document.header[i].replace("cochineal-ntxm", "auto")
908 def revert_labelonly(document):
909 " Revert labelonly tag for InsetRef "
912 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
915 j = find_end_of_inset(document.body, i)
917 document.warning("Can't find end of reference inset at line %d!!" %(i))
920 k = find_token(document.body, "LatexCommand labelonly", i, j)
924 label = get_quoted_value(document.body, "reference", i, j)
926 document.warning("Can't find label for reference at line %d!" %(i))
929 document.body[i:j+1] = put_cmd_in_ert([label])
933 def revert_plural_refs(document):
934 " Revert plural and capitalized references "
935 i = find_token(document.header, "\\use_refstyle 1", 0)
936 use_refstyle = (i != 0)
940 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
943 j = find_end_of_inset(document.body, i)
945 document.warning("Can't find end of reference inset at line %d!!" %(i))
949 plural = caps = suffix = False
950 k = find_token(document.body, "LaTeXCommand formatted", i, j)
951 if k != -1 and use_refstyle:
952 plural = get_bool_value(document.body, "plural", i, j, False)
953 caps = get_bool_value(document.body, "caps", i, j, False)
954 label = get_quoted_value(document.body, "reference", i, j)
957 (prefix, suffix) = label.split(":", 1)
959 document.warning("No `:' separator in formatted reference at line %d!" % (i))
961 document.warning("Can't find label for reference at line %d!" % (i))
963 # this effectively tests also for use_refstyle and a formatted reference
964 # we do this complicated test because we would otherwise do this erasure
965 # over and over and over
966 if not ((plural or caps) and suffix):
967 del_token(document.body, "plural", i, j)
968 del_token(document.body, "caps", i, j - 1) # since we deleted a line
973 prefix = prefix[0].title() + prefix[1:]
974 cmd = "\\" + prefix + "ref"
977 cmd += "{" + suffix + "}"
978 document.body[i:j+1] = put_cmd_in_ert([cmd])
982 def revert_noprefix(document):
983 " Revert labelonly tags with 'noprefix' set "
986 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
989 j = find_end_of_inset(document.body, i)
991 document.warning("Can't find end of reference inset at line %d!!" %(i))
994 k = find_token(document.body, "LatexCommand labelonly", i, j)
997 noprefix = get_bool_value(document.body, "noprefix", i, j)
999 # either it was not a labelonly command, or else noprefix was not set.
1000 # in that case, we just delete the option.
1001 del_token(document.body, "noprefix", i, j)
1004 label = get_quoted_value(document.body, "reference", i, j)
1006 document.warning("Can't find label for reference at line %d!" %(i))
1010 (prefix, suffix) = label.split(":", 1)
1012 document.warning("No `:' separator in formatted reference at line %d!" % (i))
1013 # we'll leave this as an ordinary labelonly reference
1014 del_token(document.body, "noprefix", i, j)
1017 document.body[i:j+1] = put_cmd_in_ert([suffix])
1021 def revert_biblatex(document):
1022 " Revert biblatex support "
1028 # 1. Get cite engine
1030 i = find_token(document.header, "\\cite_engine", 0)
1032 document.warning("Malformed document! Missing \\cite_engine")
1034 engine = get_value(document.header, "\\cite_engine", i)
1036 # 2. Store biblatex state and revert to natbib
1038 if engine in ["biblatex", "biblatex-natbib"]:
1040 document.header[i] = "\\cite_engine natbib"
1042 # 3. Store and remove new document headers
1044 i = find_token(document.header, "\\biblatex_bibstyle", 0)
1046 bibstyle = get_value(document.header, "\\biblatex_bibstyle", i)
1047 del document.header[i]
1050 i = find_token(document.header, "\\biblatex_citestyle", 0)
1052 citestyle = get_value(document.header, "\\biblatex_citestyle", i)
1053 del document.header[i]
1056 i = find_token(document.header, "\\biblio_options", 0)
1058 biblio_options = get_value(document.header, "\\biblio_options", i)
1059 del document.header[i]
1062 bbxopts = "[natbib=true"
1064 bbxopts += ",bibstyle=" + bibstyle
1066 bbxopts += ",citestyle=" + citestyle
1067 if biblio_options != "":
1068 bbxopts += "," + biblio_options
1070 add_to_preamble(document, "\\usepackage" + bbxopts + "{biblatex}")
1080 i = find_token(document.body, "\\begin_inset CommandInset bibtex", i)
1083 j = find_end_of_inset(document.body, i)
1085 document.warning("Can't find end of bibtex inset at line %d!!" %(i))
1088 bibs = get_quoted_value(document.body, "bibfiles", i, j)
1089 opts = get_quoted_value(document.body, "biblatexopts", i, j)
1092 bibresources += bibs.split(",")
1094 document.warning("Can't find bibfiles for bibtex inset at line %d!" %(i))
1095 # remove biblatexopts line
1096 k = find_token(document.body, "biblatexopts", i, j)
1098 del document.body[k]
1099 # Re-find inset end line
1100 j = find_end_of_inset(document.body, i)
1101 # Insert ERT \\printbibliography and wrap bibtex inset to a Note
1103 pcmd = "printbibliography"
1105 pcmd += "[" + opts + "]"
1106 repl = ["\\begin_inset ERT", "status open", "", "\\begin_layout Plain Layout",\
1107 "", "", "\\backslash", pcmd, "\\end_layout", "", "\\end_inset", "", "",\
1108 "\\end_layout", "", "\\begin_layout Standard", "\\begin_inset Note Note",\
1109 "status open", "", "\\begin_layout Plain Layout" ]
1110 repl += document.body[i:j+1]
1111 repl += ["", "\\end_layout", "", "\\end_inset", "", ""]
1112 document.body[i:j+1] = repl
1118 for b in bibresources:
1119 add_to_preamble(document, "\\addbibresource{" + b + ".bib}")
1121 # 2. Citation insets
1123 # Specific citation insets used in biblatex that need to be reverted to ERT
1126 "citebyear" : "citeyear",
1127 "citeyear" : "cite*",
1128 "Footcite" : "Smartcite",
1129 "footcite" : "smartcite",
1130 "Autocite" : "Autocite",
1131 "autocite" : "autocite",
1132 "citetitle" : "citetitle",
1133 "citetitle*" : "citetitle*",
1134 "fullcite" : "fullcite",
1135 "footfullcite" : "footfullcite",
1136 "supercite" : "supercite",
1137 "citeauthor" : "citeauthor",
1138 "citeauthor*" : "citeauthor*",
1139 "Citeauthor" : "Citeauthor",
1140 "Citeauthor*" : "Citeauthor*"
1143 # All commands accepted by LyX < 2.3. Everything else throws an error.
1144 old_citations = ["cite", "nocite", "citet", "citep", "citealt", "citealp",
1145 "citeauthor", "citeyear", "citeyearpar", "citet*", "citep*",
1146 "citealt*", "citealp*", "citeauthor*", "Citet", "Citep",
1147 "Citealt", "Citealp", "Citeauthor", "Citet*", "Citep*",
1148 "Citealt*", "Citealp*", "Citeauthor*", "fullcite", "footcite",
1149 "footcitet", "footcitep", "footcitealt", "footcitealp",
1150 "footciteauthor", "footciteyear", "footciteyearpar",
1151 "citefield", "citetitle", "cite*" ]
1155 i = find_token(document.body, "\\begin_inset CommandInset citation", i)
1158 j = find_end_of_inset(document.body, i)
1160 document.warning("Can't find end of citation inset at line %d!!" %(i))
1163 k = find_token(document.body, "LatexCommand", i, j)
1165 document.warning("Can't find LatexCommand for citation inset at line %d!" %(i))
1168 cmd = get_value(document.body, "LatexCommand", k)
1169 if biblatex and cmd in list(new_citations.keys()):
1170 pre = get_quoted_value(document.body, "before", i, j)
1171 post = get_quoted_value(document.body, "after", i, j)
1172 key = get_quoted_value(document.body, "key", i, j)
1174 document.warning("Citation inset at line %d does not have a key!" %(i))
1176 # Replace known new commands with ERT
1177 res = "\\" + new_citations[cmd]
1179 res += "[" + pre + "]"
1181 res += "[" + post + "]"
1184 res += "{" + key + "}"
1185 document.body[i:j+1] = put_cmd_in_ert([res])
1186 elif cmd not in old_citations:
1187 # Reset unknown commands to cite. This is what LyX does as well
1188 # (but LyX 2.2 would break on unknown commands)
1189 document.body[k] = "LatexCommand cite"
1190 document.warning("Reset unknown cite command '%s' with cite" % cmd)
1193 # Emulate the old biblatex-workaround (pretend natbib in order to use the styles)
1195 i = find_token(document.header, "\\begin_local_layout", 0)
1197 k = find_token(document.header, "\\language", 0)
1199 # this should not happen
1200 document.warning("Malformed LyX document! No \\language header found!")
1202 document.header[k-1 : k-1] = ["\\begin_local_layout", "\\end_local_layout"]
1205 j = find_end_of(document.header, i, "\\begin_local_layout", "\\end_local_layout")
1207 # this should not happen
1208 document.warning("Malformed LyX document! Can't find end of local layout!")
1211 document.header[i+1 : i+1] = [
1212 "### Inserted by lyx2lyx (biblatex emulation) ###",
1213 "Provides natbib 1",
1214 "### End of insertion by lyx2lyx (biblatex emulation) ###"
1218 def revert_citekeyonly(document):
1219 " Revert keyonly cite command to ERT "
1223 i = find_token(document.body, "\\begin_inset CommandInset citation", i)
1226 j = find_end_of_inset(document.body, i)
1228 document.warning("Can't find end of citation inset at line %d!!" %(i))
1231 k = find_token(document.body, "LatexCommand", i, j)
1233 document.warning("Can't find LatexCommand for citation inset at line %d!" %(i))
1236 cmd = get_value(document.body, "LatexCommand", k)
1237 if cmd != "keyonly":
1241 key = get_quoted_value(document.body, "key", i, j)
1243 document.warning("Citation inset at line %d does not have a key!" %(i))
1244 # Replace known new commands with ERT
1245 document.body[i:j+1] = put_cmd_in_ert([key])
1250 def revert_bibpackopts(document):
1251 " Revert support for natbib/jurabib package options "
1254 i = find_token(document.header, "\\cite_engine", 0)
1256 document.warning("Malformed document! Missing \\cite_engine")
1258 engine = get_value(document.header, "\\cite_engine", i)
1261 if engine not in ["natbib", "jurabib"]:
1264 i = find_token(document.header, "\\biblio_options", 0)
1266 # Nothing to do if we have no options
1269 biblio_options = get_value(document.header, "\\biblio_options", i)
1270 del document.header[i]
1272 if not biblio_options:
1273 # Nothing to do for empty options
1276 i = find_token(document.header, "\\begin_local_layout", 0)
1278 k = find_token(document.header, "\\language", 0)
1280 # this should not happen
1281 document.warning("Malformed LyX document! No \\language header found!")
1283 document.header[k-1 : k-1] = ["\\begin_local_layout", "\\end_local_layout"]
1286 j = find_end_of(document.header, i, "\\begin_local_layout", "\\end_local_layout")
1288 # this should not happen
1289 document.warning("Malformed LyX document! Can't find end of local layout!")
1292 document.header[i+1 : i+1] = [
1293 "### Inserted by lyx2lyx (bibliography package options) ###",
1294 "PackageOptions " + engine + " " + biblio_options,
1295 "### End of insertion by lyx2lyx (bibliography package options) ###"
1299 def revert_qualicites(document):
1300 " Revert qualified citation list commands to ERT "
1302 # Citation insets that support qualified lists, with their LaTeX code
1306 "citet" : "textcites",
1307 "Citet" : "Textcites",
1308 "citep" : "parencites",
1309 "Citep" : "Parencites",
1310 "Footcite" : "Smartcites",
1311 "footcite" : "smartcites",
1312 "Autocite" : "Autocites",
1313 "autocite" : "autocites",
1318 i = find_token(document.header, "\\cite_engine", 0)
1320 document.warning("Malformed document! Missing \\cite_engine")
1322 engine = get_value(document.header, "\\cite_engine", i)
1324 biblatex = engine in ["biblatex", "biblatex-natbib"]
1328 i = find_token(document.body, "\\begin_inset CommandInset citation", i)
1331 j = find_end_of_inset(document.body, i)
1333 document.warning("Can't find end of citation inset at line %d!!" %(i))
1336 pres = find_token(document.body, "pretextlist", i, j)
1337 posts = find_token(document.body, "posttextlist", i, j)
1338 if pres == -1 and posts == -1:
1342 pretexts = get_quoted_value(document.body, "pretextlist", pres)
1343 posttexts = get_quoted_value(document.body, "posttextlist", posts)
1344 k = find_token(document.body, "LatexCommand", i, j)
1346 document.warning("Can't find LatexCommand for citation inset at line %d!" %(i))
1349 cmd = get_value(document.body, "LatexCommand", k)
1350 if biblatex and cmd in list(ql_citations.keys()):
1351 pre = get_quoted_value(document.body, "before", i, j)
1352 post = get_quoted_value(document.body, "after", i, j)
1353 key = get_quoted_value(document.body, "key", i, j)
1355 document.warning("Citation inset at line %d does not have a key!" %(i))
1357 keys = key.split(",")
1358 prelist = pretexts.split("\t")
1361 ppp = pp.split(" ", 1)
1362 premap[ppp[0]] = ppp[1]
1363 postlist = posttexts.split("\t")
1366 ppp = pp.split(" ", 1)
1367 postmap[ppp[0]] = ppp[1]
1368 # Replace known new commands with ERT
1369 if "(" in pre or ")" in pre:
1370 pre = "{" + pre + "}"
1371 if "(" in post or ")" in post:
1372 post = "{" + post + "}"
1373 res = "\\" + ql_citations[cmd]
1375 res += "(" + pre + ")"
1377 res += "(" + post + ")"
1381 if premap.get(kk, "") != "":
1382 res += "[" + premap[kk] + "]"
1383 if postmap.get(kk, "") != "":
1384 res += "[" + postmap[kk] + "]"
1385 elif premap.get(kk, "") != "":
1387 res += "{" + kk + "}"
1388 document.body[i:j+1] = put_cmd_in_ert([res])
1390 # just remove the params
1391 del document.body[posttexts]
1392 del document.body[pretexts]
1396 command_insets = ["bibitem", "citation", "href", "index_print", "nomenclature"]
1397 def convert_literalparam(document):
1398 " Add param literal "
1400 pos = len("\\begin_inset CommandInset ")
1403 i = find_token(document.body, '\\begin_inset CommandInset', i)
1406 inset = document.body[i][pos:].strip()
1407 if not inset in command_insets:
1410 j = find_end_of_inset(document.body, i)
1412 document.warning("Malformed LyX document: Can't find end of %s inset at line %d" % (inset, i))
1415 while i < j and document.body[i].strip() != '':
1417 # href is already fully latexified. Here we can switch off literal.
1419 document.body.insert(i, "literal \"false\"")
1421 document.body.insert(i, "literal \"true\"")
1425 def revert_literalparam(document):
1426 " Remove param literal "
1428 for inset in command_insets:
1431 i = find_token(document.body, '\\begin_inset CommandInset %s' % inset, i)
1434 j = find_end_of_inset(document.body, i)
1436 document.warning("Malformed LyX document: Can't find end of %s inset at line %d" % (inset, i))
1439 k = find_token(document.body, 'literal', i, j)
1443 del document.body[k]
1446 def revert_multibib(document):
1447 " Revert multibib support "
1449 # 1. Get cite engine
1451 i = find_token(document.header, "\\cite_engine", 0)
1453 document.warning("Malformed document! Missing \\cite_engine")
1455 engine = get_value(document.header, "\\cite_engine", i)
1457 # 2. Do we use biblatex?
1459 if engine in ["biblatex", "biblatex-natbib"]:
1462 # 3. Store and remove multibib document header
1464 i = find_token(document.header, "\\multibib", 0)
1466 multibib = get_value(document.header, "\\multibib", i)
1467 del document.header[i]
1472 # 4. The easy part: Biblatex
1474 i = find_token(document.header, "\\biblio_options", 0)
1476 k = find_token(document.header, "\\use_bibtopic", 0)
1478 # this should not happen
1479 document.warning("Malformed LyX document! No \\use_bibtopic header found!")
1481 document.header[k-1 : k-1] = ["\\biblio_options " + "refsection=" + multibib]
1483 biblio_options = get_value(document.header, "\\biblio_options", i)
1485 biblio_options += ","
1486 biblio_options += "refsection=" + multibib
1487 document.header[i] = "\\biblio_options " + biblio_options
1492 i = find_token(document.body, "\\begin_inset CommandInset bibtex", i)
1495 j = find_end_of_inset(document.body, i)
1497 document.warning("Can't find end of bibtex inset at line %d!!" %(i))
1500 btprint = get_quoted_value(document.body, "btprint", i, j)
1501 if btprint != "bibbysection":
1504 opts = get_quoted_value(document.body, "biblatexopts", i, j)
1505 # change btprint line
1506 k = find_token(document.body, "btprint", i, j)
1508 document.body[k] = "btprint \"btPrintCited\""
1509 # Insert ERT \\bibbysection and wrap bibtex inset to a Note
1510 pcmd = "bibbysection"
1512 pcmd += "[" + opts + "]"
1513 repl = ["\\begin_inset ERT", "status open", "", "\\begin_layout Plain Layout",\
1514 "", "", "\\backslash", pcmd, "\\end_layout", "", "\\end_inset", "", "",\
1515 "\\end_layout", "", "\\begin_layout Standard", "\\begin_inset Note Note",\
1516 "status open", "", "\\begin_layout Plain Layout" ]
1517 repl += document.body[i:j+1]
1518 repl += ["", "\\end_layout", "", "\\end_inset", "", ""]
1519 document.body[i:j+1] = repl
1525 # 5. More tricky: Bibtex/Bibtopic
1526 k = find_token(document.header, "\\use_bibtopic", 0)
1528 # this should not happen
1529 document.warning("Malformed LyX document! No \\use_bibtopic header found!")
1531 document.header[k] = "\\use_bibtopic true"
1533 # Possible units. This assumes that the LyX name follows the std,
1534 # which might not always be the case. But it's as good as we can get.
1537 "chapter" : "Chapter",
1538 "section" : "Section",
1539 "subsection" : "Subsection",
1542 if multibib not in units.keys():
1543 document.warning("Unknown multibib value `%s'!" % nultibib)
1545 unit = units[multibib]
1549 i = find_token(document.body, "\\begin_layout " + unit, i)
1553 document.body[i-1 : i-1] = ["\\begin_layout Standard",
1554 "\\begin_inset ERT", "status open", "",
1555 "\\begin_layout Plain Layout", "", "",
1557 "end{btUnit}", "\\end_layout",
1558 "\\begin_layout Plain Layout", "",
1561 "\\end_layout", "", "\\end_inset", "", "",
1565 document.body[i-1 : i-1] = ["\\begin_layout Standard",
1566 "\\begin_inset ERT", "status open", "",
1567 "\\begin_layout Plain Layout", "", "",
1570 "\\end_layout", "", "\\end_inset", "", "",
1577 i = find_token(document.body, "\\end_body", i)
1578 document.body[i-1 : i-1] = ["\\begin_layout Standard",
1579 "\\begin_inset ERT", "status open", "",
1580 "\\begin_layout Plain Layout", "", "",
1583 "\\end_layout", "", "\\end_inset", "", "",
1587 def revert_chapterbib(document):
1588 " Revert chapterbib support "
1590 # 1. Get cite engine
1592 i = find_token(document.header, "\\cite_engine", 0)
1594 document.warning("Malformed document! Missing \\cite_engine")
1596 engine = get_value(document.header, "\\cite_engine", i)
1598 # 2. Do we use biblatex?
1600 if engine in ["biblatex", "biblatex-natbib"]:
1603 # 3. Store multibib document header value
1605 i = find_token(document.header, "\\multibib", 0)
1607 multibib = get_value(document.header, "\\multibib", i)
1609 if not multibib or multibib != "child":
1613 # 4. remove multibib header
1614 del document.header[i]
1618 # find include insets
1621 i = find_token(document.body, "\\begin_inset CommandInset include", i)
1624 j = find_end_of_inset(document.body, i)
1626 document.warning("Can't find end of bibtex inset at line %d!!" %(i))
1629 parent = get_containing_layout(document.body, i)
1632 # Insert ERT \\newrefsection before inset
1633 beg = ["\\begin_layout Standard",
1634 "\\begin_inset ERT", "status open", "",
1635 "\\begin_layout Plain Layout", "", "",
1638 "\\end_layout", "", "\\end_inset", "", "",
1640 document.body[parbeg-1:parbeg-1] = beg
1645 # 6. Bibtex/Bibtopic
1646 i = find_token(document.header, "\\use_bibtopic", 0)
1648 # this should not happen
1649 document.warning("Malformed LyX document! No \\use_bibtopic header found!")
1651 if get_value(document.header, "\\use_bibtopic", i) == "true":
1652 # find include insets
1655 i = find_token(document.body, "\\begin_inset CommandInset include", i)
1658 j = find_end_of_inset(document.body, i)
1660 document.warning("Can't find end of bibtex inset at line %d!!" %(i))
1663 parent = get_containing_layout(document.body, i)
1667 # Insert wrap inset into \\begin{btUnit}...\\end{btUnit}
1668 beg = ["\\begin_layout Standard",
1669 "\\begin_inset ERT", "status open", "",
1670 "\\begin_layout Plain Layout", "", "",
1673 "\\end_layout", "", "\\end_inset", "", "",
1675 end = ["\\begin_layout Standard",
1676 "\\begin_inset ERT", "status open", "",
1677 "\\begin_layout Plain Layout", "", "",
1680 "\\end_layout", "", "\\end_inset", "", "",
1682 document.body[parend+1:parend+1] = end
1683 document.body[parbeg-1:parbeg-1] = beg
1684 j += len(beg) + len(end)
1688 # 7. Chapterbib proper
1689 add_to_preamble(document, ["\\usepackage{chapterbib}"])
1692 def convert_dashligatures(document):
1693 """Set 'use_dash_ligatures' according to content.
1695 # Look for and remove dashligatures workaround from 2.3->2.2 reversion,
1696 # set use_dash_ligatures to True if found, to None else.
1697 use_dash_ligatures = del_complete_lines(document.preamble,
1698 ['% Added by lyx2lyx',
1699 r'\renewcommand{\textendash}{--}',
1700 r'\renewcommand{\textemdash}{---}']) or None
1702 if use_dash_ligatures is None:
1703 # Look for dashes (Documents by LyX 2.1 or older have "\twohyphens\n"
1704 # or "\threehyphens\n" as interim representation for -- an ---.)
1705 lines = document.body
1706 has_literal_dashes = has_ligature_dashes = False
1707 dash_pattern = re.compile(u".*[\u2013\u2014]|\\twohyphens|\\threehyphens")
1710 # skip lines without dashes:
1711 i = find_re(lines, dash_pattern, i+1)
1715 # skip label width string (see bug 10243):
1716 if line.startswith("\\labelwidthstring"):
1718 # do not touch hyphens in some insets (cf. lyx_2_2.convert_dashes):
1720 inset_type, start, end = get_containing_inset(lines, i)
1721 except TypeError: # no containing inset
1722 inset_type, start, end = "no inset", -1, -1
1723 if (inset_type.split()[0] in
1724 ["CommandInset", "ERT", "External", "Formula",
1725 "FormulaMacro", "Graphics", "IPA", "listings"]
1726 or inset_type == "Flex Code"):
1730 layoutname, start, end, j = get_containing_layout(lines, i)
1731 except TypeError: # no (or malformed) containing layout
1732 document.warning("Malformed LyX document: "
1733 "Can't find layout at line %d" % i)
1736 document.warning("Malformed LyX document: "
1737 "Missing layout name on line %d"%start)
1738 if layoutname == "LyX-Code":
1742 # literal dash followed by a non-white-character or no-break space:
1743 if re.search(u"[\u2013\u2014]([\S\u00A0\u202F\u2060]|$)",
1744 line, flags=re.UNICODE):
1745 has_literal_dashes = True
1746 # ligature dash followed by non-white-char or no-break space on next line:
1747 if (re.search(r"(\\twohyphens|\\threehyphens)", line) and
1748 re.match(u"[\S\u00A0\u202F\u2060]", lines[i+1], flags=re.UNICODE)):
1749 has_ligature_dashes = True
1750 if has_literal_dashes and has_ligature_dashes:
1751 # TODO: insert a warning note in the document?
1752 document.warning('This document contained both literal and '
1753 '"ligature" dashes.\n Line breaks may have changed. '
1754 'See UserGuide chapter 3.9.1 for details.')
1757 if has_literal_dashes and not has_ligature_dashes:
1758 use_dash_ligatures = False
1759 elif has_ligature_dashes and not has_literal_dashes:
1760 use_dash_ligatures = True
1762 # insert the setting if there is a preferred value
1763 if use_dash_ligatures is True:
1764 document.header.insert(-1, "\\use_dash_ligatures true")
1765 elif use_dash_ligatures is False:
1766 document.header.insert(-1, "\\use_dash_ligatures false")
1769 def revert_dashligatures(document):
1770 """Remove font ligature settings for en- and em-dashes.
1771 Revert conversion of \twodashes or \threedashes to literal dashes.
1773 use_dash_ligatures = del_value(document.header, "\\use_dash_ligatures")
1774 if use_dash_ligatures != "true" or document.backend != "latex":
1777 dash_pattern = re.compile(u".*[\u2013\u2014]")
1779 # skip lines without dashes:
1780 i = find_re(document.body, dash_pattern, i+1)
1783 line = document.body[i]
1784 # skip label width string (see bug 10243):
1785 if line.startswith("\\labelwidthstring"):
1787 # do not touch hyphens in some insets (cf. lyx_2_2.convert_dashes):
1789 inset_type, start, end = get_containing_inset(document.body, i)
1790 except TypeError: # no containing inset
1791 inset_type, start, end = "no inset", -1, -1
1792 if (inset_type.split()[0] in
1793 ["CommandInset", "ERT", "External", "Formula",
1794 "FormulaMacro", "Graphics", "IPA", "listings"]
1795 or inset_type == "Flex Code"):
1799 layoutname, start, end, j = get_containing_layout(document.body, i)
1800 except TypeError: # no (or malformed) containing layout
1801 document.warning("Malformed LyX document: "
1802 "Can't find layout at body line %d" % i)
1804 if layoutname == "LyX-Code":
1807 # TODO: skip replacement in typewriter fonts
1808 line = line.replace(u'\u2013', '\\twohyphens\n')
1809 line = line.replace(u'\u2014', '\\threehyphens\n')
1810 document.body[i:i+1] = line.split('\n')
1811 # redefine the dash LICRs to use ligature dashes:
1812 add_to_preamble(document, [r'\renewcommand{\textendash}{--}',
1813 r'\renewcommand{\textemdash}{---}'])
1816 def revert_noto(document):
1817 " Revert Noto font definitions to LaTeX "
1819 if find_token(document.header, "\\use_non_tex_fonts false", 0) != -1:
1821 i = find_token(document.header, "\\font_roman \"NotoSerif-TLF\"", 0)
1823 add_to_preamble(document, ["\\renewcommand{\\rmdefault}{NotoSerif-TLF}"])
1824 document.header[i] = document.header[i].replace("NotoSerif-TLF", "default")
1825 i = find_token(document.header, "\\font_sans \"NotoSans-TLF\"", 0)
1827 add_to_preamble(document, ["\\renewcommand{\\sfdefault}{NotoSans-TLF}"])
1828 document.header[i] = document.header[i].replace("NotoSans-TLF", "default")
1829 i = find_token(document.header, "\\font_typewriter \"NotoMono-TLF\"", 0)
1831 add_to_preamble(document, ["\\renewcommand{\\ttdefault}{NotoMono-TLF}"])
1832 document.header[i] = document.header[i].replace("NotoMono-TLF", "default")
1835 def revert_xout(document):
1836 " Reverts \\xout font attribute "
1837 changed = revert_font_attrs(document.body, "\\xout", "\\xout")
1839 insert_to_preamble(document, \
1840 ['% for proper cross-out',
1841 '\\PassOptionsToPackage{normalem}{ulem}',
1842 '\\usepackage{ulem}'])
1845 def convert_mathindent(document):
1846 """Add the \\is_math_indent tag.
1848 k = find_token(document.header, "\\quotes_style") # where to insert
1849 # check if the document uses the class option "fleqn"
1850 options = get_value(document.header, "\\options")
1851 if 'fleqn' in options:
1852 document.header.insert(k, "\\is_math_indent 1")
1853 # delete the fleqn option
1854 i = find_token(document.header, "\\options")
1855 options = [option for option in options.split(",")
1856 if option.strip() != "fleqn"]
1858 document.header[i] = "\\options " + ",".join(options)
1860 del document.header[i]
1862 document.header.insert(k, "\\is_math_indent 0")
1864 def revert_mathindent(document):
1865 " Define mathindent if set in the document "
1866 # emulate and delete \math_indentation
1867 value = get_value(document.header, "\\math_indentation",
1868 default="default", delete=True)
1869 if value != "default":
1870 add_to_preamble(document, [r"\setlength{\mathindent}{%s}"%value])
1871 # delete \is_math_indent and emulate via document class option
1872 if not get_bool_value(document.header, "\\is_math_indent", delete=True):
1874 i = find_token(document.header, "\\options")
1876 document.header[i] = document.header[i].replace("\\options ",
1879 l = find_token(document.header, "\\use_default_options")
1880 document.header.insert(l, "\\options fleqn")
1883 def revert_baselineskip(document):
1884 " Revert baselineskips to TeX code "
1887 i = find_substring(document.body, "baselineskip%", i+1)
1890 if document.body[i].startswith("\\begin_inset VSpace"):
1891 # output VSpace inset as TeX code
1892 end = find_end_of_inset(document.body, i)
1894 document.warning("Malformed LyX document: "
1895 "Can't find end of VSpace inset at line %d." % i)
1897 # read out the value
1898 baselineskip = document.body[i].split()[-1]
1899 # check if it is the starred version
1900 star = '*' if '*' in document.body[i] else ''
1901 # now output TeX code
1902 cmd = "\\vspace%s{%s}" %(star, latex_length(baselineskip)[1])
1903 document.body[i:end+1] = put_cmd_in_ert(cmd)
1906 begin, end = is_in_inset(document.body, i, "\\begin_inset space \\hspace")
1908 # output space inset as TeX code
1909 baselineskip = document.body[i].split()[-1]
1910 star = '*' if '*' in document.body[i-1] else ''
1911 cmd = "\\hspace%s{%s}" %(star, latex_length(baselineskip)[1])
1912 document.body[begin:end+1] = put_cmd_in_ert(cmd)
1915 def revert_rotfloat(document):
1916 " Revert placement options for rotated floats "
1921 i = find_token(document.body, "sideways true", i)
1924 if not document.body[i-2].startswith('placement '):
1927 # we found a sideways float with placement options
1928 # at first store the placement
1929 beg = document.body[i-2].rfind(" ");
1930 placement = document.body[i-2][beg+1:]
1931 # check if the option'H' is used
1932 if placement.find("H") != -1:
1933 add_to_preamble(document, ["\\usepackage{float}"])
1934 # now check if it is a starred type
1935 if document.body[i-1].find("wide true") != -1:
1939 # store the float type
1940 beg = document.body[i-3].rfind(" ");
1941 fType = document.body[i-3][beg+1:]
1942 # now output TeX code
1943 endInset = find_end_of_inset(document.body, i-3)
1945 document.warning("Malformed LyX document: Missing '\\end_inset' of Float inset.")
1948 document.body[endInset-2: endInset+1] = put_cmd_in_ert("\\end{sideways" + fType + star + '}')
1949 document.body[i-3: i+2] = put_cmd_in_ert("\\begin{sideways" + fType + star + "}[" + placement + ']')
1950 add_to_preamble(document, ["\\usepackage{rotfloat}"])
1955 allowbreak_emulation = [r"\begin_inset space \hspace{}",
1960 def convert_allowbreak(document):
1961 " Zero widths Space-inset -> \SpecialChar allowbreak. "
1962 lines = document.body
1963 i = find_complete_lines(lines, allowbreak_emulation, 2)
1965 lines[i-1:i+4] = [lines[i-1] + r"\SpecialChar allowbreak"]
1966 i = find_complete_lines(lines, allowbreak_emulation, i+3)
1969 def revert_allowbreak(document):
1970 " \SpecialChar allowbreak -> Zero widths Space-inset. "
1972 lines = document.body
1973 while i < len(lines):
1974 if lines[i].endswith(r"\SpecialChar allowbreak"):
1975 lines[i:i+1] = [lines[i].replace(r"\SpecialChar allowbreak", "")
1976 ] + allowbreak_emulation
1982 def convert_mathnumberpos(document):
1983 " add the \\math_number_before tag "
1984 # check if the document uses the class option "leqno"
1985 i = find_token(document.header, "\\options")
1986 k = find_token(document.header, "\\quotes_style")
1987 if 'leqno' in document.header[i]:
1988 document.header.insert(k, "\\math_number_before 1")
1989 # delete the found option
1990 document.header[i] = document.header[i].replace(",leqno", "")
1991 document.header[i] = document.header[i].replace(", leqno", "")
1992 document.header[i] = document.header[i].replace("leqno,", "")
1993 if 'leqno' in document.header[i]:
1994 # then we have leqno as the only option
1995 del document.header[i]
1997 document.header.insert(k, "\\math_number_before 0")
2000 def revert_mathnumberpos(document):
2001 """Remove \\math_number_before tag,
2002 add the document class option leqno if required.
2004 math_number_before = get_bool_value(document.header,
2005 '\\math_number_before', delete=True)
2006 if math_number_before:
2007 i = find_token(document.header, "\\options")
2008 if i != -1 and 'leqno' not in document.header[i]:
2009 document.header[i] = document.header[i].replace("\\options", "\\options leqno,")
2011 i = find_token(document.header, "\\use_default_options")
2012 document.header.insert(i, "\\options leqno")
2015 def convert_mathnumberingname(document):
2016 " rename the \\math_number_before tag to \\math_numbering_side "
2017 i = find_token(document.header, "\\math_number_before")
2018 math_number_before = get_bool_value(document.header, '\\math_number_before', i)
2019 if math_number_before:
2020 document.header[i] = "\\math_numbering_side left"
2022 # check if the document uses the class option "reqno"
2023 k = find_token(document.header, "\\options")
2024 if 'reqno' in document.header[k]:
2025 document.header[i] = "\\math_numbering_side right"
2026 # delete the found option
2027 document.header[k] = document.header[k].replace(",reqno", "")
2028 document.header[k] = document.header[k].replace(", reqno", "")
2029 document.header[k] = document.header[k].replace("reqno,", "")
2030 if 'reqno' in document.header[k]:
2031 # then we have reqno as the only option
2032 del document.header[k]
2034 document.header[i] = "\\math_numbering_side default"
2037 def revert_mathnumberingname(document):
2038 " rename the \\math_numbering_side tag back to \\math_number_before "
2039 i = find_token(document.header, "\\math_numbering_side")
2040 math_numbering_side = get_value(document.header, '\\math_numbering_side', i)
2041 # rename tag and set boolean value:
2042 if math_numbering_side == "left":
2043 document.header[i] = "\\math_number_before 1"
2044 elif math_numbering_side == "right":
2045 # also add the option reqno:
2046 document.header[i] = "\\math_number_before 0"
2047 k = find_token(document.header, "\\options")
2048 if k != -1 and 'reqno' not in document.header[k]:
2049 document.header[k] = document.header[k].replace("\\options", "\\options reqno,")
2051 l = find_token(document.header, "\\use_default_options", 0)
2052 document.header.insert(l, "\\options reqno")
2054 document.header[i] = "\\math_number_before 0"
2057 def convert_minted(document):
2058 " add the \\use_minted tag "
2059 i = find_token(document.header, "\\index ")
2060 document.header.insert(i, "\\use_minted 0")
2063 def revert_minted(document):
2064 " remove the \\use_minted tag "
2065 del_token(document.header, "\\use_minted")
2068 def revert_longtable_lscape(document):
2069 " revert the longtable landcape mode to ERT "
2071 regexp = re.compile(r'^<features rotate=\"90\"\s.*islongtable=\"true\"\s.*$', re.IGNORECASE)
2073 i = find_re(document.body, regexp, i)
2077 document.body[i] = document.body[i].replace(" rotate=\"90\"", "")
2078 lay = get_containing_layout(document.body, i)
2080 document.warning("Longtable has not layout!")
2083 begcmd = put_cmd_in_ert("\\begin{landscape}")
2084 endcmd = put_cmd_in_ert("\\end{landscape}")
2085 document.body[lay[2] : lay[2]] = endcmd + ["\\end_layout"]
2086 document.body[lay[1] : lay[1]] = ["\\begin_layout " + lay[0], ""] + begcmd
2088 add_to_preamble(document, ["\\usepackage{pdflscape}"])
2096 supported_versions = ["2.3.0", "2.3"]
2098 [509, [convert_microtype]],
2099 [510, [convert_dateinset]],
2100 [511, [convert_ibranches]],
2101 [512, [convert_beamer_article_styles]],
2105 [516, [convert_inputenc]],
2107 [518, [convert_iopart]],
2108 [519, [convert_quotestyle]],
2110 [521, [convert_frenchquotes]],
2113 [524, [convert_crimson]],
2121 [532, [convert_literalparam]],
2124 [535, [convert_dashligatures]],
2127 [538, [convert_mathindent]],
2130 [541, [convert_allowbreak]],
2131 [542, [convert_mathnumberpos]],
2132 [543, [convert_mathnumberingname]],
2133 [544, [convert_minted]]
2137 [543, [revert_minted, revert_longtable_lscape]],
2138 [542, [revert_mathnumberingname]],
2139 [541, [revert_mathnumberpos]],
2140 [540, [revert_allowbreak]],
2141 [539, [revert_rotfloat]],
2142 [538, [revert_baselineskip]],
2143 [537, [revert_mathindent]],
2144 [536, [revert_xout]],
2145 [535, [revert_noto]],
2146 [534, [revert_dashligatures]],
2147 [533, [revert_chapterbib]],
2148 [532, [revert_multibib]],
2149 [531, [revert_literalparam]],
2150 [530, [revert_qualicites]],
2151 [529, [revert_bibpackopts]],
2152 [528, [revert_citekeyonly]],
2153 [527, [revert_biblatex]],
2154 [526, [revert_noprefix]],
2155 [525, [revert_plural_refs]],
2156 [524, [revert_labelonly]],
2157 [523, [revert_crimson, revert_cochinealmath]],
2158 [522, [revert_cjkquotes]],
2159 [521, [revert_dynamicquotes]],
2160 [520, [revert_britishquotes, revert_swedishgquotes, revert_frenchquotes, revert_frenchinquotes, revert_russianquotes, revert_swissquotes]],
2161 [519, [revert_plainquote]],
2162 [518, [revert_quotestyle]],
2163 [517, [revert_iopart]],
2164 [516, [revert_quotes]],
2166 [514, [revert_urdu, revert_syriac]],
2167 [513, [revert_amharic, revert_asturian, revert_kannada, revert_khmer]],
2168 [512, [revert_new_babel_languages]],
2169 [511, [revert_beamer_article_styles]],
2170 [510, [revert_ibranches]],
2172 [508, [revert_microtype]]
2176 if __name__ == "__main__":