comparison frontends/src/tools/strings.py @ 1790:bf7e468fe440

tools (strings): add a parameter "new_target" to addURLToText
author souliane <souliane@mailoo.org>
date Wed, 13 Jan 2016 13:08:31 +0100
parents d17772b0fe22
children 07390a9d1c09
comparison
equal deleted inserted replaced
1789:8e2c831073a6 1790:bf7e468fe440
41 kv = pair.split("=", 1) 41 kv = pair.split("=", 1)
42 dict_[kv[0]] = kv[1] if len(kv) > 1 else "" 42 dict_[kv[0]] = kv[1] if len(kv) > 1 else ""
43 return dict_ 43 return dict_
44 44
45 45
46 def addURLToText(string): 46 def addURLToText(string, new_target=True):
47 """Check a text for what looks like an URL and make it clickable. Regexp 47 """Check a text for what looks like an URL and make it clickable.
48 from http://daringfireball.net/2010/07/improved_regex_for_matching_urls"""
49 48
49 @param string (unicode): text to process
50 @param new_target (bool): if True, make the link open in a new window
51 """
52 # XXX: report any change to libervia.browser.strings.addURLToText
53 # Regexp from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
50 def repl(match): 54 def repl(match):
51 url = match.group(0) 55 url = match.group(0)
52 if not re.match(r"""[a-z]{3,}://|mailto:|xmpp:""", url): 56 if not re.match(r"""[a-z]{3,}://|mailto:|xmpp:""", url):
53 url = "http://" + url 57 url = "http://" + url
54 return '<a href="%s" target="_blank" class="url">%s</a>' % (url, match.group(0)) 58 target = ' target="_blank"' if new_target else ''
59 return '<a href="%s"%s class="url">%s</a>' % (url, target, match.group(0))
55 pattern = r"""(?i)\b((?:[a-z]{3,}://|(www|ftp)\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/|mailto:|xmpp:)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?]))""" 60 pattern = r"""(?i)\b((?:[a-z]{3,}://|(www|ftp)\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/|mailto:|xmpp:)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?]))"""
56 return re.sub(pattern, repl, string) 61 return re.sub(pattern, repl, string)
57 62
58 63
59 def addURLToImage(string): 64 def addURLToImage(string):
60 """Check a XHTML text for what looks like an imageURL and make it clickable""" 65 """Check a XHTML text for what looks like an imageURL and make it clickable.
66
67 @param string (unicode): text to process
68 """
69 # XXX: report any change to libervia.browser.strings.addURLToImage
61 def repl(match): 70 def repl(match):
62 url = match.group(1) 71 url = match.group(1)
63 return '<a href="%s" target="_blank">%s</a>' % (url, match.group(0)) 72 return '<a href="%s" target="_blank">%s</a>' % (url, match.group(0))
64 pattern = r"""<img[^>]* src="([^"]+)"[^>]*>""" 73 pattern = r"""<img[^>]* src="([^"]+)"[^>]*>"""
65 return re.sub(pattern, repl, string) 74 return re.sub(pattern, repl, string)