PageRenderTime 53ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/buckyproject/Envn/lib/python3.6/site-packages/django/utils/text.py

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