# -*- coding: utf-8 -*-

# Copyright (c) 2002 - 2006 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing a Python lexer with some additional methods.
"""

import re

from qtext import QextScintillaLexerPython
from qt import *

from Lexer import Lexer
import Preferences

class LexerPython(QextScintillaLexerPython, Lexer):
    """ 
    Subclass to implement some additional lexer dependant methods.
    """
    def __init__(self, parent=None, name=None):
        """
        Constructor
        
        @param parent parent widget of this lexer
        @param name name of this lexer
        """
        QextScintillaLexerPython.__init__(self, parent, name)
        Lexer.__init__(self)
        
        self.commentString = QString("##")

    def getIndentationDifference(self, line, editor):
        """
        Private method to determine the difference for the new indentation.
        
        @param line line to perform the calculation for (integer)
        @param editor QScintilla editor
        @return amount of difference in indentation (integer)
        """
        indent_width = Preferences.getEditor('IndentWidth')
        
        lead_spaces = editor.indentation(line)
        
        pline = line - 1
        while pline >= 0 and re.match('^\s*(#.*)?$', unicode(editor.text(pline))):
            pline -= 1
            
        if pline < 0:
            last = 0
        else:
            previous_lead_spaces = editor.indentation(pline)
            # trailing spaces
            m = re.search(':\s*(#.*)?$', unicode(editor.text(pline)))
            last = previous_lead_spaces
            if m:
                last += indent_width
            else:
                # special cases, like pass (unindent) or return (also unindent)
                m = re.search('(pass\s*(#.*)?$)|(^[^#]return)', unicode(editor.text(pline)))
                if m:
                    last -= indent_width
        
        if lead_spaces % indent_width != 0 or lead_spaces == 0 \
           or self.lastIndented != line:
            indentDifference = last - lead_spaces
        else:
            indentDifference = -indent_width
        
        return indentDifference
