Advertisement
ijontichy

autotopic.py

May 7th, 2012
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import sys
  4. import re
  5.  
  6. urlRE     = re.compile("((?:ht|f)tps?://\w+(?:\.\w+)*(?::\d+)?(?:/[a-zA-Z0-9\.\-_~]*)*(?:\?(?:\w+=\S+)+)?)")
  7. titleRE   = re.compile("([\[\(])(#?[a-zA-Z0-9_-]+)([\]\)])")
  8. chanRE    = re.compile(r"(\s|\A)(#\S+)(\s|\Z)")
  9.  
  10. colorRepl = "\x03{}\x02\x02{}\x0F"
  11. titleRepl = "{0[border]}{1}\x0F{0[text]}{2}\x0F{0[border]}{3}\x0F"
  12.  
  13. urlColors = (11, 10, 8, 7, 9, 3)
  14. titleColors = {"border": "\x033\x02", "text": "\x02"}
  15.  
  16. def colorURLs(topic):
  17.    
  18.     currentColor = 0
  19.  
  20.     def nextColor(urlMatch):
  21.         nonlocal currentColor
  22.        
  23.         color = urlColors[currentColor]
  24.         currentColor = (currentColor + 1) % len(urlColors)
  25.  
  26.         return colorRepl.format(color, urlMatch.group(1))
  27.  
  28.     return urlRE.sub(nextColor, topic)
  29.  
  30. def colorTitle(topic):
  31.     def reTitleColor(topic):
  32.         return titleRepl.format(titleColors, *topic.groups())
  33.  
  34.     return titleRE.sub(reTitleColor, topic)
  35.  
  36. def colorChans(topic):
  37.  
  38.     def reChanColor(chan):
  39.         return chan.group(1) + colorRepl.format(4, chan.group(2)) + chan.group(3)
  40.  
  41.     return chanRE.sub(reChanColor, topic)
  42.  
  43.  
  44. colorFuncs = (colorURLs, colorTitle, colorChans)
  45.  
  46. def colorTopic(topic):
  47.     ret = topic
  48.  
  49.     for func in colorFuncs:
  50.         ret = func(ret)
  51.  
  52.     return ret
  53.  
  54.  
  55.  
  56. if __name__ == "__main__":
  57.     if len(sys.argv) == 1:
  58.         try:
  59.             while 1:
  60.                 nextTopic = input()
  61.                 print(colorTopic(nextTopic))
  62.  
  63.         except KeyboardInterrupt:
  64.             print()
  65.             sys.exit(1)
  66.  
  67.         except EOFError:
  68.             sys.exit()
  69.  
  70.     else:
  71.         print(colorTopic(" ".join(sys.argv[1:])))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement