1. Brodie Rao
  2. linkifier

Commits

Brodie Rao  committed 9621852

linkify: allow substitutions to specify URLs without domain names

  • Participants
  • Parent commits e25f359
  • Branches default

Comments (0)

Files changed (1)

File linkifier.py

View file
  • Ignore whitespace
 _wordsplit = _group2(re.compile(r'([^\w\-@#]+)', re.UNICODE).split)
 _isdomainname = re.compile(r'(?!-)[a-zA-Z\d\-]{0,62}[a-zA-Z\d]{1}$').match
 
-def urlizeword(word):
+def urlizeword(word, requiredomain=True):
     """Turn word into a URL if it looks valid.
 
     Example usage:
     Traceback (most recent call last):
         ...
     ValueError: not a URL
+
+    If requiredomain is False, URLs starting with a slash are allowed:
+
+    >>> urlizeword('/foo/bar', requiredomain=False)
+    '/foo/bar'
     """
-    if word.startswith(('http://', 'https://')):
+    prefixes = ('http://', 'https://')
+    if not requiredomain:
+        prefixes += ('/',)
+    if word.startswith(prefixes):
         return word
 
     if '.' in word:
 
     raise ValueError('not a URL')
 
-def linkifyword(word, text=None):
+def linkifyword(word, text=None, requiredomain=True):
     """Turn a word into an HTML anchor if it looks like a URL.
 
     For example:
     '<a href="http://google.com/search">google.com/search</a>'
     >>> linkifyword('http://google.com/reader')
     '<a href="http://google.com/reader">http://google.com/reader</a>'
+    >>> linkifyword('/about.html', requiredomain=False)
+    '<a href="/about.html">/about.html</a>'
 
     If text is specified, it's used as the anchor text:
 
         ...
     ValueError: not a URL
     """
-    url = urlizeword(word)
+    url = urlizeword(word, requiredomain)
     text = text if text is not None else word
     return '<a href="%s">%s</a>' % (url, text)
 
     order until one matches:
 
     >>> linkify('fixes PROJ-123',
-    ...         (r'#(\d+)', r'issues.com/\1'),
+    ...         (r'#(\d+)', r'/issues/\1'),
     ...         (r'([A-Z]{4})-(\d+)', r'http://issues.net/\1/\2'))
     'fixes <a href="http://issues.net/PROJ/123">PROJ-123</a>'
 
                 continue
             if nsubs > 0:
                 try:
-                    return linkifyword(url, word)
+                    return linkifyword(url, word, requiredomain=False)
                 except ValueError:
                     pass
         return word