# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - WordCount Macro

    @copyright: 2004 by Walter Aprile (walter@raingod.com)
    @license: GNU GPL, see COPYING for details.
"""

## This is my first macro!
## ... and it certainly shows ...
##
## Usage: [[WordCount]] display word count of the current page
##        [[WordCount(SummerInSiam)]] display word count of page SummerInSiam
##        [[WordCount(FrontPage, 500)]] display word count of FrontPage,
##        plus a message about the difference between the current world count
##        and the target world count of 500


Dependencies = ["pages"]

from MoinMoin.Page import Page
import string, re

def CountWords(Text):
    total = 0
    separator = re.compile(r"[' ,\.;:\-()]+")
    sepCount = len(separator.findall(line))
    return sepCount
        	
def execute(macro, args):
    targetLength = 0
    argv = string.split(args,",")
    # get list of pages and their objects
    if (args!=None):
        pagename = argv[0]
        if (len(argv)>1):
            targetLength = int(argv[1])
    else:
        pagename = macro.request.getPathinfo()[1:]
    page = Page(macro.request, pagename)
    body = page.get_raw_body()

    separator = re.compile(r"[' ,\.;:\-()]+")
    sepCount = len(separator.findall(body))

    result = []
    result.append(macro.formatter.paragraph(1))
    result.append("Word count for " + pagename + " is ")
    result.append(macro.formatter.strong(1))
    result.append(macro.formatter.text(str(sepCount)))
    result.append(macro.formatter.strong(0))
    if (targetLength):
        delta = sepCount - targetLength
        message = " exactly"
        if (delta > 0):
            message = macro.formatter.sup(1) + str(delta) + macro.formatter.sup(0) + " over count" 
        elif (delta <0):
            message = macro.formatter.sub(1) + str(abs(delta)) + macro.formatter.sub(0) + " to write"

        result.append(" (target is " + str(targetLength) + ", " + message + ")")
    result.append(macro.formatter.paragraph(0))
    
    return ''.join(result)

