1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2010 The LyX team
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 " This modules offer several free functions to help with lyx2lyx'ing. "
22 from parser_tools import find_token
23 from unicode_symbols import unicode_reps
25 # Note that text can be either a list of lines or a single line.
26 def add_to_preamble(document, text):
27 """ Add text to the preamble if it is not already there.
28 Only the first line is checked!"""
30 if not type(text) is list:
31 # split on \n just in case
32 # it'll give us the one element list we want
33 # if there's no \n, too
34 text = text.split('\n')
36 if find_token(document.preamble, text[0], 0) != -1:
39 document.preamble.extend(text)
42 # Note that text can be either a list of lines or a single line.
43 # It should really be a list.
44 def insert_to_preamble(index, document, text):
45 """ Insert text to the preamble at a given line"""
47 if not type(text) is list:
48 # split on \n just in case
49 # it'll give us the one element list we want
50 # if there's no \n, too
51 text = text.split('\n')
53 document.preamble[index:index] = text
56 # This routine wraps some content in an ERT inset.
58 # NOTE: The function accepts either a single string or a LIST of strings as
59 # argument. But it returns a LIST of strings, split on \n, so that it does
60 # not have embedded newlines.
62 # This is how lyx2lyx represents a LyX document: as a list of strings,
63 # each representing a line of a LyX file. Embedded newlines confuse
66 # A call to this routine will often go something like this:
67 # i = find_token('\\begin_inset FunkyInset', ...)
69 # j = find_end_of_inset(document.body, i)
70 # content = ...extract content from insets
71 # # that could be as simple as:
72 # # content = lyx2latex(document[i:j + 1])
73 # ert = put_cmd_in_ert(content)
74 # document.body[i:j] = ert
75 # Now, before we continue, we need to reset i appropriately. Normally,
78 # That puts us right after the ERT we just inserted.
80 def put_cmd_in_ert(arg):
81 ret = ["\\begin_inset ERT", "status collapsed", "\\begin_layout Plain Layout", ""]
82 # Despite the warnings just given, it will be faster for us to work
83 # with a single string internally. That way, we only go through the
84 # unicode_reps loop once.
89 for rep in unicode_reps:
90 s = s.replace(rep[1], rep[0].replace('\\\\', '\\'))
91 s = s.replace('\\', "\\backslash\n")
93 ret += ["\\end_layout", "\\end_inset"]
97 def lyx2latex(document, lines):
98 'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
99 # clean up multiline stuff
105 for curline in range(len(lines)):
106 line = lines[curline]
107 if line.startswith("\\begin_inset Note Note"):
108 # We want to skip LyX notes, so remember where the inset ends
109 note_end = find_end_of_inset(lines, curline + 1)
111 elif note_end >= curline:
114 elif line.startswith("\\begin_inset ERT"):
115 # We don't want to replace things inside ERT, so figure out
116 # where the end of the inset is.
117 ert_end = find_end_of_inset(lines, curline + 1)
119 elif line.startswith("\\begin_inset Formula"):
121 elif line.startswith("\\begin_inset Quotes"):
122 # For now, we do a very basic reversion. Someone who understands
123 # quotes is welcome to fix it up.
124 qtype = line[20:].strip()
138 elif line.startswith("\\begin_inset space"):
139 line = line[18:].strip()
140 if line.startswith("\\hspace"):
141 # Account for both \hspace and \hspace*
144 elif line == "\\space{}":
146 elif line == "\\thinspace{}":
149 # The LyX length is in line[8:], after the \length keyword
150 length = latex_length(line[8:])[1]
151 line = hspace + "{" + length + "}"
153 elif line.isspace() or \
154 line.startswith("\\begin_layout") or \
155 line.startswith("\\end_layout") or \
156 line.startswith("\\begin_inset") or \
157 line.startswith("\\end_inset") or \
158 line.startswith("\\lang") or \
159 line.strip() == "status collapsed" or \
160 line.strip() == "status open":
164 # this needs to be added to the preamble because of cases like
165 # \textmu, \textbackslash, etc.
166 add_to_preamble(document, ['% added by lyx2lyx for converted index entries',
167 '\\@ifundefined{textmu}',
168 ' {\\usepackage{textcomp}}{}'])
169 # a lossless reversion is not possible
170 # try at least to handle some common insets and settings
171 if ert_end >= curline:
172 line = line.replace(r'\backslash', '\\')
174 # No need to add "{}" after single-nonletter macros
175 line = line.replace('&', '\\&')
176 line = line.replace('#', '\\#')
177 line = line.replace('^', '\\textasciicircum{}')
178 line = line.replace('%', '\\%')
179 line = line.replace('_', '\\_')
180 line = line.replace('$', '\\$')
182 # Do the LyX text --> LaTeX conversion
183 for rep in unicode_reps:
184 line = line.replace(rep[1], rep[0] + "{}")
185 line = line.replace(r'\backslash', r'\textbackslash{}')
186 line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
187 line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
188 line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
189 line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
190 line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
191 line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
192 line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
193 line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
194 line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
199 def latex_length(slen):
201 Convert lengths to their LaTeX representation. Returns (bool, length),
202 where the bool tells us if it was a percentage, and the length is the
203 LaTeX representation.
207 # the slen has the form
208 # ValueUnit+ValueUnit-ValueUnit or
209 # ValueUnit+-ValueUnit
210 # the + and - (glue lengths) are optional
211 # the + always precedes the -
213 # Convert relative lengths to LaTeX units
214 units = {"text%":"\\textwidth", "col%":"\\columnwidth",
215 "page%":"\\paperwidth", "line%":"\\linewidth",
216 "theight%":"\\textheight", "pheight%":"\\paperheight"}
217 for unit in units.keys():
222 minus = slen.rfind("-", 1, i)
223 plus = slen.rfind("+", 0, i)
224 latex_unit = units[unit]
225 if plus == -1 and minus == -1:
227 value = str(float(value)/100)
228 end = slen[i + len(unit):]
229 slen = value + latex_unit + end
231 value = slen[plus + 1:i]
232 value = str(float(value)/100)
233 begin = slen[:plus + 1]
234 end = slen[i+len(unit):]
235 slen = begin + value + latex_unit + end
237 value = slen[minus + 1:i]
238 value = str(float(value)/100)
239 begin = slen[:minus + 1]
240 slen = begin + value + latex_unit
242 # replace + and -, but only if the - is not the first character
243 slen = slen[0] + slen[1:].replace("+", " plus ").replace("-", " minus ")
244 # handle the case where "+-1mm" was used, because LaTeX only understands
245 # "plus 1mm minus 1mm"
246 if slen.find("plus minus"):
247 lastvaluepos = slen.rfind(" ")
248 lastvalue = slen[lastvaluepos:]
249 slen = slen.replace(" ", lastvalue + " ")
250 return (percent, slen)
253 def revert_flex_inset(document, name, LaTeXname, position):
254 " Convert flex insets to TeX code "
257 i = find_token(document.body, '\\begin_inset Flex ' + name, i)
260 z = find_end_of_inset(document.body, i)
262 document.warning("Malformed LyX document: Can't find end of Flex " + name + " inset.")
264 # remove the \end_inset
265 document.body[z - 2:z + 1] = put_cmd_in_ert("}")
266 # we need to reset character layouts if necessary
267 j = find_token(document.body, '\\emph on', i, z)
268 k = find_token(document.body, '\\noun on', i, z)
269 l = find_token(document.body, '\\series', i, z)
270 m = find_token(document.body, '\\family', i, z)
271 n = find_token(document.body, '\\shape', i, z)
272 o = find_token(document.body, '\\color', i, z)
273 p = find_token(document.body, '\\size', i, z)
274 q = find_token(document.body, '\\bar under', i, z)
275 r = find_token(document.body, '\\uuline on', i, z)
276 s = find_token(document.body, '\\uwave on', i, z)
277 t = find_token(document.body, '\\strikeout on', i, z)
279 document.body.insert(z - 2, "\\emph default")
281 document.body.insert(z - 2, "\\noun default")
283 document.body.insert(z - 2, "\\series default")
285 document.body.insert(z - 2, "\\family default")
287 document.body.insert(z - 2, "\\shape default")
289 document.body.insert(z - 2, "\\color inherit")
291 document.body.insert(z - 2, "\\size default")
293 document.body.insert(z - 2, "\\bar default")
295 document.body.insert(z - 2, "\\uuline default")
297 document.body.insert(z - 2, "\\uwave default")
299 document.body.insert(z - 2, "\\strikeout default")
300 document.body[i:i + 4] = put_cmd_in_ert(LaTeXname + "{")
304 def revert_font_attrs(document, name, LaTeXname):
305 " Reverts font changes to TeX code "
309 i = find_token(document.body, name + ' on', i)
312 j = find_token(document.body, name + ' default', i)
313 k = find_token(document.body, name + ' on', i + 1)
314 # if there is no default set, the style ends with the layout
315 # assure hereby that we found the correct layout end
316 if j != -1 and (j < k or k == -1):
317 document.body[j:j + 1] = put_cmd_in_ert("}")
319 j = find_token(document.body, '\\end_layout', i)
320 document.body[j:j] = put_cmd_in_ert("}")
321 document.body[i:i + 1] = put_cmd_in_ert(LaTeXname + "{")
326 def revert_layout_command(document, name, LaTeXname, position):
327 " Reverts a command from a layout to TeX code "
330 i = find_token(document.body, '\\begin_layout ' + name, i)
334 # find the next layout
337 j = find_token(document.body, '\\begin_layout', j)
338 l = len(document.body)
339 # if nothing was found it was the last layout of the document
341 document.body[l - 4:l - 4] = put_cmd_in_ert("}")
343 # exclude plain layout because this can be TeX code or another inset
344 elif document.body[j] != '\\begin_layout Plain Layout':
345 document.body[j - 2:j - 2] = put_cmd_in_ert("}")
349 document.body[i] = '\\begin_layout Standard'
350 document.body[i + 1:i + 1] = put_cmd_in_ert(LaTeXname + "{")
361 return str(val / 256.0)