PageRenderTime 43ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/django/utils/text.py

https://github.com/andnils/django
Python | 453 lines | 378 code | 20 blank | 55 comment | 30 complexity | 99404b0f64a8d3a3a1a8a57f2bb3c0dd MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from __future__ import unicode_literals
  2. import re
  3. import unicodedata
  4. from gzip import GzipFile
  5. from io import BytesIO
  6. import warnings
  7. from django.utils.deprecation import RemovedInDjango19Warning
  8. from django.utils.encoding import force_text
  9. from django.utils.functional import allow_lazy, SimpleLazyObject
  10. from django.utils import six
  11. from django.utils.six.moves import html_entities
  12. from django.utils.translation import ugettext_lazy, ugettext as _, pgettext
  13. from django.utils.safestring import mark_safe
  14. if six.PY2:
  15. # Import force_unicode even though this module doesn't use it, because some
  16. # people rely on it being here.
  17. from django.utils.encoding import force_unicode # NOQA
  18. # Capitalizes the first letter of a string.
  19. capfirst = lambda x: x and force_text(x)[0].upper() + force_text(x)[1:]
  20. capfirst = allow_lazy(capfirst, six.text_type)
  21. # Set up regular expressions
  22. re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S)
  23. re_chars = re.compile(r'<.*?>|(.)', re.U | re.S)
  24. re_tag = re.compile(r'<(/)?([^ ]+?)(?:(\s*/)| .*?)?>', re.S)
  25. re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
  26. re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))')
  27. def wrap(text, width):
  28. """
  29. A word-wrap function that preserves existing line breaks and most spaces in
  30. the text. Expects that existing line breaks are posix newlines.
  31. """
  32. text = force_text(text)
  33. def _generator():
  34. it = iter(text.split(' '))
  35. word = next(it)
  36. yield word
  37. pos = len(word) - word.rfind('\n') - 1
  38. for word in it:
  39. if "\n" in word:
  40. lines = word.split('\n')
  41. else:
  42. lines = (word,)
  43. pos += len(lines[0]) + 1
  44. if pos > width:
  45. yield '\n'
  46. pos = len(lines[-1])
  47. else:
  48. yield ' '
  49. if len(lines) > 1:
  50. pos = len(lines[-1])
  51. yield word
  52. return ''.join(_generator())
  53. wrap = allow_lazy(wrap, six.text_type)
  54. class Truncator(SimpleLazyObject):
  55. """
  56. An object used to truncate text, either by characters or words.
  57. """
  58. def __init__(self, text):
  59. super(Truncator, self).__init__(lambda: force_text(text))
  60. def add_truncation_text(self, text, truncate=None):
  61. if truncate is None:
  62. truncate = pgettext(
  63. 'String to return when truncating text',
  64. '%(truncated_text)s...')
  65. truncate = force_text(truncate)
  66. if '%(truncated_text)s' in truncate:
  67. return truncate % {'truncated_text': text}
  68. # The truncation text didn't contain the %(truncated_text)s string
  69. # replacement argument so just append it to the text.
  70. if text.endswith(truncate):
  71. # But don't append the truncation text if the current text already
  72. # ends in this.
  73. return text
  74. return '%s%s' % (text, truncate)
  75. def chars(self, num, truncate=None, html=False):
  76. """
  77. Returns the text truncated to be no longer than the specified number
  78. of characters.
  79. Takes an optional argument of what should be used to notify that the
  80. string has been truncated, defaulting to a translatable string of an
  81. ellipsis (...).
  82. """
  83. length = int(num)
  84. text = unicodedata.normalize('NFC', self._wrapped)
  85. # Calculate the length to truncate to (max length - end_text length)
  86. truncate_len = length
  87. for char in self.add_truncation_text('', truncate):
  88. if not unicodedata.combining(char):
  89. truncate_len -= 1
  90. if truncate_len == 0:
  91. break
  92. if html:
  93. return self._truncate_html(length, truncate, text, truncate_len, False)
  94. return self._text_chars(length, truncate, text, truncate_len)
  95. chars = allow_lazy(chars)
  96. def _text_chars(self, length, truncate, text, truncate_len):
  97. """
  98. Truncates a string after a certain number of chars.
  99. """
  100. s_len = 0
  101. end_index = None
  102. for i, char in enumerate(text):
  103. if unicodedata.combining(char):
  104. # Don't consider combining characters
  105. # as adding to the string length
  106. continue
  107. s_len += 1
  108. if end_index is None and s_len > truncate_len:
  109. end_index = i
  110. if s_len > length:
  111. # Return the truncated string
  112. return self.add_truncation_text(text[:end_index or 0],
  113. truncate)
  114. # Return the original string since no truncation was necessary
  115. return text
  116. def words(self, num, truncate=None, html=False):
  117. """
  118. Truncates a string after a certain number of words. Takes an optional
  119. argument of what should be used to notify that the string has been
  120. truncated, defaulting to ellipsis (...).
  121. """
  122. length = int(num)
  123. if html:
  124. return self._truncate_html(length, truncate, self._wrapped, length, True)
  125. return self._text_words(length, truncate)
  126. words = allow_lazy(words)
  127. def _text_words(self, length, truncate):
  128. """
  129. Truncates a string after a certain number of words.
  130. Newlines in the string will be stripped.
  131. """
  132. words = self._wrapped.split()
  133. if len(words) > length:
  134. words = words[:length]
  135. return self.add_truncation_text(' '.join(words), truncate)
  136. return ' '.join(words)
  137. def _truncate_html(self, length, truncate, text, truncate_len, words):
  138. """
  139. Truncates HTML to a certain number of chars (not counting tags and
  140. comments), or, if words is True, then to a certain number of words.
  141. Closes opened tags if they were correctly closed in the given HTML.
  142. Newlines in the HTML are preserved.
  143. """
  144. if words and length <= 0:
  145. return ''
  146. html4_singlets = (
  147. 'br', 'col', 'link', 'base', 'img',
  148. 'param', 'area', 'hr', 'input'
  149. )
  150. # Count non-HTML chars/words and keep note of open tags
  151. pos = 0
  152. end_text_pos = 0
  153. current_len = 0
  154. open_tags = []
  155. regex = re_words if words else re_chars
  156. while current_len <= length:
  157. m = regex.search(text, pos)
  158. if not m:
  159. # Checked through whole string
  160. break
  161. pos = m.end(0)
  162. if m.group(1):
  163. # It's an actual non-HTML word or char
  164. current_len += 1
  165. if current_len == truncate_len:
  166. end_text_pos = pos
  167. continue
  168. # Check for tag
  169. tag = re_tag.match(m.group(0))
  170. if not tag or current_len >= truncate_len:
  171. # Don't worry about non tags or tags after our truncate point
  172. continue
  173. closing_tag, tagname, self_closing = tag.groups()
  174. # Element names are always case-insensitive
  175. tagname = tagname.lower()
  176. if self_closing or tagname in html4_singlets:
  177. pass
  178. elif closing_tag:
  179. # Check for match in open tags list
  180. try:
  181. i = open_tags.index(tagname)
  182. except ValueError:
  183. pass
  184. else:
  185. # SGML: An end tag closes, back to the matching start tag,
  186. # all unclosed intervening start tags with omitted end tags
  187. open_tags = open_tags[i + 1:]
  188. else:
  189. # Add it to the start of the open tags list
  190. open_tags.insert(0, tagname)
  191. if current_len <= length:
  192. return text
  193. out = text[:end_text_pos]
  194. truncate_text = self.add_truncation_text('', truncate)
  195. if truncate_text:
  196. out += truncate_text
  197. # Close any tags still open
  198. for tag in open_tags:
  199. out += '</%s>' % tag
  200. # Return string
  201. return out
  202. def get_valid_filename(s):
  203. """
  204. Returns the given string converted to a string that can be used for a clean
  205. filename. Specifically, leading and trailing spaces are removed; other
  206. spaces are converted to underscores; and anything that is not a unicode
  207. alphanumeric, dash, underscore, or dot, is removed.
  208. >>> get_valid_filename("john's portrait in 2004.jpg")
  209. 'johns_portrait_in_2004.jpg'
  210. """
  211. s = force_text(s).strip().replace(' ', '_')
  212. return re.sub(r'(?u)[^-\w.]', '', s)
  213. get_valid_filename = allow_lazy(get_valid_filename, six.text_type)
  214. def get_text_list(list_, last_word=ugettext_lazy('or')):
  215. """
  216. >>> get_text_list(['a', 'b', 'c', 'd'])
  217. 'a, b, c or d'
  218. >>> get_text_list(['a', 'b', 'c'], 'and')
  219. 'a, b and c'
  220. >>> get_text_list(['a', 'b'], 'and')
  221. 'a and b'
  222. >>> get_text_list(['a'])
  223. 'a'
  224. >>> get_text_list([])
  225. ''
  226. """
  227. if len(list_) == 0:
  228. return ''
  229. if len(list_) == 1:
  230. return force_text(list_[0])
  231. return '%s %s %s' % (
  232. # Translators: This string is used as a separator between list elements
  233. _(', ').join(force_text(i) for i in list_[:-1]),
  234. force_text(last_word), force_text(list_[-1]))
  235. get_text_list = allow_lazy(get_text_list, six.text_type)
  236. def normalize_newlines(text):
  237. """Normalizes CRLF and CR newlines to just LF."""
  238. text = force_text(text)
  239. return re_newlines.sub('\n', text)
  240. normalize_newlines = allow_lazy(normalize_newlines, six.text_type)
  241. def phone2numeric(phone):
  242. """Converts a phone number with letters into its numeric equivalent."""
  243. char2number = {'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3',
  244. 'g': '4', 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6',
  245. 'n': '6', 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8',
  246. 'u': '8', 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9'}
  247. return ''.join(char2number.get(c, c) for c in phone.lower())
  248. phone2numeric = allow_lazy(phone2numeric)
  249. # From http://www.xhaus.com/alan/python/httpcomp.html#gzip
  250. # Used with permission.
  251. def compress_string(s):
  252. zbuf = BytesIO()
  253. zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
  254. zfile.write(s)
  255. zfile.close()
  256. return zbuf.getvalue()
  257. class StreamingBuffer(object):
  258. def __init__(self):
  259. self.vals = []
  260. def write(self, val):
  261. self.vals.append(val)
  262. def read(self):
  263. ret = b''.join(self.vals)
  264. self.vals = []
  265. return ret
  266. def flush(self):
  267. return
  268. def close(self):
  269. return
  270. # Like compress_string, but for iterators of strings.
  271. def compress_sequence(sequence):
  272. buf = StreamingBuffer()
  273. zfile = GzipFile(mode='wb', compresslevel=6, fileobj=buf)
  274. # Output headers...
  275. yield buf.read()
  276. for item in sequence:
  277. zfile.write(item)
  278. zfile.flush()
  279. yield buf.read()
  280. zfile.close()
  281. yield buf.read()
  282. ustring_re = re.compile("([\u0080-\uffff])")
  283. def javascript_quote(s, quote_double_quotes=False):
  284. msg = (
  285. "django.utils.text.javascript_quote() is deprecated. "
  286. "Use django.utils.html.escapejs() instead."
  287. )
  288. warnings.warn(msg, RemovedInDjango19Warning, stacklevel=2)
  289. def fix(match):
  290. return "\\u%04x" % ord(match.group(1))
  291. if type(s) == bytes:
  292. s = s.decode('utf-8')
  293. elif type(s) != six.text_type:
  294. raise TypeError(s)
  295. s = s.replace('\\', '\\\\')
  296. s = s.replace('\r', '\\r')
  297. s = s.replace('\n', '\\n')
  298. s = s.replace('\t', '\\t')
  299. s = s.replace("'", "\\'")
  300. s = s.replace('</', '<\\/')
  301. if quote_double_quotes:
  302. s = s.replace('"', '&quot;')
  303. return ustring_re.sub(fix, s)
  304. javascript_quote = allow_lazy(javascript_quote, six.text_type)
  305. # Expression to match some_token and some_token="with spaces" (and similarly
  306. # for single-quoted strings).
  307. smart_split_re = re.compile(r"""
  308. ((?:
  309. [^\s'"]*
  310. (?:
  311. (?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*')
  312. [^\s'"]*
  313. )+
  314. ) | \S+)
  315. """, re.VERBOSE)
  316. def smart_split(text):
  317. r"""
  318. Generator that splits a string by spaces, leaving quoted phrases together.
  319. Supports both single and double quotes, and supports escaping quotes with
  320. backslashes. In the output, strings will keep their initial and trailing
  321. quote marks and escaped quotes will remain escaped (the results can then
  322. be further processed with unescape_string_literal()).
  323. >>> list(smart_split(r'This is "a person\'s" test.'))
  324. ['This', 'is', '"a person\\\'s"', 'test.']
  325. >>> list(smart_split(r"Another 'person\'s' test."))
  326. ['Another', "'person\\'s'", 'test.']
  327. >>> list(smart_split(r'A "\"funky\" style" test.'))
  328. ['A', '"\\"funky\\" style"', 'test.']
  329. """
  330. text = force_text(text)
  331. for bit in smart_split_re.finditer(text):
  332. yield bit.group(0)
  333. def _replace_entity(match):
  334. text = match.group(1)
  335. if text[0] == '#':
  336. text = text[1:]
  337. try:
  338. if text[0] in 'xX':
  339. c = int(text[1:], 16)
  340. else:
  341. c = int(text)
  342. return six.unichr(c)
  343. except ValueError:
  344. return match.group(0)
  345. else:
  346. try:
  347. return six.unichr(html_entities.name2codepoint[text])
  348. except (ValueError, KeyError):
  349. return match.group(0)
  350. _entity_re = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
  351. def unescape_entities(text):
  352. return _entity_re.sub(_replace_entity, text)
  353. unescape_entities = allow_lazy(unescape_entities, six.text_type)
  354. def unescape_string_literal(s):
  355. r"""
  356. Convert quoted string literals to unquoted strings with escaped quotes and
  357. backslashes unquoted::
  358. >>> unescape_string_literal('"abc"')
  359. 'abc'
  360. >>> unescape_string_literal("'abc'")
  361. 'abc'
  362. >>> unescape_string_literal('"a \"bc\""')
  363. 'a "bc"'
  364. >>> unescape_string_literal("'\'ab\' c'")
  365. "'ab' c"
  366. """
  367. if s[0] not in "\"'" or s[-1] != s[0]:
  368. raise ValueError("Not a string literal: %r" % s)
  369. quote = s[0]
  370. return s[1:-1].replace(r'\%s' % quote, quote).replace(r'\\', '\\')
  371. unescape_string_literal = allow_lazy(unescape_string_literal)
  372. def slugify(value):
  373. """
  374. Converts to lowercase, removes non-word characters (alphanumerics and
  375. underscores) and converts spaces to hyphens. Also strips leading and
  376. trailing whitespace.
  377. """
  378. value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
  379. value = re.sub('[^\w\s-]', '', value).strip().lower()
  380. return mark_safe(re.sub('[-\s]+', '-', value))
  381. slugify = allow_lazy(slugify, six.text_type)
  382. def camel_case_to_spaces(value):
  383. """
  384. Splits CamelCase and converts to lower case. Also strips leading and
  385. trailing whitespace.
  386. """
  387. return re_camel_case.sub(r' \1', value).strip().lower()