Project

General

Profile

1
# String manipulation
2

    
3
import codecs
4
import re
5

    
6
import util
7

    
8
##### Sentinel values
9

    
10
class NonInternedStr(str):
11
    '''Each instance is unique and does not compare identical with `is`.'''
12
    pass
13

    
14
none_str = NonInternedStr()
15
isspace_none_str = '\r\n\t\v' # clone-safe, but must be compared with ==
16

    
17
##### Parsing
18

    
19
def raw_extra_len(str_):
20
    '''Calculates the difference between the character length and byte length of
21
    a string. These lengths will differ for Unicode strings containing
22
    multi-byte characters.'''
23
    return len(to_raw_str(str_))-len(str_)
24

    
25
def concat(str0, str1, max_len):
26
    # Use to_unicode so that substring does not split Unicode characters
27
    str0, str1 = map(to_unicode, [str0, str1])
28
    # Use to_raw_str() because Unicode characters can be multi-byte, and length
29
    # limits often apply to the byte length, not the character length.
30
    return str0[:max_len-len(to_raw_str(str1))]+str1
31

    
32
def split(sep, str_):
33
    '''Returns [] if str_ == ""'''
34
    if str_ == '': return []
35
    else: return str_.split(sep)
36

    
37
def remove_prefix(prefix, str_, removed_ref=None):
38
    if removed_ref == None: removed_ref = [False]
39
    
40
    removed_ref[0] = str_.startswith(prefix)
41
    if removed_ref[0]: return str_[len(prefix):]
42
    else: return str_
43

    
44
def remove_prefixes(prefixes, str_):
45
    for prefix in prefixes: str_ = remove_prefix(prefix, str_)
46
    return str_
47

    
48
def with_prefixes(prefixes, str_): return (p+str_ for p in prefixes)
49

    
50
def remove_suffix(suffix, str_, removed_ref=None):
51
    if removed_ref == None: removed_ref = [False]
52
    
53
    removed_ref[0] = str_.endswith(suffix)
54
    if removed_ref[0]: return str_[:-len(suffix)]
55
    else: return str_
56

    
57
def contains_any(haystack, needles):
58
    for needle in needles:
59
        if haystack.find(needle) >= 0: return True
60
    return False
61

    
62
def overlaps(str0, str1): return str0.find(str1) >= 0 or str1.find(str0) >= 0
63

    
64
##### Escaping
65

    
66
def esc_for_mogrify(query):
67
    '''Escapes a query right before being passed to a mogrifying function.'''
68
    return query.replace('%', '%%')
69

    
70
##### Unicode
71

    
72
def to_raw_str(str_):
73
    if isinstance(str_, unicode): str_ = str_.encode('utf_8')
74
    return str_
75

    
76
unicode_reader = codecs.getreader('utf_8')
77

    
78
def to_unicode(str_):
79
    if isinstance(str_, unicode): return str_
80
    encodings = ['utf_8', 'latin_1']
81
    for encoding in encodings:
82
        try: return unicode(str_, encoding)
83
        except UnicodeDecodeError, e: pass
84
    raise AssertionError(encoding+' is not a catch-all encoding')
85

    
86
def ustr(value):
87
    '''Like built-in str() but converts to unicode object'''
88
    if util.is_str(value): str_ = value # already a string
89
    elif hasattr(value, '__str__'): str_ = value.__str__()
90
    else: str_ = str(value)
91
    return to_unicode(str_)
92

    
93
def urepr(value):
94
    '''Like built-in repr() but converts to unicode object'''
95
    if hasattr(value, '__repr__'): str_ = value.__repr__()
96
    else: str_ = repr(value)
97
    return to_unicode(str_)
98

    
99
def repr_no_u(value):
100
    '''Like built-in repr() but removes the "u" in `u'...'`'''
101
    return re.sub(r"^u(?=')", r'', urepr(value))
102

    
103
##### Line endings
104

    
105
def extract_line_ending(line):
106
    '''@return tuple (contents, ending)'''
107
    contents = remove_suffix('\r', remove_suffix('\n', line))
108
    return (contents, line[len(contents):])
109

    
110
def remove_line_ending(line): return extract_line_ending(line)[0]
111

    
112
def ensure_newl(str_): return remove_line_ending(str_)+'\n'
113

    
114
def is_multiline(str_):
115
    newl_idx = str_.find('\n')
116
    return newl_idx >= 0 and newl_idx != len(str_)-1 # has newline before end
117

    
118
def remove_extra_newl(str_):
119
    if is_multiline(str_): return str_
120
    else: return str_.rstrip('\n')
121

    
122
def std_newl(str_): return str_.replace('\r\n', '\n').replace('\r', '\n')
123

    
124
def join_lines(lines): return ''.join((l+'\n' for l in lines))
125

    
126
##### Whitespace
127

    
128
def cleanup(str_): return std_newl(str_.strip())
129

    
130
def single_space(str_): return re.sub(r' {2,}', r' ', str_.strip())
131

    
132
def one_line(str_): return re.sub(r'\n *', r' ', cleanup(str_))
133

    
134
##### Control characters
135

    
136
def is_ctrl(char):
137
    '''Whether char is a (non-printable) control character'''
138
    return ord(char) < 32 and not char.isspace()
139

    
140
def strip_ctrl(str_):
141
    '''Strips (non-printable) control characters'''
142
    return ''.join(filter(lambda c: not is_ctrl(c), str_))
143

    
144
##### Text
145

    
146
def first_word(str_): return str_.partition(' ')[0]
147

    
148
##### Formatting
149

    
150
def indent(str_, level=1, indent_str='    '):
151
    indent_str *= level
152
    return ('\n'.join((indent_str+l for l in str_.rstrip().split('\n'))))+'\n'
153

    
154
def as_tt(str_): return '@'+str_+'@'
155

    
156
def as_code(str_, lang=None, multiline=True):
157
    '''Wraps a string in Redmine tags to syntax-highlight it.'''
158
    str_ = '\n'+str_.rstrip('\n')+'\n'
159
    if lang != None: str_ = '<code class="'+lang+'">'+str_+'</code>'
160
    if multiline: str_ = '<pre>'+str_+'</pre>'
161
    return str_
162

    
163
def as_inline_table(dict_, key_label='Output', value_label='Input', ustr=ustr):
164
    '''Wraps a dict in Redmine tags to format it as a table.'''
165
    str_ = ''
166
    def row(entry): return (': '.join(entry))+'\n'
167
    str_ += row([key_label, value_label])
168
    for entry in dict_.iteritems(): str_ += row([ustr(v) for v in entry])
169
    return '<pre>\n'+str_+'</pre>'
170

    
171
def as_table(dict_, key_label='Output', value_label='Input', ustr=ustr):
172
    '''Wraps a dict in Redmine tags to format it as a table.'''
173
    str_ = ''
174
    def row(entry): return ('|'.join(['']+entry+['']))+'\n'# '' for outer border
175
    str_ += row([key_label, value_label])
176
    for entry in dict_.iteritems(): str_ += row([as_tt(ustr(v)) for v in entry])
177
    return '\n'+str_+' ' # space protects last \n so blank line ends table
(31-31/40)