PageRenderTime 42ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/django/utils/text.py

https://gitlab.com/asmjahid/django
Python | 438 lines | 357 code | 20 blank | 61 comment | 30 complexity | 0ee694d044fb33a3a93132f62d6db90a MD5 | raw file
  1. from __future__ import unicode_literals
  2. import re
  3. import unicodedata
  4. from gzip import GzipFile
  5. from io import BytesIO
  6. from django.utils import six
  7. from django.utils.encoding import force_text
  8. from django.utils.functional import SimpleLazyObject, keep_lazy, keep_lazy_text
  9. from django.utils.safestring import SafeText, mark_safe
  10. from django.utils.six.moves import html_entities
  11. from django.utils.translation import pgettext, ugettext as _, ugettext_lazy
  12. if six.PY2:
  13. # Import force_unicode even though this module doesn't use it, because some
  14. # people rely on it being here.
  15. from django.utils.encoding import force_unicode # NOQA
  16. # Capitalizes the first letter of a string.
  17. def capfirst(x):
  18. return x and force_text(x)[0].upper() + force_text(x)[1:]
  19. capfirst = keep_lazy_text(capfirst)
  20. # Set up regular expressions
  21. re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S)
  22. re_chars = re.compile(r'<.*?>|(.)', re.U | re.S)
  23. re_tag = re.compile(r'<(/)?([^ ]+?)(?:(\s*/)| .*?)?>', re.S)
  24. re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
  25. re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))')
  26. @keep_lazy_text
  27. def wrap(text, width):
  28. """
  29. A word-wrap function that preserves existing line breaks. Expects that
  30. existing line breaks are posix newlines.
  31. All white space is preserved except added line breaks consume the space on
  32. which they break the line.
  33. Long words are not wrapped, so the output text may have lines longer than
  34. ``width``.
  35. """
  36. text = force_text(text)
  37. def _generator():
  38. for line in text.splitlines(True): # True keeps trailing linebreaks
  39. max_width = min((line.endswith('\n') and width + 1 or width), width)
  40. while len(line) > max_width:
  41. space = line[:max_width + 1].rfind(' ') + 1
  42. if space == 0:
  43. space = line.find(' ') + 1
  44. if space == 0:
  45. yield line
  46. line = ''
  47. break
  48. yield '%s\n' % line[:space - 1]
  49. line = line[space:]
  50. max_width = min((line.endswith('\n') and width + 1 or width), width)
  51. if line:
  52. yield line
  53. return ''.join(_generator())
  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. self._setup()
  84. length = int(num)
  85. text = unicodedata.normalize('NFC', self._wrapped)
  86. # Calculate the length to truncate to (max length - end_text length)
  87. truncate_len = length
  88. for char in self.add_truncation_text('', truncate):
  89. if not unicodedata.combining(char):
  90. truncate_len -= 1
  91. if truncate_len == 0:
  92. break
  93. if html:
  94. return self._truncate_html(length, truncate, text, truncate_len, False)
  95. return self._text_chars(length, truncate, text, truncate_len)
  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. self._setup()
  123. length = int(num)
  124. if html:
  125. return self._truncate_html(length, truncate, self._wrapped, length, True)
  126. return self._text_words(length, truncate)
  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. @keep_lazy_text
  203. def get_valid_filename(s):
  204. """
  205. Returns the given string converted to a string that can be used for a clean
  206. filename. Specifically, leading and trailing spaces are removed; other
  207. spaces are converted to underscores; and anything that is not a unicode
  208. alphanumeric, dash, underscore, or dot, is removed.
  209. >>> get_valid_filename("john's portrait in 2004.jpg")
  210. 'johns_portrait_in_2004.jpg'
  211. """
  212. s = force_text(s).strip().replace(' ', '_')
  213. return re.sub(r'(?u)[^-\w.]', '', s)
  214. @keep_lazy_text
  215. def get_text_list(list_, last_word=ugettext_lazy('or')):
  216. """
  217. >>> get_text_list(['a', 'b', 'c', 'd'])
  218. 'a, b, c or d'
  219. >>> get_text_list(['a', 'b', 'c'], 'and')
  220. 'a, b and c'
  221. >>> get_text_list(['a', 'b'], 'and')
  222. 'a and b'
  223. >>> get_text_list(['a'])
  224. 'a'
  225. >>> get_text_list([])
  226. ''
  227. """
  228. if len(list_) == 0:
  229. return ''
  230. if len(list_) == 1:
  231. return force_text(list_[0])
  232. return '%s %s %s' % (
  233. # Translators: This string is used as a separator between list elements
  234. _(', ').join(force_text(i) for i in list_[:-1]),
  235. force_text(last_word), force_text(list_[-1]))
  236. @keep_lazy_text
  237. def normalize_newlines(text):
  238. """Normalizes CRLF and CR newlines to just LF."""
  239. text = force_text(text)
  240. return re_newlines.sub('\n', text)
  241. @keep_lazy_text
  242. def phone2numeric(phone):
  243. """Converts a phone number with letters into its numeric equivalent."""
  244. char2number = {
  245. 'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4',
  246. 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6',
  247. 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8', 'u': '8',
  248. 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9',
  249. }
  250. return ''.join(char2number.get(c, c) for c in phone.lower())
  251. # From http://www.xhaus.com/alan/python/httpcomp.html#gzip
  252. # Used with permission.
  253. def compress_string(s):
  254. zbuf = BytesIO()
  255. zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
  256. zfile.write(s)
  257. zfile.close()
  258. return zbuf.getvalue()
  259. class StreamingBuffer(object):
  260. def __init__(self):
  261. self.vals = []
  262. def write(self, val):
  263. self.vals.append(val)
  264. def read(self):
  265. if not self.vals:
  266. return b''
  267. ret = b''.join(self.vals)
  268. self.vals = []
  269. return ret
  270. def flush(self):
  271. return
  272. def close(self):
  273. return
  274. # Like compress_string, but for iterators of strings.
  275. def compress_sequence(sequence):
  276. buf = StreamingBuffer()
  277. zfile = GzipFile(mode='wb', compresslevel=6, fileobj=buf)
  278. # Output headers...
  279. yield buf.read()
  280. for item in sequence:
  281. zfile.write(item)
  282. data = buf.read()
  283. if data:
  284. yield data
  285. zfile.close()
  286. yield buf.read()
  287. # Expression to match some_token and some_token="with spaces" (and similarly
  288. # for single-quoted strings).
  289. smart_split_re = re.compile(r"""
  290. ((?:
  291. [^\s'"]*
  292. (?:
  293. (?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*')
  294. [^\s'"]*
  295. )+
  296. ) | \S+)
  297. """, re.VERBOSE)
  298. def smart_split(text):
  299. r"""
  300. Generator that splits a string by spaces, leaving quoted phrases together.
  301. Supports both single and double quotes, and supports escaping quotes with
  302. backslashes. In the output, strings will keep their initial and trailing
  303. quote marks and escaped quotes will remain escaped (the results can then
  304. be further processed with unescape_string_literal()).
  305. >>> list(smart_split(r'This is "a person\'s" test.'))
  306. ['This', 'is', '"a person\\\'s"', 'test.']
  307. >>> list(smart_split(r"Another 'person\'s' test."))
  308. ['Another', "'person\\'s'", 'test.']
  309. >>> list(smart_split(r'A "\"funky\" style" test.'))
  310. ['A', '"\\"funky\\" style"', 'test.']
  311. """
  312. text = force_text(text)
  313. for bit in smart_split_re.finditer(text):
  314. yield bit.group(0)
  315. def _replace_entity(match):
  316. text = match.group(1)
  317. if text[0] == '#':
  318. text = text[1:]
  319. try:
  320. if text[0] in 'xX':
  321. c = int(text[1:], 16)
  322. else:
  323. c = int(text)
  324. return six.unichr(c)
  325. except ValueError:
  326. return match.group(0)
  327. else:
  328. try:
  329. return six.unichr(html_entities.name2codepoint[text])
  330. except (ValueError, KeyError):
  331. return match.group(0)
  332. _entity_re = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
  333. @keep_lazy_text
  334. def unescape_entities(text):
  335. return _entity_re.sub(_replace_entity, force_text(text))
  336. @keep_lazy_text
  337. def unescape_string_literal(s):
  338. r"""
  339. Convert quoted string literals to unquoted strings with escaped quotes and
  340. backslashes unquoted::
  341. >>> unescape_string_literal('"abc"')
  342. 'abc'
  343. >>> unescape_string_literal("'abc'")
  344. 'abc'
  345. >>> unescape_string_literal('"a \"bc\""')
  346. 'a "bc"'
  347. >>> unescape_string_literal("'\'ab\' c'")
  348. "'ab' c"
  349. """
  350. if s[0] not in "\"'" or s[-1] != s[0]:
  351. raise ValueError("Not a string literal: %r" % s)
  352. quote = s[0]
  353. return s[1:-1].replace(r'\%s' % quote, quote).replace(r'\\', '\\')
  354. @keep_lazy(six.text_type, SafeText)
  355. def slugify(value, allow_unicode=False):
  356. """
  357. Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
  358. Remove characters that aren't alphanumerics, underscores, or hyphens.
  359. Convert to lowercase. Also strip leading and trailing whitespace.
  360. """
  361. value = force_text(value)
  362. if allow_unicode:
  363. value = unicodedata.normalize('NFKC', value)
  364. value = re.sub('[^\w\s-]', '', value, flags=re.U).strip().lower()
  365. return mark_safe(re.sub('[-\s]+', '-', value, flags=re.U))
  366. value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
  367. value = re.sub('[^\w\s-]', '', value).strip().lower()
  368. return mark_safe(re.sub('[-\s]+', '-', value))
  369. def camel_case_to_spaces(value):
  370. """
  371. Splits CamelCase and converts to lower case. Also strips leading and
  372. trailing whitespace.
  373. """
  374. return re_camel_case.sub(r' \1', value).strip().lower()