Reported bug with utf-8 strings
[be.git] / interfaces / web / Bugs-Everywhere-Web / beweb / formatting.py
1 from StringIO import StringIO
2
3 try :
4    from xml.etree.ElementTree import XML # Python 2.5 (and greater?)
5 except ImportError :
6    from elementtree.ElementTree import XML
7 from libbe.restconvert import rest_xml
8
9 def to_unix(text):
10    skip_newline = False
11    for ch in text:
12       if ch not in ('\r', '\n'):
13          yield ch
14       else:
15          if ch == '\n':
16             if skip_newline:
17                continue
18          else:
19             skip_newline = True
20          yield '\n'
21
22
23 def soft_text(text):
24    first_space = False
25    translations = {'\n': '<br />\n', '&': '&amp;', '\x3c': '&lt;', 
26                    '\x3e': '&gt;'}
27    for ch in to_unix(text):
28       if ch == ' ' and first_space is True:
29             yield '&#160;'
30       first_space = ch in (' ')
31       try:
32          yield translations[ch]
33       except KeyError:
34          yield ch
35
36
37 def soft_pre(text):
38    return XML('<div style="font-family: monospace">'+
39               ''.join(soft_text(text)).encode('utf-8')+'</div>') 
40
41
42 def get_rest_body(rest):
43     xml, warnings = rest_xml(StringIO(rest))
44     return xml.find('{http://www.w3.org/1999/xhtml}body'), warnings
45  
46
47 def comment_body_xhtml(comment):
48     if comment.content_type == "text/restructured":
49         return get_rest_body(comment.body)[0]
50     else:
51         return soft_pre(comment.body)
52
53
54 def select_among(name, options, default, display_names=None):
55     output = ['<select name="%s">' % name]
56     for option in options:
57         if option == default:
58             selected = ' selected="selected"'
59         else:
60             selected = ""
61         if display_names is None:
62             display_name = None
63         else:
64             display_name = display_names.get(option)
65
66         if option is None:
67             option = ""
68         if display_name is None:
69             display_name = option
70             value = ""
71         else:
72             value = ' value="%s"' % option
73         output.append("<option%s%s>%s</option>" % (selected, value, 
74                                                    display_name))
75     output.append("</select>")
76     return XML("".join(output))