1 # -*- coding: utf-8 -*-
2 # This file is part of lyx2lyx
3 # -*- coding: utf-8 -*-
4 # Copyright (C) 2008 José Matos <jamatos@lyx.org>
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, get_value, get_value_string
28 ####################################################################
29 # Private helper functions
31 def remove_option(document, m, option):
32 l = document.body[m].find(option)
34 val = document.body[m][l:].split('"')[1]
35 document.body[m] = document.body[m][:l - 1] + document.body[m][l+len(option + '="' + val + '"'):]
38 def find_end_of_inset(lines, i):
39 " Find end of inset, where lines[i] is included."
40 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
43 def add_to_preamble(document, text):
44 """ Add text to the preamble if it is not already there.
45 Only the first line is checked!"""
47 if not type(text) is list:
50 if find_token(document.preamble, text[0], 0) != -1:
53 document.preamble.extend(text)
56 def insert_to_preamble(index, document, text):
57 """ Insert text to the preamble at a given line"""
59 document.preamble.insert(index, text)
62 def read_unicodesymbols():
63 " Read the unicodesymbols list of unicode characters and corresponding commands."
64 pathname = os.path.abspath(os.path.dirname(sys.argv[0]))
65 fp = open(os.path.join(pathname.strip('lyx2lyx'), 'unicodesymbols'))
67 # Two backslashes, followed by some non-word character, and then a character
68 # in brackets. The idea is to check for constructs like: \"{u}, which is how
69 # they are written in the unicodesymbols file; but they can also be written
70 # as: \"u or even \" u.
71 r = re.compile(r'\\\\(\W)\{(\w)\}')
72 for line in fp.readlines():
73 if line[0] != '#' and line.strip() != "":
74 line=line.replace(' "',' ') # remove all quotation marks with spaces before
75 line=line.replace('" ',' ') # remove all quotation marks with spaces after
76 line=line.replace(r'\"','"') # replace \" by " (for characters with diaeresis)
78 [ucs4,command,dead] = line.split(None,2)
79 if command[0:1] != "\\":
81 spec_chars.append([command, unichr(eval(ucs4))])
87 # If the character is a double-quote, then we need to escape it, too,
88 # since it is done that way in the LyX file.
89 if m.group(1) == "\"":
92 command += m.group(1) + m.group(2)
93 commandbl += m.group(1) + ' ' + m.group(2)
94 spec_chars.append([command, unichr(eval(ucs4))])
95 spec_chars.append([commandbl, unichr(eval(ucs4))])
100 unicode_reps = read_unicodesymbols()
103 # DO NOT USE THIS ROUTINE ANY MORE. Better yet, replace the uses that
104 # have been made of it with uses of put_cmd_in_ert.
105 def old_put_cmd_in_ert(string):
106 for rep in unicode_reps:
107 string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
108 string = string.replace('\\', "\\backslash\n")
109 string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
110 + string + "\n\\end_layout\n\\end_inset"
114 # This routine wraps some content in an ERT inset.
116 # NOTE: The function accepts either a single string or a LIST of strings as
117 # argument. But it returns a LIST of strings, split on \n, so that it does
118 # not have embedded newlines.
120 # This is how lyx2lyx represents a LyX document: as a list of strings,
121 # each representing a line of a LyX file. Embedded newlines confuse
124 # A call to this routine will often go something like this:
125 # i = find_token('\\begin_inset FunkyInset', ...)
127 # j = find_end_of_inset(document.body, i)
128 # content = ...extract content from insets
129 # # that could be as simple as:
130 # # content = lyx2latex(document[i:j + 1])
131 # ert = put_cmd_in_ert(content)
132 # document.body[i:j] = ert
133 # Now, before we continue, we need to reset i appropriately. Normally,
136 # That puts us right after the ERT we just inserted.
138 def put_cmd_in_ert(arg):
139 ret = ["\\begin_inset ERT", "status collapsed", "\\begin_layout Plain Layout", ""]
140 # Despite the warnings just given, it will be faster for us to work
141 # with a single string internally. That way, we only go through the
142 # unicode_reps loop once.
143 if type(arg) is list:
147 for rep in unicode_reps:
148 s = s.replace(rep[1], rep[0].replace('\\\\', '\\'))
149 s = s.replace('\\', "\\backslash\n")
150 ret += s.splitlines()
151 ret += ["\\end_layout", "\\end_inset"]
155 def lyx2latex(document, lines):
156 'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
157 # clean up multiline stuff
163 for curline in range(len(lines)):
164 line = lines[curline]
165 if line.startswith("\\begin_inset Note Note"):
166 # We want to skip LyX notes, so remember where the inset ends
167 note_end = find_end_of_inset(lines, curline + 1)
169 elif note_end >= curline:
172 elif line.startswith("\\begin_inset ERT"):
173 # We don't want to replace things inside ERT, so figure out
174 # where the end of the inset is.
175 ert_end = find_end_of_inset(lines, curline + 1)
177 elif line.startswith("\\begin_inset Formula"):
179 elif line.startswith("\\begin_inset Quotes"):
180 # For now, we do a very basic reversion. Someone who understands
181 # quotes is welcome to fix it up.
182 qtype = line[20:].strip()
196 elif line.startswith("\\begin_inset space"):
197 line = line[18:].strip()
198 if line.startswith("\\hspace"):
199 # Account for both \hspace and \hspace*
202 elif line == "\\space{}":
204 elif line == "\\thinspace{}":
207 # The LyX length is in line[8:], after the \length keyword
208 # latex_length returns "bool,length"
209 length = latex_length(line[8:]).split(",")[1]
210 line = hspace + "{" + length + "}"
212 elif line.isspace() or \
213 line.startswith("\\begin_layout") or \
214 line.startswith("\\end_layout") or \
215 line.startswith("\\begin_inset") or \
216 line.startswith("\\end_inset") or \
217 line.startswith("\\lang") or \
218 line.strip() == "status collapsed" or \
219 line.strip() == "status open":
223 # this needs to be added to the preamble because of cases like
224 # \textmu, \textbackslash, etc.
225 add_to_preamble(document, ['% added by lyx2lyx for converted index entries',
226 '\\@ifundefined{textmu}',
227 ' {\\usepackage{textcomp}}{}'])
228 # a lossless reversion is not possible
229 # try at least to handle some common insets and settings
230 if ert_end >= curline:
231 line = line.replace(r'\backslash', '\\')
233 # No need to add "{}" after single-nonletter macros
234 line = line.replace('&', '\\&')
235 line = line.replace('#', '\\#')
236 line = line.replace('^', '\\textasciicircum{}')
237 line = line.replace('%', '\\%')
238 line = line.replace('_', '\\_')
239 line = line.replace('$', '\\$')
241 # Do the LyX text --> LaTeX conversion
242 for rep in unicode_reps:
243 line = line.replace(rep[1], rep[0] + "{}")
244 line = line.replace(r'\backslash', r'\textbackslash{}')
245 line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
246 line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
247 line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
248 line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
249 line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
250 line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
251 line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
252 line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
253 line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
258 def latex_length(string):
259 'Convert lengths to their LaTeX representation.'
262 # the string has the form
263 # ValueUnit+ValueUnit-ValueUnit or
264 # ValueUnit+-ValueUnit
265 # the + and - (glue lengths) are optional
266 # the + always precedes the -
268 # Convert relative lengths to LaTeX units
269 units = {"text%":"\\textwidth", "col%":"\\columnwidth",
270 "page%":"\\paperwidth", "line%":"\\linewidth",
271 "theight%":"\\textheight", "pheight%":"\\paperheight"}
272 for unit in units.keys():
273 i = string.find(unit)
276 minus = string.rfind("-", 1, i)
277 plus = string.rfind("+", 0, i)
278 latex_unit = units[unit]
279 if plus == -1 and minus == -1:
281 value = str(float(value)/100)
282 end = string[i + len(unit):]
283 string = value + latex_unit + end
285 value = string[plus + 1:i]
286 value = str(float(value)/100)
287 begin = string[:plus + 1]
288 end = string[i+len(unit):]
289 string = begin + value + latex_unit + end
291 value = string[minus + 1:i]
292 value = str(float(value)/100)
293 begin = string[:minus + 1]
294 string = begin + value + latex_unit
296 # replace + and -, but only if the - is not the first character
297 string = string[0] + string[1:].replace("+", " plus ").replace("-", " minus ")
298 # handle the case where "+-1mm" was used, because LaTeX only understands
299 # "plus 1mm minus 1mm"
300 if string.find("plus minus"):
301 lastvaluepos = string.rfind(" ")
302 lastvalue = string[lastvaluepos:]
303 string = string.replace(" ", lastvalue + " ")
305 return "False," + string
307 return "True," + string
310 def revert_flex_inset(document, name, LaTeXname, position):
311 " Convert flex insets to TeX code "
314 i = find_token(document.body, '\\begin_inset Flex ' + name, i)
317 z = find_end_of_inset(document.body, i)
319 document.warning("Malformed LyX document: Can't find end of Flex " + name + " inset.")
321 # remove the \end_inset
322 document.body[z - 2:z + 1] = put_cmd_in_ert("}")
323 # we need to reset character layouts if necessary
324 j = find_token(document.body, '\\emph on', i)
325 k = find_token(document.body, '\\noun on', i)
326 l = find_token(document.body, '\\series', i)
327 m = find_token(document.body, '\\family', i)
328 n = find_token(document.body, '\\shape', i)
329 o = find_token(document.body, '\\color', i)
330 p = find_token(document.body, '\\size', i)
331 q = find_token(document.body, '\\bar under', i)
332 r = find_token(document.body, '\\uuline on', i)
333 s = find_token(document.body, '\\uwave on', i)
334 t = find_token(document.body, '\\strikeout on', i)
335 if j != -1 and j < z:
336 document.body.insert(z - 2, "\\emph default")
337 if k != -1 and k < z:
338 document.body.insert(z - 2, "\\noun default")
339 if l != -1 and l < z:
340 document.body.insert(z - 2, "\\series default")
341 if m != -1 and m < z:
342 document.body.insert(z - 2, "\\family default")
343 if n != -1 and n < z:
344 document.body.insert(z - 2, "\\shape default")
345 if o != -1 and o < z:
346 document.body.insert(z - 2, "\\color inherit")
347 if p != -1 and p < z:
348 document.body.insert(z - 2, "\\size default")
349 if q != -1 and q < z:
350 document.body.insert(z - 2, "\\bar default")
351 if r != -1 and r < z:
352 document.body.insert(z - 2, "\\uuline default")
353 if s != -1 and s < z:
354 document.body.insert(z - 2, "\\uwave default")
355 if t != -1 and t < z:
356 document.body.insert(z - 2, "\\strikeout default")
357 document.body[i:i + 4] = put_cmd_in_ert(LaTeXname + "{")
361 def revert_charstyles(document, name, LaTeXname, changed):
362 " Reverts character styles to TeX code "
365 i = find_token(document.body, name + ' on', i)
368 j = find_token(document.body, name + ' default', i)
369 k = find_token(document.body, name + ' on', i + 1)
370 # if there is no default set, the style ends with the layout
371 # assure hereby that we found the correct layout end
372 if j != -1 and (j < k or k == -1):
373 document.body[j:j + 1] = put_cmd_in_ert("}")
375 j = find_token(document.body, '\\end_layout', i)
376 document.body[j:j] = put_cmd_in_ert("}")
377 document.body[i:i + 1] = put_cmd_in_ert(LaTeXname + "{")
382 def revert_layout_command(document, name, LaTeXname, position):
383 " Reverts a command from a layout to TeX code "
386 i = find_token(document.body, '\\begin_layout ' + name, i)
390 # find the next layout
393 j = find_token(document.body, '\\begin_layout', j)
394 l = len(document.body)
395 # if nothing was found it was the last layout of the document
397 document.body[l - 4:l - 4] = put_cmd_in_ert("}")
399 # exclude plain layout because this can be TeX code or another inset
400 elif document.body[j] != '\\begin_layout Plain Layout':
401 document.body[j - 2:j - 2] = put_cmd_in_ert("}")
405 document.body[i] = '\\begin_layout Standard'
406 document.body[i + 1:i + 1] = put_cmd_in_ert(LaTeXname + "{")
410 ####################################################################
413 def revert_swiss(document):
414 " Set language german-ch to ngerman "
416 if document.language == "german-ch":
417 document.language = "ngerman"
418 i = find_token(document.header, "\\language", 0)
420 document.header[i] = "\\language ngerman"
423 j = find_token(document.body, "\\lang german-ch", j)
426 document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
430 def revert_tabularvalign(document):
431 " Revert the tabular valign option "
434 i = find_token(document.body, "\\begin_inset Tabular", i)
437 j = find_token(document.body, "</cell>", i)
439 document.warning("Malformed LyX document: Could not find end of tabular cell.")
442 # don't set a box for longtables, only delete tabularvalignment
443 # the alignment is 2 lines below \\begin_inset Tabular
444 p = document.body[i + 2].find("islongtable")
446 q = document.body[i + 2].find("tabularvalignment")
448 document.body[i + 2] = document.body[i + 2][:q - 1]
449 document.body[i + 2] = document.body[i + 2] + '>'
454 tabularvalignment = 'c'
455 # which valignment is specified?
456 m = document.body[i + 2].find('tabularvalignment="top"')
458 tabularvalignment = 't'
459 m = document.body[ i+ 2].find('tabularvalignment="bottom"')
461 tabularvalignment = 'b'
462 # delete tabularvalignment
463 q = document.body[i + 2].find("tabularvalignment")
465 document.body[i + 2] = document.body[i + 2][:q - 1]
466 document.body[i + 2] = document.body[i + 2] + '>'
468 # don't add a box when centered
469 if tabularvalignment == 'c':
472 subst = ['\\end_layout', '\\end_inset']
473 document.body[j:j] = subst # just inserts those lines
474 subst = ['\\begin_inset Box Frameless',
475 'position "' + tabularvalignment +'"',
480 # we don't know the width, assume 50%
484 'height_special "totalheight"',
487 '\\begin_layout Plain Layout']
488 document.body[i:i] = subst # this just inserts the array at i
489 i += len(subst) + 2 # adjust i to save a few cycles
492 def revert_phantom(document):
493 " Reverts phantom to ERT "
497 i = find_token(document.body, "\\begin_inset Phantom Phantom", i)
500 substi = document.body[i].replace('\\begin_inset Phantom Phantom', \
501 '\\begin_inset ERT\nstatus collapsed\n\n' \
502 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
503 'phantom{\n\\end_layout\n\n\\end_inset\n')
504 substi = substi.split('\n')
505 document.body[i:i + 4] = substi
507 j = find_token(document.body, "\\end_layout", i)
509 document.warning("Malformed LyX document: Could not find end of Phantom inset.")
511 substj = document.body[j].replace('\\end_layout', \
512 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
513 '\\begin_layout Plain Layout\n\n' \
514 '}\n\\end_layout\n\n\\end_inset\n')
515 substj = substj.split('\n')
516 document.body[j:j + 4] = substj
520 def revert_hphantom(document):
521 " Reverts hphantom to ERT "
525 i = find_token(document.body, "\\begin_inset Phantom HPhantom", i)
528 substi = document.body[i].replace('\\begin_inset Phantom HPhantom', \
529 '\\begin_inset ERT\nstatus collapsed\n\n' \
530 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
531 'hphantom{\n\\end_layout\n\n\\end_inset\n')
532 substi = substi.split('\n')
533 document.body[i:i + 4] = substi
535 j = find_token(document.body, "\\end_layout", i)
537 document.warning("Malformed LyX document: Could not find end of HPhantom inset.")
539 substj = document.body[j].replace('\\end_layout', \
540 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
541 '\\begin_layout Plain Layout\n\n' \
542 '}\n\\end_layout\n\n\\end_inset\n')
543 substj = substj.split('\n')
544 document.body[j:j + 4] = substj
548 def revert_vphantom(document):
549 " Reverts vphantom to ERT "
553 i = find_token(document.body, "\\begin_inset Phantom VPhantom", i)
556 substi = document.body[i].replace('\\begin_inset Phantom VPhantom', \
557 '\\begin_inset ERT\nstatus collapsed\n\n' \
558 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
559 'vphantom{\n\\end_layout\n\n\\end_inset\n')
560 substi = substi.split('\n')
561 document.body[i:i + 4] = substi
563 j = find_token(document.body, "\\end_layout", i)
565 document.warning("Malformed LyX document: Could not find end of VPhantom inset.")
567 substj = document.body[j].replace('\\end_layout', \
568 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
569 '\\begin_layout Plain Layout\n\n' \
570 '}\n\\end_layout\n\n\\end_inset\n')
571 substj = substj.split('\n')
572 document.body[j:j + 4] = substj
576 def revert_xetex(document):
577 " Reverts documents that use XeTeX "
578 i = find_token(document.header, '\\use_xetex', 0)
580 document.warning("Malformed LyX document: Missing \\use_xetex.")
582 if get_value(document.header, "\\use_xetex", i) == 'false':
583 del document.header[i]
585 del document.header[i]
586 # 1.) set doc encoding to utf8-plain
587 i = find_token(document.header, "\\inputencoding", 0)
589 document.warning("Malformed LyX document: Missing \\inputencoding.")
590 document.header[i] = "\\inputencoding utf8-plain"
591 # 2.) check font settings
592 l = find_token(document.header, "\\font_roman", 0)
594 document.warning("Malformed LyX document: Missing \\font_roman.")
595 line = document.header[l]
596 l = re.compile(r'\\font_roman (.*)$')
599 l = find_token(document.header, "\\font_sans", 0)
601 document.warning("Malformed LyX document: Missing \\font_sans.")
602 line = document.header[l]
603 l = re.compile(r'\\font_sans (.*)$')
606 l = find_token(document.header, "\\font_typewriter", 0)
608 document.warning("Malformed LyX document: Missing \\font_typewriter.")
609 line = document.header[l]
610 l = re.compile(r'\\font_typewriter (.*)$')
612 typewriter = m.group(1)
613 osf = get_value(document.header, '\\font_osf', 0) == "true"
614 sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
615 tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
616 # 3.) set preamble stuff
617 pretext = '%% This document must be processed with xelatex!\n'
618 pretext += '\\usepackage{fontspec}\n'
619 if roman != "default":
620 pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
621 if sans != "default":
622 pretext += '\\setsansfont['
624 pretext += 'Scale=' + str(sf_scale / 100) + ','
625 pretext += 'Mapping=tex-text]{' + sans + '}\n'
626 if typewriter != "default":
627 pretext += '\\setmonofont'
629 pretext += '[Scale=' + str(tt_scale / 100) + ']'
630 pretext += '{' + typewriter + '}\n'
632 pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
633 pretext += '\usepackage{xunicode}\n'
634 pretext += '\usepackage{xltxtra}\n'
635 insert_to_preamble(0, document, pretext)
636 # 4.) reset font settings
637 i = find_token(document.header, "\\font_roman", 0)
639 document.warning("Malformed LyX document: Missing \\font_roman.")
640 document.header[i] = "\\font_roman default"
641 i = find_token(document.header, "\\font_sans", 0)
643 document.warning("Malformed LyX document: Missing \\font_sans.")
644 document.header[i] = "\\font_sans default"
645 i = find_token(document.header, "\\font_typewriter", 0)
647 document.warning("Malformed LyX document: Missing \\font_typewriter.")
648 document.header[i] = "\\font_typewriter default"
649 i = find_token(document.header, "\\font_osf", 0)
651 document.warning("Malformed LyX document: Missing \\font_osf.")
652 document.header[i] = "\\font_osf false"
653 i = find_token(document.header, "\\font_sc", 0)
655 document.warning("Malformed LyX document: Missing \\font_sc.")
656 document.header[i] = "\\font_sc false"
657 i = find_token(document.header, "\\font_sf_scale", 0)
659 document.warning("Malformed LyX document: Missing \\font_sf_scale.")
660 document.header[i] = "\\font_sf_scale 100"
661 i = find_token(document.header, "\\font_tt_scale", 0)
663 document.warning("Malformed LyX document: Missing \\font_tt_scale.")
664 document.header[i] = "\\font_tt_scale 100"
667 def revert_outputformat(document):
668 " Remove default output format param "
669 i = find_token(document.header, '\\default_output_format', 0)
671 document.warning("Malformed LyX document: Missing \\default_output_format.")
673 del document.header[i]
676 def revert_backgroundcolor(document):
677 " Reverts background color to preamble code "
681 i = find_token(document.header, "\\backgroundcolor", i)
684 colorcode = get_value(document.header, '\\backgroundcolor', 0)
685 del document.header[i]
686 # don't clutter the preamble if backgroundcolor is not set
687 if colorcode == "#ffffff":
689 # the color code is in the form #rrggbb where every character denotes a hex number
690 # convert the string to an int
691 red = string.atoi(colorcode[1:3],16)
692 # we want the output "0.5" for the value "127" therefore add here
695 redout = float(red) / 256
696 green = string.atoi(colorcode[3:5],16)
699 greenout = float(green) / 256
700 blue = string.atoi(colorcode[5:7],16)
703 blueout = float(blue) / 256
705 insert_to_preamble(0, document,
706 '% Commands inserted by lyx2lyx to set the background color\n'
707 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
708 + '\\definecolor{page_backgroundcolor}{rgb}{'
709 + str(redout) + ', ' + str(greenout)
710 + ', ' + str(blueout) + '}\n'
711 + '\\pagecolor{page_backgroundcolor}\n')
714 def revert_splitindex(document):
715 " Reverts splitindex-aware documents "
716 i = find_token(document.header, '\\use_indices', 0)
718 document.warning("Malformed LyX document: Missing \\use_indices.")
720 indices = get_value(document.header, "\\use_indices", i)
722 if indices == "true":
723 preamble += "\\usepackage{splitidx}\n"
724 del document.header[i]
727 i = find_token(document.header, "\\index", i)
730 k = find_token(document.header, "\\end_index", i)
732 document.warning("Malformed LyX document: Missing \\end_index.")
734 line = document.header[i]
735 l = re.compile(r'\\index (.*)$')
738 ishortcut = get_value(document.header, '\\shortcut', i, k)
739 if ishortcut != "" and indices == "true":
740 preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
741 del document.header[i:k + 1]
744 insert_to_preamble(0, document, preamble)
747 i = find_token(document.body, "\\begin_inset Index", i)
750 line = document.body[i]
751 l = re.compile(r'\\begin_inset Index (.*)$')
754 if itype == "idx" or indices == "false":
755 document.body[i] = "\\begin_inset Index"
757 k = find_end_of_inset(document.body, i)
760 content = lyx2latex(document, document.body[i:k])
762 content = content.replace('"', r'\"')
763 subst = [old_put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")]
764 document.body[i:k + 1] = subst
768 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
771 k = find_end_of_inset(document.body, i)
772 ptype = get_value(document.body, 'type', i, k).strip('"')
774 j = find_token(document.body, "type", i, k)
776 elif indices == "false":
777 del document.body[i:k + 1]
779 subst = [old_put_cmd_in_ert("\\printindex[" + ptype + "]{}")]
780 document.body[i:k + 1] = subst
784 def convert_splitindex(document):
785 " Converts index and printindex insets to splitindex-aware format "
788 i = find_token(document.body, "\\begin_inset Index", i)
791 document.body[i] = document.body[i].replace("\\begin_inset Index",
792 "\\begin_inset Index idx")
796 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
799 if document.body[i + 1].find('LatexCommand printindex') == -1:
800 document.warning("Malformed LyX document: Incomplete printindex inset.")
802 subst = ["LatexCommand printindex",
804 document.body[i + 1:i + 2] = subst
808 def revert_subindex(document):
809 " Reverts \\printsubindex CommandInset types "
810 i = find_token(document.header, '\\use_indices', 0)
812 document.warning("Malformed LyX document: Missing \\use_indices.")
814 indices = get_value(document.header, "\\use_indices", i)
817 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
820 k = find_end_of_inset(document.body, i)
821 ctype = get_value(document.body, 'LatexCommand', i, k)
822 if ctype != "printsubindex":
825 ptype = get_value(document.body, 'type', i, k).strip('"')
826 if indices == "false":
827 del document.body[i:k + 1]
829 subst = [old_put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")]
830 document.body[i:k + 1] = subst
834 def revert_printindexall(document):
835 " Reverts \\print[sub]index* CommandInset types "
836 i = find_token(document.header, '\\use_indices', 0)
838 document.warning("Malformed LyX document: Missing \\use_indices.")
840 indices = get_value(document.header, "\\use_indices", i)
843 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
846 k = find_end_of_inset(document.body, i)
847 ctype = get_value(document.body, 'LatexCommand', i, k)
848 if ctype != "printindex*" and ctype != "printsubindex*":
851 if indices == "false":
852 del document.body[i:k + 1]
854 subst = [old_put_cmd_in_ert("\\" + ctype + "{}")]
855 document.body[i:k + 1] = subst
859 def revert_strikeout(document):
860 " Reverts \\strikeout character style "
862 changed = revert_charstyles(document, "\\uuline", "\\uuline", changed)
863 changed = revert_charstyles(document, "\\uwave", "\\uwave", changed)
864 changed = revert_charstyles(document, "\\strikeout", "\\sout", changed)
866 insert_to_preamble(0, document,
867 '% Commands inserted by lyx2lyx for proper underlining\n'
868 + '\\PassOptionsToPackage{normalem}{ulem}\n'
869 + '\\usepackage{ulem}\n')
872 def revert_ulinelatex(document):
873 " Reverts \\uline character style "
874 i = find_token(document.body, '\\bar under', 0)
877 insert_to_preamble(0, document,
878 '% Commands inserted by lyx2lyx for proper underlining\n'
879 + '\\PassOptionsToPackage{normalem}{ulem}\n'
880 + '\\usepackage{ulem}\n'
881 + '\\let\\cite@rig\\cite\n'
882 + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
883 + ' \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
884 + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
887 def revert_custom_processors(document):
888 " Remove bibtex_command and index_command params "
889 i = find_token(document.header, '\\bibtex_command', 0)
891 document.warning("Malformed LyX document: Missing \\bibtex_command.")
893 del document.header[i]
894 i = find_token(document.header, '\\index_command', 0)
896 document.warning("Malformed LyX document: Missing \\index_command.")
898 del document.header[i]
901 def convert_nomencl_width(document):
902 " Add set_width param to nomencl_print "
905 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
908 document.body.insert(i + 2, "set_width \"none\"")
912 def revert_nomencl_width(document):
913 " Remove set_width param from nomencl_print "
916 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
919 j = find_end_of_inset(document.body, i)
920 l = find_token(document.body, "set_width", i, j)
922 document.warning("Can't find set_width option for nomencl_print!")
929 def revert_nomencl_cwidth(document):
930 " Remove width param from nomencl_print "
933 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
936 j = find_end_of_inset(document.body, i)
937 l = find_token(document.body, "width", i, j)
939 #Can't find width option for nomencl_print
942 width = get_value(document.body, "width", i, j).strip('"')
944 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
945 add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
949 def revert_applemac(document):
950 " Revert applemac encoding to auto "
952 if document.encoding == "applemac":
953 document.encoding = "auto"
954 i = find_token(document.header, "\\encoding", 0)
956 document.header[i] = "\\encoding auto"
959 def revert_longtable_align(document):
960 " Remove longtable alignment setting "
964 i = find_token(document.body, "\\begin_inset Tabular", i)
967 # the alignment is 2 lines below \\begin_inset Tabular
968 j = document.body[i + 2].find("longtabularalignment")
971 document.body[i + 2] = document.body[i + 2][:j - 1]
972 document.body[i + 2] = document.body[i + 2] + '>'
976 def revert_branch_filename(document):
977 " Remove \\filename_suffix parameter from branches "
980 i = find_token(document.header, "\\filename_suffix", i)
983 del document.header[i]
986 def revert_paragraph_indentation(document):
987 " Revert custom paragraph indentation to preamble code "
990 i = find_token(document.header, "\\paragraph_indentation", i)
993 # only remove the preamble line if default
994 # otherwise also write the value to the preamble
995 length = get_value(document.header, "\\paragraph_indentation", i)
996 if length == "default":
997 del document.header[i]
1000 # handle percent lengths
1001 # latex_length returns "bool,length"
1002 length = latex_length(length).split(",")[1]
1003 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1004 add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
1005 del document.header[i]
1009 def revert_percent_skip_lengths(document):
1010 " Revert relative lengths for paragraph skip separation to preamble code "
1013 i = find_token(document.header, "\\defskip", i)
1016 length = get_value(document.header, "\\defskip", i)
1017 # only revert when a custom length was set and when
1018 # it used a percent length
1019 if length not in ('smallskip', 'medskip', 'bigskip'):
1020 # handle percent lengths
1021 length = latex_length(length)
1022 # latex_length returns "bool,length"
1023 percent = length.split(",")[0]
1024 length = length.split(",")[1]
1025 if percent == "True":
1026 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1027 add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
1028 # set defskip to medskip as default
1029 document.header[i] = "\\defskip medskip"
1033 def revert_percent_vspace_lengths(document):
1034 " Revert relative VSpace lengths to ERT "
1037 i = find_token(document.body, "\\begin_inset VSpace", i)
1040 # only revert if a custom length was set and if
1041 # it used a percent length
1042 line = document.body[i]
1043 r = re.compile(r'\\begin_inset VSpace (.*)$')
1046 if length not in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
1047 # check if the space has a star (protected space)
1048 protected = (document.body[i].rfind("*") != -1)
1050 length = length.rstrip('*')
1051 # handle percent lengths
1052 length = latex_length(length)
1053 # latex_length returns "bool,length"
1054 percent = length.split(",")[0]
1055 length = length.split(",")[1]
1056 # revert the VSpace inset to ERT
1057 if percent == "True":
1059 subst = [old_put_cmd_in_ert("\\vspace*{" + length + "}")]
1061 subst = [old_put_cmd_in_ert("\\vspace{" + length + "}")]
1062 document.body[i:i + 2] = subst
1066 def revert_percent_hspace_lengths(document):
1067 " Revert relative HSpace lengths to ERT "
1070 i = find_token(document.body, "\\begin_inset space \\hspace", i)
1073 protected = (document.body[i].find("\\hspace*{}") != -1)
1074 # only revert if a custom length was set and if
1075 # it used a percent length
1076 length = get_value(document.body, '\\length', i + 1)
1078 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1080 # handle percent lengths
1081 length = latex_length(length)
1082 # latex_length returns "bool,length"
1083 percent = length.split(",")[0]
1084 length = length.split(",")[1]
1085 # revert the HSpace inset to ERT
1086 if percent == "True":
1088 subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1090 subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1091 document.body[i:i + 3] = subst
1095 def revert_hspace_glue_lengths(document):
1096 " Revert HSpace glue lengths to ERT "
1099 i = find_token(document.body, "\\begin_inset space \\hspace", i)
1102 protected = (document.body[i].find("\\hspace*{}") != -1)
1103 length = get_value(document.body, '\\length', i + 1)
1105 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1107 # only revert if the length contains a plus or minus at pos != 0
1108 glue = re.compile(r'.+[\+-]')
1109 if glue.search(length):
1110 # handle percent lengths
1111 # latex_length returns "bool,length"
1112 length = latex_length(length).split(",")[1]
1113 # revert the HSpace inset to ERT
1115 subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1117 subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1118 document.body[i:i + 3] = subst
1121 def convert_author_id(document):
1122 " Add the author_id to the \\author definition and make sure 0 is not used"
1126 i = find_token(document.header, "\\author", i)
1130 r = re.compile(r'(\\author) (\".*\")\s?(.*)$')
1131 m = r.match(document.header[i])
1136 if m.lastindex == 3:
1138 document.header[i] = "\\author %i %s %s" % (j, name, email)
1144 k = find_token(document.body, "\\change_", k)
1148 change = document.body[k].split(' ');
1149 if len(change) == 3:
1151 author_id = int(change[1])
1153 document.body[k] = "%s %i %s" % (type, author_id + 1, time)
1156 def revert_author_id(document):
1157 " Remove the author_id from the \\author definition "
1162 i = find_token(document.header, "\\author", i)
1166 r = re.compile(r'(\\author) (\d+) (\".*\")\s?(.*)$')
1167 m = r.match(document.header[i])
1169 author_id = int(m.group(2))
1170 idmap[author_id] = j
1174 if m.lastindex == 4:
1176 document.header[i] = "\\author %s %s" % (name, email)
1182 k = find_token(document.body, "\\change_", k)
1186 change = document.body[k].split(' ');
1187 if len(change) == 3:
1189 author_id = int(change[1])
1191 document.body[k] = "%s %i %s" % (type, idmap[author_id], time)
1195 def revert_suppress_date(document):
1196 " Revert suppressing of default document date to preamble code "
1199 i = find_token(document.header, "\\suppress_date", i)
1202 # remove the preamble line and write to the preamble
1203 # when suppress_date was true
1204 date = get_value(document.header, "\\suppress_date", i)
1206 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1207 add_to_preamble(document, ["\\date{}"])
1208 del document.header[i]
1212 def revert_mhchem(document):
1213 "Revert mhchem loading to preamble code"
1218 i = find_token(document.header, "\\use_mhchem 1", 0)
1222 i = find_token(document.header, "\\use_mhchem 2", 0)
1225 if mhchem == "auto":
1226 j = find_token(document.body, "\\cf{", 0)
1230 j = find_token(document.body, "\\ce{", 0)
1234 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1235 add_to_preamble(document, ["\\PassOptionsToPackage{version=3}{mhchem}"])
1236 add_to_preamble(document, ["\\usepackage{mhchem}"])
1237 k = find_token(document.header, "\\use_mhchem", 0)
1239 document.warning("Malformed LyX document: Could not find mhchem setting.")
1241 del document.header[k]
1244 def revert_fontenc(document):
1245 " Remove fontencoding param "
1246 i = find_token(document.header, '\\fontencoding', 0)
1248 document.warning("Malformed LyX document: Missing \\fontencoding.")
1250 del document.header[i]
1253 def merge_gbrief(document):
1254 " Merge g-brief-en and g-brief-de to one class "
1256 if document.textclass != "g-brief-de":
1257 if document.textclass == "g-brief-en":
1258 document.textclass = "g-brief"
1259 document.set_textclass()
1262 obsoletedby = { "Brieftext": "Letter",
1263 "Unterschrift": "Signature",
1264 "Strasse": "Street",
1265 "Zusatz": "Addition",
1268 "RetourAdresse": "ReturnAddress",
1269 "MeinZeichen": "MyRef",
1270 "IhrZeichen": "YourRef",
1271 "IhrSchreiben": "YourMail",
1274 "Konto": "BankAccount",
1275 "Postvermerk": "PostalComment",
1276 "Adresse": "Address",
1278 "Betreff": "Reference",
1279 "Anrede": "Opening",
1285 i = find_token(document.body, "\\begin_layout", i)
1289 layout = document.body[i][14:]
1290 if layout in obsoletedby:
1291 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1295 document.textclass = "g-brief"
1296 document.set_textclass()
1299 def revert_gbrief(document):
1300 " Revert g-brief to g-brief-en "
1301 if document.textclass == "g-brief":
1302 document.textclass = "g-brief-en"
1303 document.set_textclass()
1306 def revert_html_options(document):
1307 " Remove html options "
1308 i = find_token(document.header, '\\html_use_mathml', 0)
1310 del document.header[i]
1311 i = find_token(document.header, '\\html_be_strict', 0)
1313 del document.header[i]
1316 def revert_includeonly(document):
1319 i = find_token(document.header, "\\begin_includeonly", i)
1322 j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
1324 # this should not happen
1326 document.header[i : j + 1] = []
1329 def revert_includeall(document):
1330 " Remove maintain_unincluded_children param "
1331 i = find_token(document.header, '\\maintain_unincluded_children', 0)
1333 del document.header[i]
1336 def revert_multirow(document):
1337 " Revert multirow cells in tables "
1341 # cell type 3 is multirow begin cell
1342 i = find_token(document.body, '<cell multirow="3"', i)
1345 # a multirow cell was found
1347 # remove the multirow tag, set the valignment to top
1348 # and remove the bottom line
1349 document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
1350 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1351 document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
1352 # write ERT to create the multirow cell
1353 # use 2 rows and 2cm as default with because the multirow span
1354 # and the column width is only hardly accessible
1355 subst = [old_put_cmd_in_ert("\\multirow{2}{2cm}{")]
1356 document.body[i + 4:i + 4] = subst
1357 i = find_token(document.body, "</cell>", i)
1359 document.warning("Malformed LyX document: Could not find end of tabular cell.")
1361 subst = [old_put_cmd_in_ert("}")]
1362 document.body[i - 3:i - 3] = subst
1363 # cell type 4 is multirow part cell
1364 i = find_token(document.body, '<cell multirow="4"', i)
1367 # remove the multirow tag, set the valignment to top
1368 # and remove the top line
1369 document.body[i] = document.body[i].replace(' multirow="4" ', ' ')
1370 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1371 document.body[i] = document.body[i].replace(' topline="true" ', ' ')
1373 if multirow == True:
1374 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1375 add_to_preamble(document, ["\\usepackage{multirow}"])
1378 def convert_math_output(document):
1379 " Convert \html_use_mathml to \html_math_output "
1380 i = find_token(document.header, "\\html_use_mathml", 0)
1383 rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1384 m = rgx.match(document.header[i])
1386 newval = "0" # MathML
1389 newval = "2" # Images
1390 document.header[i] = "\\html_math_output " + newval
1393 def revert_math_output(document):
1394 " Revert \html_math_output to \html_use_mathml "
1395 i = find_token(document.header, "\\html_math_output", 0)
1398 rgx = re.compile(r'\\html_math_output\s+(\d)')
1399 m = rgx.match(document.header[i])
1403 if val == "1" or val == "2":
1406 document.warning("Unable to match " + document.header[i])
1407 document.header[i] = "\\html_use_mathml " + newval
1411 def revert_inset_preview(document):
1412 " Dissolves the preview inset "
1417 i = find_token(document.body, "\\begin_inset Preview", i)
1420 j = find_end_of_inset(document.body, i)
1422 document.warning("Malformed LyX document: Could not find end of Preview inset.")
1424 #If the layout is Standard we need to remove it, otherwise there
1425 #will be paragraph breaks that shouldn't be there.
1426 k = find_token(document.body, "\\begin_layout Standard", i)
1428 del document.body[i:i + 3]
1429 del document.body[j - 5:j - 2]
1432 del document.body[i]
1433 del document.body[j - 1]
1437 def revert_equalspacing_xymatrix(document):
1438 " Revert a Formula with xymatrix@! to an ERT inset "
1441 has_preamble = False
1442 has_equal_spacing = False
1445 i = find_token(document.body, "\\begin_inset Formula", i)
1448 j = find_end_of_inset(document.body, i)
1450 document.warning("Malformed LyX document: Could not find end of Formula inset.")
1453 for curline in range(i,j):
1454 found = document.body[curline].find("\\xymatrix@!")
1459 has_equal_spacing = True
1460 content = [document.body[i][21:]]
1461 content += document.body[i + 1:j]
1462 subst = put_cmd_in_ert(content)
1463 document.body[i:j + 1] = subst
1466 for curline in range(i,j):
1467 l = document.body[curline].find("\\xymatrix")
1469 has_preamble = True;
1472 if has_equal_spacing and not has_preamble:
1473 add_to_preamble(document, ['\\usepackage[all]{xy}'])
1476 def revert_notefontcolor(document):
1477 " Reverts greyed-out note font color to preamble code "
1481 i = find_token(document.header, "\\notefontcolor", i)
1484 colorcode = get_value(document.header, '\\notefontcolor', 0)
1485 del document.header[i]
1486 # the color code is in the form #rrggbb where every character denotes a hex number
1487 # convert the string to an int
1488 red = string.atoi(colorcode[1:3],16)
1489 # we want the output "0.5" for the value "127" therefore increment here
1492 redout = float(red) / 256
1493 green = string.atoi(colorcode[3:5],16)
1496 greenout = float(green) / 256
1497 blue = string.atoi(colorcode[5:7],16)
1500 blueout = float(blue) / 256
1501 # write the preamble
1502 insert_to_preamble(0, document,
1503 '% Commands inserted by lyx2lyx to set the font color\n'
1504 '% for greyed-out notes\n'
1505 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1506 + '\\definecolor{note_fontcolor}{rgb}{'
1507 + str(redout) + ', ' + str(greenout)
1508 + ', ' + str(blueout) + '}\n'
1509 + '\\renewenvironment{lyxgreyedout}\n'
1510 + ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}\n')
1513 def revert_turkmen(document):
1514 "Set language Turkmen to English"
1516 if document.language == "turkmen":
1517 document.language = "english"
1518 i = find_token(document.header, "\\language", 0)
1520 document.header[i] = "\\language english"
1523 j = find_token(document.body, "\\lang turkmen", j)
1526 document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english")
1530 def revert_fontcolor(document):
1531 " Reverts font color to preamble code "
1535 i = find_token(document.header, "\\fontcolor", i)
1538 colorcode = get_value(document.header, '\\fontcolor', 0)
1539 del document.header[i]
1540 # don't clutter the preamble if backgroundcolor is not set
1541 if colorcode == "#000000":
1543 # the color code is in the form #rrggbb where every character denotes a hex number
1544 # convert the string to an int
1545 red = string.atoi(colorcode[1:3],16)
1546 # we want the output "0.5" for the value "127" therefore add here
1549 redout = float(red) / 256
1550 green = string.atoi(colorcode[3:5],16)
1553 greenout = float(green) / 256
1554 blue = string.atoi(colorcode[5:7],16)
1557 blueout = float(blue) / 256
1558 # write the preamble
1559 insert_to_preamble(0, document,
1560 '% Commands inserted by lyx2lyx to set the font color\n'
1561 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1562 + '\\definecolor{document_fontcolor}{rgb}{'
1563 + str(redout) + ', ' + str(greenout)
1564 + ', ' + str(blueout) + '}\n'
1565 + '\\color{document_fontcolor}\n')
1568 def revert_shadedboxcolor(document):
1569 " Reverts shaded box color to preamble code "
1573 i = find_token(document.header, "\\boxbgcolor", i)
1576 colorcode = get_value(document.header, '\\boxbgcolor', 0)
1577 del document.header[i]
1578 # the color code is in the form #rrggbb where every character denotes a hex number
1579 # convert the string to an int
1580 red = string.atoi(colorcode[1:3],16)
1581 # we want the output "0.5" for the value "127" therefore increment here
1584 redout = float(red) / 256
1585 green = string.atoi(colorcode[3:5],16)
1588 greenout = float(green) / 256
1589 blue = string.atoi(colorcode[5:7],16)
1592 blueout = float(blue) / 256
1593 # write the preamble
1594 insert_to_preamble(0, document,
1595 '% Commands inserted by lyx2lyx to set the color\n'
1596 '% of boxes with shaded background\n'
1597 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1598 + '\\definecolor{shadecolor}{rgb}{'
1599 + str(redout) + ', ' + str(greenout)
1600 + ', ' + str(blueout) + '}\n')
1603 def revert_lyx_version(document):
1604 " Reverts LyX Version information from Inset Info "
1605 version = "LyX version"
1607 import lyx2lyx_version
1608 version = lyx2lyx_version.version
1614 i = find_token(document.body, '\\begin_inset Info', i)
1617 j = find_end_of_inset(document.body, i + 1)
1620 document.warning("Malformed LyX document: Could not find end of Info inset.")
1626 # but we shall try to be forgiving.
1628 for k in range(i, j):
1629 if document.body[k].startswith("arg"):
1630 arg = document.body[k][3:].strip().strip('"')
1631 if document.body[k].startswith("type"):
1632 typ = document.body[k][4:].strip().strip('"')
1633 if arg != "version" or typ != "lyxinfo":
1637 # We do not actually know the version of LyX used to produce the document.
1638 # But we can use our version, since we are reverting.
1640 # Now we want to check if the line after "\end_inset" is empty. It normally
1641 # is, so we want to remove it, too.
1643 if document.body[j + 1].strip() == "":
1645 document.body[i: lastline] = s
1649 def revert_math_scale(document):
1650 " Remove math scaling and LaTeX options "
1651 i = find_token(document.header, '\\html_math_img_scale', 0)
1653 del document.header[i]
1654 i = find_token(document.header, '\\html_latex_start', 0)
1656 del document.header[i]
1657 i = find_token(document.header, '\\html_latex_end', 0)
1659 del document.header[i]
1662 def revert_pagesizes(document):
1664 " Revert page sizes to default "
1665 i = find_token(document.header, '\\papersize', 0)
1667 size = document.header[i][11:]
1668 if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1669 or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1670 or size == "b2paper" or size == "b6paper" or size == "b0j" \
1671 or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1672 or size == "b5j" or size == "b6j":
1673 del document.header[i]
1676 def revert_DIN_C_pagesizes(document):
1678 " Revert DIN C page sizes to default "
1679 i = find_token(document.header, '\\papersize', 0)
1681 size = document.header[i][11:]
1682 if size == "c0paper" or size == "c1paper" or size == "c2paper" \
1683 or size == "c3paper" or size == "c4paper" or size == "c5paper" \
1684 or size == "c6paper":
1685 del document.header[i]
1688 def convert_html_quotes(document):
1689 " Remove quotes around html_latex_start and html_latex_end "
1691 i = find_token(document.header, '\\html_latex_start', 0)
1693 line = document.header[i]
1694 l = re.compile(r'\\html_latex_start\s+"(.*)"')
1697 document.header[i] = "\\html_latex_start " + m.group(1)
1699 i = find_token(document.header, '\\html_latex_end', 0)
1701 line = document.header[i]
1702 l = re.compile(r'\\html_latex_end\s+"(.*)"')
1705 document.header[i] = "\\html_latex_end " + m.group(1)
1708 def revert_html_quotes(document):
1709 " Remove quotes around html_latex_start and html_latex_end "
1711 i = find_token(document.header, '\\html_latex_start', 0)
1713 line = document.header[i]
1714 l = re.compile(r'\\html_latex_start\s+(.*)')
1716 document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1718 i = find_token(document.header, '\\html_latex_end', 0)
1720 line = document.header[i]
1721 l = re.compile(r'\\html_latex_end\s+(.*)')
1723 document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1726 def revert_output_sync(document):
1727 " Remove forward search options "
1728 i = find_token(document.header, '\\output_sync_macro', 0)
1730 del document.header[i]
1731 i = find_token(document.header, '\\output_sync', 0)
1733 del document.header[i]
1736 def convert_beamer_args(document):
1737 " Convert ERT arguments in Beamer to InsetArguments "
1739 if document.textclass != "beamer" and document.textclass != "article-beamer":
1742 layouts = ("Block", "ExampleBlock", "AlertBlock")
1743 for layout in layouts:
1746 blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1749 elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1751 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1754 bert = find_token(document.body, '\\begin_inset ERT', blay)
1756 document.warning("Malformed Beamer LyX document: Can't find argument of " + layout + " layout.")
1759 eert = find_end_of_inset(document.body, bert)
1761 document.warning("Malformed LyX document: Can't find end of ERT.")
1765 # So the ERT inset begins at line k and goes to line l. We now wrap it in
1766 # an argument inset.
1767 # Do the end first, so as not to mess up the variables.
1768 document.body[eert + 1:eert + 1] = ['', '\\end_layout', '', '\\end_inset', '']
1769 document.body[bert:bert] = ['\\begin_inset OptArg', 'status open', '',
1770 '\\begin_layout Plain Layout']
1774 def revert_beamer_args(document):
1775 " Revert Beamer arguments to ERT "
1777 if document.textclass != "beamer" and document.textclass != "article-beamer":
1780 layouts = ("Block", "ExampleBlock", "AlertBlock")
1781 for layout in layouts:
1784 blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1787 elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1789 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1792 bopt = find_token(document.body, '\\begin_inset OptArg', blay)
1794 # it is legal not to have one of these
1797 eopt = find_end_of_inset(document.body, bopt)
1799 document.warning("Malformed LyX document: Can't find end of argument.")
1802 bplay = find_token(document.body, '\\begin_layout Plain Layout', blay)
1804 document.warning("Malformed LyX document: Can't find plain layout.")
1807 eplay = find_end_of(document.body, bplay, '\\begin_layout', '\\end_layout')
1809 document.warning("Malformed LyX document: Can't find end of plain layout.")
1812 # So the content of the argument inset goes from bplay + 1 to eplay - 1
1816 document.warning(str(bcont) + " " + str(eplay))
1819 # we convert the content of the argument into pure LaTeX...
1820 content = lyx2latex(document, document.body[bcont:eplay])
1821 strlist = put_cmd_in_ert(["{" + content + "}"])
1823 # now replace the optional argument with the ERT
1824 document.body[bopt:eopt + 1] = strlist
1828 def revert_align_decimal(document):
1831 l = document.body[l].find('alignment=decimal')
1834 remove_option(document, l, 'decimal_point')
1835 document.body[l].replace('decimal', 'center')
1838 def convert_optarg(document):
1839 " Convert \\begin_inset OptArg to \\begin_inset Argument "
1842 i = find_token(document.body, '\\begin_inset OptArg', i)
1845 document.body[i] = "\\begin_inset Argument"
1849 def revert_argument(document):
1850 " Convert \\begin_inset Argument to \\begin_inset OptArg "
1853 i = find_token(document.body, '\\begin_inset Argument', i)
1856 document.body[i] = "\\begin_inset OptArg"
1860 def revert_makebox(document):
1861 " Convert \\makebox to TeX code "
1864 # only revert frameless boxes without an inner box
1865 i = find_token(document.body, '\\begin_inset Box Frameless', i)
1867 # remove the option use_makebox
1868 revert_use_makebox(document)
1870 z = find_end_of_inset(document.body, i)
1872 document.warning("Malformed LyX document: Can't find end of box inset.")
1874 j = find_token(document.body, 'use_makebox 1', i)
1875 # assure we found the makebox of the current box
1876 if j < z and j != -1:
1877 y = find_token(document.body, "\\begin_layout", i)
1878 if y > z or y == -1:
1879 document.warning("Malformed LyX document: Can't find layout in box.")
1881 # remove the \end_layout \end_inset pair
1882 document.body[z - 2:z + 1] = put_cmd_in_ert("}")
1883 # determine the alignment
1884 k = find_token(document.body, 'hor_pos', j - 4)
1885 align = document.body[k][9]
1886 # determine the width
1887 l = find_token(document.body, 'width "', j + 1)
1888 length = document.body[l][7:]
1889 # remove trailing '"'
1890 length = length[:-1]
1891 # latex_length returns "bool,length"
1892 length = latex_length(length).split(",")[1]
1893 subst = "\\makebox[" + length + "][" \
1895 document.body[i:y + 1] = put_cmd_in_ert(subst)
1899 def revert_use_makebox(document):
1900 " Deletes use_makebox option of boxes "
1903 # remove the option use_makebox
1904 h = find_token(document.body, 'use_makebox', 0)
1907 del document.body[h]
1911 def revert_IEEEtran(document):
1912 " Convert IEEEtran layouts and styles to TeX code "
1913 if document.textclass != "IEEEtran":
1916 revert_flex_inset(document, "IEEE membership", "\\IEEEmembership", 0)
1917 revert_flex_inset(document, "Lowercase", "\\MakeLowercase", 0)
1919 layouts = ("Special Paper Notice", "After Title Text", "Publication ID",
1920 "Page headings", "Biography without photo")
1922 latexcmd = {"Special Paper Notice": "\\IEEEspecialpapernotice",
1923 "After Title Text": "\\IEEEaftertitletext",
1924 "Publication ID": "\\IEEEpubid"}
1926 obsoletedby = {"Page headings": "MarkBoth",
1927 "Biography without photo": "BiographyNoPhoto"}
1929 for layout in layouts:
1932 i = find_token(document.body, '\\begin_layout ' + layout, i)
1935 j = find_end_of(document.body, i, '\\begin_layout', '\\end_layout')
1937 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1940 if layout in obsoletedby:
1941 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1944 content = lyx2latex(document, document.body[i:j + 1])
1945 add_to_preamble(document, [latexcmd[layout] + "{" + content + "}"])
1946 del document.body[i:j + 1]
1949 def revert_nameref(document):
1950 " Convert namerefs to regular references "
1951 cmds = ["Nameref", "nameref"]
1953 rx = re.compile(r'reference "(.*)"')
1956 oldcmd = "LatexCommand " + cmd
1958 # It seems better to look for this, as most of the reference
1959 # insets won't be ones we care about.
1960 i = find_token(document.body, oldcmd, i)
1966 # Make sure it is actually in an inset!
1967 # We could just check document.lines[i-1], but that relies
1968 # upon something that might easily change.
1969 # We'll look back a few lines.
1973 stins = find_token(document.body, "\\begin_inset CommandInset ref", stins)
1974 if stins == -1 or stins > cmdloc:
1976 endins = find_end_of_inset(document.body, stins)
1978 document.warning("Can't find end of inset at line " + stins + "!!")
1982 refline = find_token(document.body, "reference", stins)
1983 if refline == -1 or refline > endins:
1984 document.warning("Can't find reference for inset at line " + stinst + "!!")
1986 m = rx.match(document.body[refline])
1988 document.warning("Can't match reference line: " + document.body[ref])
1992 newcontent = ['\\begin_inset ERT', 'status collapsed', '', \
1993 '\\begin_layout Plain Layout', '', '\\backslash', \
1994 cmd + '{' + ref + '}', '\\end_layout', '', '\\end_inset']
1995 document.body[stins:endins + 1] = newcontent
1997 add_to_preamble(document, "\usepackage{nameref}")
2006 supported_versions = ["2.0.0","2.0"]
2007 convert = [[346, []],
2013 [352, [convert_splitindex]],
2020 [359, [convert_nomencl_width]],
2030 [369, [convert_author_id]],
2034 [373, [merge_gbrief]],
2040 [379, [convert_math_output]],
2050 [389, [convert_html_quotes]],
2053 [392, [convert_beamer_args]],
2054 [393, [convert_optarg]],
2060 revert = [[395, [revert_nameref]],
2061 [394, [revert_DIN_C_pagesizes]],
2062 [393, [revert_makebox]],
2063 [392, [revert_argument]],
2064 [391, [revert_beamer_args]],
2065 [390, [revert_align_decimal, revert_IEEEtran]],
2066 [389, [revert_output_sync]],
2067 [388, [revert_html_quotes]],
2068 [387, [revert_pagesizes]],
2069 [386, [revert_math_scale]],
2070 [385, [revert_lyx_version]],
2071 [384, [revert_shadedboxcolor]],
2072 [383, [revert_fontcolor]],
2073 [382, [revert_turkmen]],
2074 [381, [revert_notefontcolor]],
2075 [380, [revert_equalspacing_xymatrix]],
2076 [379, [revert_inset_preview]],
2077 [378, [revert_math_output]],
2079 [376, [revert_multirow]],
2080 [375, [revert_includeall]],
2081 [374, [revert_includeonly]],
2082 [373, [revert_html_options]],
2083 [372, [revert_gbrief]],
2084 [371, [revert_fontenc]],
2085 [370, [revert_mhchem]],
2086 [369, [revert_suppress_date]],
2087 [368, [revert_author_id]],
2088 [367, [revert_hspace_glue_lengths]],
2089 [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
2090 [365, [revert_percent_skip_lengths]],
2091 [364, [revert_paragraph_indentation]],
2092 [363, [revert_branch_filename]],
2093 [362, [revert_longtable_align]],
2094 [361, [revert_applemac]],
2096 [359, [revert_nomencl_cwidth]],
2097 [358, [revert_nomencl_width]],
2098 [357, [revert_custom_processors]],
2099 [356, [revert_ulinelatex]],
2101 [354, [revert_strikeout]],
2102 [353, [revert_printindexall]],
2103 [352, [revert_subindex]],
2104 [351, [revert_splitindex]],
2105 [350, [revert_backgroundcolor]],
2106 [349, [revert_outputformat]],
2107 [348, [revert_xetex]],
2108 [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2109 [346, [revert_tabularvalign]],
2110 [345, [revert_swiss]]
2114 if __name__ == "__main__":