home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 January / maximum-cd-2011-01.iso / DiscContents / calibre-0.7.26.msi / file_1498 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-10-31  |  10.6 KB  |  323 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. default_smartypants_attr = '1'
  5. import re
  6. tags_to_skip_regex = re.compile('<(/)?(style|pre|code|kbd|script|math)[^>]*>', re.I)
  7.  
  8. def verify_installation(request):
  9.     return 1
  10.  
  11.  
  12. def cb_story(args):
  13.     
  14.     try:
  15.         forbidden_flavours = args['entry']['smartypants_forbidden_flavours']
  16.     except KeyError:
  17.         forbidden_flavours = [
  18.             'rss']
  19.  
  20.     
  21.     try:
  22.         attributes = args['entry']['smartypants_attributes']
  23.     except KeyError:
  24.         attributes = default_smartypants_attr
  25.  
  26.     if attributes is None:
  27.         attributes = default_smartypants_attr
  28.     
  29.     entryData = args['entry'].getData()
  30.     
  31.     try:
  32.         if args['request']['flavour'] in forbidden_flavours:
  33.             return None
  34.     except KeyError:
  35.         if '<' in args['entry']['body'][0:15]:
  36.             return None
  37.     except:
  38.         '<' in args['entry']['body'][0:15]
  39.  
  40.     args['entry']['body'] = smartyPants(entryData, attributes)
  41.     args['entry']['title'] = smartyPants(args['entry']['title'], attributes)
  42.  
  43.  
  44. def smartyPants(text, attr = default_smartypants_attr):
  45.     convert_quot = False
  46.     skipped_tag_stack = []
  47.     do_dashes = '0'
  48.     do_backticks = '0'
  49.     do_quotes = '0'
  50.     do_ellipses = '0'
  51.     do_stupefy = '0'
  52.     if attr == '0':
  53.         return text
  54.     if attr == '1':
  55.         do_quotes = '1'
  56.         do_backticks = '1'
  57.         do_dashes = '1'
  58.         do_ellipses = '1'
  59.     elif attr == '2':
  60.         do_quotes = '1'
  61.         do_backticks = '1'
  62.         do_dashes = '2'
  63.         do_ellipses = '1'
  64.     elif attr == '3':
  65.         do_quotes = '1'
  66.         do_backticks = '1'
  67.         do_dashes = '3'
  68.         do_ellipses = '1'
  69.     elif attr == '-1':
  70.         do_stupefy = '1'
  71.     else:
  72.         for c in attr:
  73.             if c == 'q':
  74.                 do_quotes = '1'
  75.                 continue
  76.             if c == 'b':
  77.                 do_backticks = '1'
  78.                 continue
  79.             if c == 'B':
  80.                 do_backticks = '2'
  81.                 continue
  82.             if c == 'd':
  83.                 do_dashes = '1'
  84.                 continue
  85.             if c == 'D':
  86.                 do_dashes = '2'
  87.                 continue
  88.             if c == 'i':
  89.                 do_dashes = '3'
  90.                 continue
  91.             if c == 'e':
  92.                 do_ellipses = '1'
  93.                 continue
  94.             if c == 'w':
  95.                 convert_quot = '1'
  96.                 continue
  97.         
  98.     tokens = _tokenize(text)
  99.     result = []
  100.     in_pre = False
  101.     prev_token_last_char = ''
  102.     for cur_token in tokens:
  103.         if cur_token[0] == 'tag':
  104.             result.append(cur_token[1])
  105.             skip_match = tags_to_skip_regex.match(cur_token[1])
  106.             if skip_match is not None:
  107.                 if not skip_match.group(1):
  108.                     skipped_tag_stack.append(skip_match.group(2).lower())
  109.                     in_pre = True
  110.                 elif len(skipped_tag_stack) > 0:
  111.                     if skip_match.group(2).lower() == skipped_tag_stack[-1]:
  112.                         skipped_tag_stack.pop()
  113.                     
  114.                 
  115.                 if len(skipped_tag_stack) == 0:
  116.                     in_pre = False
  117.                 
  118.             
  119.         skip_match is not None
  120.         t = cur_token[1]
  121.         last_char = t[-1:]
  122.         if not in_pre:
  123.             t = processEscapes(t)
  124.             if convert_quot != '0':
  125.                 t = re.sub('"', '"', t)
  126.             
  127.             if do_dashes != '0':
  128.                 if do_dashes == '1':
  129.                     t = educateDashes(t)
  130.                 
  131.                 if do_dashes == '2':
  132.                     t = educateDashesOldSchool(t)
  133.                 
  134.                 if do_dashes == '3':
  135.                     t = educateDashesOldSchoolInverted(t)
  136.                 
  137.             
  138.             if do_ellipses != '0':
  139.                 t = educateEllipses(t)
  140.             
  141.             if do_backticks != '0':
  142.                 t = educateBackticks(t)
  143.             
  144.             if do_backticks == '2':
  145.                 t = educateSingleBackticks(t)
  146.             
  147.             if do_quotes != '0':
  148.                 if t == "'":
  149.                     if re.match('\\S', prev_token_last_char):
  150.                         t = '’'
  151.                     else:
  152.                         t = '‘'
  153.                 elif t == '"':
  154.                     if re.match('\\S', prev_token_last_char):
  155.                         t = '”'
  156.                     else:
  157.                         t = '“'
  158.                 else:
  159.                     t = educateQuotes(t)
  160.             
  161.             if do_stupefy == '1':
  162.                 t = stupefyEntities(t)
  163.             
  164.         
  165.         prev_token_last_char = last_char
  166.         result.append(t)
  167.     
  168.     return ''.join(result)
  169.  
  170.  
  171. def educateQuotes(str):
  172.     punct_class = '[!"#\\$\\%\'()*+,-.\\/:;<=>?\\@\\[\\\\\\]\\^_`{|}~]'
  173.     str = re.sub("^'(?=%s\\\\B)" % (punct_class,), '’', str)
  174.     str = re.sub('^"(?=%s\\\\B)' % (punct_class,), '”', str)
  175.     str = re.sub('"\'(?=\\w)', '“‘', str)
  176.     str = re.sub('\'"(?=\\w)', '‘“', str)
  177.     str = re.sub("\\b'(?=\\d{2}s)", '’', str)
  178.     close_class = '[^\\ \\t\\r\\n\\[\\{\\(\\-]'
  179.     dec_dashes = '–|—'
  180.     opening_single_quotes_regex = re.compile("\n\t\t\t(\n\t\t\t\t\\s          |   # a whitespace char, or\n\t\t\t\t       |   # a non-breaking space entity, or\n\t\t\t\t--          |   # dashes, or\n\t\t\t\t&[mn]dash;  |   # named dash entities\n\t\t\t\t%s          |   # or decimal entities\n\t\t\t\t&\\#x201[34];    # or hex\n\t\t\t)\n\t\t\t'                 # the quote\n\t\t\t(?=\\w)            # followed by a word character\n\t\t\t" % (dec_dashes,), re.VERBOSE)
  181.     str = opening_single_quotes_regex.sub('\\1‘', str)
  182.     closing_single_quotes_regex = re.compile("\n\t\t\t(%s)\n\t\t\t'\n\t\t\t(?!\\s | s\\b | \\d)\n\t\t\t" % (close_class,), re.VERBOSE)
  183.     str = closing_single_quotes_regex.sub('\\1’', str)
  184.     closing_single_quotes_regex = re.compile("\n\t\t\t(%s)\n\t\t\t'\n\t\t\t(\\s | s\\b)\n\t\t\t" % (close_class,), re.VERBOSE)
  185.     str = closing_single_quotes_regex.sub('\\1’\\2', str)
  186.     str = re.sub("'", '‘', str)
  187.     opening_double_quotes_regex = re.compile('\n\t\t\t(\n\t\t\t\t\\s          |   # a whitespace char, or\n\t\t\t\t       |   # a non-breaking space entity, or\n\t\t\t\t--          |   # dashes, or\n\t\t\t\t&[mn]dash;  |   # named dash entities\n\t\t\t\t%s          |   # or decimal entities\n\t\t\t\t&\\#x201[34];    # or hex\n\t\t\t)\n\t\t\t"                 # the quote\n\t\t\t(?=\\w)            # followed by a word character\n\t\t\t' % (dec_dashes,), re.VERBOSE)
  188.     str = opening_double_quotes_regex.sub('\\1“', str)
  189.     closing_double_quotes_regex = re.compile('\n\t\t\t#(%s)?   # character that indicates the quote should be closing\n\t\t\t"\n\t\t\t(?=\\s)\n\t\t\t' % (close_class,), re.VERBOSE)
  190.     str = closing_double_quotes_regex.sub('”', str)
  191.     closing_double_quotes_regex = re.compile('\n\t\t\t(%s)   # character that indicates the quote should be closing\n\t\t\t"\n\t\t\t' % (close_class,), re.VERBOSE)
  192.     str = closing_double_quotes_regex.sub('\\1”', str)
  193.     str = re.sub('"', '“', str)
  194.     return str
  195.  
  196.  
  197. def educateBackticks(str):
  198.     str = re.sub('``', '“', str)
  199.     str = re.sub("''", '”', str)
  200.     return str
  201.  
  202.  
  203. def educateSingleBackticks(str):
  204.     str = re.sub('`', '‘', str)
  205.     str = re.sub("'", '’', str)
  206.     return str
  207.  
  208.  
  209. def educateDashes(str):
  210.     str = re.sub('---', '–', str)
  211.     str = re.sub('--', '—', str)
  212.     return str
  213.  
  214.  
  215. def educateDashesOldSchool(str):
  216.     str = re.sub('---', '—', str)
  217.     str = re.sub('--', '–', str)
  218.     return str
  219.  
  220.  
  221. def educateDashesOldSchoolInverted(str):
  222.     str = re.sub('---', '–', str)
  223.     str = re.sub('--', '—', str)
  224.     return str
  225.  
  226.  
  227. def educateEllipses(str):
  228.     str = re.sub('\\.\\.\\.', '…', str)
  229.     str = re.sub('\\. \\. \\.', '…', str)
  230.     return str
  231.  
  232.  
  233. def stupefyEntities(str):
  234.     str = re.sub('–', '-', str)
  235.     str = re.sub('—', '--', str)
  236.     str = re.sub('‘', "'", str)
  237.     str = re.sub('’', "'", str)
  238.     str = re.sub('“', '"', str)
  239.     str = re.sub('”', '"', str)
  240.     str = re.sub('…', '...', str)
  241.     return str
  242.  
  243.  
  244. def processEscapes(str):
  245.     str = re.sub('\\\\\\\\', '\', str)
  246.     str = re.sub('\\\\"', '"', str)
  247.     str = re.sub("\\\\'", ''', str)
  248.     str = re.sub('\\\\\\.', '.', str)
  249.     str = re.sub('\\\\-', '-', str)
  250.     str = re.sub('\\\\`', '`', str)
  251.     return str
  252.  
  253.  
  254. def _tokenize(str):
  255.     tokens = []
  256.     tag_soup = re.compile('([^<]*)(<[^>]*>)')
  257.     token_match = tag_soup.search(str)
  258.     previous_end = 0
  259.     while token_match is not None:
  260.         if token_match.group(1):
  261.             tokens.append([
  262.                 'text',
  263.                 token_match.group(1)])
  264.         
  265.         tokens.append([
  266.             'tag',
  267.             token_match.group(2)])
  268.         previous_end = token_match.end()
  269.         token_match = tag_soup.search(str, token_match.end())
  270.     if previous_end < len(str):
  271.         tokens.append([
  272.             'text',
  273.             str[previous_end:]])
  274.     
  275.     return tokens
  276.  
  277. if __name__ == '__main__':
  278.     import locale
  279.     
  280.     try:
  281.         locale.setlocale(locale.LC_ALL, '')
  282.     except:
  283.         pass
  284.  
  285.     from docutils.core import publish_string
  286.     docstring_html = publish_string(__doc__, writer_name = 'html')
  287.     print docstring_html
  288.     import unittest
  289.     sp = smartyPants
  290.     
  291.     class TestSmartypantsAllAttributes(unittest.TestCase):
  292.         
  293.         def test_dates(self):
  294.             self.assertEqual(sp("1440-80's"), '1440-80’s')
  295.             self.assertEqual(sp("1440-'80s"), '1440-‘80s')
  296.             self.assertEqual(sp("1440---'80s"), '1440–‘80s')
  297.             self.assertEqual(sp('1960s'), '1960s')
  298.             self.assertEqual(sp("1960's"), '1960’s')
  299.             self.assertEqual(sp("one two '60s"), 'one two ‘60s')
  300.             self.assertEqual(sp("'60s"), '‘60s')
  301.  
  302.         
  303.         def test_skip_tags(self):
  304.             self.assertEqual(sp('<script type="text/javascript">\n<!--\nvar href = "http://www.google.com";\nvar linktext = "google";\ndocument.write(\'<a href="\' + href + \'">\' + linktext + "</a>");\n//-->\n</script>'), '<script type="text/javascript">\n<!--\nvar href = "http://www.google.com";\nvar linktext = "google";\ndocument.write(\'<a href="\' + href + \'">\' + linktext + "</a>");\n//-->\n</script>')
  305.             self.assertEqual(sp("<p>He said "Let's write some code." This code here <code>if True:\n\tprint "Okay"</code> is python code.</p>"), '<p>He said “Let’s write some code.” This code here <code>if True:\n\tprint "Okay"</code> is python code.</p>')
  306.  
  307.         
  308.         def test_ordinal_numbers(self):
  309.             self.assertEqual(sp('21st century'), '21st century')
  310.             self.assertEqual(sp('3rd'), '3rd')
  311.  
  312.         
  313.         def test_educated_quotes(self):
  314.             self.assertEqual(sp('"Isn\'t this fun?"'), '“Isn’t this fun?”')
  315.  
  316.  
  317.     unittest.main()
  318.  
  319. __author__ = 'Chad Miller <smartypantspy@chad.org>'
  320. __version__ = '1.5_1.6: Fri, 27 Jul 2007 07:06:40 -0400'
  321. __url__ = 'http://wiki.chad.org/SmartyPantsPy'
  322. __description__ = 'Smart-quotes, smart-ellipses, and smart-dashes for weblog entries in pyblosxom'
  323.