#! /usr/local/bin/python
#
# commentLines.py - comments or uncomments the selected lines by prefixing 
#                   with or surrounding by comment characters appropriate to
#                   the file type. The type is determined by the file extension
#                   and the comment characters are taken from the dictionary "cty".
#                   Teach this script about new files by adding entries to cty.
#
#   This script is free and comes with no guarantees. 
#   You are welcome to modify and redistribute it, as long 
#   as you retain these comments. 
#   This comes from http://www.lee-phillips.org/info/Macintosh/commentLines.py
#   Copyright Lee Phillips 

#   This is an elaboration of a script that is distributed with TextExtras 
#   by Mike Ferris (http://www.lorax.com/FreeStuff/TextExtras.html) and with 
#   ProjectBuilder (software for Mac OSX). If you use the latter but not the former,
#   you can make this work with ProjectBuilder by changing the "TE" prefixes to "PBX",
#   probably.

#
# -- TextExtras User Script Info --
# %%%{TEName=Comment Selection}%%%
# %%%{TEInput=Selection}%%%
# %%%{TEOutput=ReplaceSelection}%%%
# %%%{TEKeyEquivalent=@/}%%%
# %%%{TEArgument=-c}%%%
#
# %%%{TENewScript}%%%
# %%%{TEName=Uncomment Selection}%%%
# %%%{TEInput=Selection}%%%
# %%%{TEOutput=ReplaceSelection}%%%
# %%%{TEKeyEquivalent=@~/}%%%
# %%%{TEArgument=-u}%%%
#
ff = "%%%{TEFilePath}%%%"
txt = """%%%{TESelectedText}%%%"""
import os, sys
sw = sys.stdout.write
lc = txt[-1]
cty = {'.f':['!',''], '.py':['#',''], '.sh':['#',''], '.html':['<!--', '-->'], '.htm':['<!--', '-->'], '.c':['/*', '*/']}
ext = os.path.splitext(os.path.basename(ff))[1]
if cty.has_key(ext): 
    sw("%%%{TESelection}%%%")
    if len(sys.argv) > 1:
        if sys.argv[1] == "-u": #Uncommenting
            if cty[ext][1] == '':  # Line by line uncommenting
                txt = txt.splitlines()
                txt = [l.replace(cty[ext][0], '', 1) for l in txt]
                sw('\n'.join(txt))
            else:                  # Multiline uncommenting
                txt = txt.replace(cty[ext][0], '', 1)
                try:
                    eci = txt.rindex(cty[ext][1])
                    txt = txt[0:eci] + txt[eci+len(cty[ext][1]):-1]
                    sw(txt)
                except:
                    sw(txt); lc=''
        elif sys.argv[1] == "-c": #Commenting
            if cty[ext][1] == '':  # Line by line commenting
                txt = txt.splitlines()
                txt = [cty[ext][0] + l for l in txt]
                sw('\n'.join(txt))
            else:                   # Multiline commenting
                if txt[-1] == '\n': txt = txt[0:-1]
                txt = cty[ext][0] + txt + cty[ext][1]
                sw(txt)
    if lc == "\n": sw('\n')
    sw("%%%{TESelection}%%%")