## Static header variables
author="Fred Flintstone"
email="foo@bar.com"
company="Acme Inc"
status="Experimental (Do Not Distribute)"
##Optional functionality
getMusic=True ##Helps me remeber when it was I wrote the code but slow but slow as .....
sheBang=True  ##Should we insert a shebang at the start of the header if one not already present?
descr=True    ##Should we prompt the user for a description?

##Dynamic header variables ----------------------------------------------------
import os,time, sys
from getpass import getuser

hdrTag="komodoheader"
hdrVer="0.3"

##OS X iTunes - add in players / OS's as required
artist="Nothing"
song="Playing"
if sys.platform == "darwin" and getMusic:
    if os.popen("osascript -e 'tell application \"iTunes\" to player state as string'").readline().find("playing") != -1:
        artist=os.popen("osascript -e 'tell application \"iTunes\" to artist of current track as string'").readline()[:-1]
        song=os.popen("osascript -e 'tell application \"iTunes\" to name of current track as string'").readline()[:-1]
tune="%s - %s"%(artist,song)

##Line ends being used for this edit session
if komodo.editor.eOLMode ==0:
    #Windows
    eol="\x0D\x0A"
elif komodo.editor.eOLMode==2:
    #*NIX
    eol="\x0A"
else:
    #Mac
    eol="\x0D"

##Language being programmed in file
if komodo.document.language == "Python":
    language="Python Version %s"%(sys.version[:6]+sys.version[35:])
    shebang="#!/usr/bin/env python"
else:
    ##ToDo
    language=komodo.document.language
    shebang="#!/bin/sh"

##Get file encoding [bug reported by Dereckson | Thu, 2007-04-26 12:03 - thanks!]
if komodo.document.codePage == 65001:
    encoding="UTF-8"
elif komodo.document.codePage == 850:
    encoding="latin1"
else:
    encoding="unknown encoding-please submit this value (%d) to kh@iodboi.co.uk"%(komodo.document.codePage)

##Filename of file
try:
    fileName=komodo.document.file.baseName
except:
    fileName=""

##Header layout - Has to be one long line as komodo inserts tabs and newlines if triple quotes used ??
hdr="#%s v%s %s"%(hdrTag, hdrVer, eol)
hdr+="###############################################################################%s#%s"%(eol,eol)
hdr+="# File:         %s%s"%(fileName, eol)
hdr+="# Description:  %s"%(eol)
hdr+="# Created_On:   %s%s"%(time.ctime(),eol)
hdr+="# Created_By:   %s (%s) %s"%(author,email,eol)
hdr+="# Modified_On:  %s"%(eol)
hdr+="# Modified_By:  %s"%(eol)
hdr+="# Language:     %s%s"%(language,eol)
hdr+="# Encoding:     %s%s"%(encoding,eol)
hdr+="# Status:       %s%s"%(status,eol)
hdr+="# Music:        %s%s#%s"%(tune,eol,eol)
hdr+="# (c) Copyright %s, %s all rights reserved.%s#%s"%(time.ctime()[-4:],company,eol,eol)
hdr+="###############################################################################%s"%(eol)
numHdrLines=hdr.count("%s"%eol)
varStartCol=16  #automate this

##Actual code to put it where we want it.......
def findTag(tag,start=0,end=15, select=True, replace=None):
    #Search through a range of lines looking for the particular tag specified
    # if found return the line number it is on, else return -1
    # (by default search first 15 lines)

    for lineNo in range(start,end+1):
        komodo.editor.gotoLine(lineNo)

        ##New way to get what strings are in a line - suggested on the komodo discussion list
        ## See : http://aspn.activestate.com/ASPN/Mail/Message/komodo-discuss/3366278
        ## essentially copy in a whole line and look for the tag we want
        komodo.editor.lineEnd()
        komodo.editor.vCHomeExtend()
        curLine = komodo.editor.selText
        #komodo.editor.insertText(curPos, "\n%d-TAG (%s)[%s]"%(pos,tag,tagHere))
        if tag in curLine:
            #Are we just finding tags or overwriting them too ?
            if replace:
                pad=" "*(varStartCol-len(tag))
                komodo.editor.replaceSel("%s%s%s"%(tag,pad,replace))
            break
    else:
        ##Tag not found
        lineNo=-1

    if not select:
        ##Set back to pos 0,0 ready for new tag search
        komodo.editor.gotoLine(0)

    ##return line number of the tag
    return lineNo

##Get editor window in focus
komodo.view.setFocus()
##Wrap all our monkeying about in one easy undo step
komodo.editor.beginUndoAction()
try:
    #Save before we do anything else....just incase :)
    komodo.doCommand("cmd_save")

    #Get cursor position so we can return to it later
    curPos=komodo.editor.currentPos
    lineNum=komodo.editor.lineFromPosition(curPos)
    colNum=komodo.editor.getColumn(curPos)


    #Look for the 'komodoheader' tag to see if we are updating an existing tag or making a new header
    tagPos=findTag(hdrTag)
    if tagPos == -1:
        #no header found - INSERT A NEW HEADER

        #Check to see if there is a shebang as we don't wanna overwrite it
        shebangPos=findTag("#!",select=False)
        if shebangPos != -1:
            #Shebang found - skip a line
            komodo.editor.gotoLine(shebangPos+1)
        elif sheBang:
            #No shebang found, and sheBang var set so we should insert one
            komodo.editor.gotoLine(0)
            komodo.editor.home()
            komodo.editor.newLine()
            komodo.editor.lineUp()
            komodo.editor.insertText(komodo.editor.currentPos, shebang)
            komodo.editor.lineDown()
            numHdrLines+=1

        #Pop in the text
        komodo.editor.insertText(komodo.editor.currentPos, hdr)

        #Prompt user enter a description?
        if descr:
            tagPos=findTag("Description:")
            komodo.editor.lineEnd()
            descrSnip=komodo.findPart("snippet", "askDescription", "toolbox" )
            descrSnip.invoke()

        ##Move back to where we started allowing for new lines inserted
        komodo.editor.gotoPos(komodo.editor.positionFromLine(numHdrLines+lineNum)+colNum)

    else:
        ## UPDATE HEADER - just update the dynamic sections not write a full new header
        ## Update all the tags we want - i.e. the dynamic variables
        #tagPos=findTag("# File", start=tagPos)
        try:
            #komodo.editor.replaceSel("# File:         %s"%(komodo.document.file.baseName))
            tagPos=findTag("# File:", start=tagPos, replace="%s"%(komodo.document.file.baseName))
        except:
            pass

        tagPos=findTag("# Modified_On:", start=tagPos, replace="%s"%(time.ctime()))

        tagPos=findTag("# Modified_By:", start=tagPos, replace="%s"%(getuser()))

        tagPos=findTag("# Music:", start=tagPos, replace="%s"%(tune))

        ##Move back to where we started
        komodo.editor.gotoPos(komodo.editor.positionFromLine(lineNum)+colNum)

        #And save as we have altered the buffer
        #komodo.doCommand('cmd_save')

finally:
    komodo.editor.endUndoAction()
