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 concat(str0, str1, max_len):
20
    str0, str1 = map(to_raw_str, [str0, str1])
21
    return to_unicode(str0[:max_len-len(str1)]+str1)
22

    
23
def split(sep, str_):
24
    '''Returns [] if str_ == ""'''
25
    if str_ == '': return []
26
    else: return str_.split(sep)
27

    
28
def remove_prefix(prefix, str_, removed_ref=None):
29
    if removed_ref == None: removed_ref = [False]
30
    
31
    removed_ref[0] = str_.startswith(prefix)
32
    if removed_ref[0]: return str_[len(prefix):]
33
    else: return str_
34

    
35
def remove_prefixes(prefixes, str_):
36
    for prefix in prefixes: str_ = remove_prefix(prefix, str_)
37
    return str_
38

    
39
def with_prefixes(prefixes, str_): return (p+str_ for p in prefixes)
40

    
41
def remove_suffix(suffix, str_, removed_ref=None):
42
    if removed_ref == None: removed_ref = [False]
43
    
44
    removed_ref[0] = str_.endswith(suffix)
45
    if removed_ref[0]: return str_[:-len(suffix)]
46
    else: return str_
47

    
48
def contains_any(haystack, needles):
49
    for needle in needles:
50
        if haystack.find(needle) >= 0: return True
51
    return False
52

    
53
def overlaps(str0, str1): return str0.find(str1) >= 0 or str1.find(str0) >= 0
54

    
55
##### Escaping
56

    
57
def esc_for_mogrify(query):
58
    '''Escapes a query right before being passed to a mogrifying function.'''
59
    return query.replace('%', '%%')
60

    
61
##### Unicode
62

    
63
def to_raw_str(str_):
64
    if isinstance(str_, unicode): str_ = str_.encode('utf_8')
65
    return str_
66

    
67
unicode_reader = codecs.getreader('utf_8')
68

    
69
def to_unicode(str_):
70
    if isinstance(str_, unicode): return str_
71
    encodings = ['utf_8', 'latin_1']
72
    for encoding in encodings:
73
        try: return unicode(str_, encoding)
74
        except UnicodeDecodeError, e: pass
75
    raise AssertionError(encoding+' is not a catch-all encoding')
76

    
77
def ustr(value):
78
    '''Like built-in str() but converts to unicode object'''
79
    if util.is_str(value): str_ = value # already a string
80
    elif hasattr(value, '__str__'): str_ = value.__str__()
81
    else: str_ = str(value)
82
    return to_unicode(str_)
83

    
84
def urepr(value):
85
    '''Like built-in repr() but converts to unicode object'''
86
    if hasattr(value, '__repr__'): str_ = value.__repr__()
87
    else: str_ = repr(value)
88
    return to_unicode(str_)
89

    
90
def repr_no_u(value):
91
    '''Like built-in repr() but removes the "u" in `u'...'`'''
92
    return re.sub(r"^u(?=')", r'', urepr(value))
93

    
94
##### Line endings
95

    
96
def extract_line_ending(line):
97
    '''@return tuple (contents, ending)'''
98
    contents = remove_suffix('\r', remove_suffix('\n', line))
99
    return (contents, line[len(contents):])
100

    
101
def remove_line_ending(line): return extract_line_ending(line)[0]
102

    
103
def ensure_newl(str_): return remove_line_ending(str_)+'\n'
104

    
105
def is_multiline(str_):
106
    newl_idx = str_.find('\n')
107
    return newl_idx >= 0 and newl_idx != len(str_)-1 # has newline before end
108

    
109
def remove_extra_newl(str_):
110
    if is_multiline(str_): return str_
111
    else: return str_.rstrip('\n')
112

    
113
def std_newl(str_): return str_.replace('\r\n', '\n').replace('\r', '\n')
114

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

    
117
##### Whitespace
118

    
119
def cleanup(str_): return std_newl(str_.strip())
120

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

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

    
125
##### Control characters
126

    
127
def is_ctrl(char):
128
    '''Whether char is a (non-printable) control character'''
129
    return ord(char) < 32 and not char.isspace()
130

    
131
def strip_ctrl(str_):
132
    '''Strips (non-printable) control characters'''
133
    return ''.join(filter(lambda c: not is_ctrl(c), str_))
134

    
135
##### Text
136

    
137
def first_word(str_): return str_.partition(' ')[0]
138

    
139
##### Formatting
140

    
141
def indent(str_, level=1, indent_str='    '):
142
    indent_str *= level
143
    return ('\n'.join((indent_str+l for l in str_.rstrip().split('\n'))))+'\n'
144

    
145
def as_tt(str_): return '@'+str_+'@'
146

    
147
def as_code(str_, lang=None, multiline=True):
148
    '''Wraps a string in Redmine tags to syntax-highlight it.'''
149
    str_ = '\n'+str_.rstrip('\n')+'\n'
150
    if lang != None: str_ = '<code class="'+lang+'">'+str_+'</code>'
151
    if multiline: str_ = '<pre>'+str_+'</pre>'
152
    return str_
153

    
154
def as_inline_table(dict_, key_label='Output', value_label='Input', ustr=ustr):
155
    '''Wraps a dict in Redmine tags to format it as a table.'''
156
    str_ = ''
157
    def row(entry): return (': '.join(entry))+'\n'
158
    str_ += row([key_label, value_label])
159
    for entry in dict_.iteritems(): str_ += row([ustr(v) for v in entry])
160
    return '<pre>\n'+str_+'</pre>'
161

    
162
def as_table(dict_, key_label='Output', value_label='Input', ustr=ustr):
163
    '''Wraps a dict in Redmine tags to format it as a table.'''
164
    str_ = ''
165
    def row(entry): return ('|'.join(['']+entry+['']))+'\n'# '' for outer border
166
    str_ += row([key_label, value_label])
167
    for entry in dict_.iteritems(): str_ += row([as_tt(ustr(v)) for v in entry])
168
    return '\n'+str_+' ' # space protects last \n so blank line ends table
(31-31/40)