text.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. import html.entities
  2. import re
  3. import unicodedata
  4. import warnings
  5. from gzip import GzipFile
  6. from io import BytesIO
  7. from django.core.exceptions import SuspiciousFileOperation
  8. from django.utils.deprecation import RemovedInDjango40Warning
  9. from django.utils.functional import SimpleLazyObject, keep_lazy_text, lazy
  10. from django.utils.regex_helper import _lazy_re_compile
  11. from django.utils.translation import gettext as _, gettext_lazy, pgettext
  12. @keep_lazy_text
  13. def capfirst(x):
  14. """Capitalize the first letter of a string."""
  15. return x and str(x)[0].upper() + str(x)[1:]
  16. # Set up regular expressions
  17. re_words = _lazy_re_compile(r'<[^>]+?>|([^<>\s]+)', re.S)
  18. re_chars = _lazy_re_compile(r'<[^>]+?>|(.)', re.S)
  19. re_tag = _lazy_re_compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
  20. re_newlines = _lazy_re_compile(r'\r\n|\r') # Used in normalize_newlines
  21. re_camel_case = _lazy_re_compile(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))')
  22. @keep_lazy_text
  23. def wrap(text, width):
  24. """
  25. A word-wrap function that preserves existing line breaks. Expects that
  26. existing line breaks are posix newlines.
  27. Preserve all white space except added line breaks consume the space on
  28. which they break the line.
  29. Don't wrap long words, thus the output text may have lines longer than
  30. ``width``.
  31. """
  32. def _generator():
  33. for line in text.splitlines(True): # True keeps trailing linebreaks
  34. max_width = min((line.endswith('\n') and width + 1 or width), width)
  35. while len(line) > max_width:
  36. space = line[:max_width + 1].rfind(' ') + 1
  37. if space == 0:
  38. space = line.find(' ') + 1
  39. if space == 0:
  40. yield line
  41. line = ''
  42. break
  43. yield '%s\n' % line[:space - 1]
  44. line = line[space:]
  45. max_width = min((line.endswith('\n') and width + 1 or width), width)
  46. if line:
  47. yield line
  48. return ''.join(_generator())
  49. class Truncator(SimpleLazyObject):
  50. """
  51. An object used to truncate text, either by characters or words.
  52. """
  53. def __init__(self, text):
  54. super().__init__(lambda: str(text))
  55. def add_truncation_text(self, text, truncate=None):
  56. if truncate is None:
  57. truncate = pgettext(
  58. 'String to return when truncating text',
  59. '%(truncated_text)s…')
  60. if '%(truncated_text)s' in truncate:
  61. return truncate % {'truncated_text': text}
  62. # The truncation text didn't contain the %(truncated_text)s string
  63. # replacement argument so just append it to the text.
  64. if text.endswith(truncate):
  65. # But don't append the truncation text if the current text already
  66. # ends in this.
  67. return text
  68. return '%s%s' % (text, truncate)
  69. def chars(self, num, truncate=None, html=False):
  70. """
  71. Return the text truncated to be no longer than the specified number
  72. of characters.
  73. `truncate` specifies what should be used to notify that the string has
  74. been truncated, defaulting to a translatable string of an ellipsis.
  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[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[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(name):
  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(name).strip().replace(' ', '_')
  204. s = re.sub(r'(?u)[^-\w.]', '', s)
  205. if s in {'', '.', '..'}:
  206. raise SuspiciousFileOperation("Could not derive file name from '%s'" % name)
  207. return s
  208. @keep_lazy_text
  209. def get_text_list(list_, last_word=gettext_lazy('or')):
  210. """
  211. >>> get_text_list(['a', 'b', 'c', 'd'])
  212. 'a, b, c or d'
  213. >>> get_text_list(['a', 'b', 'c'], 'and')
  214. 'a, b and c'
  215. >>> get_text_list(['a', 'b'], 'and')
  216. 'a and b'
  217. >>> get_text_list(['a'])
  218. 'a'
  219. >>> get_text_list([])
  220. ''
  221. """
  222. if not list_:
  223. return ''
  224. if len(list_) == 1:
  225. return str(list_[0])
  226. return '%s %s %s' % (
  227. # Translators: This string is used as a separator between list elements
  228. _(', ').join(str(i) for i in list_[:-1]), str(last_word), str(list_[-1])
  229. )
  230. @keep_lazy_text
  231. def normalize_newlines(text):
  232. """Normalize CRLF and CR newlines to just LF."""
  233. return re_newlines.sub('\n', str(text))
  234. @keep_lazy_text
  235. def phone2numeric(phone):
  236. """Convert a phone number with letters into its numeric equivalent."""
  237. char2number = {
  238. 'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4',
  239. 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6',
  240. 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8', 'u': '8',
  241. 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9',
  242. }
  243. return ''.join(char2number.get(c, c) for c in phone.lower())
  244. # From http://www.xhaus.com/alan/python/httpcomp.html#gzip
  245. # Used with permission.
  246. def compress_string(s):
  247. zbuf = BytesIO()
  248. with GzipFile(mode='wb', compresslevel=6, fileobj=zbuf, mtime=0) as zfile:
  249. zfile.write(s)
  250. return zbuf.getvalue()
  251. class StreamingBuffer(BytesIO):
  252. def read(self):
  253. ret = self.getvalue()
  254. self.seek(0)
  255. self.truncate()
  256. return ret
  257. # Like compress_string, but for iterators of strings.
  258. def compress_sequence(sequence):
  259. buf = StreamingBuffer()
  260. with GzipFile(mode='wb', compresslevel=6, fileobj=buf, mtime=0) as zfile:
  261. # Output headers...
  262. yield buf.read()
  263. for item in sequence:
  264. zfile.write(item)
  265. data = buf.read()
  266. if data:
  267. yield data
  268. yield buf.read()
  269. # Expression to match some_token and some_token="with spaces" (and similarly
  270. # for single-quoted strings).
  271. smart_split_re = _lazy_re_compile(r"""
  272. ((?:
  273. [^\s'"]*
  274. (?:
  275. (?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*')
  276. [^\s'"]*
  277. )+
  278. ) | \S+)
  279. """, re.VERBOSE)
  280. def smart_split(text):
  281. r"""
  282. Generator that splits a string by spaces, leaving quoted phrases together.
  283. Supports both single and double quotes, and supports escaping quotes with
  284. backslashes. In the output, strings will keep their initial and trailing
  285. quote marks and escaped quotes will remain escaped (the results can then
  286. be further processed with unescape_string_literal()).
  287. >>> list(smart_split(r'This is "a person\'s" test.'))
  288. ['This', 'is', '"a person\\\'s"', 'test.']
  289. >>> list(smart_split(r"Another 'person\'s' test."))
  290. ['Another', "'person\\'s'", 'test.']
  291. >>> list(smart_split(r'A "\"funky\" style" test.'))
  292. ['A', '"\\"funky\\" style"', 'test.']
  293. """
  294. for bit in smart_split_re.finditer(str(text)):
  295. yield bit[0]
  296. def _replace_entity(match):
  297. text = match[1]
  298. if text[0] == '#':
  299. text = text[1:]
  300. try:
  301. if text[0] in 'xX':
  302. c = int(text[1:], 16)
  303. else:
  304. c = int(text)
  305. return chr(c)
  306. except ValueError:
  307. return match[0]
  308. else:
  309. try:
  310. return chr(html.entities.name2codepoint[text])
  311. except KeyError:
  312. return match[0]
  313. _entity_re = _lazy_re_compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
  314. @keep_lazy_text
  315. def unescape_entities(text):
  316. warnings.warn(
  317. 'django.utils.text.unescape_entities() is deprecated in favor of '
  318. 'html.unescape().',
  319. RemovedInDjango40Warning, stacklevel=2,
  320. )
  321. return _entity_re.sub(_replace_entity, str(text))
  322. @keep_lazy_text
  323. def unescape_string_literal(s):
  324. r"""
  325. Convert quoted string literals to unquoted strings with escaped quotes and
  326. backslashes unquoted::
  327. >>> unescape_string_literal('"abc"')
  328. 'abc'
  329. >>> unescape_string_literal("'abc'")
  330. 'abc'
  331. >>> unescape_string_literal('"a \"bc\""')
  332. 'a "bc"'
  333. >>> unescape_string_literal("'\'ab\' c'")
  334. "'ab' c"
  335. """
  336. if s[0] not in "\"'" or s[-1] != s[0]:
  337. raise ValueError("Not a string literal: %r" % s)
  338. quote = s[0]
  339. return s[1:-1].replace(r'\%s' % quote, quote).replace(r'\\', '\\')
  340. @keep_lazy_text
  341. def slugify(value, allow_unicode=False):
  342. """
  343. Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
  344. dashes to single dashes. Remove characters that aren't alphanumerics,
  345. underscores, or hyphens. Convert to lowercase. Also strip leading and
  346. trailing whitespace, dashes, and underscores.
  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.lower())
  354. return re.sub(r'[-\s]+', '-', value).strip('-_')
  355. def camel_case_to_spaces(value):
  356. """
  357. Split CamelCase and convert to lowercase. 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)