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

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

"""
Module implementing the editor component of the eric4 IDE.
"""

import os
import re
    
from PyQt4.Qsci import QsciScintilla, QsciPrinter, QsciMacro
from PyQt4.QtCore import *
from PyQt4.QtGui import *

from KdeQt import KQFileDialog, KQMessageBox, KQInputDialog
from KdeQt.KQPrintDialog import KQPrintDialog
from KdeQt.KQApplication import e4App

import Lexers
import TypingCompleters
from QsciScintillaCompat import QsciScintillaCompat, QSCINTILLA_VERSION

from Debugger.EditBreakpointDialog import EditBreakpointDialog

from DebugClients.Python.PyCoverage import coverage

from Checks.TabnannyDialog import TabnannyDialog

from DataViews.CodeMetricsDialog import CodeMetricsDialog
from DataViews.PyCoverageDialog import PyCoverageDialog
from DataViews.PyProfileDialog import PyProfileDialog

from Printer import Printer

import Preferences
import Utilities

import UI.PixmapCache

class Editor(QsciScintillaCompat):
    """
    Class implementing the editor component of the eric4 IDE.
    
    @signal modificationStatusChanged(boolean, editor) emitted when the
            modification status has changed
    @signal undoAvailable(boolean) emitted to signal the undo availability
    @signal redoAvailable(boolean) emitted to signal the redo availability
    @signal cursorChanged(string, int, int) emitted when the cursor position
            was changed
    @signal editorSaved(string) emitted after the editor has been saved
    @signal editorRenamed(string) emitted after the editor got a new name
            (i.e. after a 'Save As')
    @signal captionChanged(string, editor) emitted when the caption is
            updated. Typically due to a readOnly attribute change.
    @signal breakpointToggled(editor) emitted when a breakpoint is toggled
    @signal bookmarkToggled(editor) emitted when a bookmark is toggled
    @signal syntaxerrorToggled(editor) emitted when a syntax error was discovered
    @signal autoCompletionAPIsAvailable(avail) emitted after the autocompletion
            function has been configured
    @signal coverageMarkersShown(boolean) emitted after the coverage markers have been 
            shown or cleared
    @signal taskMarkersUpdated(editor) emitted when the task markers were updated
    """
    def __init__(self, dbs, fn = None, vm = None,
                 isPythonFile = False, editor = None, tv = None):
        """
        Constructor
        
        @param dbs reference to the debug server object
        @param fn name of the file to be opened (string). If it is None,
                a new (empty) editor is opened
        @param vm reference to the view manager object (ViewManager.ViewManager)
        @param isPythonFile flag indicating that this is a Python file
                even if it doesn't have the .py extension (boolean)
        @param editor reference to an Editor object, if this is a cloned view
        @param tv reference to the task viewer object
        """
        QsciScintillaCompat.__init__(self)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setAttribute(Qt.WA_KeyCompression)
        self.setUtf8(True)
        
        self.pyExtensions = ['py', 'ptl']
        self.rbExtensions = ['rb']
        
        self.dbs = dbs
        self.taskViewer = tv
        self.fileName = fn
        self.vm = vm
        self.refactoring = e4App().getObject("Refactoring")
        self.isPythonFile = isPythonFile
        self.noName = QString()
        
        # clear some variables
        self.lastHighlight   = None   # remember the last highlighted line
        self.lastErrorMarker = None   # remember the last error line
        self.lastCurrMarker  = None   # remember the last current line
        
        self.breaks = {}            # key:   marker handle, 
                                    # value: (lineno, condition, temporary, 
                                    #         enabled, ignorecount)
        self.bookmarks = []         # bookmarks are just a list of handles to the
                                    # bookmark markers
        self.syntaxerrors = {}      # key:   marker handle
                                    # value: error message
        self.notcoveredMarkers = [] # just a list of marker handles
        
        self.condHistory = QStringList()
        self.lexer = None
        self.completer = None
        self.encoding = None
        self.apiLanguage = ''
        self.lastModified = 0
        self.line = -1
        self.inReopenPrompt = False
            # true if the prompt to reload a changed source is present
        self.inFileRenamed = False  # true if we are propagating a rename action
        self.inDragDrop = False     # true if we are in drop mode
        self.__hasTaskMarkers = False # no task markers present
            
        self.macros = {}    # list of defined macros
        self.curMacro = None
        self.recording = False
        
        self.acAPI = False
        
        # clear QScintilla defined keyboard commands
        # we do our own handling through the view manager
        self.clearAlternateKeys()
        self.clearKeys()
        
        self.connect(self, SIGNAL('modificationChanged(bool)'), 
                    self.__modificationChanged)
        self.connect(self, SIGNAL('cursorPositionChanged(int,int)'),
                    self.__cursorPositionChanged)
        self.connect(self, SIGNAL('modificationAttempted()'),
                self.__modificationReadOnly)
        
        # define the markers
        # markers for margin 1
        self.breakpoint = \
            self.markerDefine(UI.PixmapCache.getPixmap("break.png"))
        self.cbreakpoint = \
            self.markerDefine(UI.PixmapCache.getPixmap("cBreak.png"))
        self.tbreakpoint = \
            self.markerDefine(UI.PixmapCache.getPixmap("tBreak.png"))
        self.tcbreakpoint = \
            self.markerDefine(UI.PixmapCache.getPixmap("tCBreak.png"))
        self.dbreakpoint = \
            self.markerDefine(UI.PixmapCache.getPixmap("breakDisabled.png"))
        self.bookmark = \
            self.markerDefine(UI.PixmapCache.getPixmap("bookmark.png"))
        self.syntaxerror = \
            self.markerDefine(UI.PixmapCache.getPixmap("syntaxError.png"))
        self.notcovered = \
            self.markerDefine(UI.PixmapCache.getPixmap("notcovered.png"))
        self.taskmarker = \
            self.markerDefine(UI.PixmapCache.getPixmap("task.png"))
        
        # set the line markers
        self.currentline = self.markerDefine(QsciScintilla.Background)
        self.errorline = self.markerDefine(QsciScintilla.Background)
        self.__setLineMarkerColours()
        
        margin1Mask = (1 << self.breakpoint)   | \
                      (1 << self.cbreakpoint)  | \
                      (1 << self.tbreakpoint)  | \
                      (1 << self.tcbreakpoint) | \
                      (1 << self.dbreakpoint)  | \
                      (1 << self.currentline)  | \
                      (1 << self.errorline)    | \
                      (1 << self.bookmark)     | \
                      (1 << self.syntaxerror)  | \
                      (1 << self.notcovered)   | \
                      (1 << self.taskmarker)
        self.breakpointMask = (1 << self.breakpoint)   | \
                              (1 << self.cbreakpoint)  | \
                              (1 << self.tbreakpoint)  | \
                              (1 << self.tcbreakpoint) | \
                              (1 << self.dbreakpoint)
        
        # configure the margins
        # margin 1 for markers (i.e. breakpoints, highlights)
        self.setMarginWidth(1, 16)
        self.setMarginSensitivity(1, True)
        self.setMarginMarkerMask(1, margin1Mask)
        
        self.connect(self, SIGNAL('marginClicked(int, int, Qt::KeyboardModifiers)'),
                    self.__marginClicked)
        
        self.isResourcesFile = False
        if self.fileName is not None:
            if editor is None:
                if (QFileInfo(self.fileName).size() / 1024) > \
                   Preferences.getEditor("WarnFilesize"):
                    res = KQMessageBox.warning(None,
                        self.trUtf8("Open File"),
                        self.trUtf8("""<p>The size of the file <b>%1</b>"""
                                    """ is <b>%2 KB</b>."""
                                    """ Do you really want to load it?</p>""")\
                                    .arg(self.fileName)\
                                    .arg(QString.number(\
                                        QFileInfo(self.fileName).size() / 1024)),
                        QMessageBox.StandardButtons(\
                            QMessageBox.No | \
                            QMessageBox.Yes),
                        QMessageBox.No)
                    if res == QMessageBox.No or res == QMessageBox.Cancel:
                        raise IOError()
                line0 = self.readLine0(self.fileName)
                bindName = self.__bindName(line0)
                self.__bindLexer(bindName)
                self.__bindCompleter(bindName)
                self.readFile(self.fileName, True)
                self.__autoSyntaxCheck()
                self.isResourcesFile = self.fileName.endswith(".qrc")
            else:
                # clone the given editor
                self.setDocument(editor.document())
                self.breaks = editor.breaks
                self.bookmarks = editor.bookmarks
                self.syntaxerrors = editor.syntaxerrors
                self.notcoveredMarkers = editor.notcoveredMarkers
                self.isResourcesFile = editor.isResourcesFile
                self.setModified(editor.isModified())
                self.lastModified = QFileInfo(self.fileName).lastModified()
                line0 = self.text(0)
                bindName = self.__bindName(line0)
                self.__bindLexer(bindName)
                self.__bindCompleter(bindName)
            self.gotoLine(0)
        elif editor is not None:
            self.setDocument(editor.document())
        
        # set the text display
        self.__setTextDisplay()
        
        # set margin 0 and 2 configuration
        # margin 0 is used for line numbers
        # margin 2 is the folding margin
        self.__setMargin0and2()
        
        # set the autocompletion and calltips function
        self.__setAutoCompletion()
        self.__setCallTips()
        
        # perform automatic eol conversion
        if Preferences.getEditor("AutomaticEOLConversion"):
            self.convertEols(self.eolMode())
        
        sh = self.sizeHint()
        if sh.height() < 300:
            sh.setHeight(300)
        self.resize(sh)
        
        # Make sure tabbing through a QWorkspace works.
        self.setFocusPolicy(Qt.StrongFocus)
        
        self.__updateReadOnly(True)
        
        self.setWhatsThis(self.trUtf8(
            """<b>A Source Editor Window</b>"""
            """<p>This window is used to display and edit a source file."""
            """  You can open as many of these as you like. The name of the file"""
            """ is displayed in the window's titlebar.</p>"""
            """<p>In order to set breakpoints just click in the space between"""
            """ the line numbers and the fold markers. Via the context menu"""
            """ of the margins they may be edited.</p>"""
            """<p>In order to set bookmarks just Shift click in the space between"""
            """ the line numbers and the fold markers.</p>"""
            """<p>These actions can be reversed via the context menu.</p>"""
        ))
        
        # Set the editors size, if it is too big for the view manager.
        if self.vm is not None:
            req = self.size()
            bnd = req.boundedTo(self.vm.size())
            
            if bnd.width() < req.width() or bnd.height() < req.height():
                self.resize(bnd)
            
        # set the autosave flag
        self.autosaveEnabled = Preferences.getEditor("AutosaveInterval") > 0
        self.autosaveManuallyDisabled = False
        
        self.__initContextMenu()
        self.__initMarginContextMenu()
        
        self.__checkLanguage()
        
        self.coverageMarkersShown = False   # flag remembering the current status of the
                                            # code coverage markers
        
        self.setAcceptDrops(True)
        
        # breakpoint handling
        self.breakpointModel = self.dbs.getBreakPointModel()
        self.__restoreBreakpoints()
        self.connect(self.breakpointModel, 
            SIGNAL("rowsAboutToBeRemoved(const QModelIndex &, int, int)"), 
            self.__deleteBreakPoints)
        self.connect(self.breakpointModel,
            SIGNAL("dataAboutToBeChanged(const QModelIndex &, const QModelIndex &)"),
            self.__breakPointDataAboutToBeChanged)
        self.connect(self.breakpointModel,
            SIGNAL("dataChanged(const QModelIndex &, const QModelIndex &)"),
            self.__changeBreakPoints)
        self.connect(self.breakpointModel,
            SIGNAL("rowsInserted(const QModelIndex &, int, int)"),
            self.__addBreakPoints)
        self.connect(self, SIGNAL("linesChanged()"), self.__linesChanged)
        
        # establish connection to some ViewManager action groups
        self.vm.editorActGrp.addTo(self)
        self.vm.editActGrp.addTo(self)
        self.vm.copyActGrp.addTo(self)
        self.vm.viewActGrp.addTo(self)
    
    def __bindName(self, txt):
        """
        Private method to generate a dummy filename for binding a lexer.
        
        @param txt first line of text to use in the generation process (QString or string)
        """
        line0 = QString(txt)
        if line0.startsWith("#!") and line0.contains("python"):
            self.isPythonFile = True
        if self.isPythonFile:
            bindName = 'dummy.py'
        else:
            bindName = self.fileName
        
        if line0.startsWith("<?xml"):
            # override extension for XML files
            bindName = "dummy.xml"
        
        # #! marker detection
        if line0.startsWith("#!"):
            if (line0.contains("/bash") or line0.contains("/sh")):
                bindName = "dummy.sh"
            elif line0.contains("ruby"):
                bindName = "dummy.rb"
            elif line0.contains("perl"):
                bindName = "dummy.pl"
            elif line0.contains("lua"):
                bindName = "dummy.lua"
            elif line0.contains("dmd"):
                bindName = "dummy.d"
        return bindName
        
    def __initContextMenu(self):
        """
        Private method used to setup the context menu
        """
        self.miniMenu = Preferences.getEditor("MiniContextMenu")
        
        self.menuActs = {}
        self.menu = QMenu()
        
        self.languagesMenu = self.__initContextMenuLanguages()
        if self.isResourcesFile:
            self.resourcesMenu = self.__initContextMenuResources()
        else:
            self.checksMenu = self.__initContextMenuChecks()
            self.showMenu = self.__initContextMenuShow()
            self.refactoringMenu = self.__initContextMenuRefactoring()
            self.graphicsMenu = self.__initContextMenuGraphics()
            self.autocompletionMenu = self.__initContextMenuAutocompletion()
        
        self.menuActs["Undo"] = \
            self.menu.addAction(UI.PixmapCache.getIcon("editUndo.png"),
            self.trUtf8('Undo'), self.undo)
        self.menuActs["Redo"] = \
            self.menu.addAction(UI.PixmapCache.getIcon("editRedo.png"),
            self.trUtf8('Redo'), self.redo)
        self.menuActs["Revert"] = \
            self.menu.addAction(self.trUtf8("Revert to last saved state"),
                self.revertToUnmodified)
        self.menu.addSeparator()
        if not self.miniMenu:
            self.menuActs["Cut"] = \
                self.menu.addAction(UI.PixmapCache.getIcon("editCut.png"),
                self.trUtf8('Cut'), self.cut)
            self.menuActs["Copy"] = \
                self.menu.addAction(UI.PixmapCache.getIcon("editCopy.png"),
                self.trUtf8('Copy'), self.copy)
            self.menu.addAction(UI.PixmapCache.getIcon("editPaste.png"),
                self.trUtf8('Paste'), self.paste)
            self.menu.addSeparator()
            self.menu.addAction(UI.PixmapCache.getIcon("editIndent.png"),
                self.trUtf8('Indent'), self.indentLineOrSelection)
            self.menu.addAction(UI.PixmapCache.getIcon("editUnindent.png"),
                self.trUtf8('Unindent'), self.unindentLineOrSelection)
            self.menuActs["Comment"] = \
                self.menu.addAction(UI.PixmapCache.getIcon("editComment.png"),
                    self.trUtf8('Comment'), self.commentLineOrSelection)
            self.menuActs["Uncomment"] = \
                self.menu.addAction(UI.PixmapCache.getIcon("editUncomment.png"),
                    self.trUtf8('Uncomment'), self.uncommentLineOrSelection)
            self.menuActs["StreamComment"] = \
                self.menu.addAction(self.trUtf8('Stream Comment'), 
                    self.streamCommentLineOrSelection)
            self.menuActs["BoxComment"] = \
                self.menu.addAction(self.trUtf8('Box Comment'), 
                    self.boxCommentLineOrSelection)
            self.menu.addSeparator()
            self.menu.addAction(self.trUtf8('Select to brace'), 
                self.selectToMatchingBrace)
            self.menu.addAction(self.trUtf8('Select all'), self.__selectAll)
            self.menu.addAction(self.trUtf8('Deselect all'), self.__deselectAll)
            self.menu.addSeparator()
        self.menu.addAction(self.trUtf8('Shorten empty lines'), 
            self.shortenEmptyLines)
        self.menu.addSeparator()
        self.menuActs["Languages"] = self.menu.addMenu(self.languagesMenu)
        self.menuActs["MonospacedFont"] = \
            self.menu.addAction(self.trUtf8("Use Monospaced Font"),
                self.handleMonospacedEnable)
        self.menuActs["MonospacedFont"].setCheckable(True)
        self.menuActs["MonospacedFont"].setChecked(self.useMonospaced)
        self.menuActs["AutosaveEnable"] = \
            self.menu.addAction(self.trUtf8("Autosave enabled"),
                self.__autosaveEnable)
        self.menuActs["AutosaveEnable"].setCheckable(True)
        self.menuActs["AutosaveEnable"].setChecked(self.autosaveEnabled)
        self.menuActs["AutoCompletionEnable"] = \
            self.menu.addAction(self.trUtf8("Autocompletion enabled"),
                self.__toggleAutoCompletionEnable)
        self.menuActs["AutoCompletionEnable"].setCheckable(True)
        self.menuActs["AutoCompletionEnable"].setChecked(\
            self.autoCompletionThreshold() != -1)
        if not self.isResourcesFile:
            self.menu.addMenu(self.autocompletionMenu)
        self.menu.addSeparator()
        if self.isResourcesFile:
            self.menu.addMenu(self.resourcesMenu)
        else:
            if not self.miniMenu:
                self.menuActs["Refactoring"] = self.menu.addMenu(self.refactoringMenu)
                self.menu.addSeparator()
            self.menuActs["Check"] = self.menu.addMenu(self.checksMenu)
            self.menu.addSeparator()
            self.menuActs["Show"] = self.menu.addMenu(self.showMenu)
            self.menu.addSeparator()
            self.menuActs["Diagrams"] = self.menu.addMenu(self.graphicsMenu)
        self.menu.addSeparator()
        self.menu.addAction(self.trUtf8('New view'), self.__newView)
        act = self.menu.addAction(self.trUtf8('New view (with new split)'), 
            self.__newViewNewSplit)
        if not self.vm.canSplit():
                act.setEnabled(False)
        self.menu.addAction(UI.PixmapCache.getIcon("close.png"),
            self.trUtf8('Close'), self.__contextClose)
        self.menu.addSeparator()
        self.menuActs["Save"] = \
            self.menu.addAction(UI.PixmapCache.getIcon("fileSave.png"),
            self.trUtf8('Save'), self.__contextSave)
        self.menu.addAction(UI.PixmapCache.getIcon("fileSaveAs.png"),
            self.trUtf8('Save As...'), self.__contextSaveAs)
        if not self.miniMenu:
            self.menu.addSeparator()
            self.menu.addAction(UI.PixmapCache.getIcon("print.png"),
                self.trUtf8('Print'), self.printFile)
            self.menuActs["PrintSel"] = \
                self.menu.addAction(UI.PixmapCache.getIcon("print.png"),
                self.trUtf8('Print Selection'), self.printSelection)
        
        self.connect(self.menu, SIGNAL('aboutToShow()'), self.__showContextMenu)

    def __initContextMenuAutocompletion(self):
        """
        Private method used to setup the Checks context sub menu.
        """
        menu = QMenu(self.trUtf8('Autocomplete'))
        
        menu.addAction(self.trUtf8('from Document'), 
            self.autoCompleteFromDocument)
        self.menuActs["acAPI"] = \
            menu.addAction(self.trUtf8('from APIs'),
                self.autoCompleteFromAPIs)
        self.menuActs["acAPIDocument"] = \
            menu.addAction(self.trUtf8('from Document and APIs'), 
                self.autoCompleteFromAll)
        
        self.connect(menu, SIGNAL('aboutToShow()'), self.__showAutocompletionMenu)
        
        return menu

    def __initContextMenuChecks(self):
        """
        Private method used to setup the Checks context sub menu.
        """
        menu = QMenu(self.trUtf8('Check'))
        
        menu.addAction(self.trUtf8('Syntax...'), self.__doSyntaxCheck)
        menu.addAction(self.trUtf8('Indentations...'), self.__doTabnanny)
        
        return menu

    def __initContextMenuShow(self):
        """
        Private method used to setup the Show context sub menu.
        """
        menu = QMenu(self.trUtf8('Show'))
        
        menu.addAction(self.trUtf8('Code metrics...'), self.__showCodeMetrics)
        self.coverageMenuAct = \
            menu.addAction(self.trUtf8('Code coverage...'), self.__showCodeCoverage)
        self.coverageShowAnnotationMenuAct = \
            menu.addAction(self.trUtf8('Show code coverage annotations'), 
                self.__codeCoverageShowAnnotations)
        self.coverageHideAnnotationMenuAct = \
            menu.addAction(self.trUtf8('Hide code coverage annotations'), 
                self.__codeCoverageHideAnnotations)
        self.profileMenuAct = \
            menu.addAction(self.trUtf8('Profile data...'), self.__showProfileData)
        self.cyclopsMenuAct = \
            menu.addAction(self.trUtf8('Cyclops report...'), self.__showCyclopsReport)
        self.removeCyclopsMenuAct = \
            menu.addAction(self.trUtf8('Remove cyclops report'), 
                self.__removeCyclopsReport)
        
        self.connect(menu, SIGNAL('aboutToShow()'), self.__showShowMenu)
        
        return menu
        
    def __initContextMenuRefactoring(self):
        """
        Private method used to setup the refactoring context sub menu.
        """
        menu = QMenu(self.trUtf8('Refactoring'))
        
        menu.addAction(self.trUtf8('Find References'), 
                        self.refactoring.queryReferences)
        menu.addAction(self.trUtf8('Find Definition'), 
                        self.refactoring.queryDefinition)
        
        return menu
        
    def __initContextMenuGraphics(self):
        """
        Private method used to setup the diagrams context sub menu.
        """
        menu = QMenu(self.trUtf8('Diagrams'))
        
        menu.addAction(self.trUtf8('Class Diagram...'), 
            self.__showClassDiagram)
        menu.addAction(self.trUtf8('Package Diagram...'), 
            self.__showPackageDiagram)
        menu.addAction(self.trUtf8('Imports Diagram...'), 
            self.__showImportsDiagram)
        self.applicationDiagramMenuAct = \
            menu.addAction(self.trUtf8('Application Diagram...'), 
                self.__showApplicationDiagram)
        
        self.connect(self.menu, SIGNAL('aboutToShow()'), self.__showContextMenuGraphics)
        
        return menu

    def __initContextMenuLanguages(self):
        """
        Private method used to setup the Languages context sub menu.
        """
        menu = QMenu(self.trUtf8("Languages"))
        
        self.languagesActGrp = QActionGroup(self)
        self.noLanguageAct = menu.addAction(self.trUtf8("No Language"))
        self.noLanguageAct.setCheckable(True)
        self.noLanguageAct.setData(QVariant("None"))
        self.languagesActGrp.addAction(self.noLanguageAct)
        menu.addSeparator()
        
        self.supportedLanguages = {}
        supportedLanguages = Lexers.getSupportedLanguages()
        languages = supportedLanguages.keys()
        languages.sort()
        for language in languages:
            self.supportedLanguages[language] = supportedLanguages[language][:]
            act = menu.addAction(self.supportedLanguages[language][0])
            act.setCheckable(True)
            act.setData(QVariant(language))
            self.supportedLanguages[language].append(act)
            self.languagesActGrp.addAction(act)
        
        self.connect(menu, SIGNAL('triggered(QAction *)'), self.__languageMenuTriggered)
        
        return menu
        
    def __initMarginContextMenu(self):
        """
        Private method used to setup the context menu for the margins
        """
        self.marginMenuActs = {}
        self.marginMenu = QMenu()
        
        self.marginMenu.addAction(self.trUtf8('Toggle bookmark'),
            self.menuToggleBookmark)
        self.marginMenuActs["NextBookmark"] = \
            self.marginMenu.addAction(self.trUtf8('Next bookmark'),
                self.nextBookmark)
        self.marginMenuActs["PreviousBookmark"] = \
            self.marginMenu.addAction(self.trUtf8('Previous bookmark'),
                self.previousBookmark)
        self.marginMenuActs["ClearBookmark"] = \
            self.marginMenu.addAction(self.trUtf8('Clear all bookmarks'),
                self.clearBookmarks)
        self.marginMenu.addSeparator()
        self.marginMenuActs["GotoSyntaxError"] = \
            self.marginMenu.addAction(self.trUtf8('Goto syntax error'),
                self.gotoSyntaxError)
        self.marginMenuActs["ShowSyntaxError"] = \
            self.marginMenu.addAction(self.trUtf8('Show syntax error message'),
                self.__showSyntaxError)
        self.marginMenuActs["ClearSyntaxError"] = \
            self.marginMenu.addAction(self.trUtf8('Clear syntax error'),
                self.clearSyntaxError)
        self.marginMenu.addSeparator()
        self.marginMenuActs["Breakpoint"] = \
            self.marginMenu.addAction(self.trUtf8('Toggle breakpoint'), 
                self.menuToggleBreakpoint)
        self.marginMenuActs["TempBreakpoint"] = \
            self.marginMenu.addAction(self.trUtf8('Toggle temporary breakpoint'), 
                self.__menuToggleTemporaryBreakpoint)
        self.marginMenuActs["EditBreakpoint"] = \
            self.marginMenu.addAction(self.trUtf8('Edit breakpoint...'), 
                self.menuEditBreakpoint)
        self.marginMenuActs["EnableBreakpoint"] = \
            self.marginMenu.addAction(self.trUtf8('Enable breakpoint'), 
                self.__menuToggleBreakpointEnabled)
        self.marginMenuActs["NextBreakpoint"] = \
            self.marginMenu.addAction(self.trUtf8('Next breakpoint'), 
                self.menuNextBreakpoint)
        self.marginMenuActs["PreviousBreakpoint"] = \
            self.marginMenu.addAction(self.trUtf8('Previous breakpoint'), 
                self.menuPreviousBreakpoint)
        self.marginMenuActs["ClearBreakpoint"] = \
            self.marginMenu.addAction(self.trUtf8('Clear all breakpoints'), 
                self.__menuClearBreakpoints)
        self.marginMenu.addSeparator()
        self.marginMenuActs["NextCoverageMarker"] = \
            self.marginMenu.addAction(self.trUtf8('Next uncovered line'),
                self.nextUncovered)
        self.marginMenuActs["PreviousCoverageMarker"] = \
            self.marginMenu.addAction(self.trUtf8('Previous uncovered line'),
                self.previousUncovered)
        self.marginMenu.addSeparator()
        self.marginMenuActs["NextTaskMarker"] = \
            self.marginMenu.addAction(self.trUtf8('Next task'),
                self.nextTask)
        self.marginMenuActs["PreviousTaskMarker"] = \
            self.marginMenu.addAction(self.trUtf8('Previous task'),
                self.previousTask)
        self.marginMenu.addSeparator()
        self.marginMenuActs["LMBbookmarks"] = \
            self.marginMenu.addAction(self.trUtf8('LMB toggles bookmarks'),
                self.__lmBbookmarks)
        self.marginMenuActs["LMBbookmarks"].setCheckable(True)
        self.marginMenuActs["LMBbookmarks"].setChecked(False)
        self.marginMenuActs["LMBbreakpoints"] = \
            self.marginMenu.addAction(self.trUtf8('LMB toggles breakpoints'),
                self.__lmBbreakpoints)
        self.marginMenuActs["LMBbreakpoints"].setCheckable(True)
        self.marginMenuActs["LMBbreakpoints"].setChecked(True)
        
        self.connect(self.marginMenu, SIGNAL('aboutToShow()'), 
            self.__showMarginContextMenu)
        
    def __languageMenuTriggered(self, act):
        """
        Private method to handle the selection of a lexer language.
        
        @param act reference to the action that was triggered (QAction)
        """
        if act == self.noLanguageAct:
            self.__resetLanguage()
        else:
            language = unicode(act.data().toString())
            if language:
                self.setLanguage(self.supportedLanguages[language][1])
        
    def __resetLanguage(self):
        """
        Private method used to reset the language selection.
        """
        self.apiLanguage = ""
        self.lexer = None
        self.setLexer()
        self.setMonospaced(self.useMonospaced)
        
    def setLanguage(self, filename, initTextDisplay = True):
        """
        Public method to set a lexer language.
        
        @param filename filename used to determine the associated lexer language (string)
        @param initTextDisplay flag indicating an initialization of the text display
            is required as well (boolean)
        """
        self.__bindLexer(filename)
        self.__bindCompleter(filename)
        self.recolor()
        self.__checkLanguage()
        
        # set the text display
        if initTextDisplay:
            self.__setTextDisplay()
        
        # set the autocompletion and calltips function
        self.__setAutoCompletion()
        self.__setCallTips()
    
    def __checkLanguage(self):
        """
        Private method to check the selected language of the language submenu.
        """
        if self.apiLanguage == "":
            self.noLanguageAct.setChecked(True)
        else:
            self.supportedLanguages[self.apiLanguage][2].setChecked(True)

    def __getExtension(self, fname):
        """
        Private method to get the file extension without a leading '.'.
        
        @param fname filename (string)
        @return extension of the filename (string)
        """
        dummy, ext = os.path.splitext(fname)

        # now split off .
        if ext.startswith('.'):
            return ext[1:]
        else:
            return ext

    def __bindLexer(self, filename):
        """
        Private slot to set the correct lexer depending on language.
        
        @param filename filename used to determine the associated lexer language (string)
        """
        filename = os.path.basename(unicode(filename))
        self.apiLanguage = Preferences.getEditorLexerAssoc(filename)
        
        self.lexer = Lexers.getLexer(self.apiLanguage, self)
        if self.lexer is None:
            self.apiLanguage = ""
            return
        
        self.setLexer(self.lexer)
        
        # get the font for style 0 and set it as the default font
        key = 'Scintilla/%s/style0/font' % unicode(self.lexer.language())
        fontVariant = Preferences.Prefs.settings.value(key)
        if fontVariant.isValid():
            fdesc = fontVariant.toStringList()
            font = QFont(fdesc[0], int(str(fdesc[1])))
            self.lexer.setDefaultFont(font)
        self.lexer.readSettings(Preferences.Prefs.settings, "Scintilla")
        
        # now set the lexer properties
        self.lexer.initProperties()
        
        # initialize the auto indent style of the lexer
        ais = self.lexer.autoIndentStyle()
        
        # initialize the lexer APIs settings
        api = self.vm.getAPIsManager().getAPIs(self.apiLanguage).getQsciAPIs()
        if api is not None:
            self.lexer.setAPIs(api)
        
    def getLexer(self):
        """
        Public method to retrieve a reference to the lexer object.
        
        @return the lexer object (Lexer)
        """
        return self.lexer
        
    def __bindCompleter(self, filename):
        """
        Private slot to set the correct typing completer depending on language.
        
        @param filename filename used to determine the associated typing
            completer language (string)
        """
        filename = os.path.basename(unicode(filename))
        apiLanguage = Preferences.getEditorLexerAssoc(filename)
        
        self.completer = TypingCompleters.getCompleter(apiLanguage, self)
        
    def getCompleter(self):
        """
        Public method to retrieve a reference to the completer object.
        
        @return the completer object (CompleterBase)
        """
        return self.completer
        
    def __modificationChanged(self, m):
        """
        Private slot to handle the modificationChanged signal. 
        
        It emits the signal modificationStatusChanged with parameters
        m and self.
        
        @param m modification status
        """
        if not m and self.fileName is not None:
            self.lastModified = QFileInfo(self.fileName).lastModified()
        if Preferences.getEditor("AutoCheckSyntax"):
            self.clearSyntaxError()
        self.emit(SIGNAL('modificationStatusChanged'), m, self)
        self.emit(SIGNAL('undoAvailable'), self.isUndoAvailable())
        self.emit(SIGNAL('redoAvailable'), self.isRedoAvailable())
        
    def __cursorPositionChanged(self, line, pos):
        """
        Private slot to handle the cursorPositionChanged signal. 
        
        It emits the signal cursorChanged with parameters fileName, 
        line and pos.
        
        @param line line number of the cursor
        @param pos position in line of the cursor
        """
        self.emit(SIGNAL('cursorChanged'), self.fileName, line+1, pos)
        
    def __modificationReadOnly(self):
        """
        Private slot to handle the modificationAttempted signal.
        """
        KQMessageBox.warning(None,
            self.trUtf8("Modification of Read Only file"),
            self.trUtf8("""You are attempting to change a read only file. """
                        """Please save to a different file first."""))
        
    def setNoName(self, noName):
        """
        Public method to set the display string for an unnamed editor.
        
        @param noName display string for this unnamed editor (QString)
        """
        self.noName = noName
        
    def getNoName(self):
        """
        Public method to get the display string for an unnamed editor.
        
        @return display string for this unnamed editor (QString)
        """
        return self.noName
        
    def getFileName(self):
        """
        Public method to return the name of the file being displayed.
        
        @return filename of the displayed file (string)
        """
        return self.fileName
        
    def isPyFile(self):
        """
        Public method to return a flag indicating a Python file.
        
        @return flag indicating a Python file (boolean)
        """
        return self.isPythonFile or \
            self.__getExtension(self.fileName) in self.pyExtensions

    def isRubyFile(self):
        """
        Public method to return a flag indicating a Ruby file.
        
        @return flag indicating a Ruby file (boolean)
        """
        return self.__getExtension(self.fileName) in self.rbExtensions
        
    def highlightVisible(self):
        """
        Public method to make sure that the highlight is visible.
        """
        if self.lastHighlight is not None:
            lineno = self.markerLine(self.lastHighlight)
            self.ensureVisible(lineno+1)
        
    def highlight(self, line = None, error = False, syntaxError = False):
        """
        Public method to highlight (or de-highlight) a particular line.
        
        @param line line number to highlight
        @param error flag indicating whether the error highlight should be used
        @param syntaxError flag indicating a syntax error
        """
        if line is None:
            self.lastHighlight = None
            if self.lastErrorMarker is not None:
                self.markerDeleteHandle(self.lastErrorMarker)
            self.lastErrorMarker = None
            if self.lastCurrMarker is not None:
                self.markerDeleteHandle(self.lastCurrMarker)
            self.lastCurrMarker = None
        else:
            if error:
                if self.lastErrorMarker is not None:
                    self.markerDeleteHandle(self.lastErrorMarker)
                self.lastErrorMarker = self.markerAdd(line-1, self.errorline)
                self.lastHighlight = self.lastErrorMarker
            else:
                if self.lastCurrMarker is not None:
                    self.markerDeleteHandle(self.lastCurrMarker)
                self.lastCurrMarker = self.markerAdd(line-1, self.currentline)
                self.lastHighlight = self.lastCurrMarker
            self.setCursorPosition(line-1, 0)
        
    def getHighlightPosition(self):
        """
        Public method to return the position of the highlight bar.
        
        @return line number of the highlight bar
        """
        if self.lastHighlight is not None:
            return self.markerLine(self.lastHighlight)
        else:
            return 1
    
    ############################################################################
    ## Breakpoint handling methods below
    ############################################################################

    def __linesChanged(self):
        """
        Private method to track text changes.
        
        This method checks, if lines have been inserted or removed in order to
        update the breakpoints.
        """
        if self.breaks:
            bps = []    # list of breakpoints
            for handle, (ln, cond, temp, enabled, ignorecount) in self.breaks.items():
                line = self.markerLine(handle) + 1
                bps.append((ln, line, (cond, temp, enabled, ignorecount)))
                self.markerDeleteHandle(handle)
            self.breaks = {}
            for bp in bps:
                index = self.breakpointModel.getBreakPointIndex(self.fileName, bp[0])
                self.breakpointModel.setBreakPointByIndex(index, 
                    self.fileName, bp[1], bp[2])
        
    def __restoreBreakpoints(self):
        """
        Private method to restore the breakpoints.
        """
        for handle in self.breaks.keys():
            self.markerDeleteHandle(handle)
        self.__addBreakPoints(QModelIndex(), 0, self.breakpointModel.rowCount() - 1)
        
    def __deleteBreakPoints(self, parentIndex, start, end):
        """
        Private slot to delete breakpoints.
        
        @param parentIndex index of parent item (QModelIndex)
        @param start start row (integer)
        @param end end row (integer)
        """
        for row in range(start, end + 1):
            index = self.breakpointModel.index(row, 0, parentIndex)
            fn, lineno = self.breakpointModel.getBreakPointByIndex(index)[0:2]
            if fn == self.fileName:
                self.clearBreakpoint(lineno)
        
    def __changeBreakPoints(self, startIndex, endIndex):
        """
        Private slot to set changed breakpoints.
        
        @param indexes indexes of changed breakpoints.
        """
        self.__addBreakPoints(QModelIndex(), startIndex.row(), endIndex.row())
        
    def __breakPointDataAboutToBeChanged(self, startIndex, endIndex):
        """
        Private slot to handle the dataAboutToBeChanged signal of the breakpoint model.
        
        @param startIndex start index of the rows to be changed (QModelIndex)
        @param endIndex end index of the rows to be changed (QModelIndex)
        """
        self.__deleteBreakPoints(QModelIndex(), startIndex.row(), endIndex.row())
        
    def __addBreakPoints(self, parentIndex, start, end):
        """
        Private slot to add breakpoints.
        
        @param parentIndex index of parent item (QModelIndex)
        @param start start row (integer)
        @param end end row (integer)
        """
        for row in range(start, end + 1):
            index = self.breakpointModel.index(row, 0, parentIndex)
            fn, line, cond, temp, enabled, ignorecount = \
                self.breakpointModel.getBreakPointByIndex(index)[:6]
            if fn == self.fileName:
                self.newBreakpointWithProperties(line, (cond, temp, enabled, ignorecount))
        
    def clearBreakpoint(self, line):
        """
        Public method to clear a breakpoint.
        
        Note: This doesn't clear the breakpoint in the debugger,
        it just deletes it from the editor internal list of breakpoints.
        
        @param line linenumber of the breakpoint
        """
        for handle, (ln, _, _, _, _) in self.breaks.items():
            if self.markerLine(handle) == line-1:
                break
        else:
            # not found, simply ignore it
            return
        
        del self.breaks[handle]
        self.markerDeleteHandle(handle)
        
    def newBreakpointWithProperties(self, line, properties):
        """
        Private method to set a new breakpoint and its properties.
        
        @param line line number of the breakpoint
        @param properties properties for the breakpoint (tuple)
                (condition, temporary flag, enabled flag, ignore count)
        """
        if not properties[2]:
            marker = self.dbreakpoint
        elif properties[0]:
            marker = properties[1] and self.tcbreakpoint or self.cbreakpoint
        else:
            marker = properties[1] and self.tbreakpoint or self.breakpoint
            
        handle = self.markerAdd(line-1, marker)
        self.breaks[handle] = (line,) + properties
        self.emit(SIGNAL('breakpointToggled'), self)
        
    def __toggleBreakpoint(self, line, temporary = False):
        """
        Private method to toggle a breakpoint.
        
        @param line line number of the breakpoint
        @param temporary flag indicating a temporary breakpoint
        """
        for handle, (ln, _, _, _, _) in self.breaks.items():
            if self.markerLine(handle) == line - 1:
                # delete breakpoint
                index = self.breakpointModel.getBreakPointIndex(self.fileName, line)
                self.breakpointModel.deleteBreakPointByIndex(index)
                self.emit(SIGNAL('breakpointToggled'), self)
                break
        else:
            # set a new breakpoint
            if self.fileName and (self.isPyFile() or self.isRubyFile()):
                self.breakpointModel.addBreakPoint(self.fileName, line,
                    ('', temporary, True, 0))
                self.emit(SIGNAL('breakpointToggled'), self)
            return
        
    def __toggleBreakpointEnabled(self, line):
        """
        Private method to toggle a breakpoints enabled status.
        
        @param line line number of the breakpoint
        """
        for handle, (ln, cond, temp, enabled, ignorecount) in self.breaks.items():
            if self.markerLine(handle) == line - 1:
                break
        else:
            # no breakpoint found on that line
            return
        
        index = self.breakpointModel.getBreakPointIndex(self.fileName, line)
        self.breakpointModel.setBreakPointEnabledByIndex(index, not enabled)
        
    def curLineHasBreakpoint(self):
        """
        Public method to check for the presence of a breakpoint at the current line.
        
        @return flag indicating the presence of a breakpoint (boolean)
        """
        line, _ = self.getCursorPosition()
        return self.markersAtLine(line) & self.breakpointMask != 0
        
    def hasBreakpoints(self):
        """
        Public method to check for the presence of breakpoints.
        
        @return flag indicating the presence of breakpoints (boolean)
        """
        return len(self.breaks) > 0
        
    def __menuToggleTemporaryBreakpoint(self):
        """
        Private slot to handle the 'Toggle temporary breakpoint' context menu action.
        """
        if self.line < 0:
            self.line, index = self.getCursorPosition()
        self.line += 1
        self.__toggleBreakpoint(self.line, 1)
        self.line = -1
        
    def menuToggleBreakpoint(self):
        """
        Public slot to handle the 'Toggle breakpoint' context menu action.
        """
        if self.line < 0:
            self.line, index = self.getCursorPosition()
        self.line += 1
        self.__toggleBreakpoint(self.line)
        self.line = -1
        
    def __menuToggleBreakpointEnabled(self):
        """
        Private slot to handle the 'Enable/Disable breakpoint' context menu action.
        """
        if self.line < 0:
            self.line, index = self.getCursorPosition()
        self.line += 1
        self.__toggleBreakpointEnabled(self.line)
        self.line = -1
        
    def menuEditBreakpoint(self, line = None):
        """
        Public slot to handle the 'Edit breakpoint' context menu action.
        
        @param line linenumber of the breakpoint to edit
        """
        if line is not None:
            self.line = line - 1
        if self.line < 0:
            self.line, index = self.getCursorPosition()
        found = False
        for handle, (ln, cond, temp, enabled, ignorecount) in self.breaks.items():
            if self.markerLine(handle) == self.line:
                found = True
                break
        
        if found:
            index = self.breakpointModel.getBreakPointIndex(self.fileName, ln)
            if not index.isValid():
                return
            
            dlg = EditBreakpointDialog((self.fileName, ln), 
                (cond, temp, enabled, ignorecount),
                self.condHistory, self, modal = True)
            if dlg.exec_() == QDialog.Accepted:
                cond, temp, enabled, ignorecount = dlg.getData()
                self.breakpointModel.setBreakPointByIndex(index, 
                    self.fileName, ln, (cond, temp, enabled, ignorecount))
        
        self.line = -1
        
    def menuNextBreakpoint(self):
        """
        Public slot to handle the 'Next breakpoint' context menu action.
        """
        line, index = self.getCursorPosition()
        if line == self.lines()-1:
            line = 0
        else:
            line += 1
        bpline = self.markerFindNext(line, self.breakpointMask)
        if bpline < 0:
            # wrap around
            bpline = self.markerFindNext(0, self.breakpointMask)
        if bpline >= 0:
            self.setCursorPosition(bpline, 0)
            self.ensureLineVisible(bpline)
        
    def menuPreviousBreakpoint(self):
        """
        Public slot to handle the 'Previous breakpoint' context menu action.
        """
        line, index = self.getCursorPosition()
        if line == 0:
            line = self.lines()-1
        else:
            line -= 1
        bpline = self.markerFindPrevious(line, self.breakpointMask)
        if bpline < 0:
            # wrap around
            bpline = self.markerFindPrevious(self.lines()-1, self.breakpointMask)
        if bpline >= 0:
            self.setCursorPosition(bpline, 0)
            self.ensureLineVisible(bpline)
        
    def __menuClearBreakpoints(self):
        """
        Private slot to handle the 'Clear all breakpoints' context menu action.
        """
        idxList = []
        for handle, (ln, _, _, _, _) in self.breaks.items():
            index = self.breakpointModel.getBreakPointIndex(self.fileName, ln)
            if index.isValid():
                idxList.append(index)
        if idxList:
            self.breakpointModel.deleteBreakPoints(idxList)
    
    ############################################################################
    ## Bookmark handling methods below
    ############################################################################
    
    def toggleBookmark(self, line):
        """
        Public method to toggle a bookmark.
        
        @param line line number of the bookmark
        """
        for handle in self.bookmarks:
            if self.markerLine(handle) == line - 1:
                break
        else:
            # set a new bookmark
            handle = self.markerAdd(line - 1, self.bookmark)
            self.bookmarks.append(handle)
            self.emit(SIGNAL('bookmarkToggled'), self)
            return
        
        self.bookmarks.remove(handle)
        self.markerDeleteHandle(handle)
        self.emit(SIGNAL('bookmarkToggled'), self)
        
    def getBookmarks(self):
        """
        Public method to retrieve the bookmarks.
        
        @return sorted list of all lines containing a bookmark
            (list of integer)
        """
        bmlist = []
        for handle in self.bookmarks:
            bmlist.append(self.markerLine(handle) + 1)
        
        bmlist.sort()
        return bmlist
        
    def hasBookmarks(self):
        """
        Public method to check for the presence of bookmarks.
        
        @return flag indicating the presence of bookmarks (boolean)
        """
        return len(self.bookmarks) > 0
    
    def menuToggleBookmark(self):
        """
        Public slot to handle the 'Toggle bookmark' context menu action.
        """
        if self.line < 0:
            self.line, index = self.getCursorPosition()
        self.line += 1
        self.toggleBookmark(self.line)
        self.line = -1
        
    def nextBookmark(self):
        """
        Public slot to handle the 'Next bookmark' context menu action.
        """
        line, index = self.getCursorPosition()
        if line == self.lines()-1:
            line = 0
        else:
            line += 1
        bmline = self.markerFindNext(line, 1 << self.bookmark)
        if bmline < 0:
            # wrap around
            bmline = self.markerFindNext(0, 1 << self.bookmark)
        if bmline >= 0:
            self.setCursorPosition(bmline, 0)
            self.ensureLineVisible(bmline)
        
    def previousBookmark(self):
        """
        Public slot to handle the 'Previous bookmark' context menu action.
        """
        line, index = self.getCursorPosition()
        if line == 0:
            line = self.lines()-1
        else:
            line -= 1
        bmline = self.markerFindPrevious(line, 1 << self.bookmark)
        if bmline < 0:
            # wrap around
            bmline = self.markerFindPrevious(self.lines() - 1, 1 << self.bookmark)
        if bmline >= 0:
            self.setCursorPosition(bmline, 0)
            self.ensureLineVisible(bmline)
        
    def clearBookmarks(self):
        """
        Public slot to handle the 'Clear all bookmarks' context menu action.
        """
        for handle in self.bookmarks:
            self.markerDeleteHandle(handle)
        self.bookmarks = []
        self.emit(SIGNAL('bookmarkToggled'), self)
    
    ############################################################################
    ## Printing methods below
    ############################################################################

    def printFile(self):
        """
        Public slot to print the text.
        """
        printer = Printer()
        sb = e4App().getObject("UserInterface").statusBar()
        printDialog = KQPrintDialog(printer, self)
        if printDialog.exec_() == QDialog.Accepted:
            sb.showMessage(self.trUtf8('Printing...'))
            QApplication.processEvents()
            fn = self.getFileName()
            if fn is not None:
                printer.setDocName(os.path.basename(fn))
            else:
                printer.setDocName(self.noName)
            res = printer.printRange(self)
            if res:
                sb.showMessage(self.trUtf8('Printing completed'), 2000)
            else:
                sb.showMessage(self.trUtf8('Error while printing'), 2000)
            QApplication.processEvents()
        else:
            sb.showMessage(self.trUtf8('Printing aborted'), 2000)
            QApplication.processEvents()
    
    def printSelection(self):
        """
        Public slot to print the selected text.
        """
        if not self.hasSelectedText():
            KQMessageBox.warning(self, self.trUtf8('Print Selection'),
                self.trUtf8('There is no selected text, printing aborted.'))
            return
        
        # get the selection
        fromLine, fromIndex, toLine, toIndex = self.getSelection()
        if toIndex == 0:
            toLine -= 1
        
        printer = Printer()
        sb = e4App().getObject("UserInterface").statusBar()
        printDialog = KQPrintDialog(printer, self)
        if printDialog.exec_() == QDialog.Accepted:
            sb.showMessage(self.trUtf8('Printing...'))
            QApplication.processEvents()
            fn = self.getFileName()
            if fn is not None:
                printer.setDocName(os.path.basename(fn))
            else:
                printer.setDocName(self.noName)
            # Qscintilla seems to print one line more than told
            res = printer.printRange(self, fromLine, toLine-1)
            if res:
                sb.showMessage(self.trUtf8('Printing completed'), 2000)
            else:
                sb.showMessage(self.trUtf8('Error while printing'), 2000)
            QApplication.processEvents()
        else:
            sb.showMessage(self.trUtf8('Printing aborted'), 2000)
            QApplication.processEvents()
    
    ############################################################################
    ## Task handling methods below
    ############################################################################

    def hasTaskMarkers(self):
        """
        Public method to determine, if this editor contains any task markers.
        
        @return flag indicating the presence of task markers (boolean)
        """
        return self.__hasTaskMarkers
        
    def nextTask(self):
        """
        Public slot to handle the 'Next task' context menu action.
        """
        line, index = self.getCursorPosition()
        if line == self.lines()-1:
            line = 0
        else:
            line += 1
        taskline = self.markerFindNext(line, 1 << self.taskmarker)
        if taskline < 0:
            # wrap around
            taskline = self.markerFindNext(0, 1 << self.taskmarker)
        if taskline >= 0:
            self.setCursorPosition(taskline, 0)
            self.ensureLineVisible(taskline)
        
    def previousTask(self):
        """
        Public slot to handle the 'Previous task' context menu action.
        """
        line, index = self.getCursorPosition()
        if line == 0:
            line = self.lines()-1
        else:
            line -= 1
        taskline = self.markerFindPrevious(line, 1 << self.taskmarker)
        if taskline < 0:
            # wrap around
            taskline = self.markerFindPrevious(self.lines() - 1, 1 << self.taskmarker)
        if taskline >= 0:
            self.setCursorPosition(taskline, 0)
            self.ensureLineVisible(taskline)
        
    def extractTasks(self):
        """
        Public slot to extract all tasks.
        """
        todoMarkers = unicode(Preferences.getTasks("TasksMarkers")).split()
        bugfixMarkers = unicode(Preferences.getTasks("TasksMarkersBugfix")).split()
        txtList = self.text().split(self.getLineSeparator())
        
        # clear all task markers and tasks
        self.markerDeleteAll(self.taskmarker)
        self.taskViewer.clearFileTasks(self.fileName)
        self.__hasTaskMarkers = False
        
        # now search tasks and record them
        lineIndex = -1
        for line in txtList:
            lineIndex += 1
            shouldContinue = False
            # normal tasks first
            for tasksMarker in todoMarkers:
                index = line.indexOf(tasksMarker)
                if index > -1:
                    task = line.mid(index)
                    self.markerAdd(lineIndex, self.taskmarker)
                    self.taskViewer.addFileTask(task, self.fileName, lineIndex+1, False)
                    self.__hasTaskMarkers = True
                    shouldContinue = True
                    break
            if shouldContinue:
                continue
            
            # bugfix tasks second
            for tasksMarker in bugfixMarkers:
                index = line.indexOf(tasksMarker)
                if index > -1:
                    task = line.mid(index)
                    self.markerAdd(lineIndex, self.taskmarker)
                    self.taskViewer.addFileTask(task, self.fileName, lineIndex+1, True)
                    self.__hasTaskMarkers = True
                    break
        self.emit(SIGNAL('taskMarkersUpdated'), self)
    
    ############################################################################
    ## File handling methods below
    ############################################################################

    def checkDirty(self):
        """
        Public method to check dirty status and open a message window.
        
        @return flag indicating successful reset of the dirty flag (boolean)
        """
        if self.isModified():
            fn = self.fileName
            if fn is None:
                fn = self.noName
            res = KQMessageBox.warning(self.vm, 
                self.trUtf8("File Modified"),
                self.trUtf8("<p>The file <b>%1</b> has unsaved changes.</p>")
                    .arg(fn),
                QMessageBox.StandardButtons(\
                    QMessageBox.Abort | \
                    QMessageBox.Discard | \
                    QMessageBox.Save),
                QMessageBox.Save)
            if res == QMessageBox.Save:
                ok, newName = self.saveFile()
                if ok:
                    self.vm.setEditorName(self, newName)
                return ok
            elif res == QMessageBox.Abort or res == QMessageBox.Cancel:
                return False
        
        return True
        
    def revertToUnmodified(self):
        """
        Public method to revert back to the last saved state.
        """
        undo_ = True
        while self.isModified():
            if undo_:
            # try undo first
                if self.isUndoAvailable():
                    self.undo()
                else:
                    undo_ = False
            else:
            # try redo next
                if self.isRedoAvailable():
                    self.redo()
                else:
                    break
                    # Couldn't find the unmodified state
    
    def readLine0(self, fn, createIt = False):
        """
        Public slot to read the first line from a file.
        
        @param fn filename to read from (string or QString)
        @param createIt flag indicating the creation of a new file, if the given
            one doesn't exist (boolean)
        @return first line of the file (string)
        """
        fn = unicode(fn)
        try:
            if createIt and not os.path.exists(fn):
                f = open(fn, "wb")
                f.close()
            f = open(fn, 'rb')
        except IOError:
            KQMessageBox.critical(self.vm, self.trUtf8('Open File'),
                self.trUtf8('<p>The file <b>%1</b> could not be opened.</p>')
                    .arg(fn))
            raise
        
        txt = f.readline()
        f.close()
        return txt
        
    def readFile(self, fn, createIt = False):
        """
        Public slot to read the text from a file.
        
        @param fn filename to read from (string or QString)
        @param createIt flag indicating the creation of a new file, if the given
            one doesn't exist (boolean)
        """
        fn = unicode(fn)
        try:
            if createIt and not os.path.exists(fn):
                f = open(fn, "wb")
                f.close()
            f = open(fn, 'rb')
        except IOError:
            KQMessageBox.critical(self.vm, self.trUtf8('Open File'),
                self.trUtf8('<p>The file <b>%1</b> could not be opened.</p>')
                    .arg(fn))
            raise
        
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        
        if fn.endswith('.ts') or fn.endswith('.ui'):
            # special treatment for Qt-Linguist and Qt-Designer files
            txt = f.read()
            self.encoding = 'latin-1'
        else:
            txt, self.encoding = Utilities.decode(f.read())
        f.close()
        
        modified = False
        if (not Preferences.getEditor("TabForIndentation")) and \
                Preferences.getEditor("ConvertTabsOnLoad") and \
                self.lexer and \
                (not self.lexer.alwaysKeepTabs()):
            txtExpanded = txt.expandtabs(Preferences.getEditor("TabWidth"))
            if txtExpanded != txt:
                modified = True
            txt = txtExpanded
            del txtExpanded
        
        self.setText(txt)
        
        self.extractTasks()
        
        QApplication.restoreOverrideCursor()
        
        self.setModified(modified)
        self.lastModified = QFileInfo(self.fileName).lastModified()
        
    def getLineSeparator(self):
        """
        Public slot to get the line separator for the current eol mode.
        
        @return eol string (string)
        """
        m = self.eolMode()
        if m == QsciScintilla.EolWindows:
            eol = '\r\n'
        elif m == QsciScintilla.EolUnix:
            eol = '\n'
        elif m == QsciScintilla.EolMac:
            eol = '\r'
        else:
            eol = ''
        return eol
        
    def writeFile(self, fn):
        """
        Public slot to write the text to a file.
        
        @param fn filename to write to (string or QString)
        @return flag indicating success
        """
        fn = unicode(fn)
        try:
            txt = Utilities.encode(unicode(self.text()), self.encoding)
        except Utilities.CodingError, e:
            KQMessageBox.critical(self, self.trUtf8('Save File'),
                self.trUtf8('<p>The file <b>%1</b> could not be saved.<br>Reason: %2</p>')
                    .arg(unicode(fn)).arg(repr(e)))
            return False
        # work around glitch in scintilla: always make sure, 
        # that the last line is terminated properly
        eol = self.getLineSeparator()
        if eol:
            if len(txt) >= len(eol):
                if txt[-len(eol):] != eol:
                    txt += eol
            else:
                txt += eol
        
        # create a backup file, if the option is set
        createBackup = Preferences.getEditor("CreateBackupFile")
        if createBackup:
            if os.path.islink(fn):
                fn = os.path.realpath(fn)
            bfn = '%s~' % fn
            try:
                permissions = os.stat(fn).st_mode
                perms_valid = True
            except:
                # if there was an error, ignore it
                perms_valid = False
            try:
                os.remove(bfn)
            except:
                # if there was an error, ignore it
                pass
            try:
                os.rename(fn, bfn)
            except:
                # if there was an error, ignore it
                pass
                
        # now write text to the file fn
        try:
            f = open(fn, 'wb')
            f.write(txt)
            f.close()
            if createBackup and perms_valid:
                os.chmod(fn, permissions)
            return True
        except IOError, why:
            KQMessageBox.critical(self, self.trUtf8('Save File'),
                self.trUtf8('<p>The file <b>%1</b> could not be saved.<br>Reason: %2</p>')
                    .arg(unicode(fn)).arg(str(why)))
            return False
        
    def saveFile(self, saveas = False, path = None):
        """
        Public slot to save the text to a file.
        
        @param saveas flag indicating a 'save as' action
        @param path directory to save the file in (string or QString)
        @return tuple of two values (boolean, string) giving a success indicator and
            the name of the saved file
        """
        if not saveas and not self.isModified():
            return (False, None)      # do nothing if text wasn't changed
            
        newName = None
        if saveas or self.fileName is None:
            saveas = True
            if (path is None or QString(path).isEmpty()) and self.fileName is not None:
                path = os.path.dirname(unicode(self.fileName))
            if path is None:
                path = QString()
            selectedFilter = QString(Preferences.getEditor("DefaultSaveFilter"))
            fn = KQFileDialog.getSaveFileName(\
                self,
                self.trUtf8("Save File"),
                path,
                Lexers.getSaveFileFiltersList(True, True), 
                selectedFilter,
                QFileDialog.Options(QFileDialog.DontConfirmOverwrite))
            
            if not fn.isEmpty():
                ext = QFileInfo(fn).suffix()
                if ext.isEmpty():
                    ex = selectedFilter.section('(*', 1, 1).section(')', 0, 0)
                    if not ex.isEmpty():
                        fn.append(ex)
                if QFileInfo(fn).exists():
                    res = KQMessageBox.warning(self,
                        self.trUtf8("Save File"),
                        self.trUtf8("<p>The file <b>%1</b> already exists.</p>")
                            .arg(fn),
                        QMessageBox.StandardButtons(\
                            QMessageBox.Abort | \
                            QMessageBox.Save),
                        QMessageBox.Abort)
                    if res == QMessageBox.Abort or res == QMessageBox.Cancel:
                        return (False, None)
                fn = unicode(Utilities.toNativeSeparators(fn))
                newName = fn
            else:
                return (False, None)
        else:
            fn = self.fileName
        
        if self.writeFile(fn):
            self.fileName = fn
            self.setModified(False)
            self.setReadOnly(False)
            self.setWindowTitle(self.fileName)
            if self.lexer is None:
                self.setLanguage(self.fileName, False)
            
            if saveas:
                self.isResourcesFile = self.fileName.endswith(".qrc")
                self.__initContextMenu()
                self.emit(SIGNAL('editorRenamed'), self.fileName)
            self.lastModified = QFileInfo(self.fileName).lastModified()
            if newName is not None:
                self.vm.addToRecentList(newName)
            self.emit(SIGNAL('editorSaved'), self.fileName)
            self.__autoSyntaxCheck()
            self.extractTasks()
            return (True, self.fileName)
        else:
            return (False, None)
        
    def saveFileAs(self, path = None):
        """
        Public slot to save a file with a new name.
        
        @param path directory to save the file in (string or QString)
        @return tuple of two values (boolean, string) giving a success indicator and
            the name of the saved file
        """
        return self.saveFile(True, path)
        
    def handleRenamed(self, fn):
        """
        Public slot to handle the editorRenamed signal.
        
        @param fn filename to be set for the editor (QString or string).
        """
        self.fileName = unicode(fn)
        self.setWindowTitle(self.fileName)
        
        if self.lexer is None:
            self.setLanguage(self.fileName, False)
        
        self.lastModified = QFileInfo(self.fileName).lastModified()
        self.vm.setEditorName(self, self.fileName)
        self.__updateReadOnly(True)
        
    def fileRenamed(self, fn):
        """
        Public slot to handle the editorRenamed signal.
        
        @param fn filename to be set for the editor (QString or string).
        """
        self.handleRenamed(fn)
        if not self.inFileRenamed:
            self.inFileRenamed = True
            self.emit(SIGNAL('editorRenamed'), self.fileName)
            self.inFileRenamed = False
    
    ############################################################################
    ## Utility methods below
    ############################################################################

    def ensureVisible(self, line):
        """
        Public slot to ensure, that the specified line is visible.
        
        @param line line number to make visible
        """
        self.ensureLineVisible(line-1)
        
    def ensureVisibleTop(self, line):
        """
        Public slot to ensure, that the specified line is visible at the top
        of the editor.
        
        @param line line number to make visible
        """
        topLine = self.firstVisibleLine()
        linesToScroll = line - topLine
        self.scrollVertical(linesToScroll)
        
    def __marginClicked(self, margin, line, modifiers):
        """
        Private slot to handle the marginClicked signal.
        
        @param margin id of the clicked margin
        @param line line number pf the click
        @param modifiers keyboard modifiers (Qt.KeyboardModifiers)
        """
        if margin == 1:
            if modifiers & Qt.KeyboardModifiers(Qt.ShiftModifier):
                if self.marginMenuActs["LMBbreakpoints"].isChecked():
                    self.toggleBookmark(line + 1)
                else:
                    self.__toggleBreakpoint(line + 1)
            else:
                if self.marginMenuActs["LMBbreakpoints"].isChecked():
                    self.__toggleBreakpoint(line + 1)
                else:
                    self.toggleBookmark(line + 1)
        
    def handleMonospacedEnable(self):
        """
        Private slot to handle the Use Monospaced Font context menu entry.
        """
        if self.menuActs["MonospacedFont"].isChecked():
            self.setMonospaced(True)
        else:
            if self.lexer:
                self.lexer.readSettings(Preferences.Prefs.settings, "Scintilla")
                self.lexer.initProperties()
            self.setMonospaced(False)
            self.__setMargin0and2()
        
    def __getWord(self, line, index):
        """
        Private method to get the word at a position.
        
        @param line number of line to look at (int)
        @param index position to look at (int)
        @return the word at that position
        """
        text = self.text(line)
        if self.caseSensitive():
            cs = Qt.CaseSensitive
        else:
            cs = Qt.CaseInsensitive
        wc = self.wordCharacters()
        if wc is None:
            regExp = QRegExp('[^\w_]', cs)
        else:
            regExp = QRegExp('[^%s]' % re.escape(wc), cs)
        start = text.lastIndexOf(regExp, index) + 1
        end = text.indexOf(regExp, index)
        if end > start:
            word = text.mid(start, end - start)
        else:
            word = QString('')
        return word
        
    def getSearchText(self, selectionOnly = False):
        """
        Public method to determine the selection or the current word for the next 
        search operation.
        
        @param selectionOnly flag indicating that only selected text should be
            returned (boolean)
        @return selection or current word (QString)
        """
        if self.hasSelectedText():
            text = self.selectedText()
            if text.contains('\r') or text.contains('\n'):
                # the selection contains at least a newline, it is
                # unlikely to be the expression to search for
                return QString('')
            
            return text
        
        if not selectionOnly:
            # no selected text, determine the word at the current position
            line, index = self.getCursorPosition()
            return self.__getWord(line, index)
        
        return QString('')
    
    ############################################################################
    ## Comment handling methods below
    ############################################################################

    def commentLine(self):
        """
        Public slot to comment the current line.
        """
        if self.lexer is None or not self.lexer.canBlockComment():
            return
        
        line, index = self.getCursorPosition()
        self.beginUndoAction()
        self.insertAt(self.lexer.commentStr(), line, 0)
        self.endUndoAction()
        
    def uncommentLine(self):
        """
        Public slot to uncomment the current line.
        
        This happens only, if it was commented by using
        the commentLine() or commentSelection() slots
        """
        if self.lexer is None or not self.lexer.canBlockComment():
            return
        
        commentStr = self.lexer.commentStr()
        line, index = self.getCursorPosition()
        
        # check if line starts with our comment string (i.e. was commented
        # by our comment...() slots
        if not self.text(line).startsWith(commentStr):
            return
        
        # now remove the comment string
        self.beginUndoAction()
        self.setSelection(line, 0, line, commentStr.length())
        self.removeSelectedText()
        self.endUndoAction()
        
    def commentSelection(self):
        """
        Public slot to comment the current selection.
        """
        if self.lexer is None or not self.lexer.canBlockComment():
            return
        
        if not self.hasSelectedText():
            return
        
        commentStr = self.lexer.commentStr()
        
        # get the selection boundaries
        lineFrom, indexFrom, lineTo, indexTo = self.getSelection()
        if indexTo == 0:
            endLine = lineTo - 1
        else:
            endLine = lineTo
        
        self.beginUndoAction()
        # iterate over the lines
        for line in range(lineFrom, endLine+1):
            self.insertAt(commentStr, line, 0)
        
        # change the selection accordingly
        self.setSelection(lineFrom, 0, endLine+1, 0)
        self.endUndoAction()
        
    def uncommentSelection(self):
        """
        Public slot to uncomment the current selection. 
        
        This happens only, if it was commented by using
        the commentLine() or commentSelection() slots
        """
        if self.lexer is None or not self.lexer.canBlockComment():
            return
        
        if not self.hasSelectedText():
            return
        
        commentStr = self.lexer.commentStr()
        
        # get the selection boundaries
        lineFrom, indexFrom, lineTo, indexTo = self.getSelection()
        if indexTo == 0:
            endLine = lineTo - 1
        else:
            endLine = lineTo
        
        self.beginUndoAction()
        # iterate over the lines
        for line in range(lineFrom, endLine+1):
            # check if line starts with our comment string (i.e. was commented
            # by our comment...() slots
            if not self.text(line).startsWith(commentStr):
                continue
            
            self.setSelection(line, 0, line, commentStr.length())
            self.removeSelectedText()
            
            # adjust selection start
            if line == lineFrom:
                indexFrom -= commentStr.length()
                if indexFrom < 0:
                    indexFrom = 0
            
            # adjust selection end
            if line == lineTo:
                indexTo -= commentStr.length()
                if indexTo < 0:
                    indexTo = 0
            
        # change the selection accordingly
        self.setSelection(lineFrom, indexFrom, lineTo, indexTo)
        self.endUndoAction()
        
    def commentLineOrSelection(self):
        """
        Public slot to comment the current line or current selection.
        """
        if self.hasSelectedText():
            self.commentSelection()
        else:
            self.commentLine()

    def uncommentLineOrSelection(self):
        """
        Public slot to uncomment the current line or current selection.
        
        This happens only, if it was commented by using
        the commentLine() or commentSelection() slots
        """
        if self.hasSelectedText():
            self.uncommentSelection()
        else:
            self.uncommentLine()

    def streamCommentLine(self):
        """
        Public slot to stream comment the current line.
        """
        if self.lexer is None or not self.lexer.canStreamComment():
            return
        
        commentStr = self.lexer.streamCommentStr()
        line, index = self.getCursorPosition()
        
        self.beginUndoAction()
        self.insertAt(commentStr['end'], line, self.lineLength(line))
        self.insertAt(commentStr['start'], line, 0)
        self.endUndoAction()
        
    def streamCommentSelection(self):
        """
        Public slot to comment the current selection.
        """
        if self.lexer is None or not self.lexer.canStreamComment():
            return
        
        if not self.hasSelectedText():
            return
        
        commentStr = self.lexer.streamCommentStr()
        
        # get the selection boundaries
        lineFrom, indexFrom, lineTo, indexTo = self.getSelection()
        if indexTo == 0:
            endLine = lineTo - 1
            endIndex = self.lineLength(endLine)
        else:
            endLine = lineTo
            endIndex = indexTo
        
        self.beginUndoAction()
        self.insertAt(commentStr['end'], endLine, endIndex)
        self.insertAt(commentStr['start'], lineFrom, indexFrom)
        
        # change the selection accordingly
        if indexTo > 0:
            indexTo += commentStr['end'].length()
            if lineFrom == endLine:
                indexTo += commentStr['start'].length()
        self.setSelection(lineFrom, indexFrom, lineTo, indexTo)
        self.endUndoAction()
        
    def streamCommentLineOrSelection(self):
        """
        Public slot to stream comment the current line or current selection.
        """
        if self.hasSelectedText():
            self.streamCommentSelection()
        else:
            self.streamCommentLine()
        
    def boxCommentLine(self):
        """
        Public slot to box comment the current line.
        """
        if self.lexer is None or not self.lexer.canBoxComment():
            return
        
        commentStr = self.lexer.boxCommentStr()
        line, index = self.getCursorPosition()
        
        eol = self.getLineSeparator()
        self.beginUndoAction()
        self.insertAt(eol, line, self.lineLength(line))
        self.insertAt(commentStr['end'], line + 1, 0)
        self.insertAt(commentStr['middle'], line, 0)
        self.insertAt(eol, line, 0)
        self.insertAt(commentStr['start'], line, 0)
        self.endUndoAction()
        
    def boxCommentSelection(self):
        """
        Public slot to box comment the current selection.
        """
        if self.lexer is None or not self.lexer.canBoxComment():
            return
        
        if not self.hasSelectedText():
            return
            
        commentStr = self.lexer.boxCommentStr()
        
        # get the selection boundaries
        lineFrom, indexFrom, lineTo, indexTo = self.getSelection()
        if indexTo == 0:
            endLine = lineTo - 1
        else:
            endLine = lineTo
        
        self.beginUndoAction()
        # iterate over the lines
        for line in range(lineFrom, endLine+1):
            self.insertAt(commentStr['middle'], line, 0)
        
        # now do the comments before and after the selection
        eol = self.getLineSeparator()
        self.insertAt(eol, endLine, self.lineLength(endLine))
        self.insertAt(commentStr['end'], endLine + 1, 0)
        self.insertAt(eol, lineFrom, 0)
        self.insertAt(commentStr['start'], lineFrom, 0)
        
        # change the selection accordingly
        self.setSelection(lineFrom, 0, endLine+3, 0)
        self.endUndoAction()
        
    def boxCommentLineOrSelection(self):
        """
        Public slot to box comment the current line or current selection.
        """
        if self.hasSelectedText():
            self.boxCommentSelection()
        else:
            self.boxCommentLine()
    
    ############################################################################
    ## Indentation handling methods below
    ############################################################################

    def __indentLine(self, indent = True):
        """
        Private method to indent or unindent the current line. 
        
        @param indent flag indicating an indent operation
                <br />If the flag is true, an indent operation is performed.
                Otherwise the current line is unindented.
        """
        line, index = self.getCursorPosition()
        self.beginUndoAction()
        if indent:
            self.indent(line)
        else:
            self.unindent(line)
        self.endUndoAction()
        if indent:
            self.setCursorPosition(line, index + self.indentationWidth())
        else:
            self.setCursorPosition(line, index - self.indentationWidth())
        
    def __indentSelection(self, indent = True):
        """
        Private method to indent or unindent the current selection. 
        
        @param indent flag indicating an indent operation
                <br />If the flag is true, an indent operation is performed.
                Otherwise the current line is unindented.
        """
        if not self.hasSelectedText():
            return
        
        # get the selection
        lineFrom, indexFrom, lineTo, indexTo = self.getSelection()
        
        if indexTo == 0:
            endLine = lineTo - 1
        else:
            endLine = lineTo
        
        self.beginUndoAction()
        # iterate over the lines
        for line in range(lineFrom, endLine+1):
            if indent:
                self.indent(line)
            else:
                self.unindent(line)
        self.endUndoAction()
        if indent:
            if indexTo == 0:
                self.setSelection(lineFrom, indexFrom + self.indentationWidth(),
                                  lineTo, 0)
            else:
                self.setSelection(lineFrom, indexFrom + self.indentationWidth(),
                                  lineTo, indexTo + self.indentationWidth())
        else:
            indexStart = indexFrom - self.indentationWidth()
            if indexStart < 0:
                indexStart = 0
            indexEnd = indexTo - self.indentationWidth()
            if indexEnd < 0:
                indexEnd = 0
            self.setSelection(lineFrom, indexStart, lineTo, indexEnd)
        
    def indentLineOrSelection(self):
        """
        Public slot to indent the current line or current selection
        """
        if self.hasSelectedText():
            self.__indentSelection(True)
        else:
            self.__indentLine(True)
        
    def unindentLineOrSelection(self):
        """
        Public slot to unindent the current line or current selection.
        """
        if self.hasSelectedText():
            self.__indentSelection(False)
        else:
            self.__indentLine(False)
        
    def smartIndentLineOrSelection(self):
        """
        Public slot to indent current line smartly.
        """
        if self.hasSelectedText():
            if self.lexer and self.lexer.hasSmartIndent():
                self.lexer.smartIndentSelection(self)
            else:
                self.__indentSelection(True)
        else:
            if self.lexer and self.lexer.hasSmartIndent():
                self.lexer.smartIndentLine(self)
            else:
                self.__indentLine(True)
        
    def gotoLine(self, line):
        """
        Public slot to jump to the beginning of a line.
        
        @param line line number to go to
        """
        self.setCursorPosition(line-1, 0)
        self.ensureVisible(line)
    
    ############################################################################
    ## Setup methods below
    ############################################################################

    def readSettings(self):
        """
        Public slot to read the settings into our lexer.
        """
        # read the lexer settings and reinit the properties
        if self.lexer is not None:
            self.lexer.readSettings(Preferences.Prefs.settings, "Scintilla")
            self.lexer.initProperties()
            
            # initialize the auto indent style of the lexer
            ais = self.lexer.autoIndentStyle()
        
        # read the typing completer settings
        if self.completer is not None:
            self.completer.readSettings()
        
        # set the line marker colours
        self.__setLineMarkerColours()
        
        # set the text display
        self.__setTextDisplay()
        
        # set margin 0 and 2 configuration
        self.__setMargin0and2()
        
        # set the autocompletion and calltips function
        self.__setAutoCompletion()
        self.__setCallTips()
        
        # set the autosave flags
        self.autosaveEnabled = Preferences.getEditor("AutosaveInterval") > 0
        
        if Preferences.getEditor("MiniContextMenu") != self.miniMenu:
            # regenerate context menu
            self.__initContextMenu()
        else:
            # set checked context menu items
            self.menuActs["AutoCompletionEnable"].setChecked(\
                self.autoCompletionThreshold() != -1)
            self.menuActs["MonospacedFont"].setChecked(\
                self.useMonospaced)
            self.menuActs["AutosaveEnable"].setChecked(\
                self.autosaveEnabled and not self.autosaveManuallyDisabled)
    
    def __setLineMarkerColours(self):
        """
        Private method to set the line marker colours.
        """
        self.setMarkerForegroundColor(Preferences.getEditorColour("CurrentMarker"),
            self.currentline)
        self.setMarkerBackgroundColor(Preferences.getEditorColour("CurrentMarker"),
            self.currentline)
        self.setMarkerForegroundColor(Preferences.getEditorColour("ErrorMarker"),
            self.errorline)
        self.setMarkerBackgroundColor(Preferences.getEditorColour("ErrorMarker"),
            self.errorline)
        
    def __setMargin0and2(self):
        """
        Private method to configure margins 0 and 2.
        """
        # set the font for all margins
        self.setMarginsFont(Preferences.getEditorOtherFonts("MarginsFont"))
        
        # set margin 0 settings
        linenoMargin = Preferences.getEditor("LinenoMargin")
        self.setMarginLineNumbers(0, linenoMargin)
        if linenoMargin:
            self.setMarginWidth(0, ' ' + '8' * Preferences.getEditor("LinenoWidth"))
        else:
            self.setMarginWidth(0, 0)
        
        # set margin 2 settings
        if Preferences.getEditor("FoldingMargin"):
            folding = Preferences.getEditor("FoldingStyle")
            try:
                folding = QsciScintilla.FoldStyle(folding)
            except AttributeError:
                pass
            self.setFolding(folding)
        else:
            self.setFolding(QsciScintilla.NoFoldStyle)
        
    def __setTextDisplay(self):
        """
        Private method to configure the text display.
        """
        self.setTabWidth(Preferences.getEditor("TabWidth"))
        self.setIndentationWidth(Preferences.getEditor("IndentWidth"))
        if self.lexer and self.lexer.alwaysKeepTabs():
            self.setIndentationsUseTabs(True)
        else:
            self.setIndentationsUseTabs(Preferences.getEditor("TabForIndentation"))
        self.setTabIndents(Preferences.getEditor("TabIndents"))
        self.setBackspaceUnindents(Preferences.getEditor("TabIndents"))
        self.setIndentationGuides(Preferences.getEditor("IndentationGuides"))
        if Preferences.getEditor("ShowWhitespace"):
            self.setWhitespaceVisibility(QsciScintilla.WsVisible)
        else:
            self.setWhitespaceVisibility(QsciScintilla.WsInvisible)
        self.setEolVisibility(Preferences.getEditor("ShowEOL"))
        self.setAutoIndent(Preferences.getEditor("AutoIndentation"))
        if Preferences.getEditor("BraceHighlighting"):
            self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
        else:
            self.setBraceMatching(QsciScintilla.NoBraceMatch)
        self.setMatchedBraceForegroundColor(
            Preferences.getEditorColour("MatchingBrace"))
        self.setMatchedBraceBackgroundColor(
            Preferences.getEditorColour("MatchingBraceBack"))
        self.setUnmatchedBraceForegroundColor(
            Preferences.getEditorColour("NonmatchingBrace"))
        self.setUnmatchedBraceBackgroundColor(
            Preferences.getEditorColour("NonmatchingBraceBack"))
        eolMode = Preferences.getEditor("EOLMode")
        eolMode = QsciScintilla.EolMode(eolMode)
        self.setEolMode(eolMode)
        if Preferences.getEditor("CustomSelectionColours"):
            self.setSelectionBackgroundColor(\
                Preferences.getEditorColour("SelectionBackground"))
        else:
            self.setSelectionBackgroundColor(\
                QApplication.palette().color(QPalette.Highlight))
        if Preferences.getEditor("ColourizeSelText"):
            self.resetSelectionForegroundColor()
        elif Preferences.getEditor("CustomSelectionColours"):
            self.setSelectionForegroundColor(\
                Preferences.getEditorColour("SelectionForeground"))
        else:
            self.setSelectionForegroundColor(\
                QApplication.palette().color(QPalette.HighlightedText))
        self.setSelectionToEol(Preferences.getEditor("ExtendSelectionToEol"))
        self.setCaretForegroundColor(
            Preferences.getEditorColour("CaretForeground"))
        self.setCaretLineBackgroundColor(
            Preferences.getEditorColour("CaretLineBackground"))
        self.setCaretLineVisible(Preferences.getEditor("CaretLineVisible"))
        self.caretWidth = Preferences.getEditor("CaretWidth")
        self.setCaretWidth(self.caretWidth)
        self.useMonospaced = Preferences.getEditor("UseMonospacedFont")
        self.setMonospaced(self.useMonospaced)
        edgeMode = Preferences.getEditor("EdgeMode")
        edge = QsciScintilla.EdgeMode(edgeMode)
        self.setEdgeMode(edge)
        if edgeMode:
            self.setEdgeColumn(Preferences.getEditor("EdgeColumn"))
            self.setEdgeColor(Preferences.getEditorColour("Edge"))
        
        if Preferences.getEditor("WrapLongLines"):
            self.setWrapMode(QsciScintilla.WrapWord)
            self.setWrapVisualFlags(\
                QsciScintilla.WrapFlagByBorder, QsciScintilla.WrapFlagByBorder)
        else:
            self.setWrapMode(QsciScintilla.WrapNone)
            self.setWrapVisualFlags(\
                QsciScintilla.WrapFlagNone, QsciScintilla.WrapFlagNone)
        
    def __setAutoCompletion(self):
        """
        Private method to configure the autocompletion function.
        """
        if self.lexer:
            self.setAutoCompletionFillupsEnabled(
                Preferences.getEditor("AutoCompletionFillups"))
        self.setAutoCompletionCaseSensitivity(
            Preferences.getEditor("AutoCompletionCaseSensitivity"))
        self.setAutoCompletionReplaceWord(
            Preferences.getEditor("AutoCompletionReplaceWord"))
        self.setAutoCompletionShowSingle(
            Preferences.getEditor("AutoCompletionShowSingle"))
        if Preferences.getEditor("AutoCompletionEnabled"):
            autoCompletionSource = Preferences.getEditor("AutoCompletionSource")
            if autoCompletionSource == QsciScintilla.AcsDocument:
                self.setAutoCompletionSource(QsciScintilla.AcsDocument)
            elif autoCompletionSource == QsciScintilla.AcsAPIs:
                self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
            else:
                self.setAutoCompletionSource(QsciScintilla.AcsAll)
            self.acAPI = True
            self.emit(SIGNAL("autoCompletionAPIsAvailable"), self.acAPI)
            self.setAutoCompletionThreshold(
                Preferences.getEditor("AutoCompletionThreshold"))
        else:
            self.setAutoCompletionSource(QsciScintilla.AcsNone)
            self.setAutoCompletionThreshold(-1)
            self.acAPI = False
        
    def __setCallTips(self):
        """
        Private method to configure the calltips function.
        """
        if Preferences.getEditor("CallTipsEnabled"):
            self.setCallTipsBackgroundColor(
                Preferences.getEditorColour("CallTipsBackground"))
            self.setCallTipsVisible(Preferences.getEditor("CallTipsVisible"))
            calltipsStyle = Preferences.getEditor("CallTipsStyle")
            if calltipsStyle == QsciScintilla.CallTipsNoContext:
                self.setCallTipsStyle(QsciScintilla.CallTipsNoContext)
            elif calltipsStyle == QsciScintilla.CallTipsNoAutoCompletionContext:
                self.setCallTipsStyle(QsciScintilla.CallTipsNoAutoCompletionContext)
            else:
                self.setCallTipsStyle(QsciScintilla.CallTipsContext)
        else:
            self.setCallTipsStyle(QsciScintilla.CallTipsNone)

    ############################################################################
    ## Autocompletion handling methods below
    ############################################################################

    def canAutoCompleteFromAPIs(self):
        """
        Public method to check for API availablity.
        
        @return flag indicating autocompletion from APIs is available (boolean)
        """
        return self.acAPI
        
    def autoComplete(self):
        """
        Public method to perform an autocompletion.
        """
        acs = self.autoCompletionSource()
        if acs == QsciScintilla.AcsDocument:
            self.autoCompleteFromDocument()
        elif acs == QsciScintilla.AcsAPIs:
            self.autoCompleteFromAPIs()
        elif acs == QsciScintilla.AcsAll:
            self.autoCompleteFromAll()
        else:
            KQMessageBox.information(None,
                self.trUtf8("Autocompletion"),
                self.trUtf8("""Autocompletion is not available because"""
                    """ there is no autocompletion source set."""))
        
    def setAutoCompletionEnabled(self, enable):
        """
        Public method to enable/disable autocompletion.
        
        @param enable flag indicating the desired autocompletion status
        """
        if enable:
            self.setAutoCompletionThreshold(
                Preferences.getEditor("AutoCompletionThreshold"))
        else:
            self.setAutoCompletionThreshold(-1)
        
    def __toggleAutoCompletionEnable(self):
        """
        Private slot to handle the Enable Autocompletion context menu entry.
        """
        if self.menuActs["AutoCompletionEnable"].isChecked():
            self.setAutoCompletionEnabled(True)
        else:
            self.setAutoCompletionEnabled(False)
    
    #################################################################
    ## Methods needed by the context menu
    #################################################################
    
    def __marginsWidth(self):
        """
        Private method to determine the width of all margins.
        
        @return width of all margins in pixels (integer)
        """
        return self.marginWidth(0) + self.marginWidth(1) + self.marginWidth(2)
        
    def contextMenuEvent(self, evt):
        """
        Private method implementing the context menu event.
        
        @param evt the context menu event (QContextMenuEvent)
        """
        evt.accept()
        if evt.x() > self.__marginsWidth():
            self.menu.popup(evt.globalPos())
        else:
            self.line = self.lineAt(evt.pos())
            self.marginMenu.popup(evt.globalPos())
        
    def __showContextMenu(self):
        """
        Private slot handling the aboutToShow signal of the context menu.
        """
        self.menuActs["Save"].setEnabled(self.isModified())
        self.menuActs["Undo"].setEnabled(self.isUndoAvailable())
        self.menuActs["Redo"].setEnabled(self.isRedoAvailable())
        self.menuActs["Revert"].setEnabled(self.isModified())
        if not self.miniMenu:
            self.menuActs["Cut"].setEnabled(self.hasSelectedText())
            self.menuActs["Copy"].setEnabled(self.hasSelectedText())
            self.menuActs["PrintSel"].setEnabled(self.hasSelectedText())
        if not self.isResourcesFile:
            if self.fileName and self.isPyFile():
                if not self.miniMenu:
                    self.menuActs["Refactoring"].setEnabled(True)
                self.menuActs["Check"].setEnabled(True)
                self.menuActs["Show"].setEnabled(True)
            else:
                if not self.miniMenu:
                    self.menuActs["Refactoring"].setEnabled(False)
                self.menuActs["Check"].setEnabled(False)
                self.menuActs["Show"].setEnabled(False)
            if self.fileName and (self.isPyFile() or self.isRubyFile()):
                self.menuActs["Diagrams"].setEnabled(True)
            else:
                self.menuActs["Diagrams"].setEnabled(False)
        if not self.miniMenu:
            if self.lexer is not None:
                self.menuActs["Comment"].setEnabled(self.lexer.canBlockComment())
                self.menuActs["Uncomment"].setEnabled(self.lexer.canBlockComment())
                self.menuActs["StreamComment"].setEnabled(self.lexer.canStreamComment())
                self.menuActs["BoxComment"].setEnabled(self.lexer.canBoxComment())
            else:
                self.menuActs["Comment"].setEnabled(False)
                self.menuActs["Uncomment"].setEnabled(False)
                self.menuActs["StreamComment"].setEnabled(False)
                self.menuActs["BoxComment"].setEnabled(False)
        
    def __showAutocompletionMenu(self):
        """
        Private slot called before the autocompletion menu is shown.
        """
        self.menuActs["acAPI"].setEnabled(self.acAPI)
        self.menuActs["acAPIDocument"].setEnabled(self.acAPI)
        
    def __showShowMenu(self):
        """
        Private slot called before the show menu is shown.
        """
        prEnable = False
        coEnable = False
        cyEnable = False
        
        # first check if the file belongs to a project
        project = e4App().getObject("Project")
        if project.isOpen() and project.isProjectSource(self.fileName):
            fn = project.getMainScript(True)
            if fn is not None:
                tfn = Utilities.getTestFileName(fn)
                basename = os.path.splitext(fn)[0]
                tbasename = os.path.splitext(tfn)[0]
                prEnable = prEnable or \
                    os.path.isfile("%s.profile" % basename) or \
                    os.path.isfile("%s.profile" % tbasename)
                coEnable = coEnable or \
                    os.path.isfile("%s.coverage" % basename) or \
                    os.path.isfile("%s.coverage" % tbasename)
                cyEnable = cyEnable or \
                    os.path.isfile("%s.cycles.html" % basename) or \
                    os.path.isfile("%s.cycles.html" % tbasename)
        
        # now check ourself
        fn = self.getFileName()
        if fn is not None:
            tfn = Utilities.getTestFileName(fn)
            basename = os.path.splitext(fn)[0]
            tbasename = os.path.splitext(tfn)[0]
            prEnable = prEnable or \
                os.path.isfile("%s.profile" % basename) or \
                os.path.isfile("%s.profile" % tbasename)
            coEnable = coEnable or \
                os.path.isfile("%s.coverage" % basename) or \
                os.path.isfile("%s.coverage" % tbasename)
            cyEnable = cyEnable or \
                os.path.isfile("%s.cycles.html" % basename) or \
                os.path.isfile("%s.cycles.html" % tbasename)
        
        self.profileMenuAct.setEnabled(prEnable)
        self.coverageMenuAct.setEnabled(coEnable)
        self.coverageShowAnnotationMenuAct.setEnabled(\
            coEnable and not self.coverageMarkersShown)
        self.coverageHideAnnotationMenuAct.setEnabled(\
            self.coverageMarkersShown)
        self.cyclopsMenuAct.setEnabled(cyEnable)
        self.removeCyclopsMenuAct.setEnabled(cyEnable)
        
    def __showContextMenuGraphics(self):
        """
        Private slot handling the aboutToShow signal of the diagrams context menu.
        """
        project = e4App().getObject("Project")
        if project.isOpen() and project.isProjectSource(self.fileName):
            self.applicationDiagramMenuAct.setEnabled(True)
        else:
            self.applicationDiagramMenuAct.setEnabled(False)

    def __showMarginContextMenu(self):
        """
        Private slot handling the aboutToShow signal of the margins context menu.
        """
        if self.fileName and (self.isPyFile() or self.isRubyFile()):
            self.marginMenuActs["Breakpoint"].setEnabled(True)
            self.marginMenuActs["TempBreakpoint"].setEnabled(True)
            if self.markersAtLine(self.line) & self.breakpointMask:
                self.marginMenuActs["EditBreakpoint"].setEnabled(True)
                self.marginMenuActs["EnableBreakpoint"].setEnabled(True)
            else:
                self.marginMenuActs["EditBreakpoint"].setEnabled(False)
                self.marginMenuActs["EnableBreakpoint"].setEnabled(False)
            if self.markersAtLine(self.line) & (1 << self.dbreakpoint):
                self.marginMenuActs["EnableBreakpoint"].setText(\
                    self.trUtf8('Enable breakpoint'))
            else:
                self.marginMenuActs["EnableBreakpoint"].setText(\
                    self.trUtf8('Disable breakpoint'))
            if self.breaks:
                self.marginMenuActs["NextBreakpoint"].setEnabled(True)
                self.marginMenuActs["PreviousBreakpoint"].setEnabled(True)
                self.marginMenuActs["ClearBreakpoint"].setEnabled(True)
            else:
                self.marginMenuActs["NextBreakpoint"].setEnabled(False)
                self.marginMenuActs["PreviousBreakpoint"].setEnabled(False)
                self.marginMenuActs["ClearBreakpoint"].setEnabled(False)
        else:
            self.marginMenuActs["Breakpoint"].setEnabled(False)
            self.marginMenuActs["TempBreakpoint"].setEnabled(False)
            self.marginMenuActs["EditBreakpoint"].setEnabled(False)
            self.marginMenuActs["EnableBreakpoint"].setEnabled(False)
            self.marginMenuActs["NextBreakpoint"].setEnabled(False)
            self.marginMenuActs["PreviousBreakpoint"].setEnabled(False)
            self.marginMenuActs["ClearBreakpoint"].setEnabled(False)
            
        if self.bookmarks:
            self.marginMenuActs["NextBookmark"].setEnabled(True)
            self.marginMenuActs["PreviousBookmark"].setEnabled(True)
            self.marginMenuActs["ClearBookmark"].setEnabled(True)
        else:
            self.marginMenuActs["NextBookmark"].setEnabled(False)
            self.marginMenuActs["PreviousBookmark"].setEnabled(False)
            self.marginMenuActs["ClearBookmark"].setEnabled(False)
            
        if len(self.syntaxerrors):
            self.marginMenuActs["GotoSyntaxError"].setEnabled(True)
            self.marginMenuActs["ClearSyntaxError"].setEnabled(True)
            if self.markersAtLine(self.line) & (1 << self.syntaxerror):
                self.marginMenuActs["ShowSyntaxError"].setEnabled(True)
            else:
                self.marginMenuActs["ShowSyntaxError"].setEnabled(False)
        else:
            self.marginMenuActs["GotoSyntaxError"].setEnabled(False)
            self.marginMenuActs["ClearSyntaxError"].setEnabled(False)
            self.marginMenuActs["ShowSyntaxError"].setEnabled(False)
        
        if self.notcoveredMarkers:
            self.marginMenuActs["NextCoverageMarker"].setEnabled(True)
            self.marginMenuActs["PreviousCoverageMarker"].setEnabled(True)
        else:
            self.marginMenuActs["NextCoverageMarker"].setEnabled(False)
            self.marginMenuActs["PreviousCoverageMarker"].setEnabled(False)
        
        if self.__hasTaskMarkers:
            self.marginMenuActs["PreviousTaskMarker"].setEnabled(True)
            self.marginMenuActs["NextTaskMarker"].setEnabled(True)
        else:
            self.marginMenuActs["PreviousTaskMarker"].setEnabled(False)
            self.marginMenuActs["NextTaskMarker"].setEnabled(False)
        
    def __contextSave(self):
        """
        Private slot handling the save context menu entry.
        """
        ok, newName = self.saveFile()
        if ok:
            self.vm.setEditorName(self, newName)
        
    def __contextSaveAs(self):
        """
        Private slot handling the save as context menu entry.
        """
        ok, newName = self.saveFileAs()
        if ok:
            self.vm.setEditorName(self, newName)
        
    def __contextClose(self):
        """
        Private slot handling the close context menu entry.
        """
        self.vm.closeEditor(self)
    
    def __newView(self):
        """
        Private slot to create a new view to an open document.
        """
        self.vm.newEditorView(self.fileName, self, self.isPythonFile)
        
    def __newViewNewSplit(self):
        """
        Private slot to create a new view to an open document.
        """
        self.vm.addSplit()
        self.vm.newEditorView(self.fileName, self, self.isPythonFile)
        
    def __selectAll(self):
        """
        Private slot handling the select all context menu action.
        """
        self.selectAll(True)
            
    def __deselectAll(self):
        """
        Private slot handling the deselect all context menu action.
        """
        self.selectAll(False)
        
    def shortenEmptyLines(self):
        """
        Public slot to compress lines consisting solely of whitespace characters.
        """
        ok = self.findFirst(r"^[ \t]+$", 1, 0, 0, 0, 1, 0, 0, 0)
        while ok:
            self.replace("")
            ok = self.findNext()
        
    def __autosaveEnable(self):
        """
        Private slot handling the autosave enable context menu action.
        """
        if self.menuActs["AutosaveEnable"].isChecked():
            self.autosaveManuallyDisabled = False
        else:
            self.autosaveManuallyDisabled = True
        
    def shouldAutosave(self):
        """
        Public slot to check the autosave flags.
        
        @return flag indicating this editor should be saved (boolean)
        """
        return self.fileName is not None and \
               not self.autosaveManuallyDisabled and \
               not self.isReadOnly()
        
    def __doTabnanny(self):
        """
        Private method to handle the tabnanny context menu action.
        """
        if not self.checkDirty():
            return
        
        self.tabnanny = TabnannyDialog()
        self.tabnanny.show()
        self.tabnanny.start(self.fileName)
        
    def __autoSyntaxCheck(self):
        """
        Private method to perform an automatic syntax check of the file.
        """
        if Preferences.getEditor("AutoCheckSyntax"):
            self.clearSyntaxError()
            if self.isPyFile():
                syntaxError, _fn, errorline, _code, _error = \
                    Utilities.compile(self.fileName)
                if syntaxError:
                    self.toggleSyntaxError(int(errorline), 1, _error)
        
    def __syntaxCheck(self, quiet = False):
        """
        Private method to perform a syntax check of the file.
        
        @param quiet flag indicating quiet operation (Boolean)
        """
        if not self.isPyFile() or not self.checkDirty():
            return
        
        self.clearSyntaxError()
        syntaxError, _fn, errorline, _code, _error = \
            Utilities.compile(self.fileName)
        if syntaxError:
            self.toggleSyntaxError(int(errorline), 1, _error)
        else:
            if not quiet:
                KQMessageBox.information(None,
                    self.trUtf8("Syntax Check"),
                    self.trUtf8("""No syntax errors found."""))
        
    def __doSyntaxCheck(self):
        """
        Private method to handle the syntax check context menu action.
        """
        self.__syntaxCheck(False)
        
    def __showCodeMetrics(self):
        """
        Private method to handle the code metrics context menu action.
        """
        if not self.checkDirty():
            return
        
        self.codemetrics = CodeMetricsDialog()
        self.codemetrics.show()
        self.codemetrics.start(self.fileName)
        
    def __getCodeCoverageFile(self):
        """
        Private method to get the filename of the file containing coverage info.
        """
        files = []
        
        # first check if the file belongs to a project and there is
        # a project coverage file
        project = e4App().getObject("Project")
        if project.isOpen() and project.isProjectSource(self.fileName):
            fn = project.getMainScript(True)
            if fn is not None:
                tfn = Utilities.getTestFileName(fn)
                basename = os.path.splitext(fn)[0]
                tbasename = os.path.splitext(tfn)[0]
                
                f = "%s.coverage" % basename
                tf = "%s.coverage" % tbasename
                if os.path.isfile(f):
                    files.append(f)
                if os.path.isfile(tf):
                    files.append(tf)
        
        # now check, if there are coverage files belonging to ourself
        fn = self.getFileName()
        if fn is not None:
            tfn = Utilities.getTestFileName(fn)
            basename = os.path.splitext(fn)[0]
            tbasename = os.path.splitext(tfn)[0]
            
            f = "%s.coverage" % basename
            tf = "%s.coverage" % tbasename
            if os.path.isfile(f) and not f in files:
                files.append(f)
            if os.path.isfile(tf) and not tf in files:
                files.append(tf)
        
        if files:
            if len(files) > 1:
                filelist = QStringList()
                for f in files:
                    filelist.append(f)
                fn, ok = KQInputDialog.getItem(\
                    self,
                    self.trUtf8("Code Coverage"),
                    self.trUtf8("Please select a coverage file"),
                    filelist,
                    0, False)
                if not ok:
                    return
                fn = unicode(fn)
            else:
                fn = files[0]
        else:
            fn = None
        
        return fn
        
    def __showCodeCoverage(self):
        """
        Private method to handle the code coverage context menu action.
        """
        fn = self.__getCodeCoverageFile()
        if fn:
            self.codecoverage = PyCoverageDialog()
            self.codecoverage.show()
            self.codecoverage.start(fn, self.fileName)
        
    def __codeCoverageShowAnnotations(self):
        """
        Private method to handle the show code coverage annotations context menu action.
        """
        fn = self.__getCodeCoverageFile()
        if fn:
            cover = coverage(fn)
            cover.get_ready()
            missing = cover.analysis(self.fileName)[2]
            if missing:
                for line in missing:
                    handle = self.markerAdd(line-1, self.notcovered)
                    self.notcoveredMarkers.append(handle)
                    self.emit(SIGNAL('coverageMarkersShown'), True)
                    self.coverageMarkersShown = True
            else:
                KQMessageBox.information(None,
                    self.trUtf8("Show Code Coverage Annotations"),
                    self.trUtf8("""All lines have been covered."""))
        else:
            KQMessageBox.warning(None,
                self.trUtf8("Show Code Coverage Annotations"),
                self.trUtf8("""There is no coverage file available."""))
        
    def __codeCoverageHideAnnotations(self):
        """
        Private method to handle the hide code coverage annotations context menu action.
        """
        for handle in self.notcoveredMarkers:
            self.markerDeleteHandle(handle)
        self.notcoveredMarkers = []
        self.emit(SIGNAL('coverageMarkersShown'), False)
        self.coverageMarkersShown = False
        
    def hasCoverageMarkers(self):
        """
        Public method to test, if there are coverage markers.
        """
        return len(self.notcoveredMarkers) > 0
        
    def nextUncovered(self):
        """
        Public slot to handle the 'Next uncovered' context menu action.
        """
        line, index = self.getCursorPosition()
        if line == self.lines()-1:
            line = 0
        else:
            line += 1
        ucline = self.markerFindNext(line, 1 << self.notcovered)
        if ucline < 0:
            # wrap around
            ucline = self.markerFindNext(0, 1 << self.notcovered)
        if ucline >= 0:
            self.setCursorPosition(ucline, 0)
            self.ensureLineVisible(ucline)
        
    def previousUncovered(self):
        """
        Public slot to handle the 'Previous uncovered' context menu action.
        """
        line, index = self.getCursorPosition()
        if line == 0:
            line = self.lines()-1
        else:
            line -= 1
        ucline = self.markerFindPrevious(line, 1 << self.notcovered)
        if ucline < 0:
            # wrap around
            ucline = self.markerFindPrevious(self.lines() - 1, 1 << self.notcovered)
        if ucline >= 0:
            self.setCursorPosition(ucline, 0)
            self.ensureLineVisible(ucline)
        
    def __showProfileData(self):
        """
        Private method to handle the show profile data context menu action.
        """
        files = []
        
        # first check if the file belongs to a project and there is
        # a project profile file
        project = e4App().getObject("Project")
        if project.isOpen() and project.isProjectSource(self.fileName):
            fn = project.getMainScript(True)
            if fn is not None:
                tfn = Utilities.getTestFileName(fn)
                basename = os.path.splitext(fn)[0]
                tbasename = os.path.splitext(tfn)[0]
                
                f = "%s.profile" % basename
                tf = "%s.profile" % tbasename
                if os.path.isfile(f):
                    files.append(f)
                if os.path.isfile(tf):
                    files.append(tf)
        
        # now check, if there are profile files belonging to ourself
        fn = self.getFileName()
        if fn is not None:
            tfn = Utilities.getTestFileName(fn)
            basename = os.path.splitext(fn)[0]
            tbasename = os.path.splitext(tfn)[0]
            
            f = "%s.profile" % basename
            tf = "%s.profile" % tbasename
            if os.path.isfile(f) and not f in files:
                files.append(f)
            if os.path.isfile(tf) and not tf in files:
                files.append(tf)
        
        if files:
            if len(files) > 1:
                filelist = QStringList()
                for f in files:
                    filelist.append(f)
                fn, ok = KQInputDialog.getItem(\
                    self,
                    self.trUtf8("Profile Data"),
                    self.trUtf8("Please select a profile file"),
                    filelist,
                    0, False)
                if not ok:
                    return
                fn = unicode(fn)
            else:
                fn = files[0]
        else:
            return
        
        self.profiledata = PyProfileDialog()
        self.profiledata.show()
        self.profiledata.start(fn, self.fileName)
        
    def __showCyclopsReport(self):
        """
        Private method to handle the Cyclops report context menu action.
        """
        files = []
        
        # first check if the file belongs to a project and there is
        # a project cyclops file
        project = e4App().getObject("Project")
        if project.isOpen() and project.isProjectSource(self.fileName):
            fn = project.getMainScript(True)
            if fn is not None:
                tfn = Utilities.getTestFileName(fn)
                basename = os.path.splitext(fn)[0]
                tbasename = os.path.splitext(tfn)[0]
                
                f = "%s.cycles.html" % basename
                tf = "%s.cycles.html" % tbasename
                if os.path.isfile(f):
                    files.append(f)
                if os.path.isfile(tf):
                    files.append(tf)
        
        # now check, if there are cyclops files belonging to ourself
        fn = self.getFileName()
        if fn is not None:
            tfn = Utilities.getTestFileName(fn)
            basename = os.path.splitext(fn)[0]
            tbasename = os.path.splitext(tfn)[0]
            
            f = "%s.cycles.html" % basename
            tf = "%s.cycles.html" % tbasename
            if os.path.isfile(f) and not f in files:
                files.append(f)
            if os.path.isfile(tf) and not tf in files:
                files.append(tf)
        
        if files:
            if len(files) > 1:
                filelist = QStringList()
                for f in files:
                    filelist.append(f)
                fn, ok = KQInputDialog.getItem(\
                    self,
                    self.trUtf8("Cyclops Report"),
                    self.trUtf8("Please select a Cyclops report file"),
                    filelist,
                    0, False)
                if not ok:
                    return
                fn = unicode(fn)
            else:
                fn = files[0]
        else:
            return
        
        e4App().getObject("UserInterface").launchHelpViewer(fn)
        
    def __removeCyclopsReport(self):
        """
        Private method to handle the Remove Cyclops report context menu action.
        """
        files = []
        
        # first check if the file belongs to a project and there is
        # a project cyclops file
        project = e4App().getObject("Project")
        if project.isOpen() and project.isProjectSource(self.fileName):
            fn = project.getMainScript(True)
            if fn is not None:
                tfn = Utilities.getTestFileName(fn)
                basename = os.path.splitext(fn)[0]
                tbasename = os.path.splitext(tfn)[0]
                
                f = "%s.cycles.html" % basename
                tf = "%s.cycles.html" % tbasename
                if os.path.isfile(f):
                    files.append(f)
                if os.path.isfile(tf):
                    files.append(tf)
        
        # now check, if there are cyclops files belonging to ourself
        fn = self.getFileName()
        if fn is not None:
            tfn = Utilities.getTestFileName(fn)
            basename = os.path.splitext(fn)[0]
            tbasename = os.path.splitext(tfn)[0]
            
            f = "%s.cycles.html" % basename
            tf = "%s.cycles.html" % tbasename
            if os.path.isfile(f) and not f in files:
                files.append(f)
            if os.path.isfile(tf) and not tf in files:
                files.append(tf)
        
        if files:
            if len(files) > 1:
                filelist = QStringList()
                for f in files:
                    filelist.append(f)
                fn, ok = KQInputDialog.getItem(\
                    self,
                    self.trUtf8("Remove Cyclops Report"),
                    self.trUtf8("Please select a Cyclops report file to be removed"),
                    filelist,
                    0, False)
                if not ok:
                    return
                fn = unicode(fn)
            else:
                fn = files[0]
        else:
            return
        
        if os.path.exists(fn):
            os.remove(fn)
        
    def __lmBbookmarks(self):
        """
        Private method to handle the 'LMB toggles bookmark' context menu action.
        """
        self.marginMenuActs["LMBbookmarks"].setChecked(True)
        self.marginMenuActs["LMBbreakpoints"].setChecked(False)
        
    def __lmBbreakpoints(self):
        """
        Private method to handle the 'LMB toggles breakpoint' context menu action.
        """
        self.marginMenuActs["LMBbookmarks"].setChecked(True)
        self.marginMenuActs["LMBbreakpoints"].setChecked(False)
    
    ############################################################################
    ## Syntax error handling methods below
    ############################################################################

    def toggleSyntaxError(self, line, error, msg = ""):
        """
        Public method to toggle a syntax error indicator.
        
        @param line line number of the syntax error
        @param error flag indicating if the error marker should be
            set or deleted (boolean)
        @param msg error message (string)
        """
        if error:
            # set a new syntax error marker
            markers = self.markersAtLine(line - 1)
            if not (markers & (1 << self.syntaxerror)):
                handle = self.markerAdd(line - 1, self.syntaxerror)
                self.syntaxerrors[handle] = msg
                self.emit(SIGNAL('syntaxerrorToggled'), self)
        else:
            for handle in self.syntaxerrors.keys():
                if self.markerLine(handle) == line - 1:
                    del self.syntaxerrors[handle]
                    self.markerDeleteHandle(handle)
                    self.emit(SIGNAL('syntaxerrorToggled'), self)
        
    def getSyntaxErrors(self):
        """
        Public method to retrieve the syntax error markers.
        
        @return sorted list of all lines containing a syntax error
            (list of integer)
        """
        selist = []
        for handle in self.syntaxerrors.keys():
            selist.append(self.markerLine(handle) + 1)
        
        selist.sort()
        return selist
        
    def hasSyntaxErrors(self):
        """
        Public method to check for the presence of bookmarks.
        
        @return flag indicating the presence of bookmarks (boolean)
        """
        return len(self.syntaxerrors) > 0
    
    def gotoSyntaxError(self):
        """
        Public slot to handle the 'Goto syntax error' context menu action.
        """
        seline = self.markerFindNext(0, 1 << self.syntaxerror)
        if seline >= 0:
            self.setCursorPosition(seline, 0)
            self.ensureLineVisible(seline)
        
    def clearSyntaxError(self):
        """
        Public slot to handle the 'Clear all syntax error' context menu action.
        """
        for handle in self.syntaxerrors.keys():
            line = self.markerLine(handle) + 1
            self.toggleSyntaxError(line, False)
        
    def __showSyntaxError(self):
        """
        Private slot to handle the 'Show syntax error message' context menu action.
        """
        for handle in self.syntaxerrors.keys():
            if self.markerLine(handle) == self.line:
                KQMessageBox.critical(None,
                    self.trUtf8("Syntax Error"),
                    self.syntaxerrors[handle])
                break
        else:
            KQMessageBox.critical(None,
                self.trUtf8("Syntax Error"),
                self.trUtf8("No syntax error message available."))
    
    #################################################################
    ## Macro handling methods
    #################################################################
    
    def __getMacroName(self):
        """
        Private method to select a macro name from the list of macros.
        
        @return Tuple of macro name and a flag, indicating, if the user pressed ok or
            canceled the operation. (QString, boolean)
        """
        qs = QStringList()
        for s in self.macros.keys():
            qs.append(s)
        qs.sort()
        return KQInputDialog.getItem(\
            self,
            self.trUtf8("Macro Name"),
            self.trUtf8("Select a macro name:"),
            qs,
            0, False)
        
    def macroRun(self):
        """
        Public method to execute a macro.
        """
        name, ok = self.__getMacroName()
        if ok and not name.isEmpty():
            self.macros[unicode(name)].play()
        
    def macroDelete(self):
        """
        Public method to delete a macro.
        """
        name, ok = self.__getMacroName()
        if ok and not name.isEmpty():
            del self.macros[unicode(name)]
        
    def macroLoad(self):
        """
        Public method to load a macro from a file.
        """
        configDir = Utilities.getConfigDir()
        fname = KQFileDialog.getOpenFileName(\
            self,
            self.trUtf8("Load macro file"),
            configDir,
            self.trUtf8("Macro files (*.macro)"),
            None)
        
        if fname.isEmpty():
            return  # user aborted
        
        try:
            f = open(unicode(fname), "rb")
            lines = f.readlines()
            f.close()
        except IOError:
            KQMessageBox.critical(self,
                self.trUtf8("Error loading macro"),
                self.trUtf8("<p>The macro file <b>%1</b> could not be read.</p>")
                    .arg(fname))
            return
        
        if len(lines) != 2:
            KQMessageBox.critical(self,
                self.trUtf8("Error loading macro"),
                self.trUtf8("<p>The macro file <b>%1</b> is corrupt.</p>")
                    .arg(fname))
            return
        
        macro = QsciMacro(lines[1], self)
        self.macros[lines[0].strip()] = macro
        
    def macroSave(self):
        """
        Public method to save a macro to a file.
        """
        configDir = Utilities.getConfigDir()
        
        name, ok = self.__getMacroName()
        if not ok or name.isEmpty():
            return  # user abort
        name = unicode(name)
        
        selectedFilter = QString('')
        fname = KQFileDialog.getSaveFileName(\
            self,
            self.trUtf8("Save macro file"),
            configDir,
            self.trUtf8("Macro files (*.macro)"),
            selectedFilter,
            QFileDialog.Options(QFileDialog.DontConfirmOverwrite))
        
        if fname.isEmpty():
            return  # user aborted
        
        ext = QFileInfo(fname).suffix()
        if ext.isEmpty():
            ex = selectedFilter.section('(*',1,1).section(')',0,0)
            if not ex.isEmpty():
                fname.append(ex)
        if QFileInfo(fname).exists():
            res = KQMessageBox.warning(self,
                self.trUtf8("Save macro"),
                self.trUtf8("<p>The macro file <b>%1</b> already exists.</p>")
                    .arg(fname),
                QMessageBox.StandardButtons(\
                    QMessageBox.Abort | \
                    QMessageBox.Save),
                QMessageBox.Abort)
            if res == QMessageBox.Abort or res == QMessageBox.Cancel:
                return
        fname = unicode(Utilities.toNativeSeparators(fname))
        
        try:
            f = open(fname, "wb")
            f.write("%s%s" % (name, os.linesep))
            f.write(unicode(self.macros[name].save()))
            f.close()
        except IOError:
            KQMessageBox.critical(self,
                self.trUtf8("Error saving macro"),
                self.trUtf8("<p>The macro file <b>%1</b> could not be written.</p>")
                    .arg(fname))
            return
        
    def macroRecordingStart(self):
        """
        Public method to start macro recording.
        """
        if self.recording:
            res = KQMessageBox.warning(self, 
                self.trUtf8("Start Macro Recording"),
                self.trUtf8("Macro recording is already active. Start new?"),
                QMessageBox.StandardButtons(\
                    QMessageBox.No | \
                    QMessageBox.Yes),
                QMessageBox.Yes)
            if res == QMessageBox.Yes:
                self.handleStopMacroRecording()
            else:
                return
        else:
            self.recording = True
        
        self.curMacro = QsciMacro(self)
        self.curMacro.startRecording()
        
    def macroRecordingStop(self):
        """
        Public method to stop macro recording.
        """
        if not self.recording:
            return      # we are not recording
        
        self.curMacro.endRecording()
        self.recording = False
        
        name, ok = KQInputDialog.getText(\
            self,
            self.trUtf8("Macro Recording"),
            self.trUtf8("Enter name of the macro:"),
            QLineEdit.Normal)
        
        if ok and not name.isEmpty():
            self.macros[unicode(name)] = self.curMacro
        
        self.curMacro = None
        
    #################################################################
    ## Overwritten methods
    #################################################################
    
    def undo(self):
        """
        Public method to undo the last recorded change.
        """
        QsciScintillaCompat.undo(self)
        self.emit(SIGNAL('undoAvailable'), self.isUndoAvailable())
        self.emit(SIGNAL('redoAvailable'), self.isRedoAvailable())
        
    def redo(self):
        """
        Public method to redo the last recorded change.
        """
        QsciScintillaCompat.redo(self)
        self.emit(SIGNAL('undoAvailable'), self.isUndoAvailable())
        self.emit(SIGNAL('redoAvailable'), self.isRedoAvailable())
        
    def close(self, alsoDelete = False):
        """
        Public method called when the window gets closed.
        
        This overwritten method redirects the action to our
        ViewManager.closeEditor, which in turn calls our closeIt
        method.
        
        @param alsoDelete ignored
        """
        return self.vm.closeEditor(self)
        
    def closeIt(self):
        """
        Public method called by the viewmanager to finally get rid of us.
        """
        if Preferences.getEditor("ClearBreaksOnClose"):
            self.__menuClearBreakpoints()
        QsciScintillaCompat.close(self)
        
    def keyPressEvent(self, ev):
        """
        Re-implemented to handle the user input a key at a time.
        
        @param ev key event (QKeyEvent)
        """
        txt = ev.text()
        key = ev.key()
        
        # See it is text to insert.
        if txt.length() and txt >= " ":
            QsciScintillaCompat.keyPressEvent(self, ev)
        else:
            ev.ignore()
        
    def focusInEvent(self, event):
        """
        Protected method called when the editor receives focus.
        
        This method checks for modifications of the current file and
        rereads it upon request. The cursor is placed at the current position
        assuming, that it is in the vicinity of the old position after the reread.
        
        @param event the event object (QFocusEvent)
        """
        self.vm.editActGrp.setEnabled(True)
        self.vm.editorActGrp.setEnabled(True)
        self.vm.copyActGrp.setEnabled(True)
        self.vm.viewActGrp.setEnabled(True)
        try:
            self.setCaretWidth(self.caretWidth)
        except AttributeError:
            pass
        self.__updateReadOnly(False)
        if self.vm.editorsCheckFocusInEnabled() and \
           not self.inReopenPrompt and self.fileName and \
           QFileInfo(self.fileName).lastModified().toString().compare(\
                self.lastModified.toString()):
            if Preferences.getEditor("AutoReopen") and not self.isModified():
                self.refresh()
            else:
                self.inReopenPrompt = True
                msg = self.trUtf8(\
                    """<p>The file <b>%1</b> has been changed while it was opened in"""
                    """ eric4.</p>""").arg(self.fileName)
                if self.isModified():
                    msg.append(self.trUtf8(\
                        """<br><b>Warning:</b> You will loose"""
                        """ your changes upon reopening it."""))
                res = KQMessageBox.warning(None,
                    self.trUtf8("File changed"), msg,
                    QMessageBox.StandardButtons(\
                        QMessageBox.Ok | \
                        QMessageBox.Open),
                    QMessageBox.Ok)
                if res == QMessageBox.Open:
                    self.refresh()
                else:
                    # do not prompt for this change again...
                    self.lastModified = QFileInfo(self.fileName).lastModified()
                self.inReopenPrompt = False
        
        QsciScintillaCompat.focusInEvent(self, event)
        
    def focusOutEvent(self, event):
        """
        Public method called when the editor loses focus.
        
        @param event the event object (QFocusEvent)
        """
        self.vm.editorActGrp.setEnabled(False)
        self.setCaretWidth(0)
        
        QsciScintillaCompat.focusOutEvent(self, event)
        
    def changeEvent(self, evt):
        """
        Protected method called to process an event.
        
        This implements special handling for the events showMaximized,
        showMinimized and showNormal. The windows caption is shortened
        for the minimized mode and reset to the full filename for the
        other modes. This is to make the editor windows work nicer
        with the QWorkspace.
        
        @param evt the event, that was generated (QEvent)
        @return flag indicating if the event could be processed (bool)
        """
        if evt.type() == QEvent.WindowStateChange and \
           self.fileName is not None:
            if self.windowState() == Qt.WindowStates(Qt.WindowMinimized):
                cap = os.path.basename(self.fileName)
            else:
                cap = self.fileName
            if self.isReadOnly():
                cap = self.trUtf8("%1 (ro)").arg(cap)
            self.setWindowTitle(cap)
        
        QsciScintillaCompat.changeEvent(self, evt)
        
    def mousePressEvent(self, event):
        """
        Protected method to handle the mouse press event.
        
        @param event the mouse press event (QMouseEvent)
        """
        self.vm.eventFilter(self, event)
        QsciScintillaCompat.mousePressEvent(self, event)
        
    def __updateReadOnly(self, bForce = True):
        """
        Private method to update the readOnly information for this editor. 
        
        If bForce is True, then updates everything regardless if
        the attributes have actually changed, such as during
        initialization time.  A signal is emitted after the
        caption change.

        @param bForce True to force change, False to only update and emit
                signal if there was an attribute change.
        """
        if self.fileName is None:
            return
        readOnly = not QFileInfo(self.fileName).isWritable()
        if not bForce and (readOnly == self.isReadOnly()):
            return
        cap = self.fileName
        if readOnly:
            cap = unicode(self.trUtf8("%1 (ro)").arg(cap))
        self.setReadOnly(readOnly)
        self.setWindowTitle(cap)
        self.emit(SIGNAL('captionChanged'), cap, self)
        
    def refresh(self):
        """
        Public slot to refresh the editor contents.
        """
        # save cursor position
        cline, cindex = self.getCursorPosition()
        
        # save bookmarks and breakpoints and clear them
        bmlist = self.getBookmarks()
        self.clearBookmarks()
        
        # reread the file
        try:
            self.readFile(self.fileName)
        except IOError:
            # do not prompt for this change again...
            self.lastModified = QFileInfo(self.fileName).lastModified()
        self.setModified(False)
        
        # reset cursor position
        self.setCursorPosition(cline, cindex)
        self.ensureCursorVisible()
        
        # reset bookmarks and breakpoints to their old position
        if bmlist:
            for bm in bmlist:
                self.toggleBookmark(bm)
        self.__restoreBreakpoints()
        
        self.emit(SIGNAL('editorSaved'), self.fileName)
        self.__autoSyntaxCheck()
        
    def setMonospaced(self, on):
        """
        Public method to set/reset a monospaced font.
        
        @param on flag to indicate usage of a monospace font (boolean)
        """
        if on:
            f = Preferences.getEditorOtherFonts("MonospacedFont")
            self.monospacedStyles(f)
        else:
            if not self.lexer:
                self.clearStyles()
            self.setFont(Preferences.getEditorOtherFonts("DefaultFont"))
        
        self.useMonospaced = on
    
    #################################################################
    ## Drag and Drop Support
    #################################################################
    
    def dragEnterEvent(self, event):
        """
        Protected method to handle the drag enter event.
        
        @param event the drag enter event (QDragEnterEvent)
        """
        self.inDragDrop = event.mimeData().hasUrls()
        if self.inDragDrop:
            event.acceptProposedAction()
        else:
            QsciScintillaCompat.dragEnterEvent(self, event)
        
    def dragMoveEvent(self, event):
        """
        Protected method to handle the drag move event.
        
        @param event the drag move event (QDragMoveEvent)
        """
        if self.inDragDrop:
            event.accept()
        else:
            QsciScintillaCompat.dragMoveEvent(self, event)
        
    def dragLeaveEvent(self, event):
        """
        Protected method to handle the drag leave event.
        
        @param event the drag leave event (QDragLeaveEvent)
        """
        if self.inDragDrop:
            self.inDragDrop = False
            event.accept()
        else:
            QsciScintillaCompat.dragLeaveEvent(self, event)
        
    def dropEvent(self, event):
        """
        Protected method to handle the drop event.
        
        @param event the drop event (QDropEvent)
        """
        if event.mimeData().hasUrls():
            for url in event.mimeData().urls():
                fname = url.toLocalFile()
                if not fname.isEmpty():
                    if not QFileInfo(fname).isDir():
                        self.vm.openSourceFile(unicode(fname))
                    else:
                        KQMessageBox.information(None,
                            self.trUtf8("Drop Error"),
                            self.trUtf8("""<p><b>%1</b> is not a file.</p>""")
                                .arg(fname))
            event.acceptProposedAction()
        else:
            QsciScintillaCompat.dropEvent(self, event)
        
        self.inDragDrop = False
    
    #################################################################
    ## Support for Qt resources files
    #################################################################
    
    def __initContextMenuResources(self):
        """
        Private method used to setup the Resources context sub menu.
        """
        menu = QMenu(self.trUtf8('Resources'))
        
        menu.addAction(self.trUtf8('Add file...'), 
            self.__addFileResource)
        menu.addAction(self.trUtf8('Add files...'), 
            self.__addFileResources)
        menu.addAction(self.trUtf8('Add aliased file...'), 
            self.__addFileAliasResource)
        menu.addAction(self.trUtf8('Add localized resource...'), 
            self.__addLocalizedResource)
        menu.addSeparator()
        menu.addAction(self.trUtf8('Add resource frame'),
            self.__addResourceFrame)
        
        return menu
        
    def __addFileResource(self):
        """
        Private method to handle the Add file context menu action.
        """
        dirStr = os.path.dirname(self.fileName)
        file = KQFileDialog.getOpenFileName(\
            self,
            self.trUtf8("Add file resource"),
            dirStr,
            QString(),
            None)
        if not file.isEmpty():
            relFile = QDir(dirStr).relativeFilePath(file)
            line, index = self.getCursorPosition()
            self.insert(QString("  <file>%1</file>\n").arg(relFile))
            self.setCursorPosition(line + 1, index)
        
    def __addFileResources(self):
        """
        Private method to handle the Add files context menu action.
        """
        dirStr = os.path.dirname(self.fileName)
        files = KQFileDialog.getOpenFileNames(\
            self,
            self.trUtf8("Add file resources"),
            dirStr,
            QString(),
            None)
        if not files.isEmpty():
            myDir = QDir(dirStr)
            filesText = QString()
            for file in files:
                relFile = myDir.relativeFilePath(file)
                filesText.append(QString("  <file>%1</file>\n").arg(relFile))
            line, index = self.getCursorPosition()
            self.insert(filesText)
            self.setCursorPosition(line + len(files), index)
        
    def __addFileAliasResource(self):
        """
        Private method to handle the Add aliased file context menu action.
        """
        dirStr = os.path.dirname(self.fileName)
        file = KQFileDialog.getOpenFileName(\
            self,
            self.trUtf8("Add aliased file resource"),
            dirStr,
            QString(),
            None)
        if not file.isEmpty():
            relFile = QDir(dirStr).relativeFilePath(file)
            alias, ok = KQInputDialog.getText(\
                self,
                self.trUtf8("Add aliased file resource"),
                self.trUtf8("Alias for file <b>%1</b>:").arg(relFile),
                QLineEdit.Normal,
                relFile)
            if ok and not alias.isEmpty():
                line, index = self.getCursorPosition()
                self.insert(QString('  <file alias="%2">%1</file>\n')\
                            .arg(relFile).arg(alias))
                self.setCursorPosition(line + 1, index)
        
    def __addLocalizedResource(self):
        """
        Private method to handle the Add localized resource context menu action.
        """
        from Project.AddLanguageDialog import AddLanguageDialog
        dlg = AddLanguageDialog(self)
        if dlg.exec_() == QDialog.Accepted:
            lang = dlg.getSelectedLanguage()
            line, index = self.getCursorPosition()
            self.insert(QString('<qresource lang="%1">\n</qresource>\n').arg(lang))
            self.setCursorPosition(line + 2, index)
        
    def __addResourceFrame(self):
        """
        Private method to handle the Add resource frame context menu action.
        """
        line, index = self.getCursorPosition()
        self.insert(QString('<!DOCTYPE RCC>\n'
                            '<RCC version="1.0">\n'
                            '<qresource>\n'
                            '</qresource>\n'
                            '</RCC>\n'))
        self.setCursorPosition(line + 5, index)
    
    #################################################################
    ## Support for diagrams below
    #################################################################
    
    def __showClassDiagram(self):
        """
        Private method to handle the Class Diagram context menu action.
        """
        from Graphics.UMLClassDiagram import UMLClassDiagram
        if not self.checkDirty():
            return
        
        self.classDiagram = UMLClassDiagram(self.fileName, self, noAttrs = False)
        self.classDiagram.show()
        
    def __showPackageDiagram(self):
        """
        Private method to handle the Package Diagram context menu action.
        """
        from Graphics.PackageDiagram import PackageDiagram
        if not self.checkDirty():
            return
        
        package = os.path.isdir(self.fileName) and self.fileName \
                                               or os.path.dirname(self.fileName)
        res = KQMessageBox.question(None,
            self.trUtf8("Package Diagram"),
            self.trUtf8("""Include class attributes?"""),
            QMessageBox.StandardButtons(\
                QMessageBox.No | \
                QMessageBox.Yes),
            QMessageBox.Yes)
        self.packageDiagram = PackageDiagram(package, self, 
            noAttrs = (res == QMessageBox.No))
        self.packageDiagram.show()
        
    def __showImportsDiagram(self):
        """
        Private method to handle the Imports Diagram context menu action.
        """
        from Graphics.ImportsDiagram import ImportsDiagram
        if not self.checkDirty():
            return
        
        package = os.path.isdir(self.fileName) and self.fileName \
                                               or os.path.dirname(self.fileName)
        self.importsDiagram = ImportsDiagram(package, self)
        self.importsDiagram.show()
        
    def __showApplicationDiagram(self):
        """
        Private method to handle the Imports Diagram context menu action.
        """
        from Graphics.ApplicationDiagram import ApplicationDiagram
        res = KQMessageBox.question(None,
            self.trUtf8("Application Diagram"),
            self.trUtf8("""Include module names?"""),
            QMessageBox.StandardButtons(\
                QMessageBox.No | \
                QMessageBox.Yes),
            QMessageBox.Yes)
        self.applicationDiagram = ApplicationDiagram(e4App().getObject("Project"), 
                                    self, noModules = (res == QMessageBox.No))
        self.applicationDiagram.show()
