""" Text Helpers """ # Last synced with Rails copy at Revision 4595 on Aug 19th, 2006. # Purposely left out sanitize, should be included at some point likely using # BeautifulSoup. from routes import request_config from webhelpers.rails.tags import content_tag, tag_options import webhelpers.textile as textile import webhelpers.markdown as markdown import itertools, re AUTO_LINK_RE = re.compile("""(<\w+.*?>|[^=!:'"\/]|^)((?:http[s]?:\/\/)|(?:www\.))(([\w]+:?[=?&\/.-]?)*\w+[\/]?(?:\#\w*)?)([\.,"'?!;:]|\s|<|$)""") def iterdict(items): return dict(items=items, iter=itertools.cycle(items)) def cycle(*args, **kargs): """ Returns the next cycle of the given list Everytime ``cycle`` is called, the value returned will be the next item in the list passed to it. This list is reset on every request, but can also be reset by calling ``reset_cycle()``. You may specify the list as either arguments, or as a single list argument. This can be used to alternate classes for table rows:: # In Myghty... % for item in items:
`` tags, and converts line breaks into ``
``
Two consecutive newlines(``\\n\\n``) are considered as a paragraph, one newline (``\\n``) is
considered a linebreak, three or more consecutive newlines are turned into two newlines.
"""
text = re.sub(r'(\r\n|\n|\r)', r'\n', text)
text = re.sub(r'\n\n+', r'\n\n', text)
text = re.sub(r'(\n\n)', r'
', text)
text = re.sub(r'([^\n])(\n)([^\n])', r'\1\2
\3', text)
text = content_tag("p", text).replace('
', r'
\n', text)
return text
def auto_link(text, link="all", **href_options):
"""
Turns all urls and email addresses into clickable links.
``link``
Used to determine what to link. Options are "all", "email_addresses", or "urls"
Example::
>>> auto_link("Go to http://www.planetpython.com and say hello to guido@python.org")
'Go to http://www.planetpython.com and say
hello to guido@python.org'
"""
if not text:
return ""
if link == "all":
return auto_link_urls(auto_link_email_addresses(text), **href_options)
elif link == "email_addresses":
return auto_link_email_addresses(text)
else:
return auto_link_urls(text, **href_options)
def auto_link_urls(text, **href_options):
extra_options = tag_options(**href_options)
def handle_match(matchobj):
all = matchobj.group()
a, b, c, d = matchobj.group(1,2,3,5)
if re.match(r'%s%s' % (a, b, c, extra_options, text, d)
return re.sub(AUTO_LINK_RE, handle_match, text)
def auto_link_email_addresses(text):
def fix_email(match):
text = matchobj.group()
return '\1', text)
def strip_links(text):
"""
Turns all links into words
Example::
>>> strip_links("else")
"else"
"""
return re.sub(r'(.*?)<\/a>', r'\1', text, re.M)
def textilize(text, sanitize=False):
"""Format the text with Textile formatting
This function uses the `PyTextile library ,
and
for proper XHTML output.
"""
texer = textile.Textiler(text)
return texer.process(sanitize=sanitize)
def markdown(text):
"""Format the text with MarkDown formatting
This function uses the `Python MarkDown library