comparison frontends/src/tools/strings.py @ 2107:2c31ddf633e5

frontends(tools/strings): put URL regex outside of getURLParams and precompile it
author Goffi <goffi@goffi.org>
date Sun, 01 Jan 2017 16:39:26 +0100
parents 1128feb54180
children
comparison
equal deleted inserted replaced
2106:5874da3811b7 2107:2c31ddf633e5
16 16
17 # You should have received a copy of the GNU Affero General Public License 17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. 18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 19
20 import re 20 import re
21
22 # Regexp from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
23 RE_URL = re.compile(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`!()\[\]{};:'".,<>?]))""")
24
25
26 # TODO: merge this class with an other module or at least rename it (strings is not a good name)
21 27
22 28
23 def getURLParams(url): 29 def getURLParams(url):
24 """This comes from pyjamas.Location.makeUrlDict with a small change 30 """This comes from pyjamas.Location.makeUrlDict with a small change
25 to also parse full URLs, and parameters with no value specified 31 to also parse full URLs, and parameters with no value specified
48 54
49 @param string (unicode): text to process 55 @param string (unicode): text to process
50 @param new_target (bool): if True, make the link open in a new window 56 @param new_target (bool): if True, make the link open in a new window
51 """ 57 """
52 # XXX: report any change to libervia.browser.strings.addURLToText 58 # XXX: report any change to libervia.browser.strings.addURLToText
53 # Regexp from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
54 def repl(match): 59 def repl(match):
55 url = match.group(0) 60 url = match.group(0)
56 if not re.match(r"""[a-z]{3,}://|mailto:|xmpp:""", url): 61 if not re.match(r"""[a-z]{3,}://|mailto:|xmpp:""", url):
57 url = "http://" + url 62 url = "http://" + url
58 target = ' target="_blank"' if new_target else '' 63 target = ' target="_blank"' if new_target else ''
59 return '<a href="%s"%s class="url">%s</a>' % (url, target, match.group(0)) 64 return '<a href="%s"%s class="url">%s</a>' % (url, target, match.group(0))
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`!()\[\]{};:'".,<>?]))""" 65 return RE_URL.sub(repl, string)
61 return re.sub(pattern, repl, string)
62 66
63 67
64 def addURLToImage(string): 68 def addURLToImage(string):
65 """Check a XHTML text for what looks like an imageURL and make it clickable. 69 """Check a XHTML text for what looks like an imageURL and make it clickable.
66 70