You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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