#!/usr/bin/env python

#	Programmer:	Daniel Pozmanter
#	E-mail:		drpython@bluebottle.com
#	Note:		You must reply to the verification e-mail to get through.
#
#	Copyright 2003-2004 Daniel Pozmanter
#
#	Distributed under the terms of the GPL (GNU Public License)
#
#	DrPython is free software; you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation; either version 2 of the License, or
#	(at your option) any later version.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with this program; if not, write to the Free Software
#	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#	Requirements(Dependencies):  Install Python, and wxPython.
#
#	Tested On Windows, Linux, Mac OS X
#
#	Icons taken from "Klassic New Crisp Icons" by Asif Ali Rizwaan (therizwaan) from the KDE-LOOK site (some edited a bit).
#	A humble and excellent artist.
#	Oh, the python icon is taken from wxPython.
#	The basic design of the program is meant to roughly (ROUGHLY) mimick DrScheme.
#	The purpose is the same, to provide a simple IDE(integrated development environment) ideal for teaching.
#	The DrPython icon itself was based on the DrScheme icon, with a slightly edited wxpython icon inserted(note yellow tongue, googly eyes).
#	
#	This program could not have been written without the wonderful work of the people behind
#	python and wxPython, in particular the Styled Text Control.  Thank you.  Hopefully this tool will be of use.
#
#	Replaced all rstrip('\n') with rstrip(), thanks Christof Ecker: (drpython.py and DrPrefs.py).
#
#	Version: 3.7.3

#franz: stat is not used
import os.path, sys, os, shutil, re, string, operator, locale

import wxversion
wxversion.select('2.5.3-unicode')
import wx, wx.stc

sys.path.insert(0, '/usr/share/drpython')

import drScrolledMessageDialog
from drText import DrText
from drPrompt import DrPrompt
from drPrinter import DrPrinter
from drFindReplaceDialog import drFindReplaceDialog, drFinder
from drBookmarksMenu import drBookmarksMenu
from drScriptMenu import drScriptMenu
from drPluginMenu import drPluginConfigureMenu, drPluginIndexMenu, drPluginAboutMenu, drPluginHelpMenu, drPluginPreferencesMenu
import drFileDialog
import drPrefsFile
import drPopUp
from drPreferences import drPreferences
import drShortcutsFile
import drShortcuts
import drToolBarFile
from drSourceBrowser import drSourceBrowserPanel
from drUTF8 import utf8Detect, SetEncodedText, GetEncodedText

#*******************************************************************************************************

class drNotebook(wx.Notebook):
	def __init__(self, parent, id, position, size, flags = 0):
		wx.Notebook.__init__(self, parent, id, position, size, flags)
		
		self.parent = parent
		
		self.PromptHasFocus = 0
		
		imagesize = (16,16)
		
		ID_CLOSE = parent.GetNewId()
		
		self.imagelist = wx.ImageList(imagesize[0], imagesize[1])
		self.images = [wx.BitmapFromImage(wx.Image(self.parent.bitmapdirectory + "/16/unmodified.png", wx.BITMAP_TYPE_PNG)), \
		wx.BitmapFromImage(wx.Image(self.parent.bitmapdirectory + "/16/modified.png", wx.BITMAP_TYPE_PNG)), \
		wx.BitmapFromImage(wx.Image(self.parent.bitmapdirectory + "/16/active unmodified.png", wx.BITMAP_TYPE_PNG)), \
		wx.BitmapFromImage(wx.Image(self.parent.bitmapdirectory + "/16/active modified.png", wx.BITMAP_TYPE_PNG))]
	
		map(self.imagelist.Add, self.images)
		
		self.AssignImageList(self.imagelist)
		
		#wxPython bug workaround, OldSelection doesn't work.
		self.oldselection = 0
		
		self.Bind(wx.EVT_LEFT_DOWN, self.OnFindFocus)
		self.Bind(wx.EVT_LEFT_UP, self.OnSelectTab)
		self.Bind(wx.EVT_RIGHT_DOWN, self.OnPopUp)
	
	def OnFindFocus(self, event):
		self.PromptHasFocus = self.parent.txtPrompt.GetSTCFocus()
		
		event.Skip()
	
	def OnPageChanged(self, event):
		if event is not None:
			i = event.GetSelection()
		else:
			i = self.GetSelection()
		l = self.GetPageCount()
		if (i < 0) or (i >= l):
			if event is not None:
				event.Skip()
			return
		if self.oldselection < l:
			self.parent.txtDocumentArray[self.oldselection].IsActive = False
			self.parent.txtDocumentArray[self.oldselection].OnModified(None)
		
		self.oldselection = i
		
		self.parent.txtDocumentArray[i].IsActive = True
		self.parent.txtDocumentArray[i].OnModified(None)
		
		if event is not None:
			event.Skip()
	
	def OnPopUp(self, event):
	
		closeallmenu = wx.Menu()				
		closeallmenu.Append(self.parent.ID_CLOSE_ALL, "Close &All Tabs"," Close All Tabs")
		closeallmenu.Append(self.parent.ID_CLOSE_ALL_OTHER_DOCUMENTS, "Close All &Other Tabs"," Close All Other Tabs")
		
		tabmenu = wx.Menu()
		tabmenu.Append(self.parent.ID_CLOSE, "&Close", "Close the file")
		tabmenu.Append(self.parent.ID_CLOSE_ALL, "Close &All Tabs")
		tabmenu.Append(self.parent.ID_CLOSE_ALL_OTHER_DOCUMENTS, "Close All &Other Tabs")
		tabmenu.AppendSeparator()
		tabmenu.Append(self.parent.ID_NEXT_DOCUMENT, "Next Tab")
		tabmenu.Append(self.parent.ID_PREVIOUS_DOCUMENT, "Previous Tab")
		tabmenu.Append(self.parent.ID_FIRST_DOCUMENT, "First Tab")
		tabmenu.Append(self.parent.ID_LAST_DOCUMENT, "Last Tab")
		tabmenu.AppendSeparator()
		tabmenu.Append(self.parent.ID_RELOAD, "&Reload File"," Reload the current file")
		tabmenu.Append(self.parent.ID_RESTORE_FROM_BACKUP, "&Restore From Backup"," Restore from the last backup made")
		tabmenu.AppendSeparator()
		tabmenu.Append(self.parent.ID_SAVE, "&Save"," Save the file")
		tabmenu.Append(self.parent.ID_SAVE_AS, "Save &As..."," Save a file as ... another file")
		
		ht = self.HitTest(event.GetPosition())[0]
		if ht > -1:
			self.SetSelection(ht)
			self.SetTab()
		
		tabmenu.Enable(self.parent.ID_RELOAD, len(self.parent.txtDocument.filename) > 0)
		tabmenu.Enable(self.parent.ID_RESTORE_FROM_BACKUP, len(self.parent.txtDocument.filename) > 0)
		self.PopupMenu(tabmenu, event.GetPosition())
		tabmenu.Destroy()

	def SetTab(self):
		selection = self.GetSelection()
		page = self.GetPage(selection)
		self.parent.setDocumentTo(selection)
		if self.PromptHasFocus and page.PromptIsVisible:
			self.parent.txtPromptArray[self.parent.docPosition].SetSTCFocus(True)
		else:
			self.parent.txtDocumentArray[self.parent.docPosition].SetSTCFocus(True)
			
	def OnSelectTab(self, event):
		selection = self.GetSelection()
		if selection is not self.parent.docPosition:
			self.SetTab()
		event.Skip()

class drSplitTextPanel(wx.Panel):
	def __init__(self, parent, grandparent, targetstc, position, index):
		docid = grandparent.txtDocument.GetId()
		wx.Panel.__init__(self, parent, docid)
		
		ID_CLOSE = grandparent.GetNewId()
		
		self.position = position
		self.index = index
		
		self.parent = parent
				
		self.grandparent = grandparent
		
		self.SetBackgroundColour(wx.Colour(0, 95, 89))
		
		if docid == targetstc.GetId():
			sv = -1
		else:
			sv = 1
		
		self.txtDoc = DrText(self, docid, grandparent, SplitView=sv)
		self.txtDoc.SetupPrefsDocument()
		self.txtDoc.SetDocPointer(targetstc.GetDocPointer())
		self.txtDoc.GotoPos(targetstc.GetCurrentPos())
		self.txtDoc.ScrollToLine(targetstc.GetCurrentLine())
		
		self.label = wx.TextCtrl(self, -1, " Viewing: " + targetstc.GetFilenameTitle(), size=(150, -1), style=wx.TE_READONLY)
		
		self.btnClose = wx.Button(self, ID_CLOSE, "x", style=wx.BU_EXACTFIT)
		
		text = self.txtDoc.GetText()
		
		#Scrolling
		linebuffer = self.txtDoc.TextWidth(wx.stc.STC_STYLE_DEFAULT, "OOO")
		lines = text.split(self.txtDoc.GetEndOfLineCharacter())
		spaces = "\t".expandtabs(self.grandparent.prefs.tabwidth)			
		line = ""
		length = 0
		for l in lines:
			if len(l) > length:
				length = len(l)
				line = l
		line = line.replace('\t', spaces)		
		self.txtDoc.SetScrollWidth(self.txtDoc.TextWidth(wx.stc.STC_STYLE_DEFAULT, line)+linebuffer)
								
		self.txtDoc.SetXOffset(0)
		#/End Scrolling
				
		self.Bind(wx.EVT_BUTTON, self.OnbtnClose, id=ID_CLOSE)		
		self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
		self.Bind(wx.EVT_SIZE, self.OnSize)

	def OnbtnClose(self, event):
		self.grandparent.currentpage.ShowPanel(self.position, self.index, False)
										
	def OnKeyDown(self, event):
		self.grandparent.RunShortcuts(event)

		event.Skip()
	
	def OnSize(self, event):
		x, y = self.GetSizeTuple()
		lX, lY = self.label.GetSizeTuple()
		bX, bY = self.btnClose.GetSizeTuple()
		pX, pY = self.GetPositionTuple()
		self.txtDoc.Move((pX,pY+lY))
		self.label.SetSize((x-bX, lY))
		self.btnClose.Move((x-bX, pY))
		self.txtDoc.SetSize((x, y-lY))
		if (x <= 0) or (y <= 0):
			self.Destroy()

class drSashWindow(wx.SashWindow):
	def __init__(self, parent, id, pos, size, style):
		wx.SashWindow.__init__(self, parent, id, pos, size, style)
				
		self.grandparent = parent.grandparent
		
		self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
										
	def OnKeyDown(self, event):
		self.grandparent.RunShortcuts(event)

		event.Skip()

class drDocPanel(wx.Panel):
	def __init__(self, parent, id):
		wx.Panel.__init__(self, parent, id)
		
		self.grandparent = parent.grandparent
		
		width, height = self.GetSizeTuple()
		
		#Variables to Keep Track of what is being used.
			
		self.ID_LEFT = 6300 + id
		self.ID_RIGHT = 6400 + id
		self.ID_TOP = 6500 + id
		self.ID_BOTTOM = 6600 + id
				
		self.centertuple = (width, height)
		
		self.center = drSashWindow(self, id, wx.DefaultPosition, wx.DefaultSize, wx.SW_3D)

		self.lefttuples = []
		self.righttuples = []
		self.toptuples = []
		self.bottomtuples = []

		self.leftsizes = []
		self.rightsizes = []
		self.bottomsizes = []
		self.topsizes = []
		
		self.leftsizestores = []
		self.rightsizestores = []
		self.bottomsizestores = []
		self.topsizestores = []
		
		self.LeftSashWindows = []
		self.RightSashWindows = []
		self.TopSashWindows = []
		self.BottomSashWindows = []
						
		self.LeftIsVisible = []
		self.RightIsVisible = []
		self.TopIsVisible = []
		self.BottomIsVisible = []
		
		self.oldwidth, self.oldheight = 0, 0
		
		self.Bind(wx.EVT_SIZE, self.OnSize)
	
	def ClosePanel(self, Position, Index):
		if Position == 0:			
			self.leftsizes.pop(Index)
			self.leftsizestores.pop(Index)
			self.lefttuples.pop(Index)
			self.LeftSashWindows[Index].Destroy()
			self.LeftSashWindows.pop(Index)
			self.LeftIsVisible.pop(Index)
		elif Position == 1:
			self.rightsizes.pop(Index)
			self.rightsizestores.pop(Index)
			self.righttuples.pop(Index)
			self.RightSashWindows[Index].Destroy()
			self.RightSashWindows.pop(Index)
			self.RightIsVisible.pop(Index)
		elif Position == 2:
			self.topsizes.pop(Index)
			self.topsizestores.pop(Index)
			self.toptuples.pop(Index)			
			self.TopSashWindows[Index].Destroy()
			self.TopSashWindows.pop(Index)
			self.TopIsVisible.pop(Index)
		elif Position == 3:
			self.bottomsizes.pop(Index)
			self.bottomsizestores.pop(Index)
			self.bottomtuples.pop(Index)
			self.BottomSashWindows[Index].Destroy()
			self.BottomSashWindows.pop(Index)
			self.BottomIsVisible.pop(Index)
		self.OnSize(None)
		self.grandparent.txtDocument.SetFocus()	
		
	def GetTargetSashWindow(self, Position=1):
		if Position == 0:
			i = len(self.LeftSashWindows)
			left = drSashWindow(self, self.ID_LEFT+i, wx.DefaultPosition, wx.DefaultSize, wx.SW_3D)
			left.SetSashVisible(wx.SASH_RIGHT, True)
			left.SetSashBorder(wx.SASH_RIGHT, True)
			
			self.LeftSashWindows.append(left)
			self.LeftIsVisible.append(True)
			
			self.Bind(wx.EVT_SASH_DRAGGED, self.OnSashDrag, id=self.ID_LEFT+i)
			
			target = self.LeftSashWindows[i]
			self.leftsizes.append(self.grandparent.prefs.sidepanelleftsize)
			self.leftsizestores.append(self.grandparent.prefs.sidepanelleftsize)
			self.lefttuples.append((0, 0))
		elif Position == 1:
			i = len(self.RightSashWindows)
			right = drSashWindow(self, self.ID_RIGHT+i, wx.DefaultPosition, wx.DefaultSize, wx.SW_3D)
			right.SetSashVisible(wx.SASH_LEFT, True)
			right.SetSashBorder(wx.SASH_LEFT, True)
			
			self.RightSashWindows.append(right)
			self.RightIsVisible.append(True)
			
			self.Bind(wx.EVT_SASH_DRAGGED, self.OnSashDrag, id=self.ID_RIGHT+i)
			
			target = self.RightSashWindows[i]
			self.rightsizes.append(self.grandparent.prefs.sidepanelrightsize)
			self.rightsizestores.append(self.grandparent.prefs.sidepanelrightsize)
			self.righttuples.append((0, 0))
		elif Position == 2:
			i = len(self.TopSashWindows)
			top = drSashWindow(self, self.ID_TOP+i, wx.DefaultPosition, wx.DefaultSize, wx.SW_3D)
			top.SetSashVisible(wx.SASH_BOTTOM, True)
			top.SetSashBorder(wx.SASH_BOTTOM, True)
			
			self.TopSashWindows.append(top)
			self.TopIsVisible.append(True)
			
			self.Bind(wx.EVT_SASH_DRAGGED, self.OnSashDrag, id=self.ID_TOP+i)
			
			target = self.TopSashWindows[i]
			self.topsizes.append(self.grandparent.prefs.sidepaneltopsize)
			self.topsizestores.append(self.grandparent.prefs.sidepaneltopsize)
			self.toptuples.append((0, 0))
		elif Position == 3:
			i = len(self.BottomSashWindows)
			bottom = drSashWindow(self, self.ID_BOTTOM+i, wx.DefaultPosition, wx.DefaultSize, wx.SW_3D)
			bottom.SetSashVisible(wx.SASH_TOP, True)
			bottom.SetSashBorder(wx.SASH_TOP, True)
			
			self.BottomSashWindows.append(bottom)
			self.BottomIsVisible.append(True)
			
			self.Bind(wx.EVT_SASH_DRAGGED, self.OnSashDrag, id=self.ID_BOTTOM+i)
			
			target = self.BottomSashWindows[i]
			self.bottomsizes.append(self.grandparent.prefs.sidepanelbottomsize)
			self.bottomsizestores.append(self.grandparent.prefs.sidepanelbottomsize)
			self.bottomtuples.append((0, 0))
		return target, i

	def IsVisible(self, Position, Index):
		if Position == 0:
			return self.LeftIsVisible[Index]
		elif Position == 1:
			return self.RightIsVisible[Index]
		elif Position == 2:
			return self.TopIsVisible[Index]
		elif Position == 3:
			return self.BottomIsVisible[Index]		

	def MoveToH(self, sasharray, tuplearray, w):
		l = len(tuplearray)
		x = 0
		while x < l:
			pos = self.SumTuple(tuplearray[:x], 0)
			sasharray[x].Move((pos+w, 0))
			x = x + 1

	def MoveToV(self, sasharray, tuplearray, w, h):
		x = 0
		l = len(tuplearray)
		while x < l:
			pos = self.SumTuple(tuplearray[:x], 1)
			sasharray[x].Move((w, pos + h))
			x = x + 1
		
	def OnSashDrag(self, event):
		evtheight = event.GetDragRect().height
		evtwidth = event.GetDragRect().width
		width, height = self.GetSizeTuple()
		if (evtwidth < 0):
			evtwidth = 0
		elif (evtwidth > width):
			evtwidth = width
		if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE:
			if (evtheight < height):
				evtheight = 0
			else:
				evtheight = height
		elif evtheight > height:
			evtheight = height

		#Edge Drag
		e = event.GetId()
		edge = event.GetEdge()
		if (e >= self.ID_LEFT) and (e < self.ID_RIGHT):
			i = e - self.ID_LEFT
			if self.lefttuples[i][0] == evtwidth:
				evtwidth = 0
				self.LeftIsVisible[i] = False
			self.lefttuples[i] = (evtwidth, height)			
			self.centertuple = (width-evtwidth, self.centertuple[1])
			self.leftsizes[i] = (evtwidth*100) / width
		elif (e >= self.ID_RIGHT) and (e < self.ID_TOP):
			i = e - self.ID_RIGHT
			if self.righttuples[i][0] == evtwidth:
				evtwidth = 0
				self.RightIsVisible[i] = False
			self.righttuples[i] = (evtwidth, height)
			self.centertuple = (width-evtwidth, self.centertuple[1])
			self.rightsizes[i] = (evtwidth*100) / width
		elif (e >= self.ID_TOP) and (e < self.ID_BOTTOM):
			i = e - self.ID_TOP
			if self.toptuples[i][1] == evtheight:
				evtheight = 0
				self.TopIsVisible[i] = False
			self.toptuples[i] = (self.toptuples[i][0], evtheight)
			self.centertuple = (self.centertuple[0], self.centertuple[1]-evtheight)
			self.topsizes[i] = (evtheight*100) / height
		elif e >= self.ID_BOTTOM:
			i = e - self.ID_BOTTOM
			if self.bottomtuples[i][1] == evtheight:
				evtheight = 0
				self.BottomIsVisible[i] = False
			self.bottomtuples[i] = (self.bottomtuples[i][0], evtheight)
			self.centertuple = (self.centertuple[0], self.centertuple[1]-evtheight)
			self.bottomsizes[i] = (evtheight*100) / height
			
		self.OnSize(None)	

	def OnSize(self, event):
		width, height = self.GetSizeTuple()
		if (event is not None) and (width == self.oldwidth) and (height == self.oldheight):
			return
		self.oldwidth, self.oldheight = width, height
				
		lleft, lright, ltop, lbottom = len(self.leftsizes), len(self.rightsizes), len(self.topsizes), len(self.bottomsizes)
		
		#Left
		if lleft > 0:
			lefttotal = self.Sum(self.leftsizes)
			self.lefttuples = map(lambda x: (((width * x) / 100), height), self.leftsizes)
			lefttupletotal = self.Sum(map(lambda x: (width * x) / 100, self.leftsizes))
			self.SetSizeFor(self.LeftSashWindows, self.lefttuples)
			self.MoveToH(self.LeftSashWindows, self.lefttuples, 0)	
			map(lambda x: x.Refresh(), self.LeftSashWindows)		
		else:
			lefttotal = 0
			lefttupletotal = 0		
		#Right
		if lright > 0:
			righttotal = self.Sum(self.rightsizes)	
			self.righttuples = map(lambda x: (((width * x) / 100), height), self.rightsizes)
			self.SetSizeFor(self.RightSashWindows, self.righttuples)
		else:
			righttotal = 0
			
		#Width
		w = (width * (100 - lefttotal - righttotal)) / 100
			
		#Top
		if ltop > 0:	
			toptotal = self.Sum(self.topsizes)
			self.toptuples = map(lambda x: (w, ((height * x) / 100)), self.topsizes)
			toptupletotal = self.Sum(map(lambda x: (height * x) / 100, self.topsizes))
			self.SetSizeFor(self.TopSashWindows, self.toptuples)
			self.MoveToV(self.TopSashWindows, self.toptuples, lefttupletotal, 0)
			map(lambda x: x.Refresh(), self.TopSashWindows)
		else:
			toptotal = 0
			toptupletotal = 0	
		
		#Bottom
		if lbottom > 0:
			bottomtotal = self.Sum(self.bottomsizes)
			self.bottomtuples = map(lambda x: (w, ((height * x) / 100)), self.bottomsizes)
			self.SetSizeFor(self.BottomSashWindows, self.bottomtuples)
		else:
			bottomtotal = 0
		
		#Height	
		h = (height * (100 - toptotal - bottomtotal)) / 100
		
		#Leftover Move
		if lright > 0:
			self.MoveToH(self.RightSashWindows, self.righttuples, w + lefttupletotal)
			map(lambda x: x.Refresh(), self.RightSashWindows)
		if lbottom > 0:
			self.MoveToV(self.BottomSashWindows, self.bottomtuples, lefttupletotal, h + toptupletotal)
			map(lambda x: x.Refresh(), self.BottomSashWindows)
		
		#Tuples
		self.centertuple = (w, h)		

		#Set Size then Move
		self.center.SetSize(self.centertuple)

		self.center.Move((lefttupletotal,toptupletotal))				

	def SetSizeFor(self, sasharray, tuplearray):
		x = 0
		l = len(tuplearray)
		while x < l:
			sasharray[x].SetSize(tuplearray[x])
			x = x + 1
			
	def ShowPanel(self, Position, Index, Show):
		if Position == 0:
			self.LeftIsVisible[Index] = Show
			if Show:
				self.leftsizes[Index] = self.leftsizestores[Index]
			else:
				self.leftsizestores[Index] = self.leftsizes[Index]
				self.leftsizes[Index] = 0
		elif Position == 1:
			self.RightIsVisible[Index] = Show
			if Show:
				self.rightsizes[Index] = self.rightsizestores[Index]
			else:
				self.rightsizestores[Index] = self.rightsizes[Index]
				self.rightsizes[Index] = 0	
		elif Position == 2:
			self.TopIsVisible[Index] = Show
			if Show:
				self.topsizes[Index] = self.topsizestores[Index]
			else:
				self.topsizestores[Index] = self.topsizes[Index]
				self.topsizes[Index] = 0
		elif Position == 3:
			self.BottomIsVisible[Index] = Show
			if Show:
				self.bottomsizes[Index] = self.bottomsizestores[Index]
			else:
				self.bottomsizestores[Index] = self.bottomsizes[Index]
				self.bottomsizes[Index] = 0
		self.OnSize(None)		
	
	def Sum(self, seq):
		if len(seq) > 0:
			return reduce(operator.add, seq)
		return 0
			
	def SumTuple(self, tuplearray, i):
		sum = 0
		for t in tuplearray:
			sum = sum + t[i]
		return sum
	
	def TogglePanel(self, Position, Index):
		if Position == 0:
			self.LeftIsVisible[Index] = not self.LeftIsVisible[Index]
			if self.LeftIsVisible[Index]:
				self.leftsizes[Index] = self.leftsizestores[Index]
			else:
				self.leftsizestores[Index] = self.leftsizes[Index]
				self.leftsizes[Index] = 0
		elif Position == 1:
			self.RightIsVisible[Index] = not self.RightIsVisible[Index]
			if self.RightIsVisible[Index]:
				self.rightsizes[Index] = self.rightsizestores[Index]
			else:
				self.rightsizestores[Index] = self.rightsizes[Index]
				self.rightsizes[Index] = 0	
		elif Position == 2:
			self.TopIsVisible[Index] = not self.TopIsVisible[Index]
			if self.TopIsVisible[Index]:
				self.topsizes[Index] = self.topsizestores[Index]
			else:
				self.topsizestores[Index] = self.topsizes[Index]
				self.topsizes[Index] = 0
		elif Position == 3:
			self.BottomIsVisible[Index] = not self.BottomIsVisible[Index]
			if self.BottomIsVisible[Index]:
				self.bottomsizes[Index] = self.bottomsizestores[Index]
			else:
				self.bottomsizestores[Index] = self.bottomsizes[Index]
				self.bottomsizes[Index] = 0
		self.OnSize(None)		
		
		
class drPanel(wx.Panel):
	def __init__(self, parent, id):
		wx.Panel.__init__(self, parent, id)
		
		self.grandparent = parent.GetParent()
		
		width, height = self.GetSizeTuple()
		
		#Variables to Keep Track of what is being used.
			
		self.ID_DOCUMENT = 6001 + id
		self.ID_PROMPT = 6002 + id
		
		self.PromptIsVisible = self.grandparent.prefs.promptisvisible
				
		self.documenttuple = (width, height)	
		self.prompttuple = (0, 0)

		self.promptsize = self.grandparent.prefs.promptsize

		self.prompt = drSashWindow(self, self.ID_PROMPT, wx.DefaultPosition, wx.DefaultSize, wx.SW_3D)

		self.prompt.SetSashVisible(wx.SASH_TOP, True)
		self.prompt.SetSashBorder(wx.SASH_TOP, True)

		self.document = drSashWindow(self, self.ID_DOCUMENT, wx.DefaultPosition, wx.DefaultSize, wx.SW_3D)

		self.documentpanel = drDocPanel(self.document, id)

		self.document.SetSashVisible(wx.SASH_BOTTOM, True)
		self.document.SetSashBorder(wx.SASH_BOTTOM, True)

		self.oldwidth, self.oldheight = 0, 0

		self.Bind(wx.EVT_SIZE, self.OnSize)
		self.Bind(wx.EVT_SASH_DRAGGED, self.OnSashDrag, id=self.ID_DOCUMENT)
		self.Bind(wx.EVT_SASH_DRAGGED, self.OnSashDrag, id=self.ID_PROMPT)
					
	def ClosePanel(self, Position, Index):
		self.documentpanel.ClosePanel(Position, Index)
	
	def GetTargetSashWindow(self, Position=1):
		return self.documentpanel.GetTargetSashWindow(Position)	
	
	def IsVisible(self, Position, Index):
		return self.documentpanel.IsVisible(Position, Index)
		
	def OnSashDrag(self, event):
		evtheight = event.GetDragRect().height
		evtwidth = event.GetDragRect().width
		width, height = self.GetSizeTuple()
		if (evtwidth < 0):
			evtwidth = 0
		elif (evtwidth > width):
			evtwidth = width
		if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE:
			if (not self.PromptIsVisible) or (evtheight < height):
				evtheight = 0
			else:
				evtheight = height
		elif evtheight > height:
			evtheight = height

		oldsize = self.promptsize

		#Edge Drag
		e = event.GetId()
		edge = event.GetEdge()
		if e == self.ID_DOCUMENT:
			if edge == wx.SASH_BOTTOM:
				self.promptsize = ((height*100) - (evtheight*100)) / height
				self.documenttuple = (self.documenttuple[0], evtheight)
				self.prompttuple = (self.prompttuple[0], height-evtheight)
		elif e == self.ID_PROMPT:
			self.promptsize = ((evtheight*100) / height)
			
		#Prompt Is Visible
		if self.promptsize == 0:
			self.promptsize = oldsize
			self.PromptIsVisible = False
		elif not self.PromptIsVisible and self.prompttuple[1] > 0:
			self.PromptIsVisible = True
					
		self.OnSize(None)		

	def OnSize(self, event):
		width, height = self.GetSizeTuple()		
		if (event is not None) and (width == self.oldwidth) and (height == self.oldheight):
			return
		self.oldwidth, self.oldheight = width, height
		
		if self.PromptIsVisible:
			heightDocument = (height * (100 - self.promptsize)) / 100
			heightPrompt = (height * self.promptsize) / 100
		else:
			heightDocument = height
			heightPrompt = 0
		
		#Tuples
		self.documenttuple = (width, heightDocument)
		self.prompttuple = (width, heightPrompt)	

		#Set Size then Move
		self.document.SetSize(self.documenttuple)
		self.documentpanel.SetSize(self.documenttuple)
		self.prompt.SetSize(self.prompttuple)

		self.document.Move((0,0))
		self.prompt.Move((0, heightDocument))
		
		#Size the document panel.
		self.documentpanel.OnSize(None)	
		
	def ShowPanel(self, Position, Index, Show):
		self.documentpanel.ShowPanel(Position, Index, Show)
		
	def TogglePanel(self, Position, Index):
		self.documentpanel.TogglePanel(Position, Index)
		
class drObject(wx.Object):
	def __init__(self):
		#wx.Object.__init__(self)
		pass
				
	def VariableExists(self, varname):
		try:
			eval("self." + varname)
		except:
			return False
		return True
		
#*******************************************************************************************************

class DrFrame(wx.Frame):
	def __init__(self, parent, id, title, fn = "", EditRecentFiles = 1, Prefs = None):

		wx.Frame.__init__(self, parent, id, title, wx.Point(0, 0), wx.Size(640, 480), name="DrPython")

		self.InitializeConstants()
				
		#Directories:
		if (not os.path.exists(self.homedirectory)):
			os.mkdir(self.homedirectory)
		if not os.path.exists(self.homedirectory + "/plugins"):
			os.mkdir(self.homedirectory + "/plugins")
		
		self.viewinpaneltarget = 0
				
		sys.path.append(self.homedirectory + "/plugins")
			
		self.lastprogargs = ""

		self.DrScript = drObject()
		self.DrPlugins = drObject()

		#Encoding
		self.defaultlocale = locale.getdefaultlocale()[1]
		if self.defaultlocale is None:
			self.defaultlocale = "ascii"

		#Sets all image handlers.  DrPython uses png, jpg, gif.
		wx.InitAllImageHandlers()

		if (not os.path.exists(self.bitmapdirectory)):
			self.ShowMessage(("Bitmap Directory (" + self.bitmapdirectory + ") Does Not Exist.\nThis is either a bug with DrPython,\n an error with your installation,\nor the bitmap directory was simply removed."), "DrPython Fatal Error")
			sys.exit(1)

		self.Printer = DrPrinter(self)

		self.breakpoints = []
		
		#Regex Line Endings:
		self.relewin = re.compile('\r\n', re.M)
		self.releunix = re.compile('\n', re.M)
		self.relemac = re.compile('\r', re.M)		
		
		self.refiletypeiscpp = re.compile("(\.c$)|(\.cc$)|(\.cpp$)|(\.cxx$)|(\.h$)|(\.hh$)|(\.hpp$)|(\.hxx$)", re.IGNORECASE)
		self.refiletypeishtml = re.compile("(\.htm$)|(\.html$)|(\.shtm$)|(\.shtml$)|(\.xml$)", re.IGNORECASE)
		self.refiletypeistxt = re.compile("(\.txt$)|(\.dat$)|(\.log$)", re.IGNORECASE)
		self.refiletypeispy = re.compile("(\.py$)|(\.pyw$)", re.IGNORECASE)
				
		self.FormatMacReTarget = re.compile('((?<!\r)\n)|(\r\n)', re.M)
		self.FormatUnixReTarget = re.compile('(\r\n)|(\r(?!\n))', re.M)
		self.FormatWinReTarget = re.compile('((?<!\r)\n)|(\r(?!\n))', re.M)
		
		#Find/Replace
		
		self.FindHistory = []
		self.ReplaceHistory = []
		
		self.FindInFilesHistory = []
		self.ReplaceInFilesHistory = []
		
		self.FindOptions = []
		self.ReplaceOptions = []
		
		#Used for current directory with open/save
		self.ddirectory = ""
		
		self.stcshortcutlist = drShortcutsFile.GetSTCShortcutList()
											
		#Preferences
		
		self.prefs = drPreferences(self.PLATFORM_IS_WIN, self.programdirectory)
				
		if Prefs is not None:
			self.prefs.Copy(Prefs)
		else:
			self.LoadPreferences()	
		
		WindowWidth = 640
		WindowHeight = 480
		if self.prefs.rememberwindowsizeandposition:
			if os.path.exists(self.homedirectory + '/drpython.sizeandposition.dat'):
				try:
					f = file(self.homedirectory + '/drpython.sizeandposition.dat', 'r')
					text = f.read()
					WindowWidth, WindowHeight, WindowX, WindowY = map(int, text.split('\n'))
					f.close()
					self.SetSize((WindowWidth, WindowHeight))
					self.Move(wx.Point(WindowX, WindowY))
				except:
					self.ShowMessage("Error Loading Window Size", 'Error')
									
		if (len(self.prefs.defaultdirectory) > 0):
			self.ddirectory = self.prefs.defaultdirectory
			try:
				os.chdir(self.ddirectory)
			except:
				self.ShowMessage('Error Changing to Default Directory: "%s"' % (self.ddirectory), 'Preferences Error')

		#Default position is for "General" preferences.
		self.prefdialogposition = 7

		icon = wx.EmptyIcon()
		icon.CopyFromBitmap(wx.BitmapFromImage(wx.Image((self.bitmapdirectory + "/drpython.png"), wx.BITMAP_TYPE_PNG)))
		self.SetIcon(icon)
		
		self.mdinotebook = drNotebook(self, -1, wx.DefaultPosition, wx.Size(WindowWidth, WindowHeight), wx.CLIP_CHILDREN)
			
		self.mdinotebook.AddPage(drPanel(self.mdinotebook, self.ID_APP), "Untitled 1")
		
		self.currentpage = self.mdinotebook.GetPage(0)
	
		self.txtDocument = DrText(self.currentpage.documentpanel.center, self.ID_DOCUMENT_BASE, self)
		self.txtPrompt = DrPrompt(self.currentpage.prompt, self.ID_PROMPT_BASE, self)
		self.txtDocument.SetTargetPosition(0)
		self.txtDocument.untitlednumber = 1
		
		self.mdinotebook.SetPageImage(0, 0)
		
		#Filenames
		self.txtDocument.filename = fn
		
		#Pop Up Menu
		
		self.popupmenulist = []
		
		self.LoadPopUpFile()
							
		self.Finder = drFinder(self)
					
		#Position in the Arrays Below:
		self.docPosition = 0
				
		#Arrays for MDI Support (Only Hold One Item if SDI):
		self.txtDocumentArray = [self.txtDocument]
		self.txtPromptArray = [self.txtPrompt]
		self.FinderArray = [self.Finder]
		self.lastprogargsArray = [self.lastprogargs]
		
		#Bind Page Changed Code:
			
		self.mdinotebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.mdinotebook.OnPageChanged)
	
		#Shortcuts
		
		self.STCShortcuts = []
		self.STCKeycodeArray = []
		self.STCShortcutsArgumentArray = drShortcuts.GetSTCCommandList()
		
		self.Shortcuts = []
		self.KeycodeArray = []
		self.ShortcutsIgnoreString = ""
		
		self.ShortcutsActionArray = []
		self.ShortcutsArgumentsArray = []
				
		#DrScript Shortcuts
		
		self.DrScriptShortcuts = []
		self.DrScriptKeycodeArray = []
		
		#Plugins
		self.LoadedPlugins = []
		
		self.PluginShortcutFunctionNames = []
		self.PluginShortcutFunctions = []
		
		self.PluginShortcuts = []
		self.PluginKeycodeArray = []
		self.PluginAction = []		
		
		self.PluginPopUpMenuNames = []
		self.PluginPopUpMenuLabels = []
		self.PluginPopUpMenuFunctions = []
				
		self.PluginToolBarLabels = []
		self.PluginToolBarIconFiles16 = []
		self.PluginToolBarIconFiles24 = []
		self.PluginToolBarFunctions = []
		
		self.STCUseDefault = 1
		self.ShortcutsUseDefault = 1
		
		#Load Shortcuts
		self.LoadShortcuts()
		
		#Shortcuts
		drShortcuts.SetSTCShortcuts(self.txtPrompt, self.STCShortcuts, self.STCUseDefault)
		self.STCKeycodeArray = drShortcuts.SetSTCShortcuts(self.txtDocument, self.STCShortcuts, self.STCUseDefault)
		self.KeycodeArray, self.ShortcutsActionArray, self.ShortcutsArgumentsArray = drShortcuts.SetShortcuts(self, self.Shortcuts, self.ShortcutsUseDefault)
			
		#Sizer
		self.bSizer = wx.BoxSizer(wx.VERTICAL)	
						
		self.windowArray = []
				
		self.recentfiles = []
		
		self.LoadRecentFiles()

		#Compile Regular Expressions for Open Import:
		self.reimport = re.compile('^\s*?import\s+?.*?$', re.M)
		self.refromimport = re.compile('^\s*?from\s+?.*?import.*?$', re.M)

		#edited by drpython
		if self.prefs.defaultdirectory == '':
			#add limodou 2004/04/17
			#if defaultdirectory is empty, then use the last recently file's dir
			if self.ddirectory == '' and len(self.recentfiles)>0:	
				self.ddirectory = os.path.dirname(self.recentfiles[0])
			#end limodou
							
		self.filemenu = wx.Menu()
		self.filemenu.Append(self.ID_NEW, "&New")
		self.filemenu.Append(self.ID_OPEN, "&Open...")
		self.filemenu.Append(self.ID_OPEN_IMPORTED_MODULE, "Open Imported Module...")
		self.recentmenu = wx.Menu()
		self.CreateRecentFileMenu()
		self.filemenu.AppendMenu(self.ID_OPEN_RECENT, "Open &Recent", self.recentmenu)
		self.filemenu.Append(self.ID_RELOAD, "&Reload File")
		self.filemenu.Append(self.ID_RESTORE_FROM_BACKUP, "&Restore From Backup")
		self.filemenu.AppendSeparator()
		self.filemenu.Append(self.ID_CLOSE, "&Close")
		self.filemenu.AppendSeparator()
		self.filemenu.Append(self.ID_CLEAR_RECENT, "Clear Recent File List")
		self.filemenu.AppendSeparator()
		self.filemenu.Append(self.ID_SAVE, "&Save")
		self.filemenu.Append(self.ID_SAVE_AS, "Save &As...")
		self.filemenu.Append(self.ID_SAVE_PROMPT, "Save Prompt Output To File...")
		self.filemenu.AppendSeparator()
		self.filemenu.Append(self.ID_PRINT_SETUP,"Print Setup...")
		self.filemenu.Append(self.ID_PRINT,"&Print File...")
		self.filemenu.Append(self.ID_PRINTPROMPT,"Print Prompt...")
		self.filemenu.AppendSeparator()
		self.filemenu.Append(self.ID_EXIT,"E&xit")

		self.commentmenu = wx.Menu()
		self.commentmenu.Append(self.ID_COMMENT_REGION, "&Comment")
		self.commentmenu.Append(self.ID_UNCOMMENT_REGION, "U&nComment")

		self.whitespacemenu = wx.Menu()		
		self.whitespacemenu.Append(self.ID_INDENT_REGION, "&Indent")
		self.whitespacemenu.Append(self.ID_DEDENT_REGION, "&Dedent")
		self.whitespacemenu.AppendSeparator()
		self.whitespacemenu.Append(self.ID_CHECK_INDENTATION, "Check Indentation Type...")
		self.whitespacemenu.Append(self.ID_CLEAN_UP_TABS, "Set Indentation To Tabs...")
		self.whitespacemenu.Append(self.ID_CLEAN_UP_SPACES, "Set Indentation To Spaces...")
		self.whitespacemenu.AppendSeparator()
		self.formatmenu = wx.Menu()
		self.formatmenu.Append(self.ID_UNIXMODE, "Unix Mode (\"\\n\")")
		self.formatmenu.Append(self.ID_WINMODE, "DOS/Windows Mode (\"\\r\\n\")")
		self.formatmenu.Append(self.ID_MACMODE, "Mac Mode (\"\\r\")")
		self.whitespacemenu.AppendMenu(self.ID_FORMATMENU, "Set Line Endings To", self.formatmenu)
				
		self.casemenu = wx.Menu()
		self.casemenu.Append(self.ID_UPPERCASE, "&Uppercase")
		self.casemenu.Append(self.ID_LOWERCASE, "&Lowercase")

		self.editmenu = wx.Menu()
		#franz:10_07
		self.editmenu.Append(self.ID_UNDO, "&Undo")
		self.editmenu.Append(self.ID_REDO, "R&edo")
		self.editmenu.AppendSeparator()
		#Order changed by drpython
		self.editmenu.Append(self.ID_CUT, "&Cut")
		self.editmenu.Append(self.ID_COPY, "&Copy")
		self.editmenu.Append(self.ID_PASTE, "&Paste")
		self.editmenu.Append(self.ID_DELETE, "&Delete")
		#end_franz:10_07
		self.editmenu.AppendSeparator()
		self.editmenu.Append(self.ID_SELECT_ALL, "&Select All")
		self.editmenu.AppendSeparator()
		self.editmenu.Append(self.ID_INSERT_REGEX, "&Insert Regular Expression...")
		self.editmenu.AppendSeparator()
		self.editmenu.Append(self.ID_FIND_AND_COMPLETE, "Find And Complete")
		self.editmenu.AppendSeparator()
		self.editmenu.AppendMenu(self.ID_COMMENT, "&Comments", self.commentmenu)
		self.editmenu.AppendMenu(self.ID_WHITESPACE, "&Whitespace", self.whitespacemenu)
		self.editmenu.AppendMenu(self.ID_CASE, "Case", self.casemenu)

		self.searchmenu = wx.Menu()
		self.searchmenu.Append(self.ID_FIND, "&Find...")
		self.searchmenu.Append(self.ID_FIND_NEXT, "Find &Next")
		self.searchmenu.Append(self.ID_FIND_PREVIOUS, "Find Previous")
		self.searchmenu.Append(self.ID_REPLACE, "&Replace...")
			
		self.foldmenu = wx.Menu()
		self.foldmenu.Append(self.ID_FOLD_ALL, "Fold All")
		self.foldmenu.Append(self.ID_EXPAND_ALL, "Expand All")

		self.highlightmenu = wx.Menu()
		self.highlightmenu.AppendRadioItem(self.ID_HIGHLIGHT_PYTHON, "Python")
		self.highlightmenu.AppendRadioItem(self.ID_HIGHLIGHT_CPP, "C/C++")
		self.highlightmenu.AppendRadioItem(self.ID_HIGHLIGHT_HTML, "HTML")
		self.highlightmenu.AppendRadioItem(self.ID_HIGHLIGHT_PLAIN_TEXT, "Plain Text")
		self.highlightmenu.Check(self.ID_HIGHLIGHT_PYTHON, True)
		
		self.viewinpanelmenu = wx.Menu()
		self.viewinpanelmenu.Append(self.ID_VIEW_IN_LEFT_PANEL, "View In Left Panel")
		self.viewinpanelmenu.Append(self.ID_VIEW_IN_RIGHT_PANEL, "View In Right Panel")
		self.viewinpanelmenu.Append(self.ID_VIEW_IN_TOP_PANEL, "View In Top Panel")
		self.viewinpanelmenu.Append(self.ID_VIEW_IN_BOTTOM_PANEL, "View In Bottom Panel")		
		
		self.viewmenu = wx.Menu()
		self.viewmenu.Append(self.ID_GOTO, "&Go To...")
		self.viewmenu.AppendSeparator()
		self.viewmenu.Append(self.ID_ZOOM_IN, "Zoom &In")
		self.viewmenu.Append(self.ID_ZOOM_OUT, "Zoom &Out")
		self.viewmenu.AppendSeparator()
		self.viewmenu.AppendMenu(self.ID_FOLDING, "&Folding", self.foldmenu)
		self.viewmenu.AppendSeparator()
		self.viewmenu.AppendMenu(self.ID_VIEW_IN_PANEL, "&View In Panel", self.viewinpanelmenu)
		self.viewmenu.AppendSeparator()
		self.viewmenu.AppendMenu(self.ID_HIGHLIGHT, "&Syntax Highlighting", self.highlightmenu)
		self.viewmenu.AppendSeparator()
		self.viewmenu.Append(self.ID_TOGGLE_SOURCEBROWSER, "Toggle &Source Browser...")
		self.viewmenu.AppendSeparator()
		#fix bug someone refered in forum limodou 2004/04/20
		self.viewmenu.Append(self.ID_TOGGLE_VIEWWHITESPACE, "Toggle View &Whitespace")
		#end limodou
		self.viewmenu.Append(self.ID_TOGGLE_PROMPT, "&Toggle Prompt")
		self.viewmenu.Append(self.ID_CLEAR_PROMPT, "C&lear Prompt")	
		
		self.programmenu = wx.Menu()
		self.programmenu.Append(self.ID_RUN, "&Run")
		self.programmenu.Append(self.ID_SET_ARGS, "Set &Arguments...")
		self.programmenu.Append(self.ID_PYTHON, "Open a Python &Interpreter")
		self.programmenu.Append(self.ID_END, "&End")
				
		self.bookmarksmenu = drBookmarksMenu(self)
		self.drscriptmenu = drScriptMenu(self)
		
		self.txtDocument.OnModified(None)
		
		#DrScript Shortcuts
		self.DrScriptShortcutsAction = self.drscriptmenu.OnScript
		
		self.pluginsconfiguremenu = drPluginConfigureMenu(self)
		self.pluginsindexmenu = drPluginIndexMenu(self)
		self.pluginsprefsmenu = drPluginPreferencesMenu(self)

		self.documentsmenu = wx.Menu()
		self.setupdocumentsmenu()
				
		self.optionsmenu = wx.Menu()
		self.optionsmenu.Append(self.ID_PREFS, "&Preferences...")
		self.optionsmenu.Append(self.ID_SHORTCUTS, "&Customize Shortcuts...")
		self.optionsmenu.Append(self.ID_POPUP, "&Customize Pop Up Menu...")
		self.optionsmenu.Append(self.ID_CUSTOMIZE_TOOLBAR, "&Customize ToolBar...")
		self.optionsmenu.AppendSeparator()		
		self.optionsmenu.Append(self.ID_EDIT_BOOKMARKS, "Edit Bookmarks...")
		self.optionsmenu.Append(self.ID_EDIT_SCRIPT_MENU, "&Edit Script Menu...")
		self.optionsmenu.AppendSeparator()
		self.optionsmenu.AppendMenu(self.ID_CONFIGURE_PLUGINS, "&Configure Plugins", self.pluginsconfiguremenu)
		self.optionsmenu.AppendMenu(self.ID_PLUGIN_PREFS, "Plugin Preferences", self.pluginsprefsmenu)
		self.optionsmenu.AppendMenu(self.ID_LOAD_PLUGIN, "&Load Plugin(s) From Index", self.pluginsindexmenu)
				
		self.pluginshelpmenu = drPluginHelpMenu(self)
		self.pluginsaboutmenu = drPluginAboutMenu(self)
				
		self.helpmenu = wx.Menu()
		self.helpmenu.Append(self.ID_ABOUT, "&About DrPython...")
		self.helpmenu.AppendMenu(self.ID_PLUGIN_ABOUT, "About Plugin", self.pluginsaboutmenu)
		self.helpmenu.AppendSeparator()
		self.helpmenu.Append(self.ID_HELP, "DrPython &Help...")
		self.helpmenu.AppendMenu(self.ID_PLUGIN_HELP, "Plugin Help", self.pluginshelpmenu)
		self.helpmenu.AppendSeparator()
		self.helpmenu.Append(self.ID_PYTHON_DOCS, "&Python Docs")
		self.helpmenu.Append(self.ID_WXWIDGETS_DOCS, "&WxWidgets Docs")
		self.helpmenu.Append(self.ID_REHOWTO_DOCS, "&Regular Expression Howto")

		self.menuBar = wx.MenuBar()
		self.menuBar.Append(self.filemenu,"&File")
		self.menuBar.Append(self.editmenu,"&Edit")
		self.menuBar.Append(self.searchmenu,"&Search")
		self.menuBar.Append(self.viewmenu,"&View")
		self.menuBar.Append(self.programmenu,"&Program")
		self.menuBar.Append(self.bookmarksmenu,"&Bookmarks")
		self.menuBar.Append(self.drscriptmenu,"&DrScript")
		self.menuBar.Append(self.documentsmenu, "&Documents")
		self.menuBar.Append(self.optionsmenu,"&Options")
		self.menuBar.Append(self.helpmenu,"&Help")
		
		self.SetMenuBar(self.menuBar)
		
		#ToolBar
		self.hasToolBar = False
		try:
			self.ToolBarList = drToolBarFile.getToolBarList(self.homedirectory)
		except:		
			self.ShowMessage(("Error Loading ToolBar List"), "DrPython Error")
			
		if (self.prefs.iconsize > 0):		
			self.hasToolBar = True
			self.toolbar = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_HORIZONTAL)

			self.ToolBarIdList = self.SetupToolBar()
			
			self.SetToolBar(self.toolbar)

		#Sizer
		
		self.bSizer.Add(self.mdinotebook, 1, wx.EXPAND)
		self.SetAutoLayout(True)
		self.SetSizer(self.bSizer)
			
		self.UpdateMenuAndToolbar()
			
		self.Bind(wx.EVT_MENU,  self.OnNew, id=self.ID_NEW)
		self.Bind(wx.EVT_MENU,  self.OnOpen, id=self.ID_OPEN)	
		self.Bind(wx.EVT_MENU,  self.OnOpenImportedModule, id=self.ID_OPEN_IMPORTED_MODULE)
				
		self.Bind(wx.EVT_MENU,  self.OnClose, id=self.ID_CLOSE)
		self.Bind(wx.EVT_MENU,  self.OnCloseAllDocuments, id=self.ID_CLOSE_ALL)
		self.Bind(wx.EVT_MENU,  self.OnCloseAllOtherDocuments, id=self.ID_CLOSE_ALL_OTHER_DOCUMENTS)
		
		self.Bind(wx.EVT_MENU,  self.OnReload, id=self.ID_RELOAD)
		self.Bind(wx.EVT_MENU,  self.OnRestoreFromBackup, id=self.ID_RESTORE_FROM_BACKUP)
		self.Bind(wx.EVT_MENU,  self.OnClearRecent, id=self.ID_CLEAR_RECENT)
		self.Bind(wx.EVT_MENU,  self.OnSave, id=self.ID_SAVE)
		self.Bind(wx.EVT_MENU,  self.OnSaveAs, id=self.ID_SAVE_AS)
		self.Bind(wx.EVT_MENU,  self.OnSaveAll, id=self.ID_SAVE_ALL)
		self.Bind(wx.EVT_MENU,  self.OnSavePrompt, id=self.ID_SAVE_PROMPT)
		self.Bind(wx.EVT_MENU,  self.OnPrintSetup, id=self.ID_PRINT_SETUP)
		self.Bind(wx.EVT_MENU,  self.OnPrint, id=self.ID_PRINT)
		self.Bind(wx.EVT_MENU,  self.OnPrintPrompt, id=self.ID_PRINTPROMPT)
		self.Bind(wx.EVT_MENU,  self.OnExit, id=self.ID_EXIT)
		
		self.Bind(wx.EVT_MENU,  self.OnMenuFind, id=self.ID_FIND)
		self.Bind(wx.EVT_MENU,  self.OnMenuFindNext, id=self.ID_FIND_NEXT)
		self.Bind(wx.EVT_MENU,  self.OnMenuFindPrevious, id=self.ID_FIND_PREVIOUS)
		self.Bind(wx.EVT_MENU,  self.OnMenuReplace, id=self.ID_REPLACE)
								
		self.Bind(wx.EVT_MENU,  self.OnInsertRegEx, id=self.ID_INSERT_REGEX)
		
		self.Bind(wx.EVT_MENU,  self.OnSelectAll, id=self.ID_SELECT_ALL)
		
		self.Bind(wx.EVT_MENU,  self.OnCommentRegion, id=self.ID_COMMENT_REGION)
		self.Bind(wx.EVT_MENU,  self.OnUnCommentRegion, id=self.ID_UNCOMMENT_REGION)
		
		self.Bind(wx.EVT_MENU,  self.OnIndentRegion, id=self.ID_INDENT_REGION)
		self.Bind(wx.EVT_MENU,  self.OnDedentRegion, id=self.ID_DEDENT_REGION)
		
		self.Bind(wx.EVT_MENU,  self.OnCheckIndentation, id=self.ID_CHECK_INDENTATION)
		self.Bind(wx.EVT_MENU,  self.OnCleanUpTabs, id=self.ID_CLEAN_UP_TABS)
		self.Bind(wx.EVT_MENU,  self.OnCleanUpSpaces, id=self.ID_CLEAN_UP_SPACES)
		
		self.Bind(wx.EVT_MENU,  self.OnFormatUnixMode, id=self.ID_UNIXMODE)
		self.Bind(wx.EVT_MENU,  self.OnFormatWinMode, id=self.ID_WINMODE)
		self.Bind(wx.EVT_MENU,  self.OnFormatMacMode, id=self.ID_MACMODE)
		
		self.Bind(wx.EVT_MENU,  self.OnFindAndComplete, id=self.ID_FIND_AND_COMPLETE)		
		
		self.Bind(wx.EVT_MENU,  self.OnUppercase, id=self.ID_UPPERCASE)
		self.Bind(wx.EVT_MENU,  self.OnLowercase, id=self.ID_LOWERCASE)
		self.Bind(wx.EVT_MENU,  self.OnUndo, id=self.ID_UNDO)
		self.Bind(wx.EVT_MENU,  self.OnRedo, id=self.ID_REDO)		
		
		self.Bind(wx.EVT_MENU,  self.OnGoTo, id=self.ID_GOTO)
		self.Bind(wx.EVT_MENU,  self.OnZoomIn, id=self.ID_ZOOM_IN)
		self.Bind(wx.EVT_MENU,  self.OnZoomOut, id=self.ID_ZOOM_OUT)
		
		self.Bind(wx.EVT_MENU,  self.OnSyntaxHighlightingPython, id=self.ID_HIGHLIGHT_PYTHON)
		self.Bind(wx.EVT_MENU,  self.OnSyntaxHighlightingCPP, id=self.ID_HIGHLIGHT_CPP)
		self.Bind(wx.EVT_MENU,  self.OnSyntaxHighlightingHTML, id=self.ID_HIGHLIGHT_HTML)
		self.Bind(wx.EVT_MENU,  self.OnSyntaxHighlightingText, id=self.ID_HIGHLIGHT_PLAIN_TEXT)
		
		self.Bind(wx.EVT_MENU,  self.OnFoldAll, id=self.ID_FOLD_ALL)
		self.Bind(wx.EVT_MENU,  self.OnExpandAll, id=self.ID_EXPAND_ALL)
		
		self.Bind(wx.EVT_MENU,  self.OnViewInLeftPanel, id=self.ID_VIEW_IN_LEFT_PANEL)
		self.Bind(wx.EVT_MENU,  self.OnViewInRightPanel, id=self.ID_VIEW_IN_RIGHT_PANEL)
		self.Bind(wx.EVT_MENU,  self.OnViewInTopPanel, id=self.ID_VIEW_IN_TOP_PANEL)
		self.Bind(wx.EVT_MENU,  self.OnViewInBottomPanel, id=self.ID_VIEW_IN_BOTTOM_PANEL)
		
		self.Bind(wx.EVT_MENU,  self.OnToggleSourceBrowser, id=self.ID_TOGGLE_SOURCEBROWSER)
		self.Bind(wx.EVT_MENU,  self.OnToggleViewWhiteSpace, id=self.ID_TOGGLE_VIEWWHITESPACE)		
		self.Bind(wx.EVT_MENU,  self.OnTogglePrompt, id=self.ID_TOGGLE_PROMPT)
		self.Bind(wx.EVT_MENU,  self.OnClearPrompt, id=self.ID_CLEAR_PROMPT)
		
		self.Bind(wx.EVT_MENU,  self.OnRun, id=self.ID_RUN)
		self.Bind(wx.EVT_MENU,  self.OnSetArgs, id=self.ID_SET_ARGS)
		self.Bind(wx.EVT_MENU,  self.OnPython, id=self.ID_PYTHON)
		self.Bind(wx.EVT_MENU,  self.OnEnd, id=self.ID_END)

		self.Bind(wx.EVT_MENU,  self.OnPrefs, id=self.ID_PREFS)
		self.Bind(wx.EVT_MENU,  self.OnCustomizeShortcuts, id=self.ID_SHORTCUTS)
		self.Bind(wx.EVT_MENU,  self.OnCustomizePopUpMenu, id=self.ID_POPUP)
		self.Bind(wx.EVT_MENU,  self.OnCustomizeToolBar, id=self.ID_CUSTOMIZE_TOOLBAR)		
		self.Bind(wx.EVT_MENU,  self.OnEditBookmarks, id=self.ID_EDIT_BOOKMARKS)		
		self.Bind(wx.EVT_MENU,  self.OnEditScriptMenu, id=self.ID_EDIT_SCRIPT_MENU)
				
		self.Bind(wx.EVT_MENU,  self.OnViewAbout, id=self.ID_ABOUT)
		self.Bind(wx.EVT_MENU,  self.OnViewHelp, id=self.ID_HELP)
		self.Bind(wx.EVT_MENU,  self.OnViewPythonDocs, id=self.ID_PYTHON_DOCS)
		self.Bind(wx.EVT_MENU,  self.OnViewWxWidgetsDocs, id=self.ID_WXWIDGETS_DOCS)
		self.Bind(wx.EVT_MENU,  self.OnViewREHowtoDocs, id=self.ID_REHOWTO_DOCS)		
		
		self.Bind(wx.EVT_MENU, self.DoBuiltIn, id=self.ID_COPY)		
		self.Bind(wx.EVT_MENU, self.DoBuiltIn, id=self.ID_PASTE)
		self.Bind(wx.EVT_MENU, self.DoBuiltIn, id=self.ID_CUT)
		self.Bind(wx.EVT_MENU, self.DoBuiltIn, id=self.ID_DELETE)
		
		self.Bind(wx.EVT_MENU, self.OnSelectDocumentNext, id=self.ID_NEXT_DOCUMENT)
		self.Bind(wx.EVT_MENU, self.OnSelectDocumentPrevious, id=self.ID_PREVIOUS_DOCUMENT)
		self.Bind(wx.EVT_MENU, self.OnSelectDocumentFirst, id=self.ID_FIRST_DOCUMENT)
		self.Bind(wx.EVT_MENU, self.OnSelectDocumentLast, id=self.ID_LAST_DOCUMENT)		
		
		self.CreateStatusBar()

		self.GetStatusBar().SetFieldsCount(3)
		#First field is hidden, to absorb wxMenuHighlight events from the menu and toolbar.
		self.GetStatusBar().SetStatusWidths([-0, -6, -4])

		if self.prefs.eolmode == 1:
			eolmodestr = "WIN"
		elif self.prefs.eolmode == 2:
			eolmodestr = "MAC"
		else:
			eolmodestr = "UNIX"
		if self.txtDocument.GetOvertype():
			ovrstring = "OVR"
		else:
			ovrstring = "INS"				

		self.txtDocument.SetupPrefsDocument()

		self.txtDocument.SetFocus()
		
		self.txtDocument.OnPositionChanged(None)
		
		self.txtPrompt.SetReadOnly(1)
		
		self.txtPrompt.SetupPrefsPrompt()
						
		#Arguments To Program
		if (len(sys.argv) > 1) and (len(self.txtDocument.filename) == 0):
			f = sys.argv[1]
			if self.PLATFORM_IS_WIN:
				f = f.replace("\\", "/")
			if os.path.exists(f):	
				self.DestroyRecentFileMenu()
				self.OpenFile(f, False)
				self.txtDocument.OnModified(None)
				x = 2
				l = len(sys.argv)
				while x < l:
					f = sys.argv[x]
					if self.PLATFORM_IS_WIN:
						f = f.replace("\\", "/")
					self.OpenFile(f, True)
					self.txtDocument.OnModified(None)
					x = x + 1			
				self.CreateRecentFileMenu()
			else:
				self.ShowMessage('"' + f + '" Does not exist.', 'File Open Error')
		#Argument to DrFrame.
		elif (len(self.txtDocument.filename) > 0):
			#Make sure the path is absolute
			self.txtDocument.filename = os.path.abspath(self.txtDocument.filename)
			#Convert Filename to correct format. (Only needed when called from the command line)
			#When called from function, already converted.
			if self.PLATFORM_IS_WIN:
				self.txtDocument.filename = self.txtDocument.filename.replace("\\", "/")
			if os.path.exists(self.txtDocument.filename):
				self.DestroyRecentFileMenu()
				self.OpenFile(self.txtDocument.filename, False, EditRecentFiles)
				self.CreateRecentFileMenu()
			else:
				self.ShowMessage('"' + self.txtDocument.filename + '" Does not exist.', 'File Open Error')
				self.txtDocument.filename = ''
		
		#Load SourceBrowser:
		if self.prefs.sourcebrowserisvisible:
			self.ShowSourceBrowser()
			
		self.Bind(wx.EVT_END_PROCESS,  self.OnProcessEnded, id=-1)	
			
		self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
		self.Bind(wx.EVT_CLOSE, self.OnCloseW)
		
		self.LoadPlugins()

	def AddKeyEvent(self, function, Keycode, Control=0, Shift=0, Alt=0, Meta=0):
		if Keycode == -1:
			return
	
		d = drShortcuts.drShortcut()
		
		d.Name = "Plugin"
		d.Control = Control
		d.Shift = Shift
		d.Meta = Meta
		d.Alt = Alt
		d.Keycode = str(Keycode)
		self.PluginShortcuts.append(d)
		self.PluginKeycodeArray.append(d.Keycode)
		self.PluginAction.append(function)

	def AddPluginFunction(self, plugin, label, function):
		self.PluginShortcutFunctionNames.append(plugin + ":" + label)
		self.PluginShortcutFunctions.append(function)
		
		self.PluginPopUpMenuNames.append(plugin)
		self.PluginPopUpMenuLabels.append(label)
		self.PluginPopUpMenuFunctions.append(function)
		
		self.PluginToolBarLabels.append("<Plugin>:"+label)
		self.PluginToolBarFunctions.append(function)

	def AddPluginIcon(self, name, location16, location24):
		ctbfile = self.homedirectory + "/toolbar.custom.icons.dat"
		if not os.path.exists(ctbfile):
			f = file(ctbfile, 'w')
			f.write('\n')
			f.close()
		f = file(ctbfile, 'r')
		lines = f.read().split('\n')
		f.close()
		name = "<Plugin>:" + name
		f = file(self.homedirectory + "/toolbar.custom.icons.dat", 'w')
		for line in lines:
			if len(line) > 0:
				currentname = drPrefsFile.ExtractPreferenceFromText(line, "Name")
				if currentname != name:
					f.write(line + '\n')
		f.write("<Name>" + name + "</Name><16>" + location16 + "</16><24>" + \
		location24 + "</24>\n")
		f.close()

	def AddPluginShortcutFunction(self, plugin, label, function):
		self.PluginShortcutFunctionNames.append(plugin + ":" + label)
		self.PluginShortcutFunctions.append(function)

	def AddPluginPopUpMenuFunction(self, plugin, label, function):
		self.PluginPopUpMenuNames.append(plugin)
		self.PluginPopUpMenuLabels.append(label)
		self.PluginPopUpMenuFunctions.append(function)
	
	def AddPluginToolBarFunction(self, label, function):
		self.PluginToolBarLabels.append("<Plugin>:"+label)
		self.PluginToolBarFunctions.append(function)
	
	def checkiffileisCPP(self, filename):
		return self.refiletypeiscpp.search(filename) is not None
				
	def checkiffileisHTML(self, filename):
		return self.refiletypeishtml.search(filename) is not None
		
	def checkiffileisPlainText(self, filename):
		return self.refiletypeistxt.search(filename) is not None
	
	def checkiffileisPython(self, filename):
		return self.refiletypeispy.search(filename) is not None
			
	def CreateRecentFileMenu(self):
		x = 0
		numfiles = len(self.recentfiles)
		while (x < numfiles):
			self.recentmenu.Append(self.ID_RECENT_FILES_BASE+x, self.recentfiles[x], ("Open " + self.recentfiles[x]))
			self.Bind(wx.EVT_MENU,  self.OnOpenRecentFile, id=self.ID_RECENT_FILES_BASE+x)
			x = x + 1
	
	def DestroyDocument(self):	
		self.txtDocumentArray.pop(self.docPosition)
		self.txtPromptArray.pop(self.docPosition)	
		self.FinderArray.pop(self.docPosition)
		self.lastprogargsArray.pop(self.docPosition)
	
	def DestroyRecentFileMenu(self):
		#You need to call this function BEFORE you update the list of recent files.
		x = 0
		mnuitems = self.recentmenu.GetMenuItems()
		num = len(mnuitems)
		while (x < num):
			self.recentmenu.Remove(self.ID_RECENT_FILES_BASE+x)
			#mnuitems[x].Destroy()
			x = x + 1
			
	def DestroyToolBar(self):
		if self.toolbar is not None:
			x = 0
			toolbarsize = len(self.ToolBarIdList)
			while (x < toolbarsize):
				if self.ToolBarIdList[x] == -300:
					self.toolbar.DeleteToolByPos(0)
				else:
					self.toolbar.DeleteTool(self.ToolBarIdList[x])
				x = x + 1
			self.toolbar.Destroy()
			self.toolbar = None
	
	def DoBuiltIn(self, event):
		objid = event.GetId()
			
		if objid == self.ID_COPY:
			self.txtDocument.CmdKeyExecute(wx.stc.STC_CMD_COPY)
		elif objid == self.ID_PASTE:
			self.txtDocument.CmdKeyExecute(wx.stc.STC_CMD_PASTE)
		elif objid == self.ID_CUT:
			self.txtDocument.CmdKeyExecute(wx.stc.STC_CMD_CUT)
		elif objid == self.ID_DELETE:
			self.txtDocument.CmdKeyExecute(wx.stc.STC_CMD_CLEAR)
	
	def dynamicdrscript(self, event):
		self.drscriptmenu.OnDynamicScript(event)
	
	def Execute(self, command, statustext = ""):
		if len(statustext) < 1:
			statustext = "Running Command"
		self.runcommand(command, statustext)
		
	def ExecutePython(self, command = "", statustext = ""):
		if len(statustext) < 1:
			statustext = "Running Python Interpreter"
		self.txtPrompt.pythonintepreter = 1
		if len(command) > 0:
			command = " " + command
		if self.PLATFORM_IS_WIN:
			self.runcommand((self.pythexecw + " -u " + self.prefs.pythonargs + command), "Running Python Interpreter")
		else:
			self.runcommand((self.pythexec + " -u " + self.prefs.pythonargs + command), "Running Python Interpreter")
	
	def GetFileName(self):
		return self.txtDocument.filename
	
	def GetNewId(self):		
		return 10000 + wx.NewId()	
	
	def GetPluginDirectory(self):
		return self.homedirectory + "/plugins"
	
	def GetPluginLabels(self, filename, doNotAppend = False):
		try:
			f = file(filename, 'r')
			text = f.read()
			f.close()
		except:
			self.ShowMessage('File error with: "' + filename + '".', "ERROR")
			return []
		
		rePopUpMenu = re.compile(r'^\s*?DrFrame\.AddPluginFunction\(.*\)', re.MULTILINE)
			
		allPopUps = rePopUpMenu.findall(text)
	
		PopUpArray = []
				
		for s in allPopUps:
			#From the Left most '('
			start = s.find('(')
			#To the Right most ')'
			end = s.rfind(')')	
			
			if (start > -1) and (end > -1):
				s = s[start+1:end]
				i = s.find(',')
				e = i + 1 + s[i+1:].find(',')
				arglabel = s[i+1:e].strip().strip('"')
				if doNotAppend:
					PopUpArray.append(arglabel)
				else:
					PopUpArray.append("<Plugin>:"+arglabel)
				
		return PopUpArray	
	
	def InitializeConstants(self):
		#Constant messages for file format checking.
		self.FFMESSAGE = ["Unix Mode ('\\n')", "DOS/Windows Mode ('\\r\\n')", "Mac Mode ('\\r')"]
		
		self.ID_DOCUMENT_BASE = 50
		self.ID_PROMPT_BASE = 340
		
		#Application ID Constants
		self.ID_APP = 101
		self.ID_NEW = 102
		self.ID_OPEN = 103
		self.ID_OPEN_IMPORTED_MODULE = 1000
		self.ID_OPEN_RECENT = 104
		self.ID_RELOAD = 105
		self.ID_RESTORE_FROM_BACKUP = 1051
		self.ID_CLOSE = 106
		self.ID_CLOSE_ALL = 6061
		self.ID_CLOSE_ALL_OTHER_DOCUMENTS = 6062
		self.ID_CLEAR_RECENT = 107
		self.ID_SAVE = 108
		self.ID_SAVE_AS = 109
		self.ID_SAVE_ALL = 1098
		self.ID_SAVE_PROMPT = 1091
		self.ID_PRINT_SETUP = 1010
		self.ID_PRINT = 1011
		self.ID_PRINTPROMPT = 1012
		self.ID_EXIT = 1014
				
		self.ID_NEXT_DOCUMENT = 801
		self.ID_PREVIOUS_DOCUMENT = 802
		self.ID_FIRST_DOCUMENT = 803
		self.ID_LAST_DOCUMENT = 804
		self.ID_DOCUMENT_NAVIGATION_MENU = 810
		self.ID_DOCUMENTS_BASE = 8000
		self.ID_DOCUMENTS_MENU_BASE = 7950
		
		self.ID_COPY = 850		
		self.ID_PASTE = 851	
		self.ID_CUT = 852	
		self.ID_DELETE = 853
				
		self.ID_FIND = 111
		self.ID_FIND_NEXT = 112
		self.ID_FIND_PREVIOUS = 1122
		self.ID_REPLACE = 113
		self.ID_GOTO = 115
		self.ID_SELECT_ALL = 1150
		
		self.ID_INSERT_REGEX = 1153
		
		self.ID_COMMENT = 1116
		self.ID_COMMENT_REGION = 116
		self.ID_UNCOMMENT_REGION = 117
		
		self.ID_WHITESPACE = 1118
		self.ID_INDENT_REGION = 118
		self.ID_DEDENT_REGION = 119
		self.ID_CHECK_INDENTATION = 1650
				
		self.ID_CLEAN_UP_TABS = 1670
		self.ID_CLEAN_UP_SPACES = 1671
				
		self.ID_FORMATMENU = 2000
		self.ID_UNIXMODE = 2001
		self.ID_WINMODE = 2002
		self.ID_MACMODE = 2003
				
		self.ID_FIND_AND_COMPLETE = 2071
		
		self.ID_CASE = 1191
		self.ID_UPPERCASE = 1192
		self.ID_LOWERCASE = 1193
		
		self.ID_UNDO = 1111
		self.ID_REDO = 1112
		
		self.ID_ZOOM_IN = 161
		self.ID_ZOOM_OUT = 162
		self.ID_FOLDING = 1600
		self.ID_FOLD_ALL = 1601
		self.ID_EXPAND_ALL = 1602
		self.ID_TOGGLE_SOURCEBROWSER = 163
		self.ID_TOGGLE_VIEWWHITESPACE = 164
		self.ID_TOGGLE_PROMPT = 165
		self.ID_CLEAR_PROMPT = 166
		
		self.ID_VIEW_IN_PANEL = 170
		self.ID_VIEW_IN_LEFT_PANEL = 171
		self.ID_VIEW_IN_RIGHT_PANEL = 172
		self.ID_VIEW_IN_TOP_PANEL = 173
		self.ID_VIEW_IN_BOTTOM_PANEL = 174
		
		self.ID_VIEW_IN_PANEL_BASE = 1700
		
		self.ID_HIGHLIGHT = 580
		
		self.ID_HIGHLIGHT_PYTHON = 585
		self.ID_HIGHLIGHT_CPP = 586
		self.ID_HIGHLIGHT_HTML = 587
		self.ID_HIGHLIGHT_PLAIN_TEXT = 589
		
		self.ID_RUN = 121
		self.ID_SET_ARGS = 122
		self.ID_PYTHON = 123
		self.ID_END = 125
		
		self.ID_PREFS = 131
		self.ID_SHORTCUTS = 133
		self.ID_POPUP = 134
		self.ID_CUSTOMIZE_TOOLBAR = 135
		
		self.ID_CONFIGURE_PLUGINS = 4005
		self.ID_LOAD_PLUGIN = 4050		
		self.ID_PLUGIN_HELP = 4051
		self.ID_PLUGIN_PREFS = 4052
		self.ID_PLUGIN_ABOUT = 4053
				
		self.ID_EDIT_BOOKMARKS = 301
		self.ID_EDIT_SCRIPT_MENU = 3004
				
		self.ID_ABOUT = 140
		self.ID_HELP = 141
		self.ID_PYTHON_DOCS = 142
		self.ID_WXWIDGETS_DOCS = 143
		self.ID_REHOWTO_DOCS = 144
		
		self.ID_OTHER = 9000
		
		self.ID_RECENT_FILES_BASE = 9930
		
		self.ID_RECENT_SESSIONS_BASE = 8330
		
		self.ID_SCRIPT_BASE = 7500
						
		#System constants
		
		self.PLATFORM_IS_WIN = (sys.platform == "win32")
		#If homedirectory does not work correctly on your self.PLATFORM,
		#comment it out, and set the variable to your homedirectory.
		#Just in case you don't check this code, and
		#homedirectory does not work, drpython will plop
		#its stuff in your root directory.
		self.homedirectory = os.path.expanduser("~")
		if (not os.path.exists(self.homedirectory)):
			if self.PLATFORM_IS_WIN:
				try:
					self.homedirectory = os.environ["APPDATA"].replace("\\", "/")
				except:
					self.homedirectory = "c:"
			else:
				self.homedirectory = "/"
		elif self.PLATFORM_IS_WIN:
			self.homedirectory = self.homedirectory.replace("\\", "/")
				
		self.userhomedirectory = self.homedirectory
		
		if self.PLATFORM_IS_WIN:
			self.homedirectory = self.homedirectory + "/drpython"
		else:
			self.homedirectory = self.homedirectory + "/.drpython"
		
		if self.PLATFORM_IS_WIN:
			self.pythexec = sys.prefix.replace("\\", "/") + "/python.exe"
			self.pythexecw = sys.prefix.replace("\\", "/") + "/pythonw.exe"
		else:
			self.pythexec = sys.executable
				
		#Thanks to Mark Rees.
		#Thanks to Guillermo Fernandez.
		#Thanks Bjorn Breid
		self.programdirectory = '/usr/share/drpython'
		self.bitmapdirectory = self.programdirectory + "/bitmaps"

	def InitializePlugin(self, plugin, ShowDialog = True):
		#Check to see if the plugin is already loaded:
		if plugin in self.LoadedPlugins:
			if ShowDialog:
				self.ShowMessage(('"' + plugin + '" has already been loaded.\nDrPython will not reload this plugin.'), "Plugin Already Loaded")
			return
		
		#Load the Plugin
		pluginfile = self.homedirectory + "/plugins/" + plugin + ".py"
		self.LoadedPlugins.append(plugin)
		try:
			exec(compile("import " + plugin, pluginfile, 'exec'))
			exec(compile(plugin + ".Plugin(self)", pluginfile, 'exec'))
		except:
			self.ShowMessage(("Error with: " + plugin + "\nDrPython will not load this plugin."), "Plugin Error")
		
		#Menus
		self.pluginsaboutmenu.AddItem(plugin)
		self.pluginshelpmenu.AddItem(plugin)
		self.pluginsprefsmenu.AddItem(plugin)
			
		#Shortcuts:
		shortcutfile = self.homedirectory + "/plugins/" + plugin + ".shortcuts.dat"
		if not os.path.exists(shortcutfile):
			return
		try:
			shortcuts, keycodes, ignorestring = drShortcutsFile.ReadShortcuts(shortcutfile, 0)
			for shortcut in shortcuts:
				try:
					i = self.PluginShortcutFunctionNames.index(plugin + ":" + shortcut.Name)
					self.PluginAction.append(self.PluginShortcutFunctions[i])
					shortcut.Name = "Plugin"
					self.PluginShortcuts.append(shortcut)
					self.PluginKeycodeArray.append(shortcut.Keycode)
				except:
					pass
		except:
			self.ShowMessage(("Error with: " + plugin + "\nDrPython will not load shortcuts for this plugin."), "Plugin Shortcuts Error")
		
	def isvalidbreakpoint(self, text):
		if (len(text) <= 0):
			return False
		elif (text.isspace()):
			return False
		else:
			ind = text.find('#')
			if not (ind == -1):
				if (text[:ind].isspace()):
					return False
				elif (ind == 0):
					return False
		return True		
	
	def LoadDialogSizeAndPosition(self, dialog, dialogfile):
		if self.prefs.rememberdialogsizesandpositions:
			try:
				if os.path.exists(self.homedirectory + '/' + dialogfile):
					f = file(self.homedirectory + '/' + dialogfile, 'r')
					text = f.read()
					x, y, px, py = map(int, text.split('\n'))
					f.close()
					dialog.SetSize((x, y))
					dialog.Move(wx.Point(px, py))
			except:
				drScrolledMessageDialog.ShowMessage(dialog, "Error Loading Dialog Size", 'Error')
		dialog.Bind(wx.EVT_CLOSE, dialog.OnCloseW)
	
	def LoadPlugins(self, plugins_file = ""):
		if len(plugins_file) > 0:
			pluginsfile = plugins_file
		else:
			pluginsfile = self.homedirectory + "/plugins/default.idx"
		if os.path.exists(pluginsfile):
			try:
				f = file(pluginsfile, 'r')
				pluginstoload = f.read().rstrip().split('\n')
				f.close()
								
				for plugin in pluginstoload:
					if len(plugin) > 0:
						self.InitializePlugin(plugin)					
			except:
				self.ShowMessage(("Error with: " + pluginsfile + "\nDrPython will not load plugins."), "Plugins Error")
		else:
			try:
				f = file(pluginsfile, 'wb')
				f.write('\n')
				f.close()				
			except:
				self.ShowMessage('Error Ceating Default Index for Plugins.\n\nPlugins may not work correctly.', 'Plugins Error')
	
	def LoadPopUpFile(self):
		#check for preferences file in user homedirectory
		if os.path.exists(self.homedirectory + "/popupmenu.dat"):
			popupfile = self.homedirectory + "/popupmenu.dat"
			try:
				f = file(popupfile, 'r')
				line = f.readline()
				while len(line) > 0:
					self.popupmenulist.append(line.rstrip())
					line = f.readline()
				f.close()
			except:
				self.ShowMessage(("Error with: " + popupfile + "\nDrPython will use the program defaults."), "Pop Up Menu Error")
				
	def LoadPreferences(self, UseDefault = False):
		#check for preferences file in user homedirectory
		if (os.path.exists(self.homedirectory + "/preferences.dat")) and (not UseDefault):
			f = self.homedirectory + "/preferences.dat"
			try:
				drPrefsFile.ReadPreferences(self.prefs, f)
			except:
				self.ShowMessage(("Error with: " + f + "\nDrPython will load the program defaults."), "Preferences Error")
				self.LoadPreferences(True)
		else:
			self.prefs.reset()
				
	def LoadRecentFiles(self):
		f = self.homedirectory + "/recent_files.log"
		if (not os.path.exists(f)):
			try:
				t = open(f, 'w')
				t.close()
			except IOError:
				self.ShowMessage(("Error Creating: " + f), "Recent Files Error")
		try:
			fin = open(f, 'r')
			s = fin.readline()
			x = 0
			while (len(s) > 0) and (x < self.prefs.recentfileslimit):
				s = s.rstrip()
				if (len(s) > 0):
					self.recentfiles.append(s)
				x = x + 1
				s = fin.readline()
			fin.close()
		except IOError:
			self.ShowMessage(("Error Reading: " + f), "Recent Files Error")
	
	def LoadShortcuts(self, UseDefault = False):
		#Load STC Shortcuts
		if (os.path.exists(self.homedirectory + "/stcshortcuts.dat")) and (not UseDefault):
			f = self.homedirectory + "/stcshortcuts.dat"
			try:
				self.STCShortcuts, self.STCKeycodeArray, t = drShortcutsFile.ReadSTCShortcuts(f)
				self.STCUseDefault = 0
			except:
				self.ShowMessage(("Error with: " + f + "\nDrPython will not load DrScript shortcuts."), "DrScript Shortcuts Error")
		else:
			self.STCShortcuts, self.STCKeycodeArray = drShortcutsFile.GetDefaultSTCShortcuts()
		
		#check for shortcuts file in user homedirectory
		if (os.path.exists(self.homedirectory + "/shortcuts.dat")) and (not UseDefault):
			f = self.homedirectory + "/shortcuts.dat"
			try:
				self.Shortcuts, self.KeycodeArray, self.ShortcutsIgnoreString = drShortcutsFile.ReadShortcuts(f)
				self.ShortcutsUseDefault = 0
			except:	
				self.ShowMessage(("Error with: " + f + "\nDrPython will load the program defaults."), "Shortcuts Error")
				self.LoadShortcuts(True)
		else:
			self.Shortcuts, self.KeycodeArray, self.ShortcutsIgnoreString = drShortcutsFile.GetDefaultShortcuts()
			
		#Load DrScript Shortcuts
		if (os.path.exists(self.homedirectory + "/drscript.shortcuts.dat")) and (not UseDefault):
			f = self.homedirectory + "/drscript.shortcuts.dat"
			try:
				self.DrScriptShortcuts, self.DrScriptKeycodeArray, t = drShortcutsFile.ReadShortcuts(f, 0)
			except:
				self.ShowMessage(("Error with: " + f + "\nDrPython will not load DrScript shortcuts."), "DrScript Shortcuts Error")
	
	def NewWindow(self):
		frame = DrFrame(None, 101, "DrPython - Untitled 1")	
		
		frame.Show(True)
	
	def OnActivate(self):
		if self.prefs.docautoreload:
			x = 0
			for Document in self.txtDocumentArray:
				if len(Document.filename) > 0:
					#Get Stat Info:
					current_mtime = int(os.stat(Document.filename).st_mtime)
					
					#Check Stat Info:
					if Document.mtime > -1:
						if current_mtime != Document.mtime:
							d = wx.MessageDialog(self, '"%s" has been modified by an outside source.  Would you like to reload?' % (Document.filename), "Reload File?", wx.YES_NO | wx.ICON_QUESTION)
							answer = d.ShowModal()
							d.Destroy()
							if (answer == wx.ID_YES):
								self.setDocumentTo(x)
								self.OpenFile(Document.filename, False)
							else:
								Document.mtime = current_mtime
				x += 1
				
	def OnCheckIndentation(self, event):
		wx.BeginBusyCursor()
		result = self.txtDocument.CheckIndentation()
		if result == 2:
			msg = "No indentation was found in this document."
		elif result == -1:
			msg = "This document uses spaces for indentation."
		elif result == 1:
			msg = "This document uses tabs for indentation."
		elif result == 0:
			msg = "This document is mixed.  It uses tabs and spaces for indentation."
		wx.EndBusyCursor()
		self.ShowMessage(msg, "Check Indentation Results")
	
	def OnCleanUpSpaces(self, event):
		d = wx.TextEntryDialog(self, "Replace a tab with how many spaces?:", "Replace Tabs With Spaces", str(self.prefs.tabwidth))
		answer = d.ShowModal()
		value = d.GetValue()
		d.Destroy()
		eol = self.txtDocument.GetEndOfLineCharacter()
		regex = re.compile('(\S)|' + eol)
		if answer == wx.ID_OK:
			wx.BeginBusyCursor()
			wx.Yield()
			try:
				x = int(value)
			except:					
				self.ShowMessage("You must enter an integer (number, eg 1,2,128)", "DrPython")
				wx.EndBusyCursor()	
				return
			if (x > -1) and (x <= 128):
				text = self.txtDocument.GetText()
				lines = text.split(eol)
				new_lines = []
				for line in lines:
					result = regex.search(line + eol)
					if result is not None:
						end = result.start()
						new_lines.append(line[0:end].expandtabs(x) + line[end:])
					else:
						new_lines.append(line)
				newtext = string.join(new_lines, eol)
				self.txtDocument.SetText(newtext)
			else:
				self.ShowMessage("That number seems WAY too high.  Just what are you doing, replacing  a tab with more than 128 spaces?", "DrPython Foolish Error")
				wx.EndBusyCursor()	
				return
			self.txtDocument.OnModified(None)
			wx.EndBusyCursor()			

	def OnCleanUpTabs(self, event):
		d = wx.TextEntryDialog(self, "Number of spaces to replace with a tab:", "Replace Spaces With Tabs", str(self.prefs.tabwidth))
		answer = d.ShowModal()
		value = d.GetValue()
		d.Destroy()
		eol = self.txtDocument.GetEndOfLineCharacter()
		regex = re.compile('(\S)|' + eol)
		if answer == wx.ID_OK:
			wx.BeginBusyCursor()		
			wx.Yield()
			try:
				x = int(value) - 1
			except:					
				self.ShowMessage("You must enter an integer (number, eg 1,2,128)", "DrPython")
				wx.EndBusyCursor()
				return
			if (x > -1) and (x <= 128):
				#Create Target String
				y = 0
				oof = " "
				while (y < x):
					oof = oof + " "
					y = y + 1
				#Continue
				text = self.txtDocument.GetText()
				lines = text.split(eol)
				new_lines = []
				for line in lines:
					result = regex.search(line + eol)
					if result is not None:
						end = result.start()
						newline = line[0:end].replace(oof, "\t") + line[end:]
						newline = newline.replace(' ', '')
						new_lines.append(newline)
					else:
						new_lines.append(line)
				newtext = string.join(new_lines, eol)
				self.txtDocument.SetText(newtext)
			else:	
				self.ShowMessage("That number seems WAY too high.  Just what are you doing, replacing more than 128 spaces with a tab?", "DrPython Foolish Error")
				wx.EndBusyCursor()
				return			
			self.txtDocument.OnModified(None)	
			wx.EndBusyCursor()

	def OnClearPrompt(self, event):
		d = wx.MessageDialog(self, "This will clear all text from the prompt.\nAre you sure you want to do this?", "DrPython", wx.YES_NO | wx.ICON_QUESTION)
		answer = d.ShowModal()
		d.Destroy()
		if (answer == wx.ID_YES):
			iii = self.txtPrompt.GetReadOnly()
			self.txtPrompt.SetReadOnly(0)
			self.txtPrompt.editpoint = 0
			self.txtPrompt.writeposition = 0
			self.txtPrompt.ClearAll()
			self.txtPrompt.SetReadOnly(iii)							

	def OnClearRecent(self, event):
		d = wx.MessageDialog(self, "This will clear all recent files.\nAre you sure you want to do this?", "DrPython", wx.YES_NO | wx.ICON_QUESTION)
		answer = d.ShowModal()
		d.Destroy()
		if (answer == wx.ID_YES):
			self.recentfiles = []
			self.DestroyRecentFileMenu()
			self.WriteRecentFiles()

	def OnClose(self, event):
		if (self.txtDocument.GetModify()):
			#prompt saving filename limodou 2004/04/19
			d = wx.MessageDialog(self, 'Would you like to save "%s"?' % self.txtDocument.GetFilename(), "DrPython", wx.YES_NO | wx.CANCEL | wx.ICON_QUESTION)
			#end limodou
			answer = d.ShowModal()
			d.Destroy()
			if (answer == wx.ID_YES):
				self.OnSave(event)
			elif (answer == wx.ID_CANCEL):
				return
		#franz: oldpos is not used
		#11/24: :) It is now!  (Adding Franz's BugFix, ironically enough).
		oldpos = self.docPosition
		oldfinder = self.FinderArray[oldpos]
		if len(self.txtDocumentArray) > 1:
			self.DestroyDocument()		
			#Update txtDocument.targetPosition
			x = 0
			l = len(self.txtDocumentArray)
			while x < l:
					self.txtDocumentArray[x].targetPosition = x
					x = x + 1					
			self.mdinotebook.DeletePage(self.docPosition)
			if (self.docPosition > 0):				
				self.docPosition = self.docPosition - 1
			elif (len(self.txtDocumentArray) > 1):
				if self.docPosition > 0:
					self.docPosition = self.docPosition + 1
			self.setDocumentTo(self.docPosition, 1)
			#11/24:
			if self.Finder:
				if oldpos > self.docPosition:
					self.Finder.Copy(oldfinder)
		else:
			#Clear the current document:
			self.txtDocument.SetText("")
			self.txtDocument.filename = ""
			self.txtDocument.mtime = -1
			self.txtDocument.EmptyUndoBuffer()
			self.txtDocument.SetSavePoint()			
			self.UpdateMenuAndToolbar()
			#The set size stuff ensures that wx.widgets repaints the tab.
			x, y = self.GetSizeTuple()
			self.SetSize(wx.Size(x-1, y-1))
			self.SetSize(wx.Size(x, y))
			self.txtDocument.untitlednumber = 1
					
		self.txtDocument.IsActive = True	
		self.txtDocument.OnModified(None)
		self.mdinotebook.OnPageChanged(None)
		self.reloaddocumentsmenu()
	
	def OnCloseAllDocuments(self, event):
		x = len(self.txtDocumentArray) - 1
		while x > -1:
			self.setDocumentTo(x, True)
			if self.txtDocument.GetModify():
				#prompt saving filename limodou 2004/04/19
				d = wx.MessageDialog(self, 'Would you like to save "%s"?' % self.txtDocument.GetFilename(), "DrPython", wx.YES_NO | wx.CANCEL | wx.ICON_QUESTION)
				#end limodou
				answer = d.ShowModal()
				d.Destroy()
				if (answer == wx.ID_YES):
					self.OnSave(event)
			self.OnClose(event)					
			x = x - 1
	
	def OnCloseAllOtherDocuments(self, event):
		if len(self.txtDocument.filename) < 1:
			self.ShowMessage("Sorry, does not work when an untitled file is selected.", "DrPython Error")
			return				
		farray = map(lambda document: document.filename, self.txtDocumentArray)
		try:
			i = farray.index(self.txtDocument.filename)
		except:
			#franz: (Updated Namespace)
			self.ShowMessage("Something went wrong trying to close all other tabs.", "DrPython Error")
			return				
		
		x = len(farray) - 1
		while x > -1:
			if x is not i:	
				self.setDocumentTo(x, True)
				if self.txtDocument.GetModify():
					#prompt saveing filename limodou 2004/04/19
					d = wx.MessageDialog(self, 'Would you like to save "%s"?' % self.txtDocument.GetFilename(), "DrPython", wx.YES_NO | wx.CANCEL | wx.ICON_QUESTION)
					#end limodou
					answer = d.ShowModal()
					d.Destroy()
					if (answer == wx.ID_YES):
						self.OnSave(event)
				self.OnClose(event)
			x = x - 1
		
	def OnCloseW(self, event):
		if event.CanVeto():
				try:
					x = self.docPosition
					if (self.docPosition > 0):
						fromzero = self.docPosition
					l = len(self.txtDocumentArray)
					while x < l:
						if self.txtDocumentArray[x].GetModify():
							d = wx.MessageDialog(self, 'Would you like to save "%s"?' % self.txtDocumentArray[x].GetFilename(), "DrPython", wx.YES_NO | wx.CANCEL | wx.ICON_QUESTION)
							answer = d.ShowModal()
							d.Destroy()
							if (answer == wx.ID_YES):
								self.setDocumentTo(x)
								self.OnSave(event)
							elif (answer == wx.ID_CANCEL):
								return
						x = x + 1
						
					if fromzero > 0:
						x = 0
						l = fromzero
						while x < l:
							if self.txtDocumentArray[x].GetModify():
								d = wx.MessageDialog(self, 'Would you like to save "%s"?' % self.txtDocumentArray[x].GetFilename(), "DrPython", wx.YES_NO | wx.CANCEL | wx.ICON_QUESTION)
								answer = d.ShowModal()
								d.Destroy()
								if (answer == wx.ID_YES):
									self.setDocumentTo(x)
									self.OnSave(event)
								elif (answer == wx.ID_CANCEL):
									return
							x = x + 1
				except:
					if self.prefs.alwayspromptonexit:
						d = wx.MessageDialog(self, "Are you sure you want to exit?   ", "DrPython", wx.YES_NO | wx.ICON_QUESTION)
						answer = d.ShowModal()
						d.Destroy()
						if (answer == wx.ID_NO):
							return
						
		if self.prefs.rememberwindowsizeandposition:
			try:
				f = file(self.homedirectory + '/drpython.sizeandposition.dat', 'w')				
				x, y = self.GetSizeTuple()
				px, py = self.GetPositionTuple()
				f.write(str(x) + '\n' + str(y) + '\n' + str(px) + '\n' + str(py))				
				f.close()
			except:
				self.ShowMessage("Error Saving Window Size", 'Error')
		event.Skip()
		
	def OnCommentRegion(self, event):
		pos = self.txtDocument.GetCurrentPos()
		selstart, selend = self.txtDocument.GetSelection()
		#From the start of the first line selected
		startline = self.txtDocument.LineFromPosition(selstart)
		self.txtDocument.GotoLine(startline)
		start = self.txtDocument.GetCurrentPos()
		#To the end of the last line selected
		#Bugfix Chris Wilson
		#Edited by Dan (selend fix)
		if selend == selstart:
			tend = selend
		else:
			tend = selend - 1
		end = self.txtDocument.GetLineEndPosition(self.txtDocument.LineFromPosition(tend))
		#End Bugfix Chris Wilson
		eol = self.txtDocument.GetEndOfLineCharacter()
		if self.prefs.doccommentmode == 0:			
			self.txtDocument.SetSelection(start, end)
			text = self.prefs.doccommentstring + self.txtDocument.GetSelectedText()
			text = text.replace(eol, eol + self.prefs.doccommentstring)
			self.txtDocument.ReplaceSelection(text)
		else:
			mask = self.txtDocument.GetModEventMask()
			self.txtDocument.SetModEventMask(0)
			wpos = start
			while wpos < end:
				ws = self.txtDocument.GetLineIndentPosition(startline)
				le = self.txtDocument.GetLineEndPosition(startline)
				if ws != le:
					self.txtDocument.InsertText(ws, self.prefs.doccommentstring)
				startline += 1
				wpos = self.txtDocument.PositionFromLine(startline)
			self.txtDocument.SetModEventMask(mask)			
		self.txtDocument.GotoPos(start)		
	
	def OnCustomizePopUpMenu(self, event):
		from drPopUpMenuDialog import drPopUpMenuDialog
		d = drPopUpMenuDialog(self)
		d.ShowModal()
		d.Destroy()
	
	def OnCustomizeToolBar(self, event):
		from drToolBarDialog import drToolBarDialog
		d = drToolBarDialog(self)
		d.ShowModal()
		d.Destroy()
	
	def OnCustomizeShortcuts(self, event):
		from drShortcutsDialog import drShortcutsDialog
		d = drShortcutsDialog(self)
		d.ShowModal()
		d.Destroy()
	
	def OnDedentRegion(self, event):		
		#Submitted Patch:  Franz Steinhausler
		#Submitted Patch (ModEvent Mask), Franz Steinhausler
		beg, end = self.txtDocument.GetSelection()
		begline = self.txtDocument.LineFromPosition(beg)
		endline = self.txtDocument.LineFromPosition(end)
		
		mask = self.txtDocument.GetModEventMask()
		self.txtDocument.SetModEventMask(0)
		
		if begline == endline:
			#This section modified by Dan
			pos = self.txtDocument.PositionFromLine(begline)
			self.txtDocument.SetSelection(pos, pos)
			self.txtDocument.GotoPos(pos)
			self.txtDocument.BackTab()
			self.txtDocument.SetSelection(pos, self.txtDocument.GetLineEndPosition(begline))
			self.txtDocument.SetModEventMask(mask)
			return
		
		#Submitted Patch:  Christian Daven
		self.txtDocument.BackTab()
		self.txtDocument.SetModEventMask(mask)

	def OnEditBookmarks(self, event):	
		from drBookmarksDialog import drBookmarksDialog
		d = drBookmarksDialog(self, (self.homedirectory + "/bookmarks.dat"))
		d.ShowModal()
		d.Destroy()
		self.bookmarksmenu.reloadBookmarks()

	def OnEditScriptMenu(self, event):
		from drScriptDialog import drScriptDialog
		d = drScriptDialog(self)
		d.ShowModal()
		d.Destroy()
		self.drscriptmenu.reloadscripts()
	
	def OnEnd(self, event):
		if (self.txtPrompt.pid is not -1):
			self.UpdateMenuAndToolbar()
			wx.Process_Kill(self.txtPrompt.pid, wx.SIGKILL)
			self.txtPrompt.SetReadOnly(1)

	def OnExit(self, event):
		self.Close(False)
	
	def OnExpandAll(self, event):
		if (self.prefs.docfolding):
			wx.BeginBusyCursor()
			self.txtDocument.FoldAll(True)
			wx.EndBusyCursor()
	
	def OnFindAndComplete(self, event):
		#Submitted Patch by Martinho
		#now stops at '.' (repre)
		#re-ordered the text so the list shows the nearer completion words first.
		
		#Get The Current Word
		text = self.txtDocument.GetText()
		pos = self.txtDocument.GetCurrentPos()	
		repre = re.compile("\(|\)|\[|\]|\{|\}|\<|\>|\.", re.IGNORECASE | re.MULTILINE)
		regex = re.compile("\w*\Z", re.IGNORECASE | re.MULTILINE)
		#franz: regexend is not used
		eol = self.txtDocument.GetEndOfLineCharacter()

		#Get the left bit
		i = text[0:pos].rfind(eol)
		if i == -1:
			i = 0
		else:
			i = i + len(eol)

		#Check for characters to stop at.
		t = re.finditer(repre, text[i:pos])
		if t is not None:
			try:
				preresult = t.next()
			except:
				preresult = None
			try:
				while t.next() is not None:					
					preresult = t.next()
			except:
				if preresult is not None:
					t = i + preresult.start() + 1
					#If t == pos, then you do not want to stop
					#at the character.
					if t < pos:
						i = t
		
		#Find Non Whitespace Characters.
		result = regex.search(text[i:pos])
		
		if result == None:
			start = i
		else:
			start = i + result.start()
			
		if (pos - start) <= 0:
			return
		
		#Handle special characters
		oword = text[start:pos]
		word = oword.replace('\\', "\\\\").replace('^', "\\^").replace('*', "\\*").replace('$', "\\$")
		word = word.replace('+', "\\+").replace('?', "\\?").replace('{', "\\{").replace('}', "\\}")
		word = word.replace('[', "\\[").replace(']', "\\]").replace('(', "\\(").replace(')', "\\)")
		word = word.replace('.', "\\.").replace('|', "\\|").replace('<', "\\<").replace('>', "\\>")
						
		#Find all matches in the document.
		findandcompleteregex = re.compile(r"\b" + word + r"\w*\b", re.MULTILINE)

		text_lines = text.split(eol)
		cl = self.txtDocument.GetCurrentLine()
		s_i = cl
		e_i = cl
		sorted_text = ""
		while (s_i>=0) or (e_i<len(text_lines)) :
			if s_i>=0 :
				sorted_text += text_lines[s_i] + eol
				s_i = s_i - 1
			if e_i<len(text_lines) :
				sorted_text += text_lines[e_i] + eol
				e_i = e_i + 1

		r = findandcompleteregex.findall(sorted_text)
		
		results = ""
		tr = []
		for item in r:
			try:
				tr.index(item)
			except:
				if not item == oword:
					results = results + " " + item
					tr.append(item)
		
		results = results.strip()
							
		if len(tr) > 0:
			try:
				self.txtDocument.AutoCompShow(len(oword), results)
			except:
				#What is this mess?
				pass
			
	def OnFoldAll(self, event):
		if (self.prefs.docfolding):
			wx.BeginBusyCursor()
			self.txtDocument.FoldAll(False)
			wx.EndBusyCursor()
				
	def OnFormatMacMode(self, event):
		wx.BeginBusyCursor()
		wx.Yield()
		self.txtDocument.SetEOLMode(wx.stc.STC_EOL_CR)
		text = self.txtDocument.GetText()
		text = self.FormatMacReTarget.sub('\r', text)
		self.txtDocument.SetText(text)
		self.txtDocument.OnPositionChanged(None)
		wx.EndBusyCursor()
	
	def OnFormatUnixMode(self, event):
		wx.BeginBusyCursor()
		wx.Yield()
		self.txtDocument.SetEOLMode(wx.stc.STC_EOL_LF)
		text = self.txtDocument.GetText()
		text = self.FormatUnixReTarget.sub('\n', text)
		self.txtDocument.SetText(text)
		self.txtDocument.OnPositionChanged(None)
		wx.EndBusyCursor()
		
	def OnFormatWinMode(self, event):
		wx.BeginBusyCursor()
		wx.Yield()
		self.txtDocument.SetEOLMode(wx.stc.STC_EOL_CRLF)
		text = self.txtDocument.GetText()
		text = self.FormatWinReTarget.sub('\r\n', text)
		self.txtDocument.SetText(text)
		self.txtDocument.OnPositionChanged(None)
		wx.EndBusyCursor()
	
	def OnGoTo(self, event):
		d = wx.TextEntryDialog(self, "Go To Line Number:", "DrPython - Go To", "")
		answer = d.ShowModal()
		v = d.GetValue()
		d.Destroy()
		if (answer == wx.ID_OK):
			try:
				v = int(v) - 1
				if (v >= 0) and (v < self.txtDocument.GetLineCount()):
					if self.prefs.docfolding:
						self.txtDocument.EnsureVisible(v)
					self.txtDocument.ScrollToLine(v)
					self.txtDocument.GotoLine(v)
				else:
					e = drScrolledMessageDialog.ScrolledMessageDialog(self, "That line does not exist", "DrPython Error")
					e.ShowModal()
					e.Destroy()
			except StandardError:
				e = drScrolledMessageDialog.ScrolledMessageDialog(self, "You must enter an integer (1, 2, 3, etc)", "DrPython Error")
				e.ShowModal()
				e.Destroy()

	def OnIdle(self, event):
		self.txtPrompt.OnIdle(event)

	def OnIndentRegion(self, event):
		#Submitted Patch:  Franz Steinhausler
		#Submitted Patch (ModEvent Mask), Franz Steinhausler
		beg, end = self.txtDocument.GetSelection()
		begline = self.txtDocument.LineFromPosition(beg)
		endline = self.txtDocument.LineFromPosition(end)
		
		mask = self.txtDocument.GetModEventMask()
		self.txtDocument.SetModEventMask(0)
		
		if begline == endline:
			#This section modified by Dan
			pos = self.txtDocument.PositionFromLine(begline)
			self.txtDocument.SetSelection(pos, pos)
			self.txtDocument.GotoPos(pos)
			self.txtDocument.Tab()
			self.txtDocument.SetSelection(pos, self.txtDocument.GetLineEndPosition(begline))
			self.txtDocument.setModEventMask(mask)
			return
		
		#Submitted Patch:  Christian Daven
		self.txtDocument.Tab()
		self.txtDocument.SetModEventMask(mask)
	
	def OnInsertRegEx(self, event):
		from drRegularExpressionDialog import drRegularExpressionDialog
		d = drRegularExpressionDialog(self, -1, "Insert Regular Expression", self.txtPrompt.GetSTCFocus())
		d.Show()
		
	def OnKeyDown(self, event):	
		self.RunShortcuts(event)

		event.Skip()
	
	def OnLowercase(self, event):
		if (self.txtPrompt.GetSTCFocus()):
			self.txtPrompt.CmdKeyExecute(wx.stc.STC_CMD_LOWERCASE)
		else:
			self.txtDocument.CmdKeyExecute(wx.stc.STC_CMD_LOWERCASE)

	def OnMenuFind(self, event):
		d = drFindReplaceDialog(self, -1, "Find")
		d.SetOptions(self.FindOptions)
		if (self.txtDocument.GetSelectionStart() < self.txtDocument.GetSelectionEnd()):
			d.SetFindString(self.txtDocument.GetSelectedText())
		elif self.prefs.findreplaceundercursor:
			pos = self.txtDocument.GetCurrentPos()
			d.SetFindString(self.txtDocument.GetTextRange(self.txtDocument.WordStartPosition(pos, 1), self.txtDocument.WordEndPosition(pos, 1)))
		d.Show(True)
	
	def OnMenuFindNext(self, event):
		self.Finder.DoFindNext()
	
	def OnMenuFindPrevious(self, event):
		self.Finder.DoFindPrevious()
		
	def OnMenuReplace(self, event):	
		d = drFindReplaceDialog(self, -1, "Replace", 1)
		d.SetOptions(self.ReplaceOptions)
		if (self.txtDocument.GetSelectionStart() < self.txtDocument.GetSelectionEnd()):
			d.SetFindString(self.txtDocument.GetTextRange(self.txtDocument.GetSelectionStart(), self.txtDocument.GetSelectionEnd()))
		else:
			d.SetFindString(self.Finder.GetFindText())
		d.Show(True)
			
	def OnNew(self, event):		
		l = len(self.txtDocumentArray)
		unumbers = map(lambda x: x.untitlednumber, self.txtDocumentArray)
		unumbers.sort()
		x = 0
		last = 0
		while x < l:
			if unumbers[x] > 0:
				if unumbers[x] != (last + 1):
					x = l
				else:
					last = unumbers[x]
					x = x + 1
			else:
				x = x + 1
		last = last + 1
		nextpage = drPanel(self.mdinotebook, self.ID_APP)
		self.txtDocumentArray.append(DrText(nextpage.documentpanel.center, self.ID_APP, self))
		self.txtDocumentArray[l].SetSize(nextpage.documentpanel.center.GetSize())
		self.mdinotebook.AddPage(nextpage, "Untitled " + str(last))
		self.txtPromptArray.append(DrPrompt(nextpage.prompt, self.ID_APP, self))
		self.txtDocumentArray[l].untitlednumber = last
		#copy old finder limodou 2004/04/19
		self.FinderArray.append(drFinder(self, self.Finder))
		#end limodou
		self.lastprogargsArray.append("")
		self.txtDocumentArray[l].SetTargetPosition(l)
		self.txtDocument.IsActive = False
		self.txtDocument.OnModified(None)
		self.setDocumentTo(l)
		
		if self.prefs.sourcebrowserisvisible:
			self.ShowSourceBrowser()
		
		self.reloaddocumentsmenu()
		
#BUG WORKAROUND:
		if self.PLATFORM_IS_WIN:
			w, h = self.currentpage.GetSizeTuple()
			self.currentpage.SetSize(wx.Size(w+1, h+1))
			self.currentpage.SetSize(wx.Size(w, h))
#END BUG WORKAROUND
		
	def OnOpen(self, event):
		dlg = drFileDialog.FileDialog(self, "Open", self.prefs.wildcard, MultipleSelection=True, ShowRecentFiles=True)
		if (len(self.ddirectory) > 0):
			try:
				dlg.SetDirectory(self.ddirectory)
			except:
				self.ShowMessage(("Error Setting Default Directory To: " + self.ddirectory), "DrPython Error")
		if (dlg.ShowModal() == wx.ID_OK):
			alreadyopen = map(lambda x: x.filename, self.txtDocumentArray)
			old = self.txtDocument.filename
			filenames = dlg.GetPaths()
			filenames = map(lambda x: x.replace("\\", '/'), filenames)
			l = len(filenames)
			c = 0
			while c < l:
				try:
					#franz: pychecker: i is not referenced
					#Franz Fixed the fix.
					i = alreadyopen.index(filenames[c])
					self.setDocumentTo(i)
					filenames.pop(c)
					c = c - 1
					l = l - 1
				except:
					pass
				c = c + 1
			if l < 1:
				return
			x = 1
			self.DestroyRecentFileMenu()
			if l > 1:
				self.OpenFile(filenames[0], len(old) > 0)
			while (x < l):
				self.OpenFile(filenames[x], True)
				x = x + 1
			if l <= 1:
				if (len(old) > 0) or (self.txtDocument.GetModify()):					
					self.OpenFile(filenames[0], True)
				else:
					self.OpenFile(filenames[0], False)
			self.CreateRecentFileMenu()
			dlg.Destroy()

	def OnOpenImportedModule(self, event):
		from drOpenImportedModuleDialog import drOpenImportedModuleDialog
		text = self.txtDocument.GetText()
		importmatches = self.reimport.findall(text)
		fromimportmatches = self.refromimport.findall(text)
		
		modulelist = []
				
		rmodulelist = []		
		imatchesarray = map(lambda x: x.strip().split(' ')[1:], importmatches)
		for imatch in imatchesarray:
			rmodulelist.extend(imatch)
		rmodulelist.extend(map(lambda x: x.strip().split(' ')[1], fromimportmatches))
				
		for mod in rmodulelist:
			modulelist.append(mod.strip(','))
			
		modulelist.sort()
		
		x = 0
		l = len(modulelist)
		while x < l:
			if modulelist.count(modulelist[x]) > 1:
				modulelist.pop(x)
				l = l - 1
			x = x + 1
		
		d = drOpenImportedModuleDialog(self, modulelist)
		answer = d.ShowModal()
		d.Destroy()

		if (answer == wx.ID_OK):
			selectedmodule, modulefile = d.GetSelectedModule()
			
			if modulefile is not None:
				self.OpenFile(modulefile, True)
			else:
				self.ShowMessage('Could not locate module "' + selectedmodule + '"!', "Error locating module")

	def OnOpenRecentFile(self, event):
		recentmenuindex = event.GetId() - self.ID_RECENT_FILES_BASE
		alreadyopen = map(lambda x: x.filename, self.txtDocumentArray)
		try:
			#franz: pychecker: i is not referenced
			#Franz fixed the fix.
			c = alreadyopen.index(self.recentfiles[recentmenuindex])
			self.setDocumentTo(c)
			return
		except:
			pass
		if not os.path.exists(self.recentfiles[recentmenuindex]):
			self.ShowMessage(('"' + self.recentfiles[recentmenuindex] + '" Does Not Exist.'), "Recent File No Longer Exists")
			return
		old = self.txtDocument.filename
		filename = self.recentfiles[recentmenuindex]
		self.DestroyRecentFileMenu()
		if (len(old) > 0) or (self.txtDocument.GetModify()):
			self.OpenFile(filename, True)
		else:
			self.OpenFile(filename, False)
		self.CreateRecentFileMenu()

	def OnPrefs(self, event):
		from drPrefsDialog import drPrefsDialog
		d = drPrefsDialog(self, -1, "DrPython - Preferences")
		d.ShowModal()		
		d.Destroy()
	
	def OnPrint(self, event):
		self.Printer.Print(self.txtDocument.GetText(), self.txtDocument.filename, self.prefs.printdoclinenumbers)

	def OnPrintSetup(self, event):
		self.Printer.PrinterSetup()
				
	def OnPrintPrompt(self, event):
		self.Printer.Print(self.txtPrompt.GetText(), self.txtDocument.filename, self.prefs.printpromptlinenumbers)
	
	def OnProcessEnded(self, event):
		#First, check for any leftover output.
		self.txtPrompt.OnIdle(event)
		
		#Set the process info to the correct position in the array.
		i = 0
		epid = event.GetPid()
		try:
			i = map(lambda tprompt: tprompt.pid == epid, self.txtPromptArray).index(True)
		except:
			return				
		#If this is the process for the current window:
		if self.docPosition == i:
			self.txtPrompt.process.Destroy()
			self.txtPrompt.process = None
			self.txtPrompt.pid = -1
			self.txtPrompt.SetReadOnly(1)
			self.txtPrompt.pythonintepreter = 0
			self.UpdateMenuAndToolbar()
			self.SetStatusText("", 2)
		else:	
			self.txtPromptArray[i].process.Destroy()
			self.txtPromptArray[i].process = None
			self.txtPromptArray[i].pid = -1
			self.txtPromptArray[i].SetReadOnly(1)
			self.txtPromptArray[i].pythonintepreter = 0		
		
	def OnPython(self, event):
		self.ExecutePython("-i")

	def OnRedo(self, event):
		if (self.txtPrompt.GetSTCFocus()):
			self.txtPrompt.Redo()
		else:
			self.txtDocument.Redo()

	def OnReload(self, event):
		d = wx.MessageDialog(self, "This will reload the current file.\nAny changes will be lost.\nAre you sure you want to do this?", "DrPython", wx.YES_NO | wx.ICON_QUESTION)
		answer = d.ShowModal()
		d.Destroy()
		if (answer == wx.ID_YES):
			if (len(self.txtDocument.filename) > 0):
				self.OpenFile(self.txtDocument.filename, False)
		event.Skip()
				
	def OnRestoreFromBackup(self, event):
		if os.path.exists(self.txtDocument.filename + ".bak"):
			d = wx.MessageDialog(self, "This will restore the current file from the last backup.\nAny changes will be lost.\nAre you sure you want to do this?", "DrPython", wx.YES_NO | wx.ICON_QUESTION)
			answer = d.ShowModal()
			d.Destroy()
			if (answer == wx.ID_YES):
				if (len(self.txtDocument.filename) > 0):
					old = self.txtDocument.filename
					filename = self.txtDocument.filename + ".bak"
					self.OpenFile(filename, False, False, False)
					self.txtDocument.filename = old
		else:
			self.ShowMessage(("No Backup File For: \"" + self.txtDocument.filename + "\""), "DrPython Error")
		
	def OnRun(self, event):
		if self.prefs.saveonrun:
			self.OnSave(event)
		elif (self.txtDocument.GetModify()):
			d = wx.MessageDialog(self, "The file has been modified.\nIt would be wise to save before running.\nWould you like to save the file?", "DrPython", wx.YES_NO | wx.ICON_QUESTION)
			answer = d.ShowModal()
			d.Destroy()
			if (answer == wx.ID_YES):
				self.OnSave(event)	
		if len(self.txtDocument.filename) > 0:
			cdir, filen = os.path.split(self.txtDocument.filename)
			try:
				os.chdir(cdir)
			except:		
				self.ShowMessage("Error Setting current directory for Python.", "DrPython RunError")
			largs = ""
			if (len(self.lastprogargs) > 0):
				largs = ' ' + self.lastprogargs
			if self.PLATFORM_IS_WIN:
				self.runcommand((self.pythexecw + " -u " +  self.prefs.pythonargs + ' "' + self.txtDocument.filename.replace("\\", "/") + '"' + largs), "Running " + filen)
			else:
				self.runcommand((self.pythexec + " -u " +  self.prefs.pythonargs + ' "' + self.txtDocument.filename + '"'  + largs), "Running " + filen)
		
	def OnSave(self, event):
		if (len(self.txtDocument.filename) <= 0):
			self.OnSaveAs(event)
		else:
			self.SaveFile(self.docPosition)
			if self.prefs.sourcebrowserautorefreshonsave and (self.txtDocument.SourceBrowser is not None):
				self.txtDocument.SourceBrowser.Browse()
	
	def OnSaveAll(self, event):
		x = 0
		if self.prefs.promptonsaveall:
			tosaveArray = []
			tosaveLabels = []
			for document in self.txtDocumentArray:
				if self.txtDocumentArray[x].GetModify():
					tosaveArray.append(x)
					tosaveLabels.append(self.txtDocumentArray[x].GetFilenameTitle())
				x += 1
			if len(tosaveLabels) == 0:
				self.ShowMessage('No Modified Documents.', 'Save All')
				return
			d = wx.lib.dialogs.MultipleChoiceDialog(self, "Save All Modified Documents?", "Save All", tosaveLabels, size=(300, 300))
			l = len(tosaveArray)
			y = 0
			while y < l:
				d.lbox.SetSelection(y)
				y += 1
			answer = d.ShowModal()
			selections = d.GetValue()
			d.Destroy()
			if (answer == wx.ID_OK):
				for selection in selections:
					if len(self.txtDocumentArray[tosaveArray[selection]].filename) <= 0:
						self.setDocumentTo(tosaveArray[selection])
						self.OnSaveAs(None)
					else:
						self.SaveFile(tosaveArray[selection])
			else:
				return False
		else:
			for document in self.txtDocumentArray:
				if self.txtDocumentArray[x].GetModify():
					if len(self.txtDocumentArray[x].filename) <= 0:
						self.setDocumentTo(x)
						self.OnSaveAs(None)
					else:
						self.SaveFile(x)
				x += 1
		return True

	def OnSaveAs(self, event):		
		dlg = drFileDialog.FileDialog(self, "Save File As", self.prefs.wildcard, IsASaveDialog=True)
		if (len(self.ddirectory) > 0):
			try:
				dlg.SetDirectory(self.ddirectory)			
			except:
				#franz: ddirectory
				self.ShowMessage(("Error Setting Default Directory To: " + self.ddirectory), "DrPython Error")
		if (dlg.ShowModal() == wx.ID_OK):
			old = self.txtDocument.filename
			if self.txtDocument.untitlednumber > 0:
				self.txtDocument.untitlednumber = -1
			self.txtDocument.filename = dlg.GetPath().replace("\\", "/")
			self.ddirectory = os.path.dirname(self.txtDocument.filename)
			self.DestroyRecentFileMenu()
			self.SaveFile(self.docPosition, not (old == self.txtDocument.filename))
			self.UpdateMenuAndToolbar()
			
			#Highlighting
			if not self.prefs.doconlyusedefaultsyntaxhighlighting:
				if self.checkiffileisPython(self.txtDocument.filename):
					#Python
					self.txtDocument.currentlanguage = 0
					self.highlightmenu.Check(self.ID_HIGHLIGHT_PYTHON, True)
				elif self.checkiffileisCPP(self.txtDocument.filename):
					#C/C++
					self.txtDocument.currentlanguage = 1
					self.highlightmenu.Check(self.ID_HIGHLIGHT_CPP, True)
				elif self.checkiffileisHTML(self.txtDocument.filename):
					#HTML
					self.txtDocument.currentlanguage = 2			
					self.highlightmenu.Check(self.ID_HIGHLIGHT_HTML, True)	
				elif self.checkiffileisPlainText(self.txtDocument.filename):
					#Plain Text
					self.txtDocument.currentlanguage = 3
					self.highlightmenu.Check(self.ID_HIGHLIGHT_PLAIN_TEXT, True)
				else:
					#Default
					pass
				self.txtDocument.SetupPrefsDocument()	
			
			#Update Recent Files
			if (self.recentfiles.count(self.txtDocument.filename) is not 0):
				self.recentfiles.remove(self.txtDocument.filename)
			if (len(self.recentfiles) is self.prefs.recentfileslimit):
				self.recentfiles.pop()
			self.recentfiles.insert(0, self.txtDocument.filename)
			self.WriteRecentFiles()
			self.CreateRecentFileMenu()
			dlg.Destroy()
			self.reloaddocumentsmenu()
			#Refreshes the tab.
			x, y = self.mdinotebook.GetSizeTuple()
			self.mdinotebook.SetSize(wx.Size(x+1, y+1))
			self.mdinotebook.SetSize(wx.Size(x, y))

	def OnSavePrompt(self, event):
		dlg = drFileDialog.FileDialog(self, 'Save Prompt Text To', 'Text File (*.txt)|*.txt|All files (*)|*', IsASaveDialog=True)
		if (len(self.ddirectory) > 0):
			try:
				dlg.SetDirectory(self.ddirectory)			
			except:
				#franz: ddirectory
				self.ShowMessage(("Error Setting Default Directory To: " + self.ddirectory), "DrPython Error")
		if (dlg.ShowModal() == wx.ID_OK):	
			pfilename = dlg.GetPath().replace("\\", "/")
			self.ddirectory = os.path.dirname(pfilename)
			try:
				cfile = file(pfilename, 'wb')
				if self.prefs.autodetectencoding:
					#Encoding (Edited by Dan for 3.6.2)
					#comment limodou 2004/04/13
					cfile.write(GetEncodedText(self.txtPrompt, self.txtPrompt.locale))
					#end limodou
				else:
					cfile.write(self.txtPrompt.GetText())
				cfile.close()
			except IOError:
				self.ShowMessage(("Error Writing: " + pfilename), "DrPython Error")
			dlg.Destroy()

	def OnSelectAll(self, event):
		if (self.txtPrompt.GetSTCFocus()):
			self.txtPrompt.SelectAll()
		else:
			self.txtDocument.SelectAll()
	
	def OnSelectDocument(self, event):
		eid = event.GetId()
		i = eid - self.ID_DOCUMENTS_BASE
		self.mdinotebook.SetSelection(i)
		self.mdinotebook.SetTab()

	def OnSelectDocumentFirst(self, event):
		self.mdinotebook.SetSelection(0)
		self.mdinotebook.SetTab()

	def OnSelectDocumentLast(self, event):
		self.mdinotebook.SetSelection(self.mdinotebook.GetPageCount()-1)
		self.mdinotebook.SetTab()
		
	def OnSelectDocumentNext(self, event):
		self.mdinotebook.AdvanceSelection(True)
		self.mdinotebook.SetTab()

	def OnSelectDocumentPrevious(self, event):
		self.mdinotebook.AdvanceSelection(False)
		self.mdinotebook.SetTab()
			
	def OnSetArgs(self, event):
		if (len(self.txtDocument.filename) > 0):
			d = wx.TextEntryDialog(self, "Arguments:", "DrPython - Set Arguments", self.lastprogargs)
			if (d.ShowModal() == wx.ID_OK):
				self.lastprogargs = d.GetValue()
				self.lastprogargsArray[self.docPosition] = self.lastprogargs
		d.Destroy()

	def OnSyntaxHighlightingPython(self, event):
		self.txtDocument.currentlanguage = 0
		self.txtDocument.SetupPrefsDocument()
		
	def OnSyntaxHighlightingCPP(self, event):
		self.txtDocument.currentlanguage = 1
		self.txtDocument.SetupPrefsDocument()
		
	def OnSyntaxHighlightingHTML(self, event):
		self.txtDocument.currentlanguage = 2
		self.txtDocument.SetupPrefsDocument()

	def OnSyntaxHighlightingText(self, event):
		self.txtDocument.currentlanguage = 3
		self.txtDocument.SetupPrefsDocument()					
						
	def OnTogglePrompt(self, event):
		if (self.currentpage.PromptIsVisible):
			self.currentpage.PromptIsVisible = False
			if self.hasToolBar:
				self.toolbar.ToggleTool(self.ID_TOGGLE_PROMPT,  False)	
			self.currentpage.OnSize(None)
			self.txtDocument.SetFocus()
		else:
			self.currentpage.PromptIsVisible = True
			if self.hasToolBar:
				self.toolbar.ToggleTool(self.ID_TOGGLE_PROMPT,  True)
			self.currentpage.OnSize(None)
			self.txtPrompt.SetFocus()
	
	def OnToggleSourceBrowser(self, event):
		if self.txtDocument.SourceBrowser is None:
			target, i = self.currentpage.GetTargetSashWindow(self.prefs.sourcebrowserpanel)
			self.txtDocument.SourceBrowser = drSourceBrowserPanel(target, -1, self.prefs.sourcebrowserpanel, i)
			self.currentpage.OnSize(None)
		else:
			if not self.currentpage.IsVisible(self.txtDocument.SourceBrowser.Position, self.txtDocument.SourceBrowser.Index):
				self.txtDocument.SourceBrowser.Browse()
			self.currentpage.TogglePanel(self.txtDocument.SourceBrowser.Position, self.txtDocument.SourceBrowser.Index)
				
	def OnToggleViewWhiteSpace(self, event):
		if (self.txtPrompt.GetSTCFocus()):
			c = self.txtPrompt.GetViewWhiteSpace()
			self.txtPrompt.SetViewWhiteSpace(not c)
			self.txtPrompt.SetViewEOL(not c)
		else:
			c = self.txtDocument.GetViewWhiteSpace()
			self.txtDocument.SetViewWhiteSpace(not c)
			self.txtDocument.SetViewEOL(not c)
	
	def OnToolBar(self, event):
		try:
			i = event.GetId() - self.ID_OTHER
			txt = self.ToolBarList[i]
			if txt in self.stcshortcutlist:
				pos = self.stcshortcutlist.index(txt)
				if (self.txtPrompt.GetSTCFocus()):
					self.txtPrompt.CmdKeyExecute(self.txtPrompt.STCCOMMANDLIST[pos])
				else:
					self.txtDocument.CmdKeyExecute(self.txtDocument.STCCOMMANDLIST[pos])
			else:
				if txt in self.PluginToolBarLabels:				
					pos = self.PluginToolBarLabels.index(txt)
					self.PluginToolBarFunctions[pos](event)
		except:
			self.ShowMessage("ToolBar Action Error", "DrPython Error")
				
	def OnUnCommentRegion(self, event):	
		#franz: pos is not used
		selstart, selend = self.txtDocument.GetSelection()
		#From the start of the first line selected
		startline = self.txtDocument.LineFromPosition(selstart)
		self.txtDocument.GotoLine(startline)
		start = self.txtDocument.GetCurrentPos()
		#To the end of the last line selected
		#Bugfix Chris Wilson
		#Edited by Dan (selend fix)
		if selend == selstart:
			tend = selend
		else:
			tend = selend - 1
		end = self.txtDocument.GetLineEndPosition(self.txtDocument.LineFromPosition(tend))
		#End Bugfix Chris Wilson
		
		mask = self.txtDocument.GetModEventMask()
		self.txtDocument.SetModEventMask(0)
		lpos = start
		newtext = ""
		ldocstring = len(self.prefs.doccommentstring)
		while lpos < end:
			lpos = self.txtDocument.PositionFromLine(startline)
			line = self.txtDocument.GetLine(startline)
			lc = line.find(self.prefs.doccommentstring)
			if lc > -1:
				prestyle = self.txtDocument.GetStyleAt(lpos + lc - 1)
				style = self.txtDocument.GetStyleAt(lpos + lc)
				if not ((not (prestyle == wx.stc.STC_P_COMMENTLINE) and not (prestyle == wx.stc.STC_P_COMMENTBLOCK)) and ((style == wx.stc.STC_P_COMMENTLINE) or (style == wx.stc.STC_P_COMMENTBLOCK))):
					newtext += line
				else:
					newtext += line[0:lc] + line[lc+ldocstring:]
			else:
				newtext += line
			startline += 1
			lpos = self.txtDocument.PositionFromLine(startline)
		self.txtDocument.SetModEventMask(mask)
		self.txtDocument.SetSelection(start, end)
		self.txtDocument.ReplaceSelection(newtext.rstrip(self.txtDocument.GetEndOfLineCharacter()))
	
	def OnUndo(self, event):
		if (self.txtPrompt.GetSTCFocus()):
			self.txtPrompt.Undo()
		else:
			self.txtDocument.Undo()
	
	def OnUppercase(self, event):
		if (self.txtPrompt.GetSTCFocus()):
			self.txtPrompt.CmdKeyExecute(wx.stc.STC_CMD_UPPERCASE)
		else:
			self.txtDocument.CmdKeyExecute(wx.stc.STC_CMD_UPPERCASE)
			
	def OnViewAbout(self, event):
		self.ViewURLInBrowser('/usr/share/doc/drpython/documentation/about.html')
				
	def OnViewHelp(self, event):
		self.ViewURLInBrowser('/usr/share/doc/drpython/documentation/help.html')

	def OnViewInBottomPanel(self, event):
		self.viewinpaneltarget = 3
		
		self.ViewInPanelMenu(event)
	
	def OnViewInLeftPanel(self, event):
		self.viewinpaneltarget = 0
		
		self.ViewInPanelMenu(event)

	def OnViewInRightPanel(self, event):
		self.viewinpaneltarget = 1
		
		self.ViewInPanelMenu(event)
		
	def OnViewInTopPanel(self, event):
		self.viewinpaneltarget = 2
		
		self.ViewInPanelMenu(event)

	def OnViewPythonDocs(self, event):
		self.ViewURLInBrowser(self.prefs.documentationpythonlocation)
	
	def OnViewREHowtoDocs(self, event):
		self.ViewURLInBrowser(self.prefs.documentationrehowtolocation)
	
	def OnViewWxWidgetsDocs(self, event):
		self.ViewURLInBrowser(self.prefs.documentationwxwidgetslocation)
	
	def OnZoomIn(self, event):
		if (self.txtPrompt.GetSTCFocus()):
			zoom = self.txtPrompt.GetZoom()
			if (zoom < 20):
				self.txtPrompt.SetZoom(zoom + 1)
		else:
			zoom = self.txtDocument.GetZoom()
			if (zoom < 20):
				self.txtDocument.SetZoom(zoom + 1)
	
	def OnZoomOut(self, event):
		if (self.txtPrompt.GetSTCFocus()):
			zoom = self.txtPrompt.GetZoom()
			if (zoom > -9):
				self.txtPrompt.SetZoom(zoom - 1)
		else:
			zoom = self.txtDocument.GetZoom()
			if (zoom > -9):
				self.txtDocument.SetZoom(zoom - 1)
	
	def OpenFile(self, filename, OpenInNewWindow, editrecentfiles = True, setTitle = True):		
		wx.BeginBusyCursor()
		filename = os.path.abspath(filename).replace("\\", '/')
		if (not os.path.exists(filename)):
			self.ShowMessage(("Error Opening: " + filename), "DrPython Error")
			wx.EndBusyCursor()
			return
		if (self.txtDocument.untitlednumber > 0) and not OpenInNewWindow:
			self.txtDocument.untitlednumber = -1
		if (editrecentfiles):
			if (self.recentfiles.count(filename) is not 0):			
				self.recentfiles.remove(filename)
			if (len(self.recentfiles) is self.prefs.recentfileslimit):
				self.recentfiles.pop()
			self.recentfiles.insert(0, filename)
			self.WriteRecentFiles()
		if (((not (self.txtDocument.filename == filename))) and (self.txtDocument.GetModify())) or OpenInNewWindow:
			#New Tab
			self.txtDocument.IsActive = False
			self.txtDocument.OnModified(None)
			nextpage = drPanel(self.mdinotebook, self.ID_APP)
			self.mdinotebook.AddPage(nextpage, "Untitled")			
			l = len(self.txtDocumentArray)
			self.txtDocumentArray.append(DrText(nextpage.documentpanel.center, self.ID_APP, self))
			self.txtPromptArray.append(DrPrompt(nextpage.prompt, self.ID_APP, self))				
			self.txtDocumentArray[l].filename = filename
			self.txtDocumentArray[l].SetTargetPosition(l)
			#copy old finder limodou 2004/04/19
			self.FinderArray.append(drFinder(self, self.Finder))
			#end limodou
			self.lastprogargsArray.append("")
			self.setDocumentTo(l, True)
			#BUG WORKAROUND:
			if self.PLATFORM_IS_WIN:
				w, h = self.currentpage.GetSizeTuple()
				self.currentpage.SetSize(wx.Size(w+1, h+1))
				self.currentpage.SetSize(wx.Size(w, h))
			#END BUG WORKAROUND
		else:
			#Current Tab
			self.txtDocumentArray[self.docPosition].filename = filename
		try:
			cfile = file(filename, 'rb')
			oof = cfile.read()
			if not self.prefs.doconlyusedefaultsyntaxhighlighting:
				if self.checkiffileisPython(filename):
					#Python
					self.txtDocument.currentlanguage = 0
					self.highlightmenu.Check(self.ID_HIGHLIGHT_PYTHON, True)
				elif self.checkiffileisCPP(filename):
					#C/C++
					self.txtDocument.currentlanguage = 1
					self.highlightmenu.Check(self.ID_HIGHLIGHT_CPP, True)
				elif self.checkiffileisHTML(filename):
					#HTML
					self.txtDocument.currentlanguage = 2			
					self.highlightmenu.Check(self.ID_HIGHLIGHT_HTML, True)	
				elif self.checkiffileisPlainText(filename):
					#Plain Text
					self.txtDocument.currentlanguage = 3
					self.highlightmenu.Check(self.ID_HIGHLIGHT_PLAIN_TEXT, True)
				else:
					#Default
					pass
				self.txtDocument.SetupPrefsDocument()

			if self.prefs.autodetectencoding:
				#Encoding (Edited by Dan, 3.6.2)
				#utf-8 auto detect limodou 2004/04/16
				#franz: pychecker: comparision against true superfluos
				if utf8Detect(oof):
					SetEncodedText(self, self.txtDocument, oof, self.defaultlocale)
					#utf-8 detect limodou 2004/04/16
					self.txtDocument.locale = 2
					self.txtPrompt.locale = 2
					#end
				else:
					SetEncodedText(self, self.txtDocument, oof, self.defaultlocale)
				#end limodou
				#/Encoding
			else:
				self.txtDocument.SetText(oof)
			
			self.txtDocument.EmptyUndoBuffer()
			self.txtDocument.SetSavePoint()
			cfile.close()
			
			#Save Stat Info:
			self.txtDocument.mtime = int(os.stat(filename).st_mtime)
			
			if setTitle:
				self.mdinotebook.SetPageText(self.docPosition, os.path.split(filename)[1])
				self.mdinotebook.SetPageImage(self.docPosition, 0)
			
			self.txtDocument.SetScrollWidth(1)
						
			self.UpdateMenuAndToolbar()
			
			if setTitle:
				self.SetTitle("DrPython - " + filename)
			
			#Indentation
			if self.prefs.docusefileindentation:
				indentation = self.txtDocument.CheckIndentation(oof)
				if indentation == -1:
					usetabs = False
				elif indentation == 1:
					usetabs = True
				else:
					usetabs = self.prefs.docusetabs
				self.txtDocument.SetUseTabs(usetabs)
				self.txtDocument.SetupTabs(usetabs)
			
			#Line Endings
						
			self.txtDocument.lineendingsaremixed = 0			
			
			win = self.relewin.search(oof) is not None
			unix = self.releunix.search(oof) is not None
			mac = self.relemac.search(oof) is not None
			
			if win:
				emodenum = 1			
			elif unix:
				emodenum = 0
			elif mac:
				emodenum = 2
			else:
				emodenum = self.prefs.eolmode
			if (win and not (unix == mac)) or ((not win) and (unix and mac)):
				self.txtDocument.lineendingsaremixed = 1

			dmodenum = self.prefs.eolmode
																																	
			if (self.prefs.checkeol):
				if (not emodenum == self.prefs.eolmode):
					if self.txtDocument.lineendingsaremixed:
						d = wx.MessageDialog(self, (filename + " is currently "\
+ self.FFMESSAGE[emodenum] + "(Mixed).\nWould you like to change it to the default?\n(Since the file is mixed, \
this is highly recommended.\nThe Default is: " + self.FFMESSAGE[dmodenum]), "Mixed Line Ending", wx.YES_NO | wx.ICON_QUESTION)
					else:
						d = wx.MessageDialog(self, (filename + " is currently " + self.FFMESSAGE[emodenum] + ".\nWould you like to change it to the default?  The Default is: " + self.FFMESSAGE[dmodenum]), "Line Ending", wx.YES_NO | wx.ICON_QUESTION)					
					answer = d.ShowModal()
					d.Destroy()
					if (answer == wx.ID_YES):
						#Bugfix, Thanks Stephen Anderson.
						if (self.prefs.eolmode == 1):
							self.OnFormatWinMode(None)
						elif (self.prefs.eolmode == 2):
							self.OnFormatMacMode(None)
						else:
							self.OnFormatUnixMode(None)
						self.txtDocument.lineendingsaremixed = 0						
						emodenum = dmodenum
			if emodenum == 1:
				emode = wx.stc.STC_EOL_CRLF
			elif emodenum == 2:
				emode = wx.stc.STC_EOL_CR
			else:
				emode = wx.stc.STC_EOL_LF
			self.txtDocument.SetEOLMode(emode)

			#Scrolling
			linebuffer = self.txtDocument.TextWidth(wx.stc.STC_STYLE_DEFAULT, "OOO")
			lines = oof.split(self.txtDocument.GetEndOfLineCharacter())
			spaces = "\t".expandtabs(self.prefs.tabwidth)			
			line = ""
			length = 0
			for l in lines:
				if len(l) > length:
					length = len(l)
					line = l
			line = line.replace('\t', spaces)		
			self.txtDocument.SetScrollWidth(self.txtDocument.TextWidth(wx.stc.STC_STYLE_DEFAULT, line)+linebuffer)
									
			self.txtDocument.SetXOffset(0)
			#/End Scrolling
			
			#self.txtDocument.OnPositionChanged(None)
			self.txtDocument.OnModified(None)
			
			#Load SourceBrowser:
			if self.prefs.sourcebrowserisvisible:
				self.ShowSourceBrowser()
				
			if (editrecentfiles):
				self.ddirectory = os.path.dirname(filename)
		except IOError:
			self.ShowMessage(("Error Opening: " + filename), "DrPython Error")
				
		#The following chunk of code is an ugly way to work around a bug in wx.STC.
		#As things stand, word wrap may not update on file load.
		#This fixes the problem, by forcing drpython to reset the wx.STC instances.
		if (self.prefs.docwordwrap):
			x, y = self.GetSizeTuple()
			self.SetSize(wx.Size(x+1, y+1))
			self.SetSize(wx.Size(x, y))
		#End of the chunk.
		
		self.reloaddocumentsmenu()
				
		wx.EndBusyCursor()

	def reloaddocumentsmenu(self):
		mnuitems = self.documentsmenu.GetMenuItems()
		num = len(mnuitems)
		x = 0
		while (x < num):
			self.documentsmenu.Remove(mnuitems[x].GetId())
			#mnuitems[x].Destroy()
			x = x + 1
			
		self.setupdocumentsmenu()

	def RemovePluginIcon(self, name):
		f = file(self.homedirectory + "/toolbar.custom.icons.dat", 'r')
		lines = f.read().split('\n')
		f.close()		
		name = "<Plugin>:" + name
		f = file(self.homedirectory + "/toolbar.custom.icons.dat", 'w')
		for line in lines:
			if len(line) > 0:
				currentname = drPrefsFile.ExtractPreferenceFromText(line, "Name")
				if currentname != name:
					f.write(line + '\n')
		f.close()
	
	def runcommand(self, command, statustext = "Running Command"):
		if (self.txtPrompt.pid is -1):
			self.txtPrompt.SetReadOnly(0)
			self.txtPrompt.SetText(command + '\n')
			if (not self.currentpage.PromptIsVisible):
				self.currentpage.PromptIsVisible = True
				self.currentpage.OnSize(None)
			self.txtPrompt.SetScrollWidth(1)
			self.txtPrompt.editpoint = self.txtPrompt.GetLength()
			self.txtPrompt.GotoPos(self.txtPrompt.editpoint)
			self.SetStatusText(statustext, 2)
			self.txtPrompt.process = wx.Process(self)
			self.txtPrompt.process.Redirect()
			if self.PLATFORM_IS_WIN:
				self.txtPrompt.pid = wx.Execute(command, wx.EXEC_ASYNC | wx.EXEC_NOHIDE, self.txtPrompt.process)
			else:
				self.txtPrompt.pid = wx.Execute(command, wx.EXEC_ASYNC, self.txtPrompt.process)
			self.txtPrompt.inputstream = self.txtPrompt.process.GetInputStream()		
			self.txtPrompt.errorstream = self.txtPrompt.process.GetErrorStream()
			self.txtPrompt.outputstream = self.txtPrompt.process.GetOutputStream()			
			self.UpdateMenuAndToolbar()
			self.txtPrompt.SetFocus()
			
	def RunShortcuts(self, event, stc = None, SplitView = 0):
		return drShortcuts.RunShortcuts(self, event, stc, SplitView)

	def SaveDialogSizeAndPosition(self, dialog, dialogfile):
		if self.prefs.rememberdialogsizesandpositions:
			try:
				f = file(self.homedirectory + '/' + dialogfile, 'w')
				x, y = dialog.GetSizeTuple()
				px, py = dialog.GetPositionTuple()
				f.write(str(x) + '\n' + str(y) + '\n' + str(px) + '\n' + str(py))
				f.close()
			except:				
				drScrolledMessageDialog.ShowMessage(dialog, "Error Saving Dialog Size", 'Error')

	def SaveFile(self, docPos, IsSaveAs = False):
		#Submitted Write Access Patch.
		#Edited slightly by Dan (one if statement, string format).
		if (not os.access(self.txtDocumentArray[docPos].filename, os.W_OK)) and (os.path.exists(self.txtDocumentArray[docPos].filename)):
			self.ShowMessage('Error: Write Access: "%s"' % (self.txtDocumentArray[docPos].filename), 'Save Error')
			return
		try:
			if self.prefs.backupfileonsave and not IsSaveAs:
				try:
					shutil.copyfile(self.txtDocumentArray[docPos].filename, self.txtDocumentArray[docPos].filename+".bak")
				except:
					self.ShowMessage(("Error Backing up to: " + self.txtDocumentArray[docPos].filename + ".bak"), "DrPython Error")
				
			cfile = file(self.txtDocumentArray[docPos].filename, 'wb')
			if self.prefs.autodetectencoding:
				#Encoding (Edited by Dan, 3.6.2)
				#comment limodou 2004/04/16
				cfile.write(GetEncodedText(self.txtDocument, self.txtDocument.locale))
				#end limodou
			else:
				cfile.write(self.txtDocumentArray[docPos].GetText())
			cfile.close()
			
			#Save Stat Info:
			self.txtDocumentArray[docPos].mtime = int(os.stat(self.txtDocumentArray[docPos].filename).st_mtime)
		except IOError:
			self.ShowMessage(("Error Writing: " + self.txtDocumentArray[docPos].filename), "DrPython Error")
		self.txtDocumentArray[docPos].SetSavePoint()
		self.txtDocumentArray[docPos].OnModified(None)
				
	def setDocumentTo(self, number, ignoreold = 0):
		prompthasfocus = (self.prefs.promptsize == 100)
		if not ignoreold:
			self.lastprogargsArray[self.docPosition] = self.lastprogargs
			prompthasfocus = self.txtPrompt.GetSTCFocus()
		#copy old finder limodou 2004/04/19
		oldfinder = self.FinderArray[self.docPosition]
		#end limodou
		self.docPosition = number
		self.txtDocument = self.txtDocumentArray[self.docPosition]
		self.txtPrompt = self.txtPromptArray[self.docPosition]
		self.Finder = self.FinderArray[self.docPosition]
		#copy old finder limodou 2004/04/19
		self.Finder.Copy(oldfinder)
		#end limodou
		self.lastprogargs = self.lastprogargsArray[self.docPosition]
		
		self.currentpage = self.mdinotebook.GetPage(number)
		
		if len(self.txtDocument.filename) > 0:
			self.ddirectory = os.path.split(self.txtDocument.filename)[0]
		
		#franz: (Bad Argument).
		self.updatePrefsMDI()
				
		#Syntax Highlighting
		if self.txtDocument.currentlanguage == 0:
			self.highlightmenu.Check(self.ID_HIGHLIGHT_PYTHON, True)
		if self.txtDocument.currentlanguage == 1:
			self.highlightmenu.Check(self.ID_HIGHLIGHT_CPP, True)
		if self.txtDocument.currentlanguage == 2:
			self.highlightmenu.Check(self.ID_HIGHLIGHT_HTML, True)
		if self.txtDocument.currentlanguage == 3:
			#comment limodou 2004/04/13
			self.highlightmenu.Check(self.ID_HIGHLIGHT_PLAIN_TEXT, True)
			#end limodou
							
		if (self.txtDocument.GetModify()):
			if (len(self.txtDocument.filename) <= 0):
				self.SetTitle("DrPython - Untitled " + str(self.txtDocument.untitlednumber) + '[Modified]')
			else:
				self.SetTitle("DrPython - " + self.txtDocument.filename + "[Modified]")
		else:
			if (len(self.txtDocument.filename) <= 0):
				self.SetTitle("DrPython - Untitled " + str(self.txtDocument.untitlednumber))
			else:
				self.SetTitle("DrPython - " + self.txtDocument.filename)
			
		if self.txtPromptArray[self.docPosition].pid is not -1:
			if self.txtPrompt.pythonintepreter:
				self.SetStatusText("Running Python Interpreter", 2)
			else:
				self.SetStatusText(("Running " + os.path.split(self.txtDocument.filename)[1]), 2)
		else:
			self.SetStatusText("", 2)		
		
		self.txtDocument.IsActive = True
		self.txtDocument.targetPosition = number
		self.txtDocument.OnModified(None)
			
		if prompthasfocus:
			self.txtPrompt.SetFocus()
		else:
			self.txtDocument.SetFocus()		
			
		self.mdinotebook.SetSelection(self.docPosition)		

	def setupdocumentsmenu(self):
		self.tabnavmenu = wx.Menu()
		self.tabnavmenu.Append(self.ID_NEXT_DOCUMENT, "Next Document")
		self.tabnavmenu.Append(self.ID_PREVIOUS_DOCUMENT, "Previous Document")
		self.tabnavmenu.Append(self.ID_FIRST_DOCUMENT, "First Document")
		self.tabnavmenu.Append(self.ID_LAST_DOCUMENT, "Last Document")
		self.documentsmenu.AppendMenu(self.ID_DOCUMENT_NAVIGATION_MENU, "Navigation", self.tabnavmenu)
		self.documentsmenu.AppendSeparator()
		self.documentsmenu.Append(self.ID_SAVE_ALL, "Save All Documents")
		self.documentsmenu.AppendSeparator()
		self.documentsmenu.Append(self.ID_CLOSE_ALL, "Close &All Documents")
		self.documentsmenu.Append(self.ID_CLOSE_ALL_OTHER_DOCUMENTS, "Close All &Other Documents")
		self.documentsmenu.AppendSeparator()
		
		x = 0
		l = len(self.txtDocumentArray)
		if l > 10:
			y = 0
			yl = 10
			if yl > l:
				yl = l
			a = 0
			self.documentsubmenus = []
			while y < yl:		
				self.documentsubmenus.append(wx.Menu())
				self.documentsmenu.AppendMenu(self.ID_DOCUMENTS_MENU_BASE+a, str(y+1) + " - " + str(yl), self.documentsubmenus[a])
				while x < yl:
					if len(self.txtDocumentArray[x].filename) > 0:					
						self.documentsubmenus[a].Append(self.ID_DOCUMENTS_BASE+x, os.path.basename(self.txtDocumentArray[x].filename))
					else:
						self.documentsubmenus[a].Append(self.ID_DOCUMENTS_BASE+x, "Untitled " + str(self.txtDocumentArray[x].untitlednumber))
					self.Bind(wx.EVT_MENU, self.OnSelectDocument, id=self.ID_DOCUMENTS_BASE+x)
					x = x + 1
				if y == l:
					break
				y = y + 10
				yl = yl + 10
				a = a + 1
				if yl > l:
					yl = l
		else:
			while x < l:
				if len(self.txtDocumentArray[x].filename) > 0:					
					self.documentsmenu.Append(self.ID_DOCUMENTS_BASE+x, os.path.basename(self.txtDocumentArray[x].filename))
				else:
					self.documentsmenu.Append(self.ID_DOCUMENTS_BASE+x, "Untitled " + str(self.txtDocumentArray[x].untitlednumber))
				self.Bind(wx.EVT_MENU, self.OnSelectDocument, id=self.ID_DOCUMENTS_BASE+x)
				x = x + 1	
	
	def SetupToolBar(self):
		return drToolBarFile.SetupToolBar(self)
	
	def ShowMessage(self, msg, title='DrPython'):
		drScrolledMessageDialog.ShowMessage(self, msg, title)
	
	def ShowSourceBrowser(self):		
		if self.txtDocument.SourceBrowser is None:
			target, i = self.currentpage.GetTargetSashWindow(self.prefs.sourcebrowserpanel)
			self.txtDocument.SourceBrowser = drSourceBrowserPanel(target, -1, self.prefs.sourcebrowserpanel, i)
			self.currentpage.OnSize(None)
		else:
			self.txtDocument.SourceBrowser.Browse()
			self.currentpage.ShowPanel(self.txtDocument.SourceBrowser.Position, self.txtDocument.SourceBrowser.Index, True)
			
	def ShowPrompt(self, Visible = True):
		if Visible:
			if self.currentpage.PromptIsVisible:
				return
			self.currentpage.PromptIsVisible = True
			if self.hasToolBar:
				self.toolbar.ToggleTool(self.ID_TOGGLE_PROMPT,  True)		
			self.currentpage.OnSize(None)
			self.txtPrompt.SetFocus()
		else:
			if not self.currentpage.PromptIsVisible:
				return
			self.currentpage.PromptIsVisible = False
			if self.hasToolBar:
				self.toolbar.ToggleTool(self.ID_TOGGLE_PROMPT,  False)
			self.currentpage.OnSize(None)
			self.txtDocument.SetFocus()			
	
	def UpdateMenuAndToolbar(self):
		thereisafile = (len(self.txtDocument.filename) > 0)
		
		#Toolbar
		if (self.hasToolBar):
			self.toolbar.EnableTool(self.ID_RELOAD, thereisafile)
			
			if (self.txtPrompt.pid is -1):
				self.toolbar.EnableTool(self.ID_PYTHON, True)
				self.toolbar.EnableTool(self.ID_END, False)
				self.toolbar.EnableTool(self.ID_RUN, thereisafile)
				self.toolbar.EnableTool(self.ID_SET_ARGS, thereisafile)			
			else:
				self.toolbar.EnableTool(self.ID_PYTHON, False)
				self.toolbar.EnableTool(self.ID_END, True)
				if thereisafile:
					self.toolbar.EnableTool(self.ID_RUN, False)
					self.toolbar.EnableTool(self.ID_SET_ARGS, False)
		
		#Menus
		self.filemenu.Enable(self.ID_RELOAD, thereisafile)
		self.filemenu.Enable(self.ID_RESTORE_FROM_BACKUP, thereisafile)
		
		if (self.txtPrompt.pid is -1):
			self.programmenu.Enable(self.ID_PYTHON, True)
			self.programmenu.Enable(self.ID_END, False)
			self.programmenu.Enable(self.ID_RUN, thereisafile)
			self.programmenu.Enable(self.ID_SET_ARGS, thereisafile)				
		else:
			self.programmenu.Enable(self.ID_PYTHON, False)
			self.programmenu.Enable(self.ID_END, True)
			if thereisafile:
				self.programmenu.Enable(self.ID_RUN, False)
				self.programmenu.Enable(self.ID_SET_ARGS, False)	
	
	#franz: oldprefs not used.
	def updatePrefsMDI(self):	
		#Determine What is showing
		self.currentpage.OnSize(None)
		
		self.Layout()
		
		self.UpdateMenuAndToolbar()

		#Styling:
		self.txtDocument.StyleResetDefault()
		self.txtDocument.StyleClearAll()
		
		self.txtPrompt.StyleResetDefault()
		self.txtPrompt.StyleClearAll()
				
		self.txtDocument.SetupPrefsDocument(0)
		self.txtPrompt.SetupPrefsPrompt(0)
		
		#Shortcuts
		drShortcuts.SetSTCShortcuts(self.txtPrompt, self.STCShortcuts, self.STCUseDefault)
		self.STCKeycodeArray = drShortcuts.SetSTCShortcuts(self.txtDocument, self.STCShortcuts, self.STCUseDefault)
			
	
	def updatePrefs(self, oldprefs):					
		self.bSizer.Remove(self.mdinotebook)
	
		#Prompt Size:
		self.currentpage.promptsize = self.prefs.promptsize
		
		self.currentpage.OnSize(None)
		
		#Find/Replace:
		if 	(self.prefs.findreplaceregularexpression is not oldprefs.findreplaceregularexpression) or \
		(self.prefs.findreplacematchcase is not oldprefs.findreplacematchcase) or \
		(self.prefs.findreplacefindbackwards is not oldprefs.findreplacefindbackwards) or \
		(self.prefs.findreplacewholeword is not oldprefs.findreplacewholeword) or \
		(self.prefs.findreplaceinselection is not oldprefs.findreplaceinselection) or \
		(self.prefs.findreplacefromcursor is not oldprefs.findreplacefromcursor) or \
		(self.prefs.findreplacepromptonreplace is not oldprefs.findreplacepromptonreplace):
			self.FindOptions = []
			self.ReplaceOptions = []
		
		#SourceBrowser:
		if not (self.prefs.sourcebrowserpanel == oldprefs.sourcebrowserpanel):
			for document in self.txtDocumentArray:
				if document.SourceBrowser:
					document.SourceBrowser = None
		
		#DrScript:
		if self.prefs.drscriptloadexamples is not oldprefs.drscriptloadexamples:
			self.drscriptmenu.reloadscripts()			
		
		#Toolbar
		if (self.prefs.iconsize > 0):
			if (self.hasToolBar):
				self.DestroyToolBar()
				self.SetToolBar(None)
			self.toolbar = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_HORIZONTAL)
			self.ToolBarIdList = self.SetupToolBar()
			self.SetToolBar(self.toolbar)
			self.hasToolBar = 1
		else:
			if (self.hasToolBar):
				self.DestroyToolBar()
				self.SetToolBar(None)
				self.hasToolBar = 0		
		
		if not (oldprefs.recentfileslimit is self.prefs.recentfileslimit):
			self.DestroyRecentFileMenu()
			self.recentfiles = []

			self.LoadRecentFiles()
			self.CreateRecentFileMenu()		

		#Styling:
		self.txtDocument.StyleResetDefault()
		self.txtDocument.StyleClearAll()
		
		self.txtPrompt.StyleResetDefault()
		self.txtPrompt.StyleClearAll()
		
		self.txtDocument.SetupPrefsDocument()
		self.txtPrompt.SetupPrefsPrompt()

		if (oldprefs.docfolding):
			if (not self.prefs.docfolding):
				self.txtDocument.FoldAll(True)
		
		#Add The Stuff to the Sizer
		
		self.bSizer.Add(self.mdinotebook, 1, wx.EXPAND)
		
		self.txtDocument.OnModified(None)
		self.txtDocument.OnPositionChanged(None)
		
		#Parenthesis Matching:
		if oldprefs.docparenthesismatching != self.prefs.docparenthesismatching:
			if not self.prefs.docparenthesismatching:
				#Clear Parenthesis Highlighting
				self.txtDocument.BraceBadLight(wx.stc.STC_INVALID_POSITION)
				self.txtDocument.BraceHighlight(wx.stc.STC_INVALID_POSITION, wx.stc.STC_INVALID_POSITION)
		
		self.Layout()

	def ViewInPanel(self, event):
		docnumber = event.GetId() - self.ID_VIEW_IN_PANEL_BASE		
		
		target, i = self.currentpage.GetTargetSashWindow(self.viewinpaneltarget)
		if docnumber < 0:
			txtDocument = drSplitTextPanel(target, self, self.txtDocumentArray[self.docPosition], self.viewinpaneltarget, i)
		else:
			txtDocument = drSplitTextPanel(target, self, self.txtDocumentArray[docnumber], self.viewinpaneltarget, i)
		self.currentpage.OnSize(None)	
		
	def ViewInPanelMenu(self, event):
		docMenu = wx.Menu()
		x = 0
		l = len(self.txtDocumentArray)
		docMenu.Append(self.ID_VIEW_IN_PANEL_BASE-1, "Current Document")
		self.Bind(wx.EVT_MENU, self.ViewInPanel, id=self.ID_VIEW_IN_PANEL_BASE-1)
		docMenu.AppendSeparator()
		if l > 10:
			y = 0
			yl = 10
			if yl > l:
				yl = l
			a = 0
			docSubMenus = []
			while y < yl:		
				docSubMenus.append(wx.Menu())
				docMenu.AppendMenu(self.ID_VIEW_IN_PANEL_BASE+a, str(y+1) + " - " + str(yl), docSubMenus[a])
				while x < yl:
					if len(self.txtDocumentArray[x].filename) > 0:					
						docSubMenus[a].Append(self.ID_VIEW_IN_PANEL_BASE+x, os.path.basename(self.txtDocumentArray[x].filename))
					else:
						docSubMenus[a].Append(self.ID_VIEW_IN_PANEL_BASE+x, "Untitled " + str(self.txtDocumentArray[x].untitlednumber))
					self.Bind(wx.EVT_MENU, self.ViewInPanel, id=self.ID_VIEW_IN_PANEL_BASE+x)
					x = x + 1
				if y == l:
					break
				y = y + 10
				yl = yl + 10
				a = a + 1
				if yl > l:
					yl = l
		else:
			while x < l:
				if len(self.txtDocumentArray[x].filename) > 0:					
					docMenu.Append(self.ID_VIEW_IN_PANEL_BASE+x, os.path.basename(self.txtDocumentArray[x].filename))
				else:
					docMenu.Append(self.ID_VIEW_IN_PANEL_BASE+x, "Untitled " + str(self.txtDocumentArray[x].untitlednumber))
				self.Bind(wx.EVT_MENU, self.ViewInPanel, id=self.ID_VIEW_IN_PANEL_BASE+x)
				x = x + 1
				
		self.PopupMenu(docMenu, self.ScreenToClient(wx.GetMousePosition()))
		docMenu.Destroy()

	def ViewURLInBrowser(self, url):
		if url.find('http:') == -1:
			url = os.path.normpath(url)
		wx.Execute((self.prefs.documentationbrowser + ' "' + url + '"'), wx.EXEC_ASYNC)
		
	def WriteRecentFiles(self):
		try:
			fin = open((self.homedirectory + "/recent_files.log"), 'w')
			x = 0
			length = len(self.recentfiles)
			while (x < self.prefs.recentfileslimit) and (x < length):
				fin.write(self.recentfiles[x] + '\n')
				x = x + 1
			fin.close()
		except IOError:
			self.ShowMessage(("Error Writing: " + self.homedirectory + "/recent_files.log"), "Recent Files Error")
			
#*******************************************************************************************************

class DrApp(wx.App):

	def OnInit(self):
				
		self.frame = DrFrame(None, 101, "DrPython - Untitled 1")	
		
		self.frame.Show(True)

		self.SetTopWindow(self.frame)
		
		self.Bind(wx.EVT_ACTIVATE_APP, self.OnActivate)

		return True
	
	def OnActivate(self, event):
		if event.GetActive():
			self.frame.OnActivate()
		event.Skip()
	
if __name__ == '__main__':
	app = DrApp(0)
	app.MainLoop()
