1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008 José Matos <jamatos@lyx.org>
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 """ Convert files to the file format generated by lyx 2.0"""
25 from parser_tools import find_token, find_end_of, find_tokens, get_value, get_value_string
27 ####################################################################
28 # Private helper functions
30 def find_end_of_inset(lines, i):
31 " Find end of inset, where lines[i] is included."
32 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
35 def add_to_preamble(document, text):
36 """ Add text to the preamble if it is not already there.
37 Only the first line is checked!"""
39 if find_token(document.preamble, text[0], 0) != -1:
42 document.preamble.extend(text)
45 def insert_to_preamble(index, document, text):
46 """ Insert text to the preamble at a given line"""
48 document.preamble.insert(index, text)
51 def read_unicodesymbols():
52 " Read the unicodesymbols list of unicode characters and corresponding commands."
53 pathname = os.path.abspath(os.path.dirname(sys.argv[0]))
54 fp = open(os.path.join(pathname.strip('lyx2lyx'), 'unicodesymbols'))
56 # Two backslashes, followed by some non-word character, and then a character
57 # in brackets. The idea is to check for constructs like: \"{u}, which is how
58 # they are written in the unicodesymbols file; but they can also be written
59 # as: \"u or even \" u.
60 r = re.compile(r'\\\\(\W)\{(\w)\}')
61 for line in fp.readlines():
62 if line[0] != '#' and line.strip() != "":
63 line=line.replace(' "',' ') # remove all quotation marks with spaces before
64 line=line.replace('" ',' ') # remove all quotation marks with spaces after
65 line=line.replace(r'\"','"') # replace \" by " (for characters with diaeresis)
67 [ucs4,command,dead] = line.split(None,2)
68 if command[0:1] != "\\":
70 spec_chars.append([command, unichr(eval(ucs4))])
76 # If the character is a double-quote, then we need to escape it, too,
77 # since it is done that way in the LyX file.
78 if m.group(1) == "\"":
81 command += m.group(1) + m.group(2)
82 commandbl += m.group(1) + ' ' + m.group(2)
83 spec_chars.append([command, unichr(eval(ucs4))])
84 spec_chars.append([commandbl, unichr(eval(ucs4))])
89 unicode_reps = read_unicodesymbols()
92 def put_cmd_in_ert(string):
93 for rep in unicode_reps:
94 string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
95 string = string.replace('\\', "\\backslash\n")
96 string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
97 + string + "\n\\end_layout\n\\end_inset"
101 def lyx2latex(document, lines):
102 'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
103 # clean up multiline stuff
107 for curline in range(len(lines)):
108 line = lines[curline]
109 if line.startswith("\\begin_inset ERT"):
110 # We don't want to replace things inside ERT, so figure out
111 # where the end of the inset is.
112 ert_end = find_end_of_inset(lines, curline + 1)
114 elif line.startswith("\\begin_inset Formula"):
116 elif line.startswith("\\begin_inset Quotes"):
117 # For now, we do a very basic reversion. Someone who understands
118 # quotes is welcome to fix it up.
119 qtype = line[20:].strip()
133 elif line.isspace() or \
134 line.startswith("\\begin_layout") or \
135 line.startswith("\\end_layout") or \
136 line.startswith("\\begin_inset") or \
137 line.startswith("\\end_inset") or \
138 line.startswith("\\lang") or \
139 line.strip() == "status collapsed" or \
140 line.strip() == "status open":
144 # this needs to be added to the preamble because of cases like
145 # \textmu, \textbackslash, etc.
146 add_to_preamble(document, ['% added by lyx2lyx for converted index entries',
147 '\\@ifundefined{textmu}',
148 ' {\\usepackage{textcomp}}{}'])
149 # a lossless reversion is not possible
150 # try at least to handle some common insets and settings
151 if ert_end >= curline:
152 line = line.replace(r'\backslash', r'\\')
154 line = line.replace('&', '\\&{}')
155 line = line.replace('#', '\\#{}')
156 line = line.replace('^', '\\^{}')
157 line = line.replace('%', '\\%{}')
158 line = line.replace('_', '\\_{}')
159 line = line.replace('$', '\\${}')
161 # Do the LyX text --> LaTeX conversion
162 for rep in unicode_reps:
163 line = line.replace(rep[1], rep[0] + "{}")
164 line = line.replace(r'\backslash', r'\textbackslash{}')
165 line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
166 line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
167 line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
168 line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
169 line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
170 line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
171 line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
172 line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
173 line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
178 def latex_length(string):
179 'Convert lengths to their LaTeX representation.'
182 # the string has always the form
183 # ValueUnit+ValueUnit-ValueUnit
184 # the + and - lengths are optional
185 # the + is always before the -
186 i = string.find("text%")
189 minus = string.rfind("-", 0, i)
190 plus = string.rfind("+", 0, i)
191 if plus == -1 and minus == -1:
193 value = str(float(value)/100)
195 string = value + "\\textwidth" + end
197 value = string[plus+1:i]
198 value = str(float(value)/100)
199 begin = string[:plus+1]
201 string = begin + value + "\\textwidth" + end
203 value = string[minus+1:i]
204 value = str(float(value)/100)
205 begin = string[:minus+1]
206 string = begin + value + "\\textwidth"
207 i = string.find("col%")
210 minus = string.rfind("-", 0, i)
211 plus = string.rfind("+", 0, i)
212 if plus == -1 and minus == -1:
214 value = str(float(value)/100)
216 string = value + "\\columnwidth" + end
218 value = string[plus+1:i]
219 value = str(float(value)/100)
220 begin = string[:plus+1]
222 string = begin + value + "\\columnwidth" + end
224 value = string[minus+1:i]
225 value = str(float(value)/100)
226 begin = string[:minus+1]
227 string = begin + value + "\\columnwidth"
228 i = string.find("page%")
231 minus = string.rfind("-", 0, i)
232 plus = string.rfind("+", 0, i)
233 if plus == -1 and minus == -1:
235 value = str(float(value)/100)
237 string = value + "\\paperwidth" + end
239 value = string[plus+1:i]
240 value = str(float(value)/100)
241 begin = string[:plus+1]
243 string = begin + value + "\\paperwidth" + end
245 value = string[minus+1:i]
246 value = str(float(value)/100)
247 begin = string[:minus+1]
248 string = begin + value + "\\paperwidth"
249 i = string.find("line%")
252 minus = string.rfind("-", 0, i)
253 plus = string.rfind("+", 0, i)
254 if plus == -1 and minus == -1:
256 value = str(float(value)/100)
258 string = value + "\\linewidth" + end
260 value = string[plus+1:i]
261 value = str(float(value)/100)
262 begin = string[:plus+1]
264 string = begin + value + "\\linewidth" + end
266 value = string[minus+1:i]
267 value = str(float(value)/100)
268 begin = string[:minus+1]
269 string = begin + value + "\\linewidth"
270 i = string.find("theight%")
273 minus = string.rfind("-", 0, i)
274 plus = string.rfind("+", 0, i)
275 if plus == -1 and minus == -1:
277 value = str(float(value)/100)
279 string = value + "\\textheight" + end
281 value = string[plus+1:i]
282 value = str(float(value)/100)
283 begin = string[:plus+1]
285 string = begin + value + "\\textheight" + end
287 value = string[minus+1:i]
288 value = str(float(value)/100)
289 begin = string[:minus+1]
290 string = begin + value + "\\textheight"
291 i = string.find("pheight%")
294 minus = string.rfind("-", 0, i)
295 plus = string.rfind("+", 0, i)
296 if plus == -1 and minus == -1:
298 value = str(float(value)/100)
300 string = value + "\\paperheight" + end
302 value = string[plus+1:i]
303 value = str(float(value)/100)
304 begin = string[:plus+1]
306 string = begin + value + "\\paperheight" + end
308 value = string[minus+1:i]
309 value = str(float(value)/100)
310 begin = string[:minus+1]
311 string = begin + value + "\\paperheight"
312 # replace + and -, but only when the - is not the first character
313 string = string.replace("+", " plus ")
314 if string.find("-") == 0:
315 minusstring = string[1:]
316 minusstring = minusstring.replace("-", " minus ")
317 string = "-" + minusstring
319 string = string.replace("-", " minus ")
320 # handle the case that "+-1mm" was used because LaTeX only understands
321 # "plus 1mm minus 1mm"
322 if string.find("plus minus"):
323 lastvaluepos = string.rfind(" ")
324 lastvalue = string[lastvaluepos:]
325 string = string.replace(" ", lastvalue + " ")
327 return "False," + string
329 return "True," + string
332 ####################################################################
335 def revert_swiss(document):
336 " Set language german-ch to ngerman "
338 if document.language == "german-ch":
339 document.language = "ngerman"
340 i = find_token(document.header, "\\language", 0)
342 document.header[i] = "\\language ngerman"
345 j = find_token(document.body, "\\lang german-ch", j)
348 document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
352 def revert_tabularvalign(document):
353 " Revert the tabular valign option "
356 i = find_token(document.body, "\\begin_inset Tabular", i)
359 j = find_end_of_inset(document.body, i)
361 document.warning("Malformed LyX document: Could not find end of tabular.")
364 # don't set a box for longtables, only delete tabularvalignment
365 # the alignment is 2 lines below \\begin_inset Tabular
366 p = document.body[i+2].find("islongtable")
368 q = document.body[i+2].find("tabularvalignment")
370 document.body[i+2] = document.body[i+2][:q-1]
371 document.body[i+2] = document.body[i+2] + '>'
376 tabularvalignment = 'c'
377 # which valignment is specified?
378 m = document.body[i+2].find('tabularvalignment="top"')
380 tabularvalignment = 't'
381 m = document.body[i+2].find('tabularvalignment="bottom"')
383 tabularvalignment = 'b'
384 # delete tabularvalignment
385 q = document.body[i+2].find("tabularvalignment")
387 document.body[i+2] = document.body[i+2][:q-1]
388 document.body[i+2] = document.body[i+2] + '>'
390 # don't add a box when centered
391 if tabularvalignment == 'c':
394 subst = ['\\end_layout', '\\end_inset']
395 document.body[j+1:j+1] = subst # just inserts those lines
396 subst = ['\\begin_inset Box Frameless',
397 'position "' + tabularvalignment +'"',
402 # we don't know the width, assume 50%
406 'height_special "totalheight"',
409 '\\begin_layout Plain Layout']
410 document.body[i:i] = subst # this just inserts the array at i
411 i += len(subst) + 2 # adjust i to save a few cycles
414 def revert_phantom(document):
415 " Reverts phantom to ERT "
419 i = find_token(document.body, "\\begin_inset Phantom Phantom", i)
422 substi = document.body[i].replace('\\begin_inset Phantom Phantom', \
423 '\\begin_inset ERT\nstatus collapsed\n\n' \
424 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
425 'phantom{\n\\end_layout\n\n\\end_inset\n')
426 substi = substi.split('\n')
427 document.body[i : i+4] = substi
429 j = find_token(document.body, "\\end_layout", i)
431 document.warning("Malformed LyX document: Could not find end of Phantom inset.")
433 substj = document.body[j].replace('\\end_layout', \
434 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
435 '\\begin_layout Plain Layout\n\n' \
436 '}\n\\end_layout\n\n\\end_inset\n')
437 substj = substj.split('\n')
438 document.body[j : j+4] = substj
442 def revert_hphantom(document):
443 " Reverts hphantom to ERT "
447 i = find_token(document.body, "\\begin_inset Phantom HPhantom", i)
450 substi = document.body[i].replace('\\begin_inset Phantom HPhantom', \
451 '\\begin_inset ERT\nstatus collapsed\n\n' \
452 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
453 'hphantom{\n\\end_layout\n\n\\end_inset\n')
454 substi = substi.split('\n')
455 document.body[i : i+4] = substi
457 j = find_token(document.body, "\\end_layout", i)
459 document.warning("Malformed LyX document: Could not find end of HPhantom inset.")
461 substj = document.body[j].replace('\\end_layout', \
462 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
463 '\\begin_layout Plain Layout\n\n' \
464 '}\n\\end_layout\n\n\\end_inset\n')
465 substj = substj.split('\n')
466 document.body[j : j+4] = substj
470 def revert_vphantom(document):
471 " Reverts vphantom to ERT "
475 i = find_token(document.body, "\\begin_inset Phantom VPhantom", i)
478 substi = document.body[i].replace('\\begin_inset Phantom VPhantom', \
479 '\\begin_inset ERT\nstatus collapsed\n\n' \
480 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
481 'vphantom{\n\\end_layout\n\n\\end_inset\n')
482 substi = substi.split('\n')
483 document.body[i : i+4] = substi
485 j = find_token(document.body, "\\end_layout", i)
487 document.warning("Malformed LyX document: Could not find end of VPhantom inset.")
489 substj = document.body[j].replace('\\end_layout', \
490 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
491 '\\begin_layout Plain Layout\n\n' \
492 '}\n\\end_layout\n\n\\end_inset\n')
493 substj = substj.split('\n')
494 document.body[j : j+4] = substj
498 def revert_xetex(document):
499 " Reverts documents that use XeTeX "
500 i = find_token(document.header, '\\use_xetex', 0)
502 document.warning("Malformed LyX document: Missing \\use_xetex.")
504 if get_value(document.header, "\\use_xetex", i) == 'false':
505 del document.header[i]
507 del document.header[i]
508 # 1.) set doc encoding to utf8-plain
509 i = find_token(document.header, "\\inputencoding", 0)
511 document.warning("Malformed LyX document: Missing \\inputencoding.")
512 document.header[i] = "\\inputencoding utf8-plain"
513 # 2.) check font settings
514 l = find_token(document.header, "\\font_roman", 0)
516 document.warning("Malformed LyX document: Missing \\font_roman.")
517 line = document.header[l]
518 l = re.compile(r'\\font_roman (.*)$')
521 l = find_token(document.header, "\\font_sans", 0)
523 document.warning("Malformed LyX document: Missing \\font_sans.")
524 line = document.header[l]
525 l = re.compile(r'\\font_sans (.*)$')
528 l = find_token(document.header, "\\font_typewriter", 0)
530 document.warning("Malformed LyX document: Missing \\font_typewriter.")
531 line = document.header[l]
532 l = re.compile(r'\\font_typewriter (.*)$')
534 typewriter = m.group(1)
535 osf = get_value(document.header, '\\font_osf', 0) == "true"
536 sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
537 tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
538 # 3.) set preamble stuff
539 pretext = '%% This document must be processed with xelatex!\n'
540 pretext += '\\usepackage{fontspec}\n'
541 if roman != "default":
542 pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
543 if sans != "default":
544 pretext += '\\setsansfont['
546 pretext += 'Scale=' + str(sf_scale / 100) + ','
547 pretext += 'Mapping=tex-text]{' + sans + '}\n'
548 if typewriter != "default":
549 pretext += '\\setmonofont'
551 pretext += '[Scale=' + str(tt_scale / 100) + ']'
552 pretext += '{' + typewriter + '}\n'
554 pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
555 pretext += '\usepackage{xunicode}\n'
556 pretext += '\usepackage{xltxtra}\n'
557 insert_to_preamble(0, document, pretext)
558 # 4.) reset font settings
559 i = find_token(document.header, "\\font_roman", 0)
561 document.warning("Malformed LyX document: Missing \\font_roman.")
562 document.header[i] = "\\font_roman default"
563 i = find_token(document.header, "\\font_sans", 0)
565 document.warning("Malformed LyX document: Missing \\font_sans.")
566 document.header[i] = "\\font_sans default"
567 i = find_token(document.header, "\\font_typewriter", 0)
569 document.warning("Malformed LyX document: Missing \\font_typewriter.")
570 document.header[i] = "\\font_typewriter default"
571 i = find_token(document.header, "\\font_osf", 0)
573 document.warning("Malformed LyX document: Missing \\font_osf.")
574 document.header[i] = "\\font_osf false"
575 i = find_token(document.header, "\\font_sc", 0)
577 document.warning("Malformed LyX document: Missing \\font_sc.")
578 document.header[i] = "\\font_sc false"
579 i = find_token(document.header, "\\font_sf_scale", 0)
581 document.warning("Malformed LyX document: Missing \\font_sf_scale.")
582 document.header[i] = "\\font_sf_scale 100"
583 i = find_token(document.header, "\\font_tt_scale", 0)
585 document.warning("Malformed LyX document: Missing \\font_tt_scale.")
586 document.header[i] = "\\font_tt_scale 100"
589 def revert_outputformat(document):
590 " Remove default output format param "
591 i = find_token(document.header, '\\default_output_format', 0)
593 document.warning("Malformed LyX document: Missing \\default_output_format.")
595 del document.header[i]
598 def revert_backgroundcolor(document):
599 " Reverts background color to preamble code "
603 i = find_token(document.header, "\\backgroundcolor", i)
606 colorcode = get_value(document.header, '\\backgroundcolor', 0)
607 del document.header[i]
608 # don't clutter the preamble if backgroundcolor is not set
609 if colorcode == "#ffffff":
611 # the color code is in the form #rrggbb where every character denotes a hex number
612 # convert the string to an int
613 red = string.atoi(colorcode[1:3],16)
614 # we want the output "0.5" for the value "127" therefore add here
617 redout = float(red) / 256
618 green = string.atoi(colorcode[3:5],16)
621 greenout = float(green) / 256
622 blue = string.atoi(colorcode[5:7],16)
625 blueout = float(blue) / 256
627 insert_to_preamble(0, document,
628 '% Commands inserted by lyx2lyx to set the background color\n'
629 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
630 + '\\definecolor{page_backgroundcolor}{rgb}{'
631 + str(redout) + ', ' + str(greenout)
632 + ', ' + str(blueout) + '}\n'
633 + '\\pagecolor{page_backgroundcolor}\n')
636 def revert_splitindex(document):
637 " Reverts splitindex-aware documents "
638 i = find_token(document.header, '\\use_indices', 0)
640 document.warning("Malformed LyX document: Missing \\use_indices.")
642 indices = get_value(document.header, "\\use_indices", i)
644 if indices == "true":
645 preamble += "\\usepackage{splitidx}\n"
646 del document.header[i]
649 i = find_token(document.header, "\\index", i)
652 k = find_token(document.header, "\\end_index", i)
654 document.warning("Malformed LyX document: Missing \\end_index.")
656 line = document.header[i]
657 l = re.compile(r'\\index (.*)$')
660 ishortcut = get_value(document.header, '\\shortcut', i, k)
661 if ishortcut != "" and indices == "true":
662 preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
663 del document.header[i:k+1]
666 insert_to_preamble(0, document, preamble)
669 i = find_token(document.body, "\\begin_inset Index", i)
672 line = document.body[i]
673 l = re.compile(r'\\begin_inset Index (.*)$')
676 if itype == "idx" or indices == "false":
677 document.body[i] = "\\begin_inset Index"
679 k = find_end_of_inset(document.body, i)
682 content = lyx2latex(document, document.body[i:k])
684 content = content.replace('"', r'\"')
685 subst = [put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")]
686 document.body[i:k+1] = subst
690 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
693 k = find_end_of_inset(document.body, i)
694 ptype = get_value(document.body, 'type', i, k).strip('"')
696 j = find_token(document.body, "type", i, k)
698 elif indices == "false":
699 del document.body[i:k+1]
701 subst = [put_cmd_in_ert("\\printindex[" + ptype + "]{}")]
702 document.body[i:k+1] = subst
706 def convert_splitindex(document):
707 " Converts index and printindex insets to splitindex-aware format "
710 i = find_token(document.body, "\\begin_inset Index", i)
713 document.body[i] = document.body[i].replace("\\begin_inset Index",
714 "\\begin_inset Index idx")
718 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
721 if document.body[i + 1].find('LatexCommand printindex') == -1:
722 document.warning("Malformed LyX document: Incomplete printindex inset.")
724 subst = ["LatexCommand printindex",
726 document.body[i + 1:i + 2] = subst
730 def revert_subindex(document):
731 " Reverts \\printsubindex CommandInset types "
732 i = find_token(document.header, '\\use_indices', 0)
734 document.warning("Malformed LyX document: Missing \\use_indices.")
736 indices = get_value(document.header, "\\use_indices", i)
739 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
742 k = find_end_of_inset(document.body, i)
743 ctype = get_value(document.body, 'LatexCommand', i, k)
744 if ctype != "printsubindex":
747 ptype = get_value(document.body, 'type', i, k).strip('"')
748 if indices == "false":
749 del document.body[i:k+1]
751 subst = [put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")]
752 document.body[i:k+1] = subst
756 def revert_printindexall(document):
757 " Reverts \\print[sub]index* CommandInset types "
758 i = find_token(document.header, '\\use_indices', 0)
760 document.warning("Malformed LyX document: Missing \\use_indices.")
762 indices = get_value(document.header, "\\use_indices", i)
765 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
768 k = find_end_of_inset(document.body, i)
769 ctype = get_value(document.body, 'LatexCommand', i, k)
770 if ctype != "printindex*" and ctype != "printsubindex*":
773 if indices == "false":
774 del document.body[i:k+1]
776 subst = [put_cmd_in_ert("\\" + ctype + "{}")]
777 document.body[i:k+1] = subst
781 def revert_strikeout(document):
782 " Reverts \\strikeout character style "
784 i = find_token(document.body, '\\strikeout', 0)
790 def revert_uulinewave(document):
791 " Reverts \\uuline, and \\uwave character styles "
793 i = find_token(document.body, '\\uuline', 0)
798 i = find_token(document.body, '\\uwave', 0)
804 def revert_ulinelatex(document):
805 " Reverts \\uline character style "
806 i = find_token(document.body, '\\bar under', 0)
809 insert_to_preamble(0, document,
810 '% Commands inserted by lyx2lyx for proper underlining\n'
811 + '\\PassOptionsToPackage{normalem}{ulem}\n'
812 + '\\usepackage{ulem}\n'
813 + '\\let\\cite@rig\\cite\n'
814 + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
815 + ' \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
816 + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
819 def revert_custom_processors(document):
820 " Remove bibtex_command and index_command params "
821 i = find_token(document.header, '\\bibtex_command', 0)
823 document.warning("Malformed LyX document: Missing \\bibtex_command.")
825 del document.header[i]
826 i = find_token(document.header, '\\index_command', 0)
828 document.warning("Malformed LyX document: Missing \\index_command.")
830 del document.header[i]
833 def convert_nomencl_width(document):
834 " Add set_width param to nomencl_print "
837 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
840 document.body.insert(i + 2, "set_width \"none\"")
844 def revert_nomencl_width(document):
845 " Remove set_width param from nomencl_print "
848 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
851 j = find_end_of_inset(document.body, i)
852 l = find_token(document.body, "set_width", i, j)
854 document.warning("Can't find set_width option for nomencl_print!")
861 def revert_nomencl_cwidth(document):
862 " Remove width param from nomencl_print "
865 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
868 j = find_end_of_inset(document.body, i)
869 l = find_token(document.body, "width", i, j)
871 document.warning("Can't find width option for nomencl_print!")
874 width = get_value(document.body, "width", i, j).strip('"')
876 add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
880 def revert_applemac(document):
881 " Revert applemac encoding to auto "
883 if document.encoding == "applemac":
884 document.encoding = "auto"
885 i = find_token(document.header, "\\encoding", 0)
887 document.header[i] = "\\encoding auto"
890 def revert_longtable_align(document):
891 " Remove longtable alignment setting "
895 i = find_token(document.body, "\\begin_inset Tabular", i)
898 # the alignment is 2 lines below \\begin_inset Tabular
899 j = document.body[i+2].find("longtabularalignment")
902 document.body[i+2] = document.body[i+2][:j-1]
903 document.body[i+2] = document.body[i+2] + '>'
907 def revert_branch_filename(document):
908 " Remove \\filename_suffix parameter from branches "
911 i = find_token(document.header, "\\filename_suffix", i)
914 del document.header[i]
917 def revert_paragraph_indentation(document):
918 " Revert custom paragraph indentation to preamble code "
921 i = find_token(document.header, "\\paragraph_indentation", i)
924 # only remove the preamble line when default
925 # otherwise also write the value to the preamble
926 j = document.header[i].find("default")
928 del document.header[i]
931 # search for the beginning of the value via the space
932 j = document.header[i].find(" ")
933 length = document.header[i][j+1:]
934 # handle percent lengths
935 length = latex_length(length)
936 # latex_length returns "bool,length"
938 length = length[k+1:]
939 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
940 add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
941 del document.header[i]
945 def revert_percent_skip_lengths(document):
946 " Revert relative lengths for paragraph skip separation to preamble code "
949 i = find_token(document.header, "\\defskip", i)
952 # only revert when a custom length was set and when
953 # it used a percent length
954 j = document.header[i].find("smallskip")
955 k = document.header[i].find("medskip")
956 l = document.header[i].find("bigskip")
957 if (j > -1) or (k > -1) or (l > -1):
960 # search for the beginning of the value via the space
961 j = document.header[i].find(" ")
962 length = document.header[i][j+1:]
963 # handle percent lengths
964 length = latex_length(length)
965 # latex_length returns "bool,length"
968 length = length[l+1:]
969 if percent == "True":
970 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
971 add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
972 # set defskip to medskip as default
973 document.header[i] = "\\defskip medskip"
977 def revert_percent_vspace_lengths(document):
978 " Revert relative VSpace lengths to ERT "
981 i = find_token(document.body, "\\begin_inset VSpace", i)
984 # only revert when a custom length was set and when
985 # it used a percent length
986 j = document.body[i].find("defskip")
987 k = document.body[i].find("smallskip")
988 l = document.body[i].find("medskip")
989 m = document.body[i].find("bigskip")
990 n = document.body[i].find("vfill")
991 if (j > -1) or (k > -1) or (l > -1) or (m > -1) or (n > -1):
994 # search for the beginning of the value via the last space
995 o = document.body[i].rfind(" ")
996 length = document.body[i][o+1:]
997 # check if the space has a star (protected space)
998 p = document.body[i].rfind("*")
1000 length = length[:-1]
1001 # handle percent lengths
1002 length = latex_length(length)
1003 # latex_length returns "bool,length"
1004 q = length.find(",")
1005 percent = length[:q]
1006 length = length[q+1:]
1007 # revert the VSpace inset to ERT
1008 if percent == "True":
1010 subst = [put_cmd_in_ert("\\vspace*{" + length + "}")]
1012 subst = [put_cmd_in_ert("\\vspace{" + length + "}")]
1013 document.body[i:i+2] = subst
1017 def revert_percent_hspace_lengths(document):
1018 " Revert relative HSpace lengths to ERT "
1022 i = find_token(document.body, "\\begin_inset space \hspace{}", i)
1024 j = find_token(document.body, "\\begin_inset space \hspace*{}", j)
1032 # only revert when a custom length was set and when
1033 # it used a percent length
1034 o = document.body[i+1].find("\\length")
1036 document.warning("Error: Cannot find lenght for \\hspace!")
1038 # search for the beginning of the value via the space
1039 k = document.body[i+1].find(" ")
1040 length = document.body[i+1][k+1:]
1041 # handle percent lengths
1042 length = latex_length(length)
1043 # latex_length returns "bool,length"
1044 m = length.find(",")
1045 percent = length[:m]
1046 length = length[m+1:]
1047 # revert the HSpace inset to ERT
1048 if percent == "True":
1050 subst = [put_cmd_in_ert("\\hspace*{" + length + "}")]
1052 subst = [put_cmd_in_ert("\\hspace{" + length + "}")]
1053 document.body[i:i+3] = subst
1058 def revert_hspace_glue_lengths(document):
1059 " Revert HSpace glue lengths to ERT "
1063 i = find_token(document.body, "\\begin_inset space \hspace{}", i)
1065 j = find_token(document.body, "\\begin_inset space \hspace*{}", j)
1073 o = document.body[i+1].find("\\length")
1075 document.warning("Error: Cannot find lenght for \\hspace!")
1077 # search for the beginning of the value via the space
1078 k = document.body[i+1].find(" ")
1079 length = document.body[i+1][k+1:]
1080 # only revert when the length contains a plus or minus
1081 l = length.find("+")
1083 l = length.find("-")
1086 # handle percent lengths
1087 length = latex_length(length)
1088 # latex_length returns "bool,length"
1089 m = length.find(",")
1090 length = length[m+1:]
1091 # revert the HSpace inset to ERT
1093 n = length.find("-")
1094 if n <> 0 or (n == 0 and (length.rfind("plus") > -1 or length.rfind("minus") > -1)):
1096 subst = [put_cmd_in_ert("\\hspace*{" + length + "}")]
1098 subst = [put_cmd_in_ert("\\hspace{" + length + "}")]
1099 document.body[i:i+3] = subst
1108 supported_versions = ["2.0.0","2.0"]
1109 convert = [[346, []],
1115 [352, [convert_splitindex]],
1122 [359, [convert_nomencl_width]],
1134 revert = [[367, [revert_hspace_glue_lengths]],
1135 [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
1136 [365, [revert_percent_skip_lengths]],
1137 [364, [revert_paragraph_indentation]],
1138 [363, [revert_branch_filename]],
1139 [362, [revert_longtable_align]],
1140 [361, [revert_applemac]],
1142 [359, [revert_nomencl_cwidth]],
1143 [358, [revert_nomencl_width]],
1144 [357, [revert_custom_processors]],
1145 [356, [revert_ulinelatex]],
1146 [355, [revert_uulinewave]],
1147 [354, [revert_strikeout]],
1148 [353, [revert_printindexall]],
1149 [352, [revert_subindex]],
1150 [351, [revert_splitindex]],
1151 [350, [revert_backgroundcolor]],
1152 [349, [revert_outputformat]],
1153 [348, [revert_xetex]],
1154 [347, [revert_phantom, revert_hphantom, revert_vphantom]],
1155 [346, [revert_tabularvalign]],
1156 [345, [revert_swiss]]
1160 if __name__ == "__main__":