2012-06-08 00:08:47 +08:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
import re
|
2011-07-14 21:47:10 +08:00
|
|
|
import unicodedata
|
2011-07-13 17:35:51 +08:00
|
|
|
from gzip import GzipFile
|
2012-05-06 01:47:03 +08:00
|
|
|
from io import BytesIO
|
2014-02-21 21:46:23 +08:00
|
|
|
import warnings
|
2011-07-13 17:35:51 +08:00
|
|
|
|
2012-08-16 10:08:16 +08:00
|
|
|
from django.utils.encoding import force_text
|
2011-07-14 21:47:10 +08:00
|
|
|
from django.utils.functional import allow_lazy, SimpleLazyObject
|
2012-07-20 20:48:51 +08:00
|
|
|
from django.utils import six
|
2012-08-23 16:16:16 +08:00
|
|
|
from django.utils.six.moves import html_entities
|
2011-07-14 21:47:10 +08:00
|
|
|
from django.utils.translation import ugettext_lazy, ugettext as _, pgettext
|
2012-08-18 20:53:22 +08:00
|
|
|
from django.utils.safestring import mark_safe
|
2005-12-04 20:06:16 +08:00
|
|
|
|
2013-09-02 18:06:32 +08:00
|
|
|
if six.PY2:
|
2012-08-23 16:23:23 +08:00
|
|
|
# Import force_unicode even though this module doesn't use it, because some
|
|
|
|
# people rely on it being here.
|
2013-10-18 19:25:30 +08:00
|
|
|
from django.utils.encoding import force_unicode # NOQA
|
2012-08-23 16:23:23 +08:00
|
|
|
|
2013-12-26 20:46:15 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
# Capitalizes the first letter of a string.
|
2012-07-21 16:00:10 +08:00
|
|
|
capfirst = lambda x: x and force_text(x)[0].upper() + force_text(x)[1:]
|
2012-07-20 20:48:51 +08:00
|
|
|
capfirst = allow_lazy(capfirst, six.text_type)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2011-07-14 21:47:10 +08:00
|
|
|
# Set up regular expressions
|
2013-10-21 20:52:21 +08:00
|
|
|
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S)
|
2013-01-10 17:27:20 +08:00
|
|
|
re_chars = re.compile(r'<.*?>|(.)', re.U | re.S)
|
2013-02-14 01:24:49 +08:00
|
|
|
re_tag = re.compile(r'<(/)?([^ ]+?)(?:(\s*/)| .*?)?>', re.S)
|
2013-12-07 16:54:50 +08:00
|
|
|
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
|
2013-12-26 20:46:15 +08:00
|
|
|
re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))')
|
2011-07-14 21:47:10 +08:00
|
|
|
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def wrap(text, width):
|
|
|
|
"""
|
|
|
|
A word-wrap function that preserves existing line breaks and most spaces in
|
2006-12-16 03:05:57 +08:00
|
|
|
the text. Expects that existing line breaks are posix newlines.
|
2005-07-13 09:25:57 +08:00
|
|
|
"""
|
2012-07-21 16:00:10 +08:00
|
|
|
text = force_text(text)
|
2013-10-22 18:21:07 +08:00
|
|
|
|
2006-12-16 03:05:57 +08:00
|
|
|
def _generator():
|
|
|
|
it = iter(text.split(' '))
|
2012-05-11 02:14:04 +08:00
|
|
|
word = next(it)
|
2006-12-16 03:05:57 +08:00
|
|
|
yield word
|
|
|
|
pos = len(word) - word.rfind('\n') - 1
|
|
|
|
for word in it:
|
|
|
|
if "\n" in word:
|
2007-03-20 19:07:52 +08:00
|
|
|
lines = word.split('\n')
|
2006-12-16 03:05:57 +08:00
|
|
|
else:
|
|
|
|
lines = (word,)
|
|
|
|
pos += len(lines[0]) + 1
|
|
|
|
if pos > width:
|
|
|
|
yield '\n'
|
|
|
|
pos = len(lines[-1])
|
|
|
|
else:
|
|
|
|
yield ' '
|
|
|
|
if len(lines) > 1:
|
|
|
|
pos = len(lines[-1])
|
|
|
|
yield word
|
2012-06-08 00:08:47 +08:00
|
|
|
return ''.join(_generator())
|
2012-07-20 20:48:51 +08:00
|
|
|
wrap = allow_lazy(wrap, six.text_type)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2010-08-07 22:57:24 +08:00
|
|
|
|
2011-07-14 21:47:10 +08:00
|
|
|
class Truncator(SimpleLazyObject):
|
2010-08-07 22:57:24 +08:00
|
|
|
"""
|
2011-07-14 21:47:10 +08:00
|
|
|
An object used to truncate text, either by characters or words.
|
|
|
|
"""
|
|
|
|
def __init__(self, text):
|
2012-07-21 16:00:10 +08:00
|
|
|
super(Truncator, self).__init__(lambda: force_text(text))
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2011-07-14 21:47:10 +08:00
|
|
|
def add_truncation_text(self, text, truncate=None):
|
|
|
|
if truncate is None:
|
|
|
|
truncate = pgettext(
|
|
|
|
'String to return when truncating text',
|
2012-06-08 00:08:47 +08:00
|
|
|
'%(truncated_text)s...')
|
2012-07-21 16:00:10 +08:00
|
|
|
truncate = force_text(truncate)
|
2011-07-14 21:47:10 +08:00
|
|
|
if '%(truncated_text)s' in truncate:
|
|
|
|
return truncate % {'truncated_text': text}
|
|
|
|
# The truncation text didn't contain the %(truncated_text)s string
|
|
|
|
# replacement argument so just append it to the text.
|
|
|
|
if text.endswith(truncate):
|
|
|
|
# But don't append the truncation text if the current text already
|
|
|
|
# ends in this.
|
|
|
|
return text
|
|
|
|
return '%s%s' % (text, truncate)
|
2010-08-07 22:57:24 +08:00
|
|
|
|
2013-01-10 17:27:20 +08:00
|
|
|
def chars(self, num, truncate=None, html=False):
|
2011-07-14 21:47:10 +08:00
|
|
|
"""
|
|
|
|
Returns the text truncated to be no longer than the specified number
|
|
|
|
of characters.
|
|
|
|
|
|
|
|
Takes an optional argument of what should be used to notify that the
|
|
|
|
string has been truncated, defaulting to a translatable string of an
|
|
|
|
ellipsis (...).
|
|
|
|
"""
|
|
|
|
length = int(num)
|
|
|
|
text = unicodedata.normalize('NFC', self._wrapped)
|
|
|
|
|
|
|
|
# Calculate the length to truncate to (max length - end_text length)
|
|
|
|
truncate_len = length
|
|
|
|
for char in self.add_truncation_text('', truncate):
|
|
|
|
if not unicodedata.combining(char):
|
|
|
|
truncate_len -= 1
|
|
|
|
if truncate_len == 0:
|
|
|
|
break
|
2013-01-10 17:27:20 +08:00
|
|
|
if html:
|
|
|
|
return self._truncate_html(length, truncate, text, truncate_len, False)
|
|
|
|
return self._text_chars(length, truncate, text, truncate_len)
|
|
|
|
chars = allow_lazy(chars)
|
2011-07-14 21:47:10 +08:00
|
|
|
|
2013-01-10 17:27:20 +08:00
|
|
|
def _text_chars(self, length, truncate, text, truncate_len):
|
|
|
|
"""
|
|
|
|
Truncates a string after a certain number of chars.
|
|
|
|
"""
|
2011-07-14 21:47:10 +08:00
|
|
|
s_len = 0
|
|
|
|
end_index = None
|
|
|
|
for i, char in enumerate(text):
|
|
|
|
if unicodedata.combining(char):
|
|
|
|
# Don't consider combining characters
|
|
|
|
# as adding to the string length
|
|
|
|
continue
|
|
|
|
s_len += 1
|
|
|
|
if end_index is None and s_len > truncate_len:
|
|
|
|
end_index = i
|
|
|
|
if s_len > length:
|
|
|
|
# Return the truncated string
|
|
|
|
return self.add_truncation_text(text[:end_index or 0],
|
|
|
|
truncate)
|
|
|
|
|
|
|
|
# Return the original string since no truncation was necessary
|
|
|
|
return text
|
|
|
|
|
|
|
|
def words(self, num, truncate=None, html=False):
|
|
|
|
"""
|
|
|
|
Truncates a string after a certain number of words. Takes an optional
|
|
|
|
argument of what should be used to notify that the string has been
|
|
|
|
truncated, defaulting to ellipsis (...).
|
|
|
|
"""
|
|
|
|
length = int(num)
|
|
|
|
if html:
|
2013-01-10 17:27:20 +08:00
|
|
|
return self._truncate_html(length, truncate, self._wrapped, length, True)
|
2011-07-14 21:47:10 +08:00
|
|
|
return self._text_words(length, truncate)
|
|
|
|
words = allow_lazy(words)
|
|
|
|
|
|
|
|
def _text_words(self, length, truncate):
|
|
|
|
"""
|
|
|
|
Truncates a string after a certain number of words.
|
|
|
|
|
|
|
|
Newlines in the string will be stripped.
|
|
|
|
"""
|
|
|
|
words = self._wrapped.split()
|
|
|
|
if len(words) > length:
|
|
|
|
words = words[:length]
|
2012-06-08 00:08:47 +08:00
|
|
|
return self.add_truncation_text(' '.join(words), truncate)
|
|
|
|
return ' '.join(words)
|
2011-07-14 21:47:10 +08:00
|
|
|
|
2013-01-10 17:27:20 +08:00
|
|
|
def _truncate_html(self, length, truncate, text, truncate_len, words):
|
2011-07-14 21:47:10 +08:00
|
|
|
"""
|
2013-01-10 17:27:20 +08:00
|
|
|
Truncates HTML to a certain number of chars (not counting tags and
|
|
|
|
comments), or, if words is True, then to a certain number of words.
|
|
|
|
Closes opened tags if they were correctly closed in the given HTML.
|
2011-07-14 21:47:10 +08:00
|
|
|
|
|
|
|
Newlines in the HTML are preserved.
|
|
|
|
"""
|
2013-01-10 17:27:20 +08:00
|
|
|
if words and length <= 0:
|
2012-06-08 00:08:47 +08:00
|
|
|
return ''
|
2013-01-10 17:27:20 +08:00
|
|
|
|
2011-07-14 21:47:10 +08:00
|
|
|
html4_singlets = (
|
|
|
|
'br', 'col', 'link', 'base', 'img',
|
|
|
|
'param', 'area', 'hr', 'input'
|
|
|
|
)
|
2013-01-10 17:27:20 +08:00
|
|
|
|
|
|
|
# Count non-HTML chars/words and keep note of open tags
|
2011-07-14 21:47:10 +08:00
|
|
|
pos = 0
|
|
|
|
end_text_pos = 0
|
2013-01-10 17:27:20 +08:00
|
|
|
current_len = 0
|
2011-07-14 21:47:10 +08:00
|
|
|
open_tags = []
|
2013-01-10 17:27:20 +08:00
|
|
|
|
|
|
|
regex = re_words if words else re_chars
|
|
|
|
|
|
|
|
while current_len <= length:
|
|
|
|
m = regex.search(text, pos)
|
2011-07-14 21:47:10 +08:00
|
|
|
if not m:
|
|
|
|
# Checked through whole string
|
|
|
|
break
|
|
|
|
pos = m.end(0)
|
|
|
|
if m.group(1):
|
2013-01-10 17:27:20 +08:00
|
|
|
# It's an actual non-HTML word or char
|
|
|
|
current_len += 1
|
|
|
|
if current_len == truncate_len:
|
2011-07-14 21:47:10 +08:00
|
|
|
end_text_pos = pos
|
|
|
|
continue
|
|
|
|
# Check for tag
|
|
|
|
tag = re_tag.match(m.group(0))
|
2013-01-10 17:27:20 +08:00
|
|
|
if not tag or current_len >= truncate_len:
|
2011-07-14 21:47:10 +08:00
|
|
|
# Don't worry about non tags or tags after our truncate point
|
|
|
|
continue
|
|
|
|
closing_tag, tagname, self_closing = tag.groups()
|
|
|
|
# Element names are always case-insensitive
|
|
|
|
tagname = tagname.lower()
|
|
|
|
if self_closing or tagname in html4_singlets:
|
2007-02-10 10:51:27 +08:00
|
|
|
pass
|
2011-07-14 21:47:10 +08:00
|
|
|
elif closing_tag:
|
|
|
|
# Check for match in open tags list
|
|
|
|
try:
|
|
|
|
i = open_tags.index(tagname)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
# SGML: An end tag closes, back to the matching start tag,
|
|
|
|
# all unclosed intervening start tags with omitted end tags
|
|
|
|
open_tags = open_tags[i + 1:]
|
2007-02-10 10:51:27 +08:00
|
|
|
else:
|
2011-07-14 21:47:10 +08:00
|
|
|
# Add it to the start of the open tags list
|
|
|
|
open_tags.insert(0, tagname)
|
2013-01-10 17:27:20 +08:00
|
|
|
|
|
|
|
if current_len <= length:
|
|
|
|
return text
|
|
|
|
out = text[:end_text_pos]
|
2011-07-14 21:47:10 +08:00
|
|
|
truncate_text = self.add_truncation_text('', truncate)
|
|
|
|
if truncate_text:
|
|
|
|
out += truncate_text
|
|
|
|
# Close any tags still open
|
|
|
|
for tag in open_tags:
|
|
|
|
out += '</%s>' % tag
|
|
|
|
# Return string
|
|
|
|
return out
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def get_valid_filename(s):
|
|
|
|
"""
|
|
|
|
Returns the given string converted to a string that can be used for a clean
|
|
|
|
filename. Specifically, leading and trailing spaces are removed; other
|
2009-04-05 01:34:58 +08:00
|
|
|
spaces are converted to underscores; and anything that is not a unicode
|
|
|
|
alphanumeric, dash, underscore, or dot, is removed.
|
2005-07-13 09:25:57 +08:00
|
|
|
>>> get_valid_filename("john's portrait in 2004.jpg")
|
2012-06-08 00:08:47 +08:00
|
|
|
'johns_portrait_in_2004.jpg'
|
2005-07-13 09:25:57 +08:00
|
|
|
"""
|
2012-07-21 16:00:10 +08:00
|
|
|
s = force_text(s).strip().replace(' ', '_')
|
2009-04-05 01:34:58 +08:00
|
|
|
return re.sub(r'(?u)[^-\w.]', '', s)
|
2012-07-20 20:48:51 +08:00
|
|
|
get_valid_filename = allow_lazy(get_valid_filename, six.text_type)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2012-06-08 00:08:47 +08:00
|
|
|
def get_text_list(list_, last_word=ugettext_lazy('or')):
|
2005-07-13 09:25:57 +08:00
|
|
|
"""
|
|
|
|
>>> get_text_list(['a', 'b', 'c', 'd'])
|
2012-06-08 00:08:47 +08:00
|
|
|
'a, b, c or d'
|
2005-07-13 09:25:57 +08:00
|
|
|
>>> get_text_list(['a', 'b', 'c'], 'and')
|
2012-06-08 00:08:47 +08:00
|
|
|
'a, b and c'
|
2005-07-13 09:25:57 +08:00
|
|
|
>>> get_text_list(['a', 'b'], 'and')
|
2012-06-08 00:08:47 +08:00
|
|
|
'a and b'
|
2005-07-13 09:25:57 +08:00
|
|
|
>>> get_text_list(['a'])
|
2012-06-08 00:08:47 +08:00
|
|
|
'a'
|
2005-07-13 09:25:57 +08:00
|
|
|
>>> get_text_list([])
|
2012-06-08 00:08:47 +08:00
|
|
|
''
|
2005-07-13 09:25:57 +08:00
|
|
|
"""
|
2013-10-17 16:17:41 +08:00
|
|
|
if len(list_) == 0:
|
|
|
|
return ''
|
|
|
|
if len(list_) == 1:
|
|
|
|
return force_text(list_[0])
|
2012-06-08 00:08:47 +08:00
|
|
|
return '%s %s %s' % (
|
2010-12-13 06:53:49 +08:00
|
|
|
# Translators: This string is used as a separator between list elements
|
2013-08-30 07:20:00 +08:00
|
|
|
_(', ').join(force_text(i) for i in list_[:-1]),
|
2012-07-21 16:00:10 +08:00
|
|
|
force_text(last_word), force_text(list_[-1]))
|
2012-07-20 20:48:51 +08:00
|
|
|
get_text_list = allow_lazy(get_text_list, six.text_type)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def normalize_newlines(text):
|
2013-12-12 22:58:14 +08:00
|
|
|
"""Normalizes CRLF and CR newlines to just LF."""
|
|
|
|
text = force_text(text)
|
|
|
|
return re_newlines.sub('\n', text)
|
2012-07-20 20:48:51 +08:00
|
|
|
normalize_newlines = allow_lazy(normalize_newlines, six.text_type)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def phone2numeric(phone):
|
2013-12-12 22:57:39 +08:00
|
|
|
"""Converts a phone number with letters into its numeric equivalent."""
|
2012-04-28 15:29:42 +08:00
|
|
|
char2number = {'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3',
|
|
|
|
'g': '4', 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6',
|
|
|
|
'n': '6', 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8',
|
2013-12-09 01:20:06 +08:00
|
|
|
'u': '8', 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9'}
|
2012-06-08 00:08:47 +08:00
|
|
|
return ''.join(char2number.get(c, c) for c in phone.lower())
|
2012-04-28 15:33:37 +08:00
|
|
|
phone2numeric = allow_lazy(phone2numeric)
|
2005-07-19 01:23:04 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2005-07-19 01:23:04 +08:00
|
|
|
# From http://www.xhaus.com/alan/python/httpcomp.html#gzip
|
|
|
|
# Used with permission.
|
|
|
|
def compress_string(s):
|
2012-05-06 01:47:03 +08:00
|
|
|
zbuf = BytesIO()
|
2011-07-13 17:35:51 +08:00
|
|
|
zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
|
2005-07-19 01:23:04 +08:00
|
|
|
zfile.write(s)
|
|
|
|
zfile.close()
|
|
|
|
return zbuf.getvalue()
|
2005-12-04 20:06:16 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2012-10-20 23:40:14 +08:00
|
|
|
class StreamingBuffer(object):
|
|
|
|
def __init__(self):
|
|
|
|
self.vals = []
|
|
|
|
|
|
|
|
def write(self, val):
|
|
|
|
self.vals.append(val)
|
|
|
|
|
|
|
|
def read(self):
|
|
|
|
ret = b''.join(self.vals)
|
|
|
|
self.vals = []
|
|
|
|
return ret
|
|
|
|
|
|
|
|
def flush(self):
|
|
|
|
return
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
return
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2012-10-20 23:40:14 +08:00
|
|
|
# Like compress_string, but for iterators of strings.
|
|
|
|
def compress_sequence(sequence):
|
|
|
|
buf = StreamingBuffer()
|
|
|
|
zfile = GzipFile(mode='wb', compresslevel=6, fileobj=buf)
|
|
|
|
# Output headers...
|
|
|
|
yield buf.read()
|
|
|
|
for item in sequence:
|
|
|
|
zfile.write(item)
|
|
|
|
zfile.flush()
|
|
|
|
yield buf.read()
|
|
|
|
zfile.close()
|
|
|
|
yield buf.read()
|
|
|
|
|
2012-06-08 00:08:47 +08:00
|
|
|
ustring_re = re.compile("([\u0080-\uffff])")
|
2006-09-22 10:22:58 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2006-09-22 10:22:58 +08:00
|
|
|
def javascript_quote(s, quote_double_quotes=False):
|
2014-02-21 21:46:23 +08:00
|
|
|
msg = (
|
|
|
|
"django.utils.text.javascript_quote() is deprecated. "
|
|
|
|
"Use django.utils.html.escapejs() instead."
|
|
|
|
)
|
|
|
|
warnings.warn(msg, PendingDeprecationWarning, stacklevel=2)
|
2005-12-04 20:06:16 +08:00
|
|
|
|
|
|
|
def fix(match):
|
2012-08-14 20:36:11 +08:00
|
|
|
return "\\u%04x" % ord(match.group(1))
|
2005-12-04 20:06:16 +08:00
|
|
|
|
2012-07-20 20:48:51 +08:00
|
|
|
if type(s) == bytes:
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
s = s.decode('utf-8')
|
2012-07-20 20:48:51 +08:00
|
|
|
elif type(s) != six.text_type:
|
2010-01-11 02:36:20 +08:00
|
|
|
raise TypeError(s)
|
2005-12-04 20:06:16 +08:00
|
|
|
s = s.replace('\\', '\\\\')
|
2006-09-22 10:22:58 +08:00
|
|
|
s = s.replace('\r', '\\r')
|
2005-12-04 20:06:16 +08:00
|
|
|
s = s.replace('\n', '\\n')
|
|
|
|
s = s.replace('\t', '\\t')
|
|
|
|
s = s.replace("'", "\\'")
|
2014-01-04 12:57:50 +08:00
|
|
|
s = s.replace('</', '<\\/')
|
2006-09-22 10:22:58 +08:00
|
|
|
if quote_double_quotes:
|
|
|
|
s = s.replace('"', '"')
|
2014-02-16 01:55:33 +08:00
|
|
|
return ustring_re.sub(fix, s)
|
2012-07-20 20:48:51 +08:00
|
|
|
javascript_quote = allow_lazy(javascript_quote, six.text_type)
|
2005-12-04 20:06:16 +08:00
|
|
|
|
2009-04-10 12:13:27 +08:00
|
|
|
# Expression to match some_token and some_token="with spaces" (and similarly
|
|
|
|
# for single-quoted strings).
|
|
|
|
smart_split_re = re.compile(r"""
|
2010-02-25 04:52:14 +08:00
|
|
|
((?:
|
|
|
|
[^\s'"]*
|
|
|
|
(?:
|
|
|
|
(?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*')
|
|
|
|
[^\s'"]*
|
|
|
|
)+
|
|
|
|
) | \S+)
|
|
|
|
""", re.VERBOSE)
|
2009-04-10 12:13:27 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2006-06-07 14:08:23 +08:00
|
|
|
def smart_split(text):
|
2008-06-06 22:09:20 +08:00
|
|
|
r"""
|
2006-06-08 12:26:23 +08:00
|
|
|
Generator that splits a string by spaces, leaving quoted phrases together.
|
|
|
|
Supports both single and double quotes, and supports escaping quotes with
|
|
|
|
backslashes. In the output, strings will keep their initial and trailing
|
2009-03-23 17:40:25 +08:00
|
|
|
quote marks and escaped quotes will remain escaped (the results can then
|
|
|
|
be further processed with unescape_string_literal()).
|
2007-03-30 19:57:50 +08:00
|
|
|
|
2008-06-06 22:09:20 +08:00
|
|
|
>>> list(smart_split(r'This is "a person\'s" test.'))
|
2012-06-08 00:08:47 +08:00
|
|
|
['This', 'is', '"a person\\\'s"', 'test.']
|
2009-03-23 17:40:25 +08:00
|
|
|
>>> list(smart_split(r"Another 'person\'s' test."))
|
2012-06-08 00:08:47 +08:00
|
|
|
['Another', "'person\\'s'", 'test.']
|
2009-03-23 17:40:25 +08:00
|
|
|
>>> list(smart_split(r'A "\"funky\" style" test.'))
|
2012-06-08 00:08:47 +08:00
|
|
|
['A', '"\\"funky\\" style"', 'test.']
|
2006-06-08 12:26:23 +08:00
|
|
|
"""
|
2012-07-21 16:00:10 +08:00
|
|
|
text = force_text(text)
|
2006-06-07 14:08:23 +08:00
|
|
|
for bit in smart_split_re.finditer(text):
|
2009-03-23 17:40:25 +08:00
|
|
|
yield bit.group(0)
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2008-07-01 23:10:51 +08:00
|
|
|
def _replace_entity(match):
|
2009-03-30 11:03:37 +08:00
|
|
|
text = match.group(1)
|
2012-06-08 00:08:47 +08:00
|
|
|
if text[0] == '#':
|
2009-03-30 11:03:37 +08:00
|
|
|
text = text[1:]
|
|
|
|
try:
|
2012-06-08 00:08:47 +08:00
|
|
|
if text[0] in 'xX':
|
2009-03-30 11:03:37 +08:00
|
|
|
c = int(text[1:], 16)
|
|
|
|
else:
|
|
|
|
c = int(text)
|
2013-09-27 23:00:42 +08:00
|
|
|
return six.unichr(c)
|
2009-03-30 11:03:37 +08:00
|
|
|
except ValueError:
|
|
|
|
return match.group(0)
|
|
|
|
else:
|
|
|
|
try:
|
2013-09-27 23:00:42 +08:00
|
|
|
return six.unichr(html_entities.name2codepoint[text])
|
2009-03-30 11:03:37 +08:00
|
|
|
except (ValueError, KeyError):
|
|
|
|
return match.group(0)
|
2008-07-01 23:10:51 +08:00
|
|
|
|
|
|
|
_entity_re = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2008-07-01 23:10:51 +08:00
|
|
|
def unescape_entities(text):
|
2009-03-30 11:03:37 +08:00
|
|
|
return _entity_re.sub(_replace_entity, text)
|
2012-07-20 20:48:51 +08:00
|
|
|
unescape_entities = allow_lazy(unescape_entities, six.text_type)
|
2009-03-23 17:40:25 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2009-03-23 17:40:25 +08:00
|
|
|
def unescape_string_literal(s):
|
|
|
|
r"""
|
|
|
|
Convert quoted string literals to unquoted strings with escaped quotes and
|
|
|
|
backslashes unquoted::
|
|
|
|
|
|
|
|
>>> unescape_string_literal('"abc"')
|
|
|
|
'abc'
|
|
|
|
>>> unescape_string_literal("'abc'")
|
|
|
|
'abc'
|
|
|
|
>>> unescape_string_literal('"a \"bc\""')
|
|
|
|
'a "bc"'
|
|
|
|
>>> unescape_string_literal("'\'ab\' c'")
|
|
|
|
"'ab' c"
|
|
|
|
"""
|
|
|
|
if s[0] not in "\"'" or s[-1] != s[0]:
|
|
|
|
raise ValueError("Not a string literal: %r" % s)
|
|
|
|
quote = s[0]
|
|
|
|
return s[1:-1].replace(r'\%s' % quote, quote).replace(r'\\', '\\')
|
|
|
|
unescape_string_literal = allow_lazy(unescape_string_literal)
|
2012-08-18 20:53:22 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2012-08-18 20:53:22 +08:00
|
|
|
def slugify(value):
|
|
|
|
"""
|
|
|
|
Converts to lowercase, removes non-word characters (alphanumerics and
|
|
|
|
underscores) and converts spaces to hyphens. Also strips leading and
|
|
|
|
trailing whitespace.
|
|
|
|
"""
|
2012-08-18 23:47:21 +08:00
|
|
|
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
|
|
|
|
value = re.sub('[^\w\s-]', '', value).strip().lower()
|
2012-08-18 20:53:22 +08:00
|
|
|
return mark_safe(re.sub('[-\s]+', '-', value))
|
2012-08-18 23:47:21 +08:00
|
|
|
slugify = allow_lazy(slugify, six.text_type)
|
2013-12-26 20:46:15 +08:00
|
|
|
|
|
|
|
|
|
|
|
def camel_case_to_spaces(value):
|
|
|
|
"""
|
|
|
|
Splits CamelCase and converts to lower case. Also strips leading and
|
|
|
|
trailing whitespace.
|
|
|
|
"""
|
|
|
|
return re_camel_case.sub(r' \1', value).strip().lower()
|