text.py 14 KB

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