]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx2lyx_tools.py
Improve hex2ratio.
[lyx.git] / lib / lyx2lyx / lyx2lyx_tools.py
1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2010 The LyX team
4 #
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.
9 #
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.
14 #
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.
18
19 " This modules offer several free functions to help with lyx2lyx'ing. "
20
21 import string
22 from parser_tools import find_token
23 from unicode_symbols import unicode_reps
24
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!"""
29
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')
35
36     if find_token(document.preamble, text[0], 0) != -1:
37         return
38
39     document.preamble.extend(text)
40
41
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"""
46     
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')
52
53     document.preamble[index:index] = text
54
55
56 # This routine wraps some content in an ERT inset. 
57 #
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.
61
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 
64 # lyx2lyx very much.
65 #
66 # A call to this routine will often go something like this:
67 #   i = find_token('\\begin_inset FunkyInset', ...)
68 #   ...
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,
76 # this would be: 
77 #   i += len(ert)
78 # That puts us right after the ERT we just inserted.
79 #
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.
85     if type(arg) is list:
86       s = "\n".join(arg)
87     else:
88       s = arg
89     for rep in unicode_reps:
90       s = s.replace(rep[1], rep[0].replace('\\\\', '\\'))
91     s = s.replace('\\', "\\backslash\n")
92     ret += s.splitlines()
93     ret += ["\\end_layout", "\\end_inset"]
94     return ret
95
96             
97 def lyx2latex(document, lines):
98     'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
99     # clean up multiline stuff
100     content = ""
101     ert_end = 0
102     note_end = 0
103     hspace = ""
104
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)
110           continue
111       elif note_end >= curline:
112           # Skip LyX notes
113           continue
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)
118           continue
119       elif line.startswith("\\begin_inset Formula"):
120           line = line[20:]
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()
125           # lang = qtype[0]
126           side = qtype[1]
127           dbls = qtype[2]
128           if side == "l":
129               if dbls == "d":
130                   line = "``"
131               else:
132                   line = "`"
133           else:
134               if dbls == "d":
135                   line = "''"
136               else:
137                   line = "'"
138       elif line.startswith("\\begin_inset space"):
139           line = line[18:].strip()
140           if line.startswith("\\hspace"):
141               # Account for both \hspace and \hspace*
142               hspace = line[:-2]
143               continue
144           elif line == "\\space{}":
145               line = "\\ "
146           elif line == "\\thinspace{}":
147               line = "\\,"
148       elif hspace != "":
149           # The LyX length is in line[8:], after the \length keyword
150           length = latex_length(line[8:])[1]
151           line = hspace + "{" + length + "}"
152           hspace = ""
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":
161           #skip all that stuff
162           continue
163
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', '\\')
173       else:
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('$', '\\$')
181
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'')
195       content += line
196     return content
197
198
199 def latex_length(slen):
200     ''' 
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.
204     '''
205     i = 0
206     percent = False
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 -
212
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():
218         i = slen.find(unit)
219         if i == -1:
220             continue
221         percent = True
222         minus = slen.rfind("-", 1, i)
223         plus = slen.rfind("+", 0, i)
224         latex_unit = units[unit]
225         if plus == -1 and minus == -1:
226             value = slen[:i]
227             value = str(float(value)/100)
228             end = slen[i + len(unit):]
229             slen = value + latex_unit + end
230         if plus > minus:
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
236         if plus < minus:
237             value = slen[minus + 1:i]
238             value = str(float(value)/100)
239             begin = slen[:minus + 1]
240             slen = begin + value + latex_unit
241
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)
251
252
253 def revert_flex_inset(document, name, LaTeXname, position):
254   " Convert flex insets to TeX code "
255   i = position
256   while True:
257     i = find_token(document.body, '\\begin_inset Flex ' + name, i)
258     if i == -1:
259       return
260     z = find_end_of_inset(document.body, i)
261     if z == -1:
262       document.warning("Malformed LyX document: Can't find end of Flex " + name + " inset.")
263       return
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)
278     if j != -1:
279       document.body.insert(z - 2, "\\emph default")
280     if k != -1:
281       document.body.insert(z - 2, "\\noun default")
282     if l != -1:
283       document.body.insert(z - 2, "\\series default")
284     if m != -1:
285       document.body.insert(z - 2, "\\family default")
286     if n != -1:
287       document.body.insert(z - 2, "\\shape default")
288     if o != -1:
289       document.body.insert(z - 2, "\\color inherit")
290     if p != -1:
291       document.body.insert(z - 2, "\\size default")
292     if q != -1:
293       document.body.insert(z - 2, "\\bar default")
294     if r != -1:
295       document.body.insert(z - 2, "\\uuline default")
296     if s != -1:
297       document.body.insert(z - 2, "\\uwave default")
298     if t != -1:
299       document.body.insert(z - 2, "\\strikeout default")
300     document.body[i:i + 4] = put_cmd_in_ert(LaTeXname + "{")
301     i += 1
302
303
304 def revert_font_attrs(document, name, LaTeXname):
305   " Reverts font changes to TeX code "
306   i = 0
307   changed = False
308   while True:
309     i = find_token(document.body, name + ' on', i)
310     if i == -1:
311       return changed
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("}")
318     else:
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 + "{")
322     changed = True
323     i += 1
324
325
326 def revert_layout_command(document, name, LaTeXname, position):
327   " Reverts a command from a layout to TeX code "
328   i = position
329   while True:
330     i = find_token(document.body, '\\begin_layout ' + name, i)
331     if i == -1:
332       return
333     k = -1
334     # find the next layout
335     j = i + 1
336     while k == -1:
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
340       if j == -1:
341         document.body[l - 4:l - 4] = put_cmd_in_ert("}")
342         k = 0
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("}")
346         k = 0
347       else:
348         j += 1
349     document.body[i] = '\\begin_layout Standard'
350     document.body[i + 1:i + 1] = put_cmd_in_ert(LaTeXname + "{")
351     i += 1
352
353
354 def hex2ratio(s):
355   try:
356     val = int(s, 16)
357   except:
358     val = 0
359   if val != 0:
360     val += 1
361   return str(val / 256.0)
362