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 find_token(document.preamble, text[0], 0) != -1:
50 document.preamble.extend(text)
53 def insert_to_preamble(index, document, text):
54 """ Insert text to the preamble at a given line"""
56 document.preamble.insert(index, text)
59 def read_unicodesymbols():
60 " Read the unicodesymbols list of unicode characters and corresponding commands."
61 pathname = os.path.abspath(os.path.dirname(sys.argv[0]))
62 fp = open(os.path.join(pathname.strip('lyx2lyx'), 'unicodesymbols'))
64 # Two backslashes, followed by some non-word character, and then a character
65 # in brackets. The idea is to check for constructs like: \"{u}, which is how
66 # they are written in the unicodesymbols file; but they can also be written
67 # as: \"u or even \" u.
68 r = re.compile(r'\\\\(\W)\{(\w)\}')
69 for line in fp.readlines():
70 if line[0] != '#' and line.strip() != "":
71 line=line.replace(' "',' ') # remove all quotation marks with spaces before
72 line=line.replace('" ',' ') # remove all quotation marks with spaces after
73 line=line.replace(r'\"','"') # replace \" by " (for characters with diaeresis)
75 [ucs4,command,dead] = line.split(None,2)
76 if command[0:1] != "\\":
78 spec_chars.append([command, unichr(eval(ucs4))])
84 # If the character is a double-quote, then we need to escape it, too,
85 # since it is done that way in the LyX file.
86 if m.group(1) == "\"":
89 command += m.group(1) + m.group(2)
90 commandbl += m.group(1) + ' ' + m.group(2)
91 spec_chars.append([command, unichr(eval(ucs4))])
92 spec_chars.append([commandbl, unichr(eval(ucs4))])
97 unicode_reps = read_unicodesymbols()
100 # DO NOT USE THIS ROUTINE ANY MORE. Better yet, replace the uses that
101 # have been made of it with uses of put_cmd_in_ert.
102 def old_put_cmd_in_ert(string):
103 for rep in unicode_reps:
104 string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
105 string = string.replace('\\', "\\backslash\n")
106 string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
107 + string + "\n\\end_layout\n\\end_inset"
111 # This routine wraps some content in an ERT inset.
113 # NOTE: The function accepts either a single string or a LIST of strings as
114 # argument. But it returns a LIST of strings, split on \n, so that it does
115 # not have embedded newlines.
117 # This is how lyx2lyx represents a LyX document: as a list of strings,
118 # each representing a line of a LyX file. Embedded newlines confuse
121 # A call to this routine will often go something like this:
122 # i = find_token('\\begin_inset FunkyInset', ...)
124 # j = find_end_of_inset(document.body, i)
125 # content = ...extract content from insets
126 # # that could be as simple as:
127 # # content = lyx2latex(document[i:j + 1])
128 # ert = put_cmd_in_ert(content)
129 # document.body[i:j] = ert
130 # Now, before we continue, we need to reset i appropriately. Normally,
133 # That puts us right after the ERT we just inserted.
135 def put_cmd_in_ert(arg):
136 ret = ["\\begin_inset ERT", "status collapsed", "\\begin_layout Plain Layout", ""]
137 # Despite the warnings just given, it will be faster for us to work
138 # with a single string internally. That way, we only go through the
139 # unicode_reps loop once.
140 if type(arg) is list:
144 for rep in unicode_reps:
145 s = s.replace(rep[1], rep[0].replace('\\\\', '\\'))
146 s = s.replace('\\', "\\backslash\n")
147 ret += s.splitlines()
148 ret += ["\\end_layout", "\\end_inset"]
152 def lyx2latex(document, lines):
153 'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
154 # clean up multiline stuff
160 for curline in range(len(lines)):
161 line = lines[curline]
162 if line.startswith("\\begin_inset Note Note"):
163 # We want to skip LyX notes, so remember where the inset ends
164 note_end = find_end_of_inset(lines, curline + 1)
166 elif note_end >= curline:
169 elif line.startswith("\\begin_inset ERT"):
170 # We don't want to replace things inside ERT, so figure out
171 # where the end of the inset is.
172 ert_end = find_end_of_inset(lines, curline + 1)
174 elif line.startswith("\\begin_inset Formula"):
176 elif line.startswith("\\begin_inset Quotes"):
177 # For now, we do a very basic reversion. Someone who understands
178 # quotes is welcome to fix it up.
179 qtype = line[20:].strip()
193 elif line.startswith("\\begin_inset space"):
194 line = line[18:].strip()
195 if line.startswith("\\hspace"):
196 # Account for both \hspace and \hspace*
199 elif line == "\\space{}":
201 elif line == "\\thinspace{}":
204 # The LyX length is in line[8:], after the \length keyword
205 # latex_length returns "bool,length"
206 length = latex_length(line[8:]).split(",")[1]
207 line = hspace + "{" + length + "}"
209 elif line.isspace() or \
210 line.startswith("\\begin_layout") or \
211 line.startswith("\\end_layout") or \
212 line.startswith("\\begin_inset") or \
213 line.startswith("\\end_inset") or \
214 line.startswith("\\lang") or \
215 line.strip() == "status collapsed" or \
216 line.strip() == "status open":
220 # this needs to be added to the preamble because of cases like
221 # \textmu, \textbackslash, etc.
222 add_to_preamble(document, ['% added by lyx2lyx for converted index entries',
223 '\\@ifundefined{textmu}',
224 ' {\\usepackage{textcomp}}{}'])
225 # a lossless reversion is not possible
226 # try at least to handle some common insets and settings
227 if ert_end >= curline:
228 line = line.replace(r'\backslash', '\\')
230 # No need to add "{}" after single-nonletter macros
231 line = line.replace('&', '\\&')
232 line = line.replace('#', '\\#')
233 line = line.replace('^', '\\textasciicircum{}')
234 line = line.replace('%', '\\%')
235 line = line.replace('_', '\\_')
236 line = line.replace('$', '\\$')
238 # Do the LyX text --> LaTeX conversion
239 for rep in unicode_reps:
240 line = line.replace(rep[1], rep[0] + "{}")
241 line = line.replace(r'\backslash', r'\textbackslash{}')
242 line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
243 line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
244 line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
245 line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
246 line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
247 line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
248 line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
249 line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
250 line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
255 def latex_length(string):
256 'Convert lengths to their LaTeX representation.'
259 # the string has the form
260 # ValueUnit+ValueUnit-ValueUnit or
261 # ValueUnit+-ValueUnit
262 # the + and - (glue lengths) are optional
263 # the + always precedes the -
265 # Convert relative lengths to LaTeX units
266 units = {"text%":"\\textwidth", "col%":"\\columnwidth",
267 "page%":"\\paperwidth", "line%":"\\linewidth",
268 "theight%":"\\textheight", "pheight%":"\\paperheight"}
269 for unit in units.keys():
270 i = string.find(unit)
273 minus = string.rfind("-", 1, i)
274 plus = string.rfind("+", 0, i)
275 latex_unit = units[unit]
276 if plus == -1 and minus == -1:
278 value = str(float(value)/100)
279 end = string[i + len(unit):]
280 string = value + latex_unit + end
282 value = string[plus + 1:i]
283 value = str(float(value)/100)
284 begin = string[:plus + 1]
285 end = string[i+len(unit):]
286 string = begin + value + latex_unit + end
288 value = string[minus + 1:i]
289 value = str(float(value)/100)
290 begin = string[:minus + 1]
291 string = begin + value + latex_unit
293 # replace + and -, but only if the - is not the first character
294 string = string[0] + string[1:].replace("+", " plus ").replace("-", " minus ")
295 # handle the case where "+-1mm" was used, because LaTeX only understands
296 # "plus 1mm minus 1mm"
297 if string.find("plus minus"):
298 lastvaluepos = string.rfind(" ")
299 lastvalue = string[lastvaluepos:]
300 string = string.replace(" ", lastvalue + " ")
302 return "False," + string
304 return "True," + string
307 def revert_flex_inset(document, name, LaTeXname, position):
308 " Convert flex insets to TeX code "
311 i = find_token(document.body, '\\begin_inset Flex ' + name, i)
314 z = find_end_of_inset(document.body, i)
316 document.warning("Malformed LyX document: Can't find end of Flex " + name + " inset.")
318 # remove the \end_inset
319 document.body[z - 2:z + 1] = put_cmd_in_ert("}")
320 # we need to reset character layouts if necessary
321 j = find_token(document.body, '\\emph on', i)
322 k = find_token(document.body, '\\noun on', i)
323 l = find_token(document.body, '\\series', i)
324 m = find_token(document.body, '\\family', i)
325 n = find_token(document.body, '\\shape', i)
326 o = find_token(document.body, '\\color', i)
327 p = find_token(document.body, '\\size', i)
328 q = find_token(document.body, '\\bar under', i)
329 r = find_token(document.body, '\\uuline on', i)
330 s = find_token(document.body, '\\uwave on', i)
331 t = find_token(document.body, '\\strikeout on', i)
332 if j != -1 and j < z:
333 document.body.insert(z - 2, "\\emph default")
334 if k != -1 and k < z:
335 document.body.insert(z - 2, "\\noun default")
336 if l != -1 and l < z:
337 document.body.insert(z - 2, "\\series default")
338 if m != -1 and m < z:
339 document.body.insert(z - 2, "\\family default")
340 if n != -1 and n < z:
341 document.body.insert(z - 2, "\\shape default")
342 if o != -1 and o < z:
343 document.body.insert(z - 2, "\\color inherit")
344 if p != -1 and p < z:
345 document.body.insert(z - 2, "\\size default")
346 if q != -1 and q < z:
347 document.body.insert(z - 2, "\\bar default")
348 if r != -1 and r < z:
349 document.body.insert(z - 2, "\\uuline default")
350 if s != -1 and s < z:
351 document.body.insert(z - 2, "\\uwave default")
352 if t != -1 and t < z:
353 document.body.insert(z - 2, "\\strikeout default")
354 document.body[i:i + 4] = put_cmd_in_ert(LaTeXname + "{")
358 def revert_charstyles(document, name, LaTeXname, changed):
359 " Reverts character styles to TeX code "
362 i = find_token(document.body, name + ' on', i)
365 j = find_token(document.body, name + ' default', i)
366 k = find_token(document.body, name + ' on', i + 1)
367 # if there is no default set, the style ends with the layout
368 # assure hereby that we found the correct layout end
369 if j != -1 and (j < k or k == -1):
370 document.body[j:j + 1] = put_cmd_in_ert("}")
372 j = find_token(document.body, '\\end_layout', i)
373 document.body[j:j] = put_cmd_in_ert("}")
374 document.body[i:i + 1] = put_cmd_in_ert(LaTeXname + "{")
379 def revert_layout_command(document, name, LaTeXname, position):
380 " Reverts a command from a layout to TeX code "
383 i = find_token(document.body, '\\begin_layout ' + name, i)
387 # find the next layout
390 j = find_token(document.body, '\\begin_layout', j)
391 l = len(document.body)
392 # if nothing was found it was the last layout of the document
394 document.body[l - 4:l - 4] = put_cmd_in_ert("}")
396 # exclude plain layout because this can be TeX code or another inset
397 elif document.body[j] != '\\begin_layout Plain Layout':
398 document.body[j - 2:j - 2] = put_cmd_in_ert("}")
402 document.body[i] = '\\begin_layout Standard'
403 document.body[i + 1:i + 1] = put_cmd_in_ert(LaTeXname + "{")
407 ####################################################################
410 def revert_swiss(document):
411 " Set language german-ch to ngerman "
413 if document.language == "german-ch":
414 document.language = "ngerman"
415 i = find_token(document.header, "\\language", 0)
417 document.header[i] = "\\language ngerman"
420 j = find_token(document.body, "\\lang german-ch", j)
423 document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
427 def revert_tabularvalign(document):
428 " Revert the tabular valign option "
431 i = find_token(document.body, "\\begin_inset Tabular", i)
434 j = find_token(document.body, "</cell>", i)
436 document.warning("Malformed LyX document: Could not find end of tabular cell.")
439 # don't set a box for longtables, only delete tabularvalignment
440 # the alignment is 2 lines below \\begin_inset Tabular
441 p = document.body[i + 2].find("islongtable")
443 q = document.body[i + 2].find("tabularvalignment")
445 document.body[i + 2] = document.body[i + 2][:q - 1]
446 document.body[i + 2] = document.body[i + 2] + '>'
451 tabularvalignment = 'c'
452 # which valignment is specified?
453 m = document.body[i + 2].find('tabularvalignment="top"')
455 tabularvalignment = 't'
456 m = document.body[ i+ 2].find('tabularvalignment="bottom"')
458 tabularvalignment = 'b'
459 # delete tabularvalignment
460 q = document.body[i + 2].find("tabularvalignment")
462 document.body[i + 2] = document.body[i + 2][:q - 1]
463 document.body[i + 2] = document.body[i + 2] + '>'
465 # don't add a box when centered
466 if tabularvalignment == 'c':
469 subst = ['\\end_layout', '\\end_inset']
470 document.body[j:j] = subst # just inserts those lines
471 subst = ['\\begin_inset Box Frameless',
472 'position "' + tabularvalignment +'"',
477 # we don't know the width, assume 50%
481 'height_special "totalheight"',
484 '\\begin_layout Plain Layout']
485 document.body[i:i] = subst # this just inserts the array at i
486 i += len(subst) + 2 # adjust i to save a few cycles
489 def revert_phantom(document):
490 " Reverts phantom to ERT "
494 i = find_token(document.body, "\\begin_inset Phantom Phantom", i)
497 substi = document.body[i].replace('\\begin_inset Phantom Phantom', \
498 '\\begin_inset ERT\nstatus collapsed\n\n' \
499 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
500 'phantom{\n\\end_layout\n\n\\end_inset\n')
501 substi = substi.split('\n')
502 document.body[i:i + 4] = substi
504 j = find_token(document.body, "\\end_layout", i)
506 document.warning("Malformed LyX document: Could not find end of Phantom inset.")
508 substj = document.body[j].replace('\\end_layout', \
509 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
510 '\\begin_layout Plain Layout\n\n' \
511 '}\n\\end_layout\n\n\\end_inset\n')
512 substj = substj.split('\n')
513 document.body[j:j + 4] = substj
517 def revert_hphantom(document):
518 " Reverts hphantom to ERT "
522 i = find_token(document.body, "\\begin_inset Phantom HPhantom", i)
525 substi = document.body[i].replace('\\begin_inset Phantom HPhantom', \
526 '\\begin_inset ERT\nstatus collapsed\n\n' \
527 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
528 'hphantom{\n\\end_layout\n\n\\end_inset\n')
529 substi = substi.split('\n')
530 document.body[i:i + 4] = substi
532 j = find_token(document.body, "\\end_layout", i)
534 document.warning("Malformed LyX document: Could not find end of HPhantom inset.")
536 substj = document.body[j].replace('\\end_layout', \
537 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
538 '\\begin_layout Plain Layout\n\n' \
539 '}\n\\end_layout\n\n\\end_inset\n')
540 substj = substj.split('\n')
541 document.body[j:j + 4] = substj
545 def revert_vphantom(document):
546 " Reverts vphantom to ERT "
550 i = find_token(document.body, "\\begin_inset Phantom VPhantom", i)
553 substi = document.body[i].replace('\\begin_inset Phantom VPhantom', \
554 '\\begin_inset ERT\nstatus collapsed\n\n' \
555 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
556 'vphantom{\n\\end_layout\n\n\\end_inset\n')
557 substi = substi.split('\n')
558 document.body[i:i + 4] = substi
560 j = find_token(document.body, "\\end_layout", i)
562 document.warning("Malformed LyX document: Could not find end of VPhantom inset.")
564 substj = document.body[j].replace('\\end_layout', \
565 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
566 '\\begin_layout Plain Layout\n\n' \
567 '}\n\\end_layout\n\n\\end_inset\n')
568 substj = substj.split('\n')
569 document.body[j:j + 4] = substj
573 def revert_xetex(document):
574 " Reverts documents that use XeTeX "
575 i = find_token(document.header, '\\use_xetex', 0)
577 document.warning("Malformed LyX document: Missing \\use_xetex.")
579 if get_value(document.header, "\\use_xetex", i) == 'false':
580 del document.header[i]
582 del document.header[i]
583 # 1.) set doc encoding to utf8-plain
584 i = find_token(document.header, "\\inputencoding", 0)
586 document.warning("Malformed LyX document: Missing \\inputencoding.")
587 document.header[i] = "\\inputencoding utf8-plain"
588 # 2.) check font settings
589 l = find_token(document.header, "\\font_roman", 0)
591 document.warning("Malformed LyX document: Missing \\font_roman.")
592 line = document.header[l]
593 l = re.compile(r'\\font_roman (.*)$')
596 l = find_token(document.header, "\\font_sans", 0)
598 document.warning("Malformed LyX document: Missing \\font_sans.")
599 line = document.header[l]
600 l = re.compile(r'\\font_sans (.*)$')
603 l = find_token(document.header, "\\font_typewriter", 0)
605 document.warning("Malformed LyX document: Missing \\font_typewriter.")
606 line = document.header[l]
607 l = re.compile(r'\\font_typewriter (.*)$')
609 typewriter = m.group(1)
610 osf = get_value(document.header, '\\font_osf', 0) == "true"
611 sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
612 tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
613 # 3.) set preamble stuff
614 pretext = '%% This document must be processed with xelatex!\n'
615 pretext += '\\usepackage{fontspec}\n'
616 if roman != "default":
617 pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
618 if sans != "default":
619 pretext += '\\setsansfont['
621 pretext += 'Scale=' + str(sf_scale / 100) + ','
622 pretext += 'Mapping=tex-text]{' + sans + '}\n'
623 if typewriter != "default":
624 pretext += '\\setmonofont'
626 pretext += '[Scale=' + str(tt_scale / 100) + ']'
627 pretext += '{' + typewriter + '}\n'
629 pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
630 pretext += '\usepackage{xunicode}\n'
631 pretext += '\usepackage{xltxtra}\n'
632 insert_to_preamble(0, document, pretext)
633 # 4.) reset font settings
634 i = find_token(document.header, "\\font_roman", 0)
636 document.warning("Malformed LyX document: Missing \\font_roman.")
637 document.header[i] = "\\font_roman default"
638 i = find_token(document.header, "\\font_sans", 0)
640 document.warning("Malformed LyX document: Missing \\font_sans.")
641 document.header[i] = "\\font_sans default"
642 i = find_token(document.header, "\\font_typewriter", 0)
644 document.warning("Malformed LyX document: Missing \\font_typewriter.")
645 document.header[i] = "\\font_typewriter default"
646 i = find_token(document.header, "\\font_osf", 0)
648 document.warning("Malformed LyX document: Missing \\font_osf.")
649 document.header[i] = "\\font_osf false"
650 i = find_token(document.header, "\\font_sc", 0)
652 document.warning("Malformed LyX document: Missing \\font_sc.")
653 document.header[i] = "\\font_sc false"
654 i = find_token(document.header, "\\font_sf_scale", 0)
656 document.warning("Malformed LyX document: Missing \\font_sf_scale.")
657 document.header[i] = "\\font_sf_scale 100"
658 i = find_token(document.header, "\\font_tt_scale", 0)
660 document.warning("Malformed LyX document: Missing \\font_tt_scale.")
661 document.header[i] = "\\font_tt_scale 100"
664 def revert_outputformat(document):
665 " Remove default output format param "
666 i = find_token(document.header, '\\default_output_format', 0)
668 document.warning("Malformed LyX document: Missing \\default_output_format.")
670 del document.header[i]
673 def revert_backgroundcolor(document):
674 " Reverts background color to preamble code "
678 i = find_token(document.header, "\\backgroundcolor", i)
681 colorcode = get_value(document.header, '\\backgroundcolor', 0)
682 del document.header[i]
683 # don't clutter the preamble if backgroundcolor is not set
684 if colorcode == "#ffffff":
686 # the color code is in the form #rrggbb where every character denotes a hex number
687 # convert the string to an int
688 red = string.atoi(colorcode[1:3],16)
689 # we want the output "0.5" for the value "127" therefore add here
692 redout = float(red) / 256
693 green = string.atoi(colorcode[3:5],16)
696 greenout = float(green) / 256
697 blue = string.atoi(colorcode[5:7],16)
700 blueout = float(blue) / 256
702 insert_to_preamble(0, document,
703 '% Commands inserted by lyx2lyx to set the background color\n'
704 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
705 + '\\definecolor{page_backgroundcolor}{rgb}{'
706 + str(redout) + ', ' + str(greenout)
707 + ', ' + str(blueout) + '}\n'
708 + '\\pagecolor{page_backgroundcolor}\n')
711 def revert_splitindex(document):
712 " Reverts splitindex-aware documents "
713 i = find_token(document.header, '\\use_indices', 0)
715 document.warning("Malformed LyX document: Missing \\use_indices.")
717 indices = get_value(document.header, "\\use_indices", i)
719 if indices == "true":
720 preamble += "\\usepackage{splitidx}\n"
721 del document.header[i]
724 i = find_token(document.header, "\\index", i)
727 k = find_token(document.header, "\\end_index", i)
729 document.warning("Malformed LyX document: Missing \\end_index.")
731 line = document.header[i]
732 l = re.compile(r'\\index (.*)$')
735 ishortcut = get_value(document.header, '\\shortcut', i, k)
736 if ishortcut != "" and indices == "true":
737 preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
738 del document.header[i:k + 1]
741 insert_to_preamble(0, document, preamble)
744 i = find_token(document.body, "\\begin_inset Index", i)
747 line = document.body[i]
748 l = re.compile(r'\\begin_inset Index (.*)$')
751 if itype == "idx" or indices == "false":
752 document.body[i] = "\\begin_inset Index"
754 k = find_end_of_inset(document.body, i)
757 content = lyx2latex(document, document.body[i:k])
759 content = content.replace('"', r'\"')
760 subst = [old_put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")]
761 document.body[i:k + 1] = subst
765 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
768 k = find_end_of_inset(document.body, i)
769 ptype = get_value(document.body, 'type', i, k).strip('"')
771 j = find_token(document.body, "type", i, k)
773 elif indices == "false":
774 del document.body[i:k + 1]
776 subst = [old_put_cmd_in_ert("\\printindex[" + ptype + "]{}")]
777 document.body[i:k + 1] = subst
781 def convert_splitindex(document):
782 " Converts index and printindex insets to splitindex-aware format "
785 i = find_token(document.body, "\\begin_inset Index", i)
788 document.body[i] = document.body[i].replace("\\begin_inset Index",
789 "\\begin_inset Index idx")
793 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
796 if document.body[i + 1].find('LatexCommand printindex') == -1:
797 document.warning("Malformed LyX document: Incomplete printindex inset.")
799 subst = ["LatexCommand printindex",
801 document.body[i + 1:i + 2] = subst
805 def revert_subindex(document):
806 " Reverts \\printsubindex CommandInset types "
807 i = find_token(document.header, '\\use_indices', 0)
809 document.warning("Malformed LyX document: Missing \\use_indices.")
811 indices = get_value(document.header, "\\use_indices", i)
814 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
817 k = find_end_of_inset(document.body, i)
818 ctype = get_value(document.body, 'LatexCommand', i, k)
819 if ctype != "printsubindex":
822 ptype = get_value(document.body, 'type', i, k).strip('"')
823 if indices == "false":
824 del document.body[i:k + 1]
826 subst = [old_put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")]
827 document.body[i:k + 1] = subst
831 def revert_printindexall(document):
832 " Reverts \\print[sub]index* CommandInset types "
833 i = find_token(document.header, '\\use_indices', 0)
835 document.warning("Malformed LyX document: Missing \\use_indices.")
837 indices = get_value(document.header, "\\use_indices", i)
840 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
843 k = find_end_of_inset(document.body, i)
844 ctype = get_value(document.body, 'LatexCommand', i, k)
845 if ctype != "printindex*" and ctype != "printsubindex*":
848 if indices == "false":
849 del document.body[i:k + 1]
851 subst = [old_put_cmd_in_ert("\\" + ctype + "{}")]
852 document.body[i:k + 1] = subst
856 def revert_strikeout(document):
857 " Reverts \\strikeout character style "
859 changed = revert_charstyles(document, "\\uuline", "\\uuline", changed)
860 changed = revert_charstyles(document, "\\uwave", "\\uwave", changed)
861 changed = revert_charstyles(document, "\\strikeout", "\\sout", changed)
863 insert_to_preamble(0, document,
864 '% Commands inserted by lyx2lyx for proper underlining\n'
865 + '\\PassOptionsToPackage{normalem}{ulem}\n'
866 + '\\usepackage{ulem}\n')
869 def revert_ulinelatex(document):
870 " Reverts \\uline character style "
871 i = find_token(document.body, '\\bar under', 0)
874 insert_to_preamble(0, document,
875 '% Commands inserted by lyx2lyx for proper underlining\n'
876 + '\\PassOptionsToPackage{normalem}{ulem}\n'
877 + '\\usepackage{ulem}\n'
878 + '\\let\\cite@rig\\cite\n'
879 + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
880 + ' \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
881 + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
884 def revert_custom_processors(document):
885 " Remove bibtex_command and index_command params "
886 i = find_token(document.header, '\\bibtex_command', 0)
888 document.warning("Malformed LyX document: Missing \\bibtex_command.")
890 del document.header[i]
891 i = find_token(document.header, '\\index_command', 0)
893 document.warning("Malformed LyX document: Missing \\index_command.")
895 del document.header[i]
898 def convert_nomencl_width(document):
899 " Add set_width param to nomencl_print "
902 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
905 document.body.insert(i + 2, "set_width \"none\"")
909 def revert_nomencl_width(document):
910 " Remove set_width param from nomencl_print "
913 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
916 j = find_end_of_inset(document.body, i)
917 l = find_token(document.body, "set_width", i, j)
919 document.warning("Can't find set_width option for nomencl_print!")
926 def revert_nomencl_cwidth(document):
927 " Remove width param from nomencl_print "
930 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
933 j = find_end_of_inset(document.body, i)
934 l = find_token(document.body, "width", i, j)
936 #Can't find width option for nomencl_print
939 width = get_value(document.body, "width", i, j).strip('"')
941 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
942 add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
946 def revert_applemac(document):
947 " Revert applemac encoding to auto "
949 if document.encoding == "applemac":
950 document.encoding = "auto"
951 i = find_token(document.header, "\\encoding", 0)
953 document.header[i] = "\\encoding auto"
956 def revert_longtable_align(document):
957 " Remove longtable alignment setting "
961 i = find_token(document.body, "\\begin_inset Tabular", i)
964 # the alignment is 2 lines below \\begin_inset Tabular
965 j = document.body[i + 2].find("longtabularalignment")
968 document.body[i + 2] = document.body[i + 2][:j - 1]
969 document.body[i + 2] = document.body[i + 2] + '>'
973 def revert_branch_filename(document):
974 " Remove \\filename_suffix parameter from branches "
977 i = find_token(document.header, "\\filename_suffix", i)
980 del document.header[i]
983 def revert_paragraph_indentation(document):
984 " Revert custom paragraph indentation to preamble code "
987 i = find_token(document.header, "\\paragraph_indentation", i)
990 # only remove the preamble line if default
991 # otherwise also write the value to the preamble
992 length = get_value(document.header, "\\paragraph_indentation", i)
993 if length == "default":
994 del document.header[i]
997 # handle percent lengths
998 # latex_length returns "bool,length"
999 length = latex_length(length).split(",")[1]
1000 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1001 add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
1002 del document.header[i]
1006 def revert_percent_skip_lengths(document):
1007 " Revert relative lengths for paragraph skip separation to preamble code "
1010 i = find_token(document.header, "\\defskip", i)
1013 length = get_value(document.header, "\\defskip", i)
1014 # only revert when a custom length was set and when
1015 # it used a percent length
1016 if length not in ('smallskip', 'medskip', 'bigskip'):
1017 # handle percent lengths
1018 length = latex_length(length)
1019 # latex_length returns "bool,length"
1020 percent = length.split(",")[0]
1021 length = length.split(",")[1]
1022 if percent == "True":
1023 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1024 add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
1025 # set defskip to medskip as default
1026 document.header[i] = "\\defskip medskip"
1030 def revert_percent_vspace_lengths(document):
1031 " Revert relative VSpace lengths to ERT "
1034 i = find_token(document.body, "\\begin_inset VSpace", i)
1037 # only revert if a custom length was set and if
1038 # it used a percent length
1039 line = document.body[i]
1040 r = re.compile(r'\\begin_inset VSpace (.*)$')
1043 if length not in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
1044 # check if the space has a star (protected space)
1045 protected = (document.body[i].rfind("*") != -1)
1047 length = length.rstrip('*')
1048 # handle percent lengths
1049 length = latex_length(length)
1050 # latex_length returns "bool,length"
1051 percent = length.split(",")[0]
1052 length = length.split(",")[1]
1053 # revert the VSpace inset to ERT
1054 if percent == "True":
1056 subst = [old_put_cmd_in_ert("\\vspace*{" + length + "}")]
1058 subst = [old_put_cmd_in_ert("\\vspace{" + length + "}")]
1059 document.body[i:i + 2] = subst
1063 def revert_percent_hspace_lengths(document):
1064 " Revert relative HSpace lengths to ERT "
1067 i = find_token(document.body, "\\begin_inset space \\hspace", i)
1070 protected = (document.body[i].find("\\hspace*{}") != -1)
1071 # only revert if a custom length was set and if
1072 # it used a percent length
1073 length = get_value(document.body, '\\length', i + 1)
1075 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1077 # handle percent lengths
1078 length = latex_length(length)
1079 # latex_length returns "bool,length"
1080 percent = length.split(",")[0]
1081 length = length.split(",")[1]
1082 # revert the HSpace inset to ERT
1083 if percent == "True":
1085 subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1087 subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1088 document.body[i:i + 3] = subst
1092 def revert_hspace_glue_lengths(document):
1093 " Revert HSpace glue lengths to ERT "
1096 i = find_token(document.body, "\\begin_inset space \\hspace", i)
1099 protected = (document.body[i].find("\\hspace*{}") != -1)
1100 length = get_value(document.body, '\\length', i + 1)
1102 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1104 # only revert if the length contains a plus or minus at pos != 0
1105 glue = re.compile(r'.+[\+-]')
1106 if glue.search(length):
1107 # handle percent lengths
1108 # latex_length returns "bool,length"
1109 length = latex_length(length).split(",")[1]
1110 # revert the HSpace inset to ERT
1112 subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1114 subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1115 document.body[i:i + 3] = subst
1118 def convert_author_id(document):
1119 " Add the author_id to the \\author definition and make sure 0 is not used"
1123 i = find_token(document.header, "\\author", i)
1127 r = re.compile(r'(\\author) (\".*\")\s?(.*)$')
1128 m = r.match(document.header[i])
1133 if m.lastindex == 3:
1135 document.header[i] = "\\author %i %s %s" % (j, name, email)
1141 k = find_token(document.body, "\\change_", k)
1145 change = document.body[k].split(' ');
1146 if len(change) == 3:
1148 author_id = int(change[1])
1150 document.body[k] = "%s %i %s" % (type, author_id + 1, time)
1153 def revert_author_id(document):
1154 " Remove the author_id from the \\author definition "
1159 i = find_token(document.header, "\\author", i)
1163 r = re.compile(r'(\\author) (\d+) (\".*\")\s?(.*)$')
1164 m = r.match(document.header[i])
1166 author_id = int(m.group(2))
1167 idmap[author_id] = j
1171 if m.lastindex == 4:
1173 document.header[i] = "\\author %s %s" % (name, email)
1179 k = find_token(document.body, "\\change_", k)
1183 change = document.body[k].split(' ');
1184 if len(change) == 3:
1186 author_id = int(change[1])
1188 document.body[k] = "%s %i %s" % (type, idmap[author_id], time)
1192 def revert_suppress_date(document):
1193 " Revert suppressing of default document date to preamble code "
1196 i = find_token(document.header, "\\suppress_date", i)
1199 # remove the preamble line and write to the preamble
1200 # when suppress_date was true
1201 date = get_value(document.header, "\\suppress_date", i)
1203 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1204 add_to_preamble(document, ["\\date{}"])
1205 del document.header[i]
1209 def revert_mhchem(document):
1210 "Revert mhchem loading to preamble code"
1215 i = find_token(document.header, "\\use_mhchem 1", 0)
1219 i = find_token(document.header, "\\use_mhchem 2", 0)
1222 if mhchem == "auto":
1223 j = find_token(document.body, "\\cf{", 0)
1227 j = find_token(document.body, "\\ce{", 0)
1231 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1232 add_to_preamble(document, ["\\PassOptionsToPackage{version=3}{mhchem}"])
1233 add_to_preamble(document, ["\\usepackage{mhchem}"])
1234 k = find_token(document.header, "\\use_mhchem", 0)
1236 document.warning("Malformed LyX document: Could not find mhchem setting.")
1238 del document.header[k]
1241 def revert_fontenc(document):
1242 " Remove fontencoding param "
1243 i = find_token(document.header, '\\fontencoding', 0)
1245 document.warning("Malformed LyX document: Missing \\fontencoding.")
1247 del document.header[i]
1250 def merge_gbrief(document):
1251 " Merge g-brief-en and g-brief-de to one class "
1253 if document.textclass != "g-brief-de":
1254 if document.textclass == "g-brief-en":
1255 document.textclass = "g-brief"
1256 document.set_textclass()
1259 obsoletedby = { "Brieftext": "Letter",
1260 "Unterschrift": "Signature",
1261 "Strasse": "Street",
1262 "Zusatz": "Addition",
1265 "RetourAdresse": "ReturnAddress",
1266 "MeinZeichen": "MyRef",
1267 "IhrZeichen": "YourRef",
1268 "IhrSchreiben": "YourMail",
1271 "Konto": "BankAccount",
1272 "Postvermerk": "PostalComment",
1273 "Adresse": "Address",
1275 "Betreff": "Reference",
1276 "Anrede": "Opening",
1282 i = find_token(document.body, "\\begin_layout", i)
1286 layout = document.body[i][14:]
1287 if layout in obsoletedby:
1288 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1292 document.textclass = "g-brief"
1293 document.set_textclass()
1296 def revert_gbrief(document):
1297 " Revert g-brief to g-brief-en "
1298 if document.textclass == "g-brief":
1299 document.textclass = "g-brief-en"
1300 document.set_textclass()
1303 def revert_html_options(document):
1304 " Remove html options "
1305 i = find_token(document.header, '\\html_use_mathml', 0)
1307 del document.header[i]
1308 i = find_token(document.header, '\\html_be_strict', 0)
1310 del document.header[i]
1313 def revert_includeonly(document):
1316 i = find_token(document.header, "\\begin_includeonly", i)
1319 j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
1321 # this should not happen
1323 document.header[i : j + 1] = []
1326 def revert_includeall(document):
1327 " Remove maintain_unincluded_children param "
1328 i = find_token(document.header, '\\maintain_unincluded_children', 0)
1330 del document.header[i]
1333 def revert_multirow(document):
1334 " Revert multirow cells in tables "
1338 # cell type 3 is multirow begin cell
1339 i = find_token(document.body, '<cell multirow="3"', i)
1342 # a multirow cell was found
1344 # remove the multirow tag, set the valignment to top
1345 # and remove the bottom line
1346 document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
1347 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1348 document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
1349 # write ERT to create the multirow cell
1350 # use 2 rows and 2cm as default with because the multirow span
1351 # and the column width is only hardly accessible
1352 subst = [old_put_cmd_in_ert("\\multirow{2}{2cm}{")]
1353 document.body[i + 4:i + 4] = subst
1354 i = find_token(document.body, "</cell>", i)
1356 document.warning("Malformed LyX document: Could not find end of tabular cell.")
1358 subst = [old_put_cmd_in_ert("}")]
1359 document.body[i - 3:i - 3] = subst
1360 # cell type 4 is multirow part cell
1361 i = find_token(document.body, '<cell multirow="4"', i)
1364 # remove the multirow tag, set the valignment to top
1365 # and remove the top line
1366 document.body[i] = document.body[i].replace(' multirow="4" ', ' ')
1367 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1368 document.body[i] = document.body[i].replace(' topline="true" ', ' ')
1370 if multirow == True:
1371 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1372 add_to_preamble(document, ["\\usepackage{multirow}"])
1375 def convert_math_output(document):
1376 " Convert \html_use_mathml to \html_math_output "
1377 i = find_token(document.header, "\\html_use_mathml", 0)
1380 rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1381 m = rgx.match(document.header[i])
1383 newval = "0" # MathML
1386 newval = "2" # Images
1387 document.header[i] = "\\html_math_output " + newval
1390 def revert_math_output(document):
1391 " Revert \html_math_output to \html_use_mathml "
1392 i = find_token(document.header, "\\html_math_output", 0)
1395 rgx = re.compile(r'\\html_math_output\s+(\d)')
1396 m = rgx.match(document.header[i])
1400 if val == "1" or val == "2":
1403 document.warning("Unable to match " + document.header[i])
1404 document.header[i] = "\\html_use_mathml " + newval
1408 def revert_inset_preview(document):
1409 " Dissolves the preview inset "
1414 i = find_token(document.body, "\\begin_inset Preview", i)
1417 j = find_end_of_inset(document.body, i)
1419 document.warning("Malformed LyX document: Could not find end of Preview inset.")
1421 #If the layout is Standard we need to remove it, otherwise there
1422 #will be paragraph breaks that shouldn't be there.
1423 k = find_token(document.body, "\\begin_layout Standard", i)
1425 del document.body[i:i + 3]
1426 del document.body[j - 5:j - 2]
1429 del document.body[i]
1430 del document.body[j - 1]
1434 def revert_equalspacing_xymatrix(document):
1435 " Revert a Formula with xymatrix@! to an ERT inset "
1438 has_preamble = False
1439 has_equal_spacing = False
1442 i = find_token(document.body, "\\begin_inset Formula", i)
1445 j = find_end_of_inset(document.body, i)
1447 document.warning("Malformed LyX document: Could not find end of Formula inset.")
1450 for curline in range(i,j):
1451 found = document.body[curline].find("\\xymatrix@!")
1456 has_equal_spacing = True
1457 content = [document.body[i][21:]]
1458 content += document.body[i + 1:j]
1459 subst = put_cmd_in_ert(content)
1460 document.body[i:j + 1] = subst
1463 for curline in range(i,j):
1464 l = document.body[curline].find("\\xymatrix")
1466 has_preamble = True;
1469 if has_equal_spacing and not has_preamble:
1470 add_to_preamble(document, ['\\usepackage[all]{xy}'])
1473 def revert_notefontcolor(document):
1474 " Reverts greyed-out note font color to preamble code "
1478 i = find_token(document.header, "\\notefontcolor", i)
1481 colorcode = get_value(document.header, '\\notefontcolor', 0)
1482 del document.header[i]
1483 # the color code is in the form #rrggbb where every character denotes a hex number
1484 # convert the string to an int
1485 red = string.atoi(colorcode[1:3],16)
1486 # we want the output "0.5" for the value "127" therefore increment here
1489 redout = float(red) / 256
1490 green = string.atoi(colorcode[3:5],16)
1493 greenout = float(green) / 256
1494 blue = string.atoi(colorcode[5:7],16)
1497 blueout = float(blue) / 256
1498 # write the preamble
1499 insert_to_preamble(0, document,
1500 '% Commands inserted by lyx2lyx to set the font color\n'
1501 '% for greyed-out notes\n'
1502 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1503 + '\\definecolor{note_fontcolor}{rgb}{'
1504 + str(redout) + ', ' + str(greenout)
1505 + ', ' + str(blueout) + '}\n'
1506 + '\\renewenvironment{lyxgreyedout}\n'
1507 + ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}\n')
1510 def revert_turkmen(document):
1511 "Set language Turkmen to English"
1513 if document.language == "turkmen":
1514 document.language = "english"
1515 i = find_token(document.header, "\\language", 0)
1517 document.header[i] = "\\language english"
1520 j = find_token(document.body, "\\lang turkmen", j)
1523 document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english")
1527 def revert_fontcolor(document):
1528 " Reverts font color to preamble code "
1532 i = find_token(document.header, "\\fontcolor", i)
1535 colorcode = get_value(document.header, '\\fontcolor', 0)
1536 del document.header[i]
1537 # don't clutter the preamble if backgroundcolor is not set
1538 if colorcode == "#000000":
1540 # the color code is in the form #rrggbb where every character denotes a hex number
1541 # convert the string to an int
1542 red = string.atoi(colorcode[1:3],16)
1543 # we want the output "0.5" for the value "127" therefore add here
1546 redout = float(red) / 256
1547 green = string.atoi(colorcode[3:5],16)
1550 greenout = float(green) / 256
1551 blue = string.atoi(colorcode[5:7],16)
1554 blueout = float(blue) / 256
1555 # write the preamble
1556 insert_to_preamble(0, document,
1557 '% Commands inserted by lyx2lyx to set the font color\n'
1558 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1559 + '\\definecolor{document_fontcolor}{rgb}{'
1560 + str(redout) + ', ' + str(greenout)
1561 + ', ' + str(blueout) + '}\n'
1562 + '\\color{document_fontcolor}\n')
1565 def revert_shadedboxcolor(document):
1566 " Reverts shaded box color to preamble code "
1570 i = find_token(document.header, "\\boxbgcolor", i)
1573 colorcode = get_value(document.header, '\\boxbgcolor', 0)
1574 del document.header[i]
1575 # the color code is in the form #rrggbb where every character denotes a hex number
1576 # convert the string to an int
1577 red = string.atoi(colorcode[1:3],16)
1578 # we want the output "0.5" for the value "127" therefore increment here
1581 redout = float(red) / 256
1582 green = string.atoi(colorcode[3:5],16)
1585 greenout = float(green) / 256
1586 blue = string.atoi(colorcode[5:7],16)
1589 blueout = float(blue) / 256
1590 # write the preamble
1591 insert_to_preamble(0, document,
1592 '% Commands inserted by lyx2lyx to set the color\n'
1593 '% of boxes with shaded background\n'
1594 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1595 + '\\definecolor{shadecolor}{rgb}{'
1596 + str(redout) + ', ' + str(greenout)
1597 + ', ' + str(blueout) + '}\n')
1600 def revert_lyx_version(document):
1601 " Reverts LyX Version information from Inset Info "
1602 version = "LyX version"
1604 import lyx2lyx_version
1605 version = lyx2lyx_version.version
1611 i = find_token(document.body, '\\begin_inset Info', i)
1614 j = find_end_of_inset(document.body, i + 1)
1617 document.warning("Malformed LyX document: Could not find end of Info inset.")
1623 # but we shall try to be forgiving.
1625 for k in range(i, j):
1626 if document.body[k].startswith("arg"):
1627 arg = document.body[k][3:].strip().strip('"')
1628 if document.body[k].startswith("type"):
1629 typ = document.body[k][4:].strip().strip('"')
1630 if arg != "version" or typ != "lyxinfo":
1634 # We do not actually know the version of LyX used to produce the document.
1635 # But we can use our version, since we are reverting.
1637 # Now we want to check if the line after "\end_inset" is empty. It normally
1638 # is, so we want to remove it, too.
1640 if document.body[j + 1].strip() == "":
1642 document.body[i: lastline] = s
1646 def revert_math_scale(document):
1647 " Remove math scaling and LaTeX options "
1648 i = find_token(document.header, '\\html_math_img_scale', 0)
1650 del document.header[i]
1651 i = find_token(document.header, '\\html_latex_start', 0)
1653 del document.header[i]
1654 i = find_token(document.header, '\\html_latex_end', 0)
1656 del document.header[i]
1659 def revert_pagesizes(document):
1661 " Revert page sizes to default "
1662 i = find_token(document.header, '\\papersize', 0)
1664 size = document.header[i][11:]
1665 if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1666 or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1667 or size == "b2paper" or size == "b6paper" or size == "b0j" \
1668 or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1669 or size == "b5j" or size == "b6j":
1670 del document.header[i]
1673 def revert_DIN_C_pagesizes(document):
1675 " Revert DIN C page sizes to default "
1676 i = find_token(document.header, '\\papersize', 0)
1678 size = document.header[i][11:]
1679 if size == "c0paper" or size == "c1paper" or size == "c2paper" \
1680 or size == "c3paper" or size == "c4paper" or size == "c5paper" \
1681 or size == "c6paper":
1682 del document.header[i]
1685 def convert_html_quotes(document):
1686 " Remove quotes around html_latex_start and html_latex_end "
1688 i = find_token(document.header, '\\html_latex_start', 0)
1690 line = document.header[i]
1691 l = re.compile(r'\\html_latex_start\s+"(.*)"')
1694 document.header[i] = "\\html_latex_start " + m.group(1)
1696 i = find_token(document.header, '\\html_latex_end', 0)
1698 line = document.header[i]
1699 l = re.compile(r'\\html_latex_end\s+"(.*)"')
1702 document.header[i] = "\\html_latex_end " + m.group(1)
1705 def revert_html_quotes(document):
1706 " Remove quotes around html_latex_start and html_latex_end "
1708 i = find_token(document.header, '\\html_latex_start', 0)
1710 line = document.header[i]
1711 l = re.compile(r'\\html_latex_start\s+(.*)')
1713 document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1715 i = find_token(document.header, '\\html_latex_end', 0)
1717 line = document.header[i]
1718 l = re.compile(r'\\html_latex_end\s+(.*)')
1720 document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1723 def revert_output_sync(document):
1724 " Remove forward search options "
1725 i = find_token(document.header, '\\output_sync_macro', 0)
1727 del document.header[i]
1728 i = find_token(document.header, '\\output_sync', 0)
1730 del document.header[i]
1733 def convert_beamer_args(document):
1734 " Convert ERT arguments in Beamer to InsetArguments "
1736 if document.textclass != "beamer" and document.textclass != "article-beamer":
1739 layouts = ("Block", "ExampleBlock", "AlertBlock")
1740 for layout in layouts:
1743 blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1746 elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1748 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1751 bert = find_token(document.body, '\\begin_inset ERT', blay)
1753 document.warning("Malformed Beamer LyX document: Can't find argument of " + layout + " layout.")
1756 eert = find_end_of_inset(document.body, bert)
1758 document.warning("Malformed LyX document: Can't find end of ERT.")
1762 # So the ERT inset begins at line k and goes to line l. We now wrap it in
1763 # an argument inset.
1764 # Do the end first, so as not to mess up the variables.
1765 document.body[eert + 1:eert + 1] = ['', '\\end_layout', '', '\\end_inset', '']
1766 document.body[bert:bert] = ['\\begin_inset OptArg', 'status open', '',
1767 '\\begin_layout Plain Layout']
1771 def revert_beamer_args(document):
1772 " Revert Beamer arguments to ERT "
1774 if document.textclass != "beamer" and document.textclass != "article-beamer":
1777 layouts = ("Block", "ExampleBlock", "AlertBlock")
1778 for layout in layouts:
1781 blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1784 elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1786 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1789 bopt = find_token(document.body, '\\begin_inset OptArg', blay)
1791 # it is legal not to have one of these
1794 eopt = find_end_of_inset(document.body, bopt)
1796 document.warning("Malformed LyX document: Can't find end of argument.")
1799 bplay = find_token(document.body, '\\begin_layout Plain Layout', blay)
1801 document.warning("Malformed LyX document: Can't find plain layout.")
1804 eplay = find_end_of(document.body, bplay, '\\begin_layout', '\\end_layout')
1806 document.warning("Malformed LyX document: Can't find end of plain layout.")
1809 # So the content of the argument inset goes from bplay + 1 to eplay - 1
1813 document.warning(str(bcont) + " " + str(eplay))
1816 # we convert the content of the argument into pure LaTeX...
1817 content = lyx2latex(document, document.body[bcont:eplay])
1818 strlist = put_cmd_in_ert(["{" + content + "}"])
1820 # now replace the optional argument with the ERT
1821 document.body[bopt:eopt + 1] = strlist
1825 def revert_align_decimal(document):
1828 l = document.body[l].find('alignment=decimal')
1831 remove_option(document, l, 'decimal_point')
1832 document.body[l].replace('decimal', 'center')
1835 def convert_optarg(document):
1836 " Convert \\begin_inset OptArg to \\begin_inset Argument "
1839 i = find_token(document.body, '\\begin_inset OptArg', i)
1842 document.body[i] = "\\begin_inset Argument"
1846 def revert_argument(document):
1847 " Convert \\begin_inset Argument to \\begin_inset OptArg "
1850 i = find_token(document.body, '\\begin_inset Argument', i)
1853 document.body[i] = "\\begin_inset OptArg"
1857 def revert_makebox(document):
1858 " Convert \\makebox to TeX code "
1861 # only revert frameless boxes without an inner box
1862 i = find_token(document.body, '\\begin_inset Box Frameless', i)
1864 # remove the option use_makebox
1865 revert_use_makebox(document)
1867 z = find_end_of_inset(document.body, i)
1869 document.warning("Malformed LyX document: Can't find end of box inset.")
1871 j = find_token(document.body, 'use_makebox 1', i)
1872 # assure we found the makebox of the current box
1873 if j < z and j != -1:
1874 y = find_token(document.body, "\\begin_layout", i)
1875 if y > z or y == -1:
1876 document.warning("Malformed LyX document: Can't find layout in box.")
1878 # remove the \end_layout \end_inset pair
1879 document.body[z - 2:z + 1] = put_cmd_in_ert("}")
1880 # determine the alignment
1881 k = find_token(document.body, 'hor_pos', j - 4)
1882 align = document.body[k][9]
1883 # determine the width
1884 l = find_token(document.body, 'width "', j + 1)
1885 length = document.body[l][7:]
1886 # remove trailing '"'
1887 length = length[:-1]
1888 # latex_length returns "bool,length"
1889 length = latex_length(length).split(",")[1]
1890 subst = "\\makebox[" + length + "][" \
1892 document.body[i:y + 1] = put_cmd_in_ert(subst)
1896 def revert_use_makebox(document):
1897 " Deletes use_makebox option of boxes "
1900 # remove the option use_makebox
1901 h = find_token(document.body, 'use_makebox', 0)
1904 del document.body[h]
1908 def revert_IEEEtran(document):
1909 " Convert IEEEtran layouts and styles to TeX code "
1910 if document.textclass != "IEEEtran":
1913 revert_flex_inset(document, "IEEE membership", "\\IEEEmembership", 0)
1914 revert_flex_inset(document, "Lowercase", "\\MakeLowercase", 0)
1916 layouts = ("Special Paper Notice", "After Title Text", "Publication ID",
1917 "Page headings", "Biography without photo")
1919 latexcmd = {"Special Paper Notice": "\\IEEEspecialpapernotice",
1920 "After Title Text": "\\IEEEaftertitletext",
1921 "Publication ID": "\\IEEEpubid"}
1923 obsoletedby = {"Page headings": "MarkBoth",
1924 "Biography without photo": "BiographyNoPhoto"}
1926 for layout in layouts:
1929 i = find_token(document.body, '\\begin_layout ' + layout, i)
1932 j = find_end_of(document.body, i, '\\begin_layout', '\\end_layout')
1934 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1937 if layout in obsoletedby:
1938 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1941 content = lyx2latex(document, document.body[i:j + 1])
1942 add_to_preamble(document, [latexcmd[layout] + "{" + content + "}"])
1943 del document.body[i:j + 1]
1946 def revert_nameref(document):
1947 " Convert namerefs to regular references "
1948 # We cannot really revert these properly, so we will
1949 # revert them to commands we understand.
1950 cmds = [["Nameref", "vref"], ["nameref", "ref"]]
1953 oldcmd = "LatexCommand " + cmd[0]
1954 newcmd = "LatexCommand " + cmd[1]
1956 i = find_token(document.body, oldcmd, i)
1959 # Make sure it is actually in an inset!
1960 # We could just check document.lines[i-1], but that relies
1961 # upon something that might easily change.
1962 # We'll look back a few lines.
1966 j = find_token(document.body, "\\begin_inset CommandInset ref", j)
1967 if j == -1 or j > i:
1970 k = find_end_of_inset(document.body, i)
1972 document.warning("Can't find end of inset at line " + j + "!!")
1978 document.body[i] = newcmd
1986 supported_versions = ["2.0.0","2.0"]
1987 convert = [[346, []],
1993 [352, [convert_splitindex]],
2000 [359, [convert_nomencl_width]],
2010 [369, [convert_author_id]],
2014 [373, [merge_gbrief]],
2020 [379, [convert_math_output]],
2030 [389, [convert_html_quotes]],
2033 [392, [convert_beamer_args]],
2034 [393, [convert_optarg]],
2040 revert = [[395, [revert_nameref]],
2041 [394, [revert_DIN_C_pagesizes]],
2042 [393, [revert_makebox]],
2043 [392, [revert_argument]],
2044 [391, [revert_beamer_args]],
2045 [390, [revert_align_decimal, revert_IEEEtran]],
2046 [389, [revert_output_sync]],
2047 [388, [revert_html_quotes]],
2048 [387, [revert_pagesizes]],
2049 [386, [revert_math_scale]],
2050 [385, [revert_lyx_version]],
2051 [384, [revert_shadedboxcolor]],
2052 [383, [revert_fontcolor]],
2053 [382, [revert_turkmen]],
2054 [381, [revert_notefontcolor]],
2055 [380, [revert_equalspacing_xymatrix]],
2056 [379, [revert_inset_preview]],
2057 [378, [revert_math_output]],
2059 [376, [revert_multirow]],
2060 [375, [revert_includeall]],
2061 [374, [revert_includeonly]],
2062 [373, [revert_html_options]],
2063 [372, [revert_gbrief]],
2064 [371, [revert_fontenc]],
2065 [370, [revert_mhchem]],
2066 [369, [revert_suppress_date]],
2067 [368, [revert_author_id]],
2068 [367, [revert_hspace_glue_lengths]],
2069 [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
2070 [365, [revert_percent_skip_lengths]],
2071 [364, [revert_paragraph_indentation]],
2072 [363, [revert_branch_filename]],
2073 [362, [revert_longtable_align]],
2074 [361, [revert_applemac]],
2076 [359, [revert_nomencl_cwidth]],
2077 [358, [revert_nomencl_width]],
2078 [357, [revert_custom_processors]],
2079 [356, [revert_ulinelatex]],
2081 [354, [revert_strikeout]],
2082 [353, [revert_printindexall]],
2083 [352, [revert_subindex]],
2084 [351, [revert_splitindex]],
2085 [350, [revert_backgroundcolor]],
2086 [349, [revert_outputformat]],
2087 [348, [revert_xetex]],
2088 [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2089 [346, [revert_tabularvalign]],
2090 [345, [revert_swiss]]
2094 if __name__ == "__main__":