plugins/aspell_plugin.py
author Mikael Berthe <mikael@lilotux.net>
Thu, 03 May 2007 22:41:58 +0200
changeset 34 535d03a56f9d
parent 30 33af762962f1
permissions -rw-r--r--
Improve DICT module readbility

#$ neutron_plugin 01
# 2007-05 Mikael Berthe <mikael@lilotux.net>

import subprocess
import locale
import re

def handler_aspell(type, source, parameters):
    parameters = parameters.strip()
    splitdata = parameters.split()
    cmd = ['/usr/bin/aspell', '-a']
    reply = ""

    if not parameters:
        return

    LC, encoding = locale.getdefaultlocale()
    if not encoding:
        encoding = 'ascii'

    # Check if the language is specified (two-letter code)
    if len(splitdata) > 1:
        lang = parameters.lower()
        if re.match(r"\w\w ", lang):
            parameters = parameters[3:].lstrip()
            cmd.append("--lang=" + lang)

    # Spawn an aspell process
    aspell = subprocess.Popen(cmd, stdin=subprocess.PIPE,
                              stdout=subprocess.PIPE)

    aspell.stdin.write(parameters.encode(encoding))
    aspell.stdin.close()

    # Skip the first line (banner)
    aspell.stdout.readline()

    # Process all result lines
    for r in aspell.stdout.readlines():
        r = r.decode(encoding)
        if r == "*\n":
            reply += "* Word correctly spelled.\n"
        elif r.startswith("& "):
            if r.count(": "):
                reply += "* Let me suggest " + r[r.find(": ")+2:].strip()
                reply += ".\n"
            else:
                # I don't know if it can happen
                reply += r

    aspell.stdout.close()

    if not reply:
        reply = "Unknown error (no reply)"

    smsg(type, source, reply.rstrip())

register_command_handler(handler_aspell, 'aspell', 0, 'Check the spelling',
                         'aspell [lang]', ['aspell fr bonjour'])

# vim:set et sts=4: