PageRenderTime 55ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/site-packages/django/utils/text.py

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