Diff of /pype.py [fa04f8] .. [09cb6c] Maximize Restore

  Switch to unified view

a/pype.py b/pype.py
...
...
5
as it appears here: http://www.gnu.org/copyleft/gpl.html
5
as it appears here: http://www.gnu.org/copyleft/gpl.html
6
It is also included with this archive as `gpl.txt <gpl.txt>`_.
6
It is also included with this archive as `gpl.txt <gpl.txt>`_.
7
'''
7
'''
8
8
9
#------------ User-changable settings are available in the menus -------------
9
#------------ User-changable settings are available in the menus -------------
10
from __version__ import *
10
from __version__ import VERSION_, VERSION
11
11
12
#------------------------ Startup/restart information ------------------------
12
#------------------------ Startup/restart information ------------------------
13
import sys, os
13
import sys, os
14
14
15
if sys.platform == 'linux2' and 'DISPLAY' not in os.environ:
15
if sys.platform == 'linux2' and 'DISPLAY' not in os.environ:
16
    raise SystemError('DISPLAY not set when importing or running pype')
16
    raise SystemError('DISPLAY not set when importing or running pype')
17
17
18
from optparse import OptionParser
19
_options = OptionParser()
20
_options.add_option('--version', dest='version', default='2.8',
21
    help='This sets the minimal version of wxPython you would like to use')
22
_options.add_option('--ansi', dest='use_ansi', action='store_true', default=None,
23
    help='This tells PyPE to use an ansi version of wxPython')
24
_options.add_option('--unicode', dest='use_unicode', action='store_true', default=None,
25
    help='This tells PyPE to use a unicode version of wxPython')
26
_options.add_option('--debug', dest='debug', action='store_true', default=False,
27
    help='Enable the debugger shell within PyPE')
28
_options.add_option('--standalone', dest='standalone', action='store_true', default=False,
29
    help='Uses the local .pype for preferences')
30
_options.add_option('--fontsize', dest='fontsize', action='store', type=int, default=None,
31
    help='Sets the base font size')
32
_options.add_option('--port', dest='port', action='store', type=int, default=None,
33
    help='Sets the port on which to listen/check for the other PyPE instance')
34
_options.add_option('--font', dest='font', default=None,
35
    help='Sets the font for PyPE to use instead of it\'s default font')
36
_options.add_option('--use_old_parser', '--use-old-parser', dest='use_old', action='store_true', default=False,
37
    help='Use the older parser instead of the Python 2.6 and later AST parser')
38
_options.add_option('--last', dest='last', action='store_true', default=False,
39
    help='Load the documents that were open when PyPE last closed')
40
41
_options, _args = _options.parse_args()
42
18
if not hasattr(sys, 'frozen'):
43
if not hasattr(sys, 'frozen'):
19
    v = '2.8'
44
    v = _options.version
20
    import wxversion
45
    import wxversion
21
    if '--unicode' in sys.argv:
46
    if _options.use_ansi and _options.use_unicode:
22
        wxversion.ensureMinimal(v+'-unicode', optionsRequired=True)
47
        print 'You can only enable ansi OR unicode, not both'
23
    elif '--ansi' in sys.argv:
48
        raise SystemExit
49
    
50
    if _options.use_ansi or _options.use_unicode:
51
        v = v.split('-')[0]
52
    if _options.use_ansi:
53
        v += '-ansi'
54
    if _options.use_unicode:
55
        v += '-unicode'
24
        wxversion.ensureMinimal(v+'-ansi', optionsRequired=True)
56
    wxversion.ensureMinimal(v, optionsRequired=('-' in v))
25
    else:
26
        wxversion.ensureMinimal(v)
27
57
28
DEBUG = '--debug' in sys.argv
58
DEBUG = _options.debug
29
_standalone = '--standalone' in sys.argv
59
_standalone = _options.standalone
30
USE_THREAD = 1#'--nothread' not in sys.argv
60
USE_THREAD = True
31
32
PRINTMACROS = 0
61
PRINTMACROS = 0
33
#get font size modifications
62
if _options.fontsize:
34
for i in sys.argv:
63
    FONTSIZE = _options.fontsize
35
    if i.startswith('--fontsize='):
64
if _options.port:
36
        try:
65
    PORTNUM = _options.port
37
            FONTSIZE = int(i[11:])
66
if _options.font:
38
        except:
39
            pass
40
        else:
41
            break
42
43
for i in sys.argv:
44
    if i.startswith('--port='):
45
        try:
46
            PORTNUM = int(i[11:])
47
        except:
48
            pass
49
        else:
50
            break
51
52
for i in sys.argv:
53
    if i.startswith('--font='):
54
        FONT = i[7:].replace('_', ' ').replace('-', ' ')
67
    FONT = _options.font.replace('_', ' ').replace('-', ' ')
55
        break
68
USE_NEW = not _options.use_old
56
57
USE_NEW = '--use_old_parser' not in sys.argv
58
69
59
def _restart(orig_path=os.getcwd(), orig_sysargv=sys.argv[:]):
70
def _restart(orig_path=os.getcwd(), orig_sysargv=sys.argv[:]):
60
    os.chdir(orig_path)
71
    os.chdir(orig_path)
61
    args = [sys.executable] + orig_sysargv
72
    args = [sys.executable] + orig_sysargv
62
    if len(spawnargs) == 1:
73
    if len(spawnargs) == 1:
63
        _ = args.pop(0)
74
        _ = args.pop(0)
64
75
65
    os.execvp(args[0], args + ['--last'])
76
    os.execvp(args[0], args + ['--last'])
66
77
67
def keep(i):
68
    if i in ('--ansi', '--unicode', '--debug', '--nothread', '--macros', '--standalone'):
69
        return 0
70
    if i.startswith('--font=') or i.startswith('--fontsize=') or i.startswith('--port='):
71
        return 0
72
    return 1
73
74
sys.argv = [i for i in sys.argv if keep(i)]
75
#-------------- Create reference to this module in __builtins__ --------------
78
#-------------- Create reference to this module in __builtins__ --------------
76
if isinstance(__builtins__, dict):
79
if isinstance(__builtins__, dict):
77
    __builtins__['_pype'] = sys.modules[__name__]
80
    __builtins__['_pype'] = sys.modules[__name__]
78
    __builtins__['USE_NEW'] = USE_NEW
81
    __builtins__['USE_NEW'] = USE_NEW
79
else:
82
else:
...
...
86
import keyword
89
import keyword
87
import imp
90
import imp
88
import md5
91
import md5
89
import pprint
92
import pprint
90
import Queue
93
import Queue
91
import random
92
import re
94
import re
93
import stat
94
import string
95
import string
95
import textwrap
96
import textwrap
96
import threading
97
import threading
97
import time
98
import time
98
import traceback
99
import traceback
...
...
112
from wx import aui
113
from wx import aui
113
_style = aui.AUI_NB_SCROLL_BUTTONS|aui.AUI_NB_TOP
114
_style = aui.AUI_NB_SCROLL_BUTTONS|aui.AUI_NB_TOP
114
from wx import stc
115
from wx import stc
115
wxstc = stc
116
wxstc = stc
116
from wx.lib.dialogs import ScrolledMessageDialog
117
from wx.lib.dialogs import ScrolledMessageDialog
117
from wx.lib.mixins import listctrl
118
from wx.lib.rcsizer import RowColSizer
119
if DEBUG:
118
if DEBUG:
120
    try:
119
    try:
121
        from wx.py import crust
120
        from wx.py import crust
122
    except:
121
    except:
123
        print "Debugging console not available, try to source version of PyPE"
122
        print "Debugging console not available, try to source version of PyPE"
...
...
125
current_path = os.getcwd()
124
current_path = os.getcwd()
126
EFFECTUAL_NORMCASE = os.path.normcase('AbCdEf') == 'abcdef'
125
EFFECTUAL_NORMCASE = os.path.normcase('AbCdEf') == 'abcdef'
127
UNICODE = wx.USE_UNICODE
126
UNICODE = wx.USE_UNICODE
128
127
129
#--------------------- configuration and plugins imports ---------------------
128
#--------------------- configuration and plugins imports ---------------------
130
from configuration import *
129
from configuration import (
130
    REM_SWAP, collapse_style, eol, extns, fmt_Rmode, fmt_mode, getData,
131
    homedir, nosocket, runpath, spawnargs, str_unrepr, stylefile,
132
    unrepr, validate, wildcard
133
)
131
134
132
MAX_SAVE_STATE_DOC_SIZE = 0x400000 #2**22 bytes, a little over a 4 megs
135
MAX_SAVE_STATE_DOC_SIZE = 0x400000 #2**22 bytes, a little over a 4 megs
133
MAX_SAVE_STATE_LINE_COUNT = 20000  #anything more than 4 megs or 20k lines
136
MAX_SAVE_STATE_LINE_COUNT = 20000  #anything more than 4 megs or 20k lines
134
137
135
#change the standard font size
138
#change the standard font size
...
...
153
from plugins import logger
156
from plugins import logger
154
from plugins import lru
157
from plugins import lru
155
from plugins import macro
158
from plugins import macro
156
from plugins import methodhelper
159
from plugins import methodhelper
157
from plugins import parsers
160
from plugins import parsers
161
from plugins import pubsub
158
from plugins import scheduler
162
from plugins import scheduler
159
from plugins import shell
163
from plugins import shell
160
from plugins import single_instance
164
from plugins import single_instance
161
if 'PORTNUM' in globals():
165
if 'PORTNUM' in globals():
162
    single_instance.port = PORTNUM
166
    single_instance.port = PORTNUM
...
...
393
    SOURCE_ID_TO_OPTIONS2 = dict([(i[5], (i[2], i[6])) for i in ASSOC])
397
    SOURCE_ID_TO_OPTIONS2 = dict([(i[5], (i[2], i[6])) for i in ASSOC])
394
    ASSOC.insert(1, ASSOC.pop(0))
398
    ASSOC.insert(1, ASSOC.pop(0))
395
399
396
#checkbox ids
400
#checkbox ids
397
if 1:
401
if 1:
402
    MIDDLE_CL = wx.NewId()
398
    AUTO = wx.NewId()
403
    AUTO = wx.NewId()
399
    FETCH_M = wx.NewId()
404
    FETCH_M = wx.NewId()
405
    AC_KEYWORDS = wx.NewId()
406
    AC_LENGTH = wx.NewId()
400
    NUM = wx.NewId()
407
    NUM = wx.NewId()
401
    MARGIN = wx.NewId()
408
    MARGIN = wx.NewId()
402
    USETABS = wx.NewId()
409
    USETABS = wx.NewId()
403
    INDENTGUIDE = wx.NewId()
410
    INDENTGUIDE = wx.NewId()
404
    WRAPL = wx.NewId()
411
    WRAPL = wx.NewId()
...
...
570
    TOOLS_ENABLE_LKP = dict([(i[3], i[4]) for i in TOOLS_ENABLE_L])
577
    TOOLS_ENABLE_LKP = dict([(i[3], i[4]) for i in TOOLS_ENABLE_L])
571
578
572
    #bookmark support
579
    #bookmark support
573
    BOOKMARKNUMBER = 1
580
    BOOKMARKNUMBER = 1
574
    BOOKMARKSYMBOL = stc.STC_MARK_CIRCLE
581
    BOOKMARKSYMBOL = stc.STC_MARK_CIRCLE
582
    NOTIFICATIONNUMBER = 2
583
    NOTIFICATIONSYMBOL = stc.STC_MARK_SHORTARROW
575
    BOOKMARKMASK = 2
584
    BOOKMARKMASK = 6
585
    NOTIFICATIONMASK = 4
586
    
576
587
577
588
578
#unicode BOM stuff
589
#unicode BOM stuff
579
if 1:
590
if 1:
580
    BOM = [('+/v8-', 'utf-7'),
591
    BOM = [('+/v8-', 'utf-7'),
...
...
661
#
672
#
662
673
663
def get_filetype(fn):
674
def get_filetype(fn):
664
    return extns.get(fn.split('.')[-1].lower(), 'python')
675
    return extns.get(fn.split('.')[-1].lower(), 'python')
665
676
666
def GetClipboardText():
677
fake_primary_clipboard = ''
678
def GetClipboardText(use_primary=False):
667
    success = False
679
    success = False
680
    if not sys.platform.startswith('win'):
681
        wx.TheClipboard.UsePrimarySelection(use_primary)
682
    elif use_primary:
683
        return fake_primary_clipboard
684
668
    do = wx.TextDataObject()
685
    do = wx.TextDataObject()
669
    if wx.TheClipboard.Open():
686
    if wx.TheClipboard.Open():
670
        success = wx.TheClipboard.GetData(do)
687
        success = wx.TheClipboard.GetData(do)
671
        wx.TheClipboard.Close()
688
        wx.TheClipboard.Close()
672
689
673
    if success:
690
    if success:
674
        return do.GetText()
691
        return do.GetText()
675
    return None
692
    return None
676
693
677
def SetClipboardText(txt):
694
def SetClipboardText(txt, use_primary=False):
695
    if not sys.platform.startswith('win'):
696
        wx.TheClipboard.UsePrimarySelection(use_primary)
697
    elif use_primary:
698
        global fake_primary_clipboard
699
        fake_primary_clipboard = txt
700
        return True
678
    do = wx.TextDataObject()
701
    do = wx.TextDataObject()
679
    do.SetText(txt)
702
    do.SetText(txt)
680
    if wx.TheClipboard.Open():
703
    if wx.TheClipboard.Open():
681
        wx.TheClipboard.SetData(do)
704
        wx.TheClipboard.SetData(do)
682
        wx.TheClipboard.Close()
705
        wx.TheClipboard.Close()
683
        return 1
706
        return True
684
    return 0
707
    return False
685
708
686
RESET = {'cursor_posn':0,
709
RESET = {'cursor_posn':0,
687
         'BM':[],
710
         'BM':[],
688
         'FOLD':[]}
711
         'FOLD':[]}
689
712
...
...
1030
            menuAdd(self, editmenu, "Start/End Selection",  "Will allow you to set selection start and end positions without holding shift", self.redirect.OnSelectToggle, wx.NewId())
1053
            menuAdd(self, editmenu, "Start/End Selection",  "Will allow you to set selection start and end positions without holding shift", self.redirect.OnSelectToggle, wx.NewId())
1031
            menuAdd(self, editmenu, "Cut\tCtrl+X",          "Cut selected text", self.OnCut, wx.ID_CUT)
1054
            menuAdd(self, editmenu, "Cut\tCtrl+X",          "Cut selected text", self.OnCut, wx.ID_CUT)
1032
            menuAdd(self, editmenu, "Copy\tCtrl+C",         "Copy selected text", self.OnCopy, wx.ID_COPY)
1055
            menuAdd(self, editmenu, "Copy\tCtrl+C",         "Copy selected text", self.OnCopy, wx.ID_COPY)
1033
            menuAdd(self, editmenu, "Paste\tCtrl+V",        "Paste clipboard text", self.OnPaste, wx.ID_PASTE)
1056
            menuAdd(self, editmenu, "Paste\tCtrl+V",        "Paste clipboard text", self.OnPaste, wx.ID_PASTE)
1034
            menuAdd(self, editmenu, "Delete",               "Delete selected text", self.OnDeleteSelection, pypeID_DELETE)
1057
            menuAdd(self, editmenu, "Delete",               "Delete selected text", self.OnDeleteSelection, pypeID_DELETE)
1058
            
1035
            editmenu.AppendSeparator()
1059
            editmenu.AppendSeparator()
1036
            menuAdd(self, editmenu, "PasteAndDown",         "Paste clipboard text and move cursor down", self.OnPasteAndDown, wx.NewId())
1060
            menuAdd(self, editmenu, "PasteAndDown",         "Paste clipboard text and move cursor down", self.OnPasteAndDown, wx.NewId())
1037
            menuAdd(self, editmenu, "Paste Rectangular",    "Paste clipboard text as a rectangle", self.OnPasteRectangular, wx.NewId())
1061
            menuAdd(self, editmenu, "Paste Rectangular",    "Paste clipboard text as a rectangle", self.OnPasteRectangular, wx.NewId())
1038
            menuAdd(self, editmenu, "Delete Right",         "Delete from caret to end of line", self.OnDeleteRight, wx.NewId())
1062
            menuAdd(self, editmenu, "Delete Right",         "Delete from caret to end of line", self.OnDeleteRight, wx.NewId())
1039
            menuAdd(self, editmenu, "Delete Line",          "Delete current line", self.OnDeleteLine, wx.NewId())
1063
            menuAdd(self, editmenu, "Delete Line",          "Delete current line", self.OnDeleteLine, wx.NewId())
...
...
1131
                menuAdd(self, endingmenu, name, helpt, self.OnLineEndChange, idn, typ)
1155
                menuAdd(self, endingmenu, name, helpt, self.OnLineEndChange, idn, typ)
1132
            #
1156
            #
1133
            setmenu.AppendSeparator()
1157
            setmenu.AppendSeparator()
1134
            menuAdd(self, setmenu, "Show Autocomplete", "Show the autocomplete dropdown while typing", self.OnAutoCompleteToggle, AUTO, wx.ITEM_CHECK)
1158
            menuAdd(self, setmenu, "Show Autocomplete", "Show the autocomplete dropdown while typing", self.OnAutoCompleteToggle, AUTO, wx.ITEM_CHECK)
1135
            menuAdd(self, setmenu, "Use Methods", "Try to only display methods of classes during autocomplete", self.OnUseMethodsToggle, FETCH_M, wx.ITEM_CHECK)
1159
            menuAdd(self, setmenu, "Use Methods", "Try to only display methods of classes during autocomplete", self.OnUseMethodsToggle, FETCH_M, wx.ITEM_CHECK)
1160
            menuAdd(self, setmenu, "Autocomplete Keywords", "Include standard Python keywords and names in the autocomplete list", self.OnUseKeywordsToggle, AC_KEYWORDS, wx.ITEM_CHECK)
1161
            menuAdd(self, setmenu, "Set Autocomplete Length", "The number of characters necessary to produce an autocomplete list", self.OnAutocompleteLength, AC_LENGTH)
1136
            menuAdd(self, setmenu, "Show line numbers", "Show or hide the line numbers on the current document", self.OnNumberToggle, NUM, wx.ITEM_CHECK)
1162
            menuAdd(self, setmenu, "Show line numbers", "Show or hide the line numbers on the current document", self.OnNumberToggle, NUM, wx.ITEM_CHECK)
1137
            menuAdd(self, setmenu, "Show margin", "Show or hide the bookmark signifier margin on the current document", self.OnMarginToggle, MARGIN, wx.ITEM_CHECK)
1163
            menuAdd(self, setmenu, "Show margin", "Show or hide the bookmark signifier margin on the current document", self.OnMarginToggle, MARGIN, wx.ITEM_CHECK)
1138
            menuAdd(self, setmenu, "Show Indentation Guide", "Show or hide gray indentation guides in indentation", self.OnIndentGuideToggle, INDENTGUIDE, wx.ITEM_CHECK)
1164
            menuAdd(self, setmenu, "Show Indentation Guide", "Show or hide gray indentation guides in indentation", self.OnIndentGuideToggle, INDENTGUIDE, wx.ITEM_CHECK)
1139
            menuAdd(self, setmenu, "Show Whitespace", "Show or hide 'whitespace' characters", self.OnWhitespaceToggle, S_WHITE, wx.ITEM_CHECK)
1165
            menuAdd(self, setmenu, "Show Whitespace", "Show or hide 'whitespace' characters", self.OnWhitespaceToggle, S_WHITE, wx.ITEM_CHECK)
1140
            menuAdd(self, setmenu, "Show Line Endings", "Show or hide line ending characters", self.OnLineEndingToggle, S_LEND, wx.ITEM_CHECK)
1166
            menuAdd(self, setmenu, "Show Line Endings", "Show or hide line ending characters", self.OnLineEndingToggle, S_LEND, wx.ITEM_CHECK)
...
...
1197
            menuAdd(self, optionsmenu, "One PyPE", "When checked, will listen on port 9999 for filenames to open", self.OnSingleToggle, SINGLE_ID, wx.ITEM_CHECK)
1223
            menuAdd(self, optionsmenu, "One PyPE", "When checked, will listen on port 9999 for filenames to open", self.OnSingleToggle, SINGLE_ID, wx.ITEM_CHECK)
1198
            menuAdd(self, optionsmenu, "Use Icons", "When checked, the editor uses filetype-specific icons next to file names", self.OnIconToggle, IT_ID, wx.ITEM_CHECK)
1224
            menuAdd(self, optionsmenu, "Use Icons", "When checked, the editor uses filetype-specific icons next to file names", self.OnIconToggle, IT_ID, wx.ITEM_CHECK)
1199
            menuAdd(self, optionsmenu, "Method Colors", "When checked, the editor will use colored icons next to functions and methods based on how 'public' a method is (requires refresh)", self.OnMethodColorToggle, METH_C_ID, wx.ITEM_CHECK)
1225
            menuAdd(self, optionsmenu, "Method Colors", "When checked, the editor will use colored icons next to functions and methods based on how 'public' a method is (requires refresh)", self.OnMethodColorToggle, METH_C_ID, wx.ITEM_CHECK)
1200
            if UNICODE:
1226
            if UNICODE:
1201
                menuAdd(self, optionsmenu, "Always Write BOM", "If checked, will write BOM when coding: directive is found, otherwise not", self.OnBOMToggle, USEBOM_ID, wx.ITEM_CHECK)
1227
                menuAdd(self, optionsmenu, "Always Write BOM", "If checked, will write BOM when coding: directive is found, otherwise not", self.OnBOMToggle, USEBOM_ID, wx.ITEM_CHECK)
1228
            if sys.platform.startswith('win32'):
1229
                menuAdd(self, editmenu, "Enable Middle Paste", "Allows PyPE-centric middle-paste in Windows", self.OnMiddleClickToggle, MIDDLE_CL, wx.ITEM_CHECK)
1202
            menuAdd(self, optionsmenu, "Strict Todo", "When checked, todos must also begin with > character (except xml/html)", self.OnStrictTodoToggle, STRICT_TODO_ID, wx.ITEM_CHECK)
1230
            menuAdd(self, optionsmenu, "Strict Todo", "When checked, todos must also begin with > character (except xml/html)", self.OnStrictTodoToggle, STRICT_TODO_ID, wx.ITEM_CHECK)
1203
            menuAdd(self, optionsmenu, "Set Line Color", "The color of the current line when 'Highlight Current Line' is enabled", self.OnLineColor, wx.NewId())
1231
            menuAdd(self, optionsmenu, "Set Line Color", "The color of the current line when 'Highlight Current Line' is enabled", self.OnLineColor, wx.NewId())
1204
1232
1205
            _om = wx.Menu()
1233
            _om = wx.Menu()
1206
            menuAddM(optionsmenu, _om, "Layout Options", "Options regarding the PyPE window layout")
1234
            menuAddM(optionsmenu, _om, "Layout Options", "Options regarding the PyPE window layout")
...
...
1383
            self.menubar.Check(DOCUMENT_LIST_OPTION_TO_ID[document_options], 1)
1411
            self.menubar.Check(DOCUMENT_LIST_OPTION_TO_ID[document_options], 1)
1384
            if hasattr(self.docpanel, 'recentlyclosed'):
1412
            if hasattr(self.docpanel, 'recentlyclosed'):
1385
                self.menubar.Check(DOCUMENT_LIST_OPTION_TO_ID2[document_options2], 1)
1413
                self.menubar.Check(DOCUMENT_LIST_OPTION_TO_ID2[document_options2], 1)
1386
            self.menubar.Check(SHOW_RECENT, show_recent)
1414
            self.menubar.Check(SHOW_RECENT, show_recent)
1387
            self.menubar.Check(SHOW_SEARCH, show_search)
1415
            self.menubar.Check(SHOW_SEARCH, show_search)
1416
            self.menubar.Check(MIDDLE_CL, MIDDLE_PASTE)
1388
1417
1389
            for i in TOOLS_ENABLE_L:
1418
            for i in TOOLS_ENABLE_L:
1390
                if i[4] in window_management.enabled:
1419
                if i[4] in window_management.enabled:
1391
                    self.menubar.Check(i[0], 1)
1420
                    self.menubar.Check(i[0], 1)
1392
                elif i[1] == 'Global Filter' and global_filter_table:
1421
                elif i[1] == 'Global Filter' and global_filter_table:
...
...
1448
        if USE_THREAD:
1477
        if USE_THREAD:
1449
            self.Bind(EVT_DONE_PARSING, self.doneParsing)
1478
            self.Bind(EVT_DONE_PARSING, self.doneParsing)
1450
            wx.CallAfter(parse_thread, self)
1479
            wx.CallAfter(parse_thread, self)
1451
            wx.CallAfter(check_files, self)
1480
            wx.CallAfter(check_files, self)
1452
1481
1482
        subscribe('document.selected', self.OnDocumentChange)
1483
1453
    ## def RunEvents(self, evt):
1484
    ## def RunEvents(self, evt):
1454
        ## scheduler.GlobalSchedule.run(time.time())
1485
        ## scheduler.GlobalSchedule.run(time.time())
1455
1486
1456
    #...
1487
    #...
1457
    def _activity(self, py=None, stc=None):
1488
    def _activity(self, py=None, stc=None):
...
...
1587
        tb.AddSimpleTool(wx.ID_HELP, icon, "Help!",
1618
        tb.AddSimpleTool(wx.ID_HELP, icon, "Help!",
1588
            "Opens up the help for PyPE")
1619
            "Opens up the help for PyPE")
1589
1620
1590
        tb.Realize()
1621
        tb.Realize()
1591
1622
1592
    def OnDocumentChange(self, stc, forced=False):
1623
    def OnDocumentChange(self, stc_or_msg, forced=False):
1624
        if isinstance(stc_or_msg, dict):
1625
            for stc in self.control:
1626
                if id(stc) == stc_or_msg.stc_id:
1627
                    break
1628
            else:
1629
                return
1630
        else:
1631
            stc = stc_or_msg
1632
1593
        if not forced and not self.starting:
1633
        if not forced and not self.starting:
1594
            self.t.Stop()
1634
            self.t.Stop()
1595
            self.t2.Stop()
1635
            self.t2.Stop()
1596
1636
1597
        if not self.starting:
1637
        if not self.starting:
...
...
1765
            e.Skip()
1805
            e.Skip()
1766
            return
1806
            return
1767
        self.OnCheckMods(force=False)
1807
        self.OnCheckMods(force=False)
1768
        self.redrawvisible()
1808
        self.redrawvisible()
1769
        self.SendSizeEvent()
1809
        self.SendSizeEvent()
1810
        e.Skip()
1770
1811
1771
    def OnCheckMods(self, evt=None, force=True):
1812
    def OnCheckMods(self, evt=None, force=True):
1772
        try:
1813
        try:
1773
            self.control.__iter__
1814
            self.control.__iter__
1774
        except wx.PyDeadObjectError:
1815
        except wx.PyDeadObjectError:
...
...
1853
        if 'lastpath' in self.config:
1894
        if 'lastpath' in self.config:
1854
            self.lastpath = self.config['lastpath']
1895
            self.lastpath = self.config['lastpath']
1855
1896
1856
        doc_def = {}
1897
        doc_def = {}
1857
        #insert global document defaults here
1898
        #insert global document defaults here
1858
        dct =     {'use_tabs':0,
1899
        dct = {
1900
            'use_tabs':0,
1859
             'spaces_per_tab':8,
1901
            'spaces_per_tab':8,
1860
                     'indent':4,
1902
            'indent':4,
1861
                   'collapse':1,
1903
            'collapse':1,
1862
              'marker_margin':1,
1904
            'marker_margin':1,
1863
                'line_margin':1,
1905
            'line_margin':1,
1864
                   'col_line':78,
1906
            'col_line':78,
1865
                   'col_mode':stc.STC_EDGE_LINE,
1907
            'col_mode':stc.STC_EDGE_LINE,
1866
               'indent_guide':0,
1908
            'indent_guide':0,
1867
               'showautocomp':0,
1909
            'showautocomp':0,
1868
              'fetch_methods':1,
1910
            'fetch_methods':1,
1911
            'use_keywords':1,
1869
                   'wrapmode':stc.STC_WRAP_NONE,
1912
            'wrapmode':stc.STC_WRAP_NONE,
1870
                   'sortmode':1,
1913
            'sortmode':1,
1871
                'save_cursor':0,
1914
            'save_cursor':0,
1872
                'cursor_posn':0,
1915
            'cursor_posn':0,
1873
                 'whitespace':0,
1916
            'whitespace':0,
1874
             'show_line_ends':0,
1917
            'show_line_ends':0,
1875
                ## 'triggers':{},
1918
            ## 'triggers':{},
1876
               'findbarprefs':{},
1919
            'findbarprefs':{},
1877
                     'sloppy':0,
1920
            'sloppy':0,
1878
                 'smartpaste':0,
1921
            'smartpaste':0,
1879
                   'showline':0}
1922
            'showline':0,
1923
            'fetch_methods':1,
1924
            'use_keywords':1,
1925
            'ac_length':1,
1926
        }
1880
        for _i in ASSOC:
1927
        for _i in ASSOC:
1881
            doc_def[_i[2]] = dict(dct)
1928
            doc_def[_i[2]] = dict(dct)
1882
            if _i[2] in ('xml', 'html'):
1929
            if _i[2] in ('xml', 'html'):
1883
                doc_def['indent'] = 2
1930
                doc_def['indent'] = 2
1884
            doc_def[_i[2]]['triggers'] = {}
1931
            doc_def[_i[2]]['triggers'] = {}
...
...
1944
                            ('disabled_tools', []),
1991
                            ('disabled_tools', []),
1945
                            ('paths_to_watch', []),
1992
                            ('paths_to_watch', []),
1946
                            ('extensions_to_watch', list(set(extns))),
1993
                            ('extensions_to_watch', list(set(extns))),
1947
                            ('show_search', 1),
1994
                            ('show_search', 1),
1948
                            ('global_filter_table', 0),
1995
                            ('global_filter_table', 0),
1996
                            ('MIDDLE_PASTE', 0),
1949
                            ]:
1997
                            ]:
1950
            if nam in self.config:
1998
            if nam in self.config:
1951
                if isinstance(dflt, dict):
1999
                if isinstance(dflt, dict):
1952
                    for k,v in dflt.iteritems():
2000
                    for k,v in dflt.iteritems():
1953
                        if k not in self.config[nam]:
2001
                        if k not in self.config[nam]:
...
...
2043
        self.config['disabled_tools'] = [i for i in window_management.possible if i not in window_management.enabled]
2091
        self.config['disabled_tools'] = [i for i in window_management.possible if i not in window_management.enabled]
2044
        self.config['paths_to_watch'] = paths_to_watch
2092
        self.config['paths_to_watch'] = paths_to_watch
2045
        self.config['extensions_to_watch'] = extensions_to_watch
2093
        self.config['extensions_to_watch'] = extensions_to_watch
2046
        self.config['show_search'] = show_search
2094
        self.config['show_search'] = show_search
2047
        self.config['global_filter_table'] = global_filter_table
2095
        self.config['global_filter_table'] = global_filter_table
2096
        self.config['MIDDLE_PASTE'] = MIDDLE_PASTE
2048
        try:
2097
        try:
2049
            if UNICODE:
2098
            if UNICODE:
2050
                path = os.sep.join([self.configPath, 'history.u.txt'])
2099
                path = os.sep.join([self.configPath, 'history.u.txt'])
2051
            else:
2100
            else:
2052
                path = os.sep.join([self.configPath, 'history.txt'])
2101
                path = os.sep.join([self.configPath, 'history.txt'])
...
...
2470
2519
2471
        if used_default and nwin.GetTextLength() < 200000:
2520
        if used_default and nwin.GetTextLength() < 200000:
2472
            # try to detect the "true" defaults
2521
            # try to detect the "true" defaults
2473
            state['use_tabs'], state['spaces_per_tab'], state['indent'] = \
2522
            state['use_tabs'], state['spaces_per_tab'], state['indent'] = \
2474
                parsers.detectLineIndent(nwin.lines, state['use_tabs'], state['spaces_per_tab'], state['indent'])
2523
                parsers.detectLineIndent(nwin.lines, state['use_tabs'], state['spaces_per_tab'], state['indent'])
2475
            print "detected", state['use_tabs'], state['spaces_per_tab'], state['indent']
2524
            ## print "detected", state['use_tabs'], state['spaces_per_tab'], state['indent']
2476
2525
2477
        nwin.SetSaveState(state)
2526
        nwin.SetSaveState(state)
2478
2527
2479
        ## print 3
2528
        ## print 3
2480
        if fn == ' ':
2529
        if fn == ' ':
...
...
2496
        if switch:
2545
        if switch:
2497
            nwin.SetFocus()
2546
            nwin.SetFocus()
2498
        ## self.OnDocumentChange(nwin)
2547
        ## self.OnDocumentChange(nwin)
2499
        self.docpanel._refresh()
2548
        self.docpanel._refresh()
2500
        wx.CallAfter(self._updateChecks)
2549
        wx.CallAfter(self._updateChecks)
2550
        pubsub.publish('document.open', stc_id=id(nwin))
2501
        return nwin.enc
2551
        return nwin.enc
2552
    ## newTab = auto_thaw(newTab)
2502
2553
2503
    def OnReload(self, e, win=None):
2554
    def OnReload(self, e, win=None):
2504
        if win == None:
2555
        if win == None:
2505
            num, win = self.getNumWin(e)
2556
            num, win = self.getNumWin(e)
2506
        if not e is None:
2557
        if not e is None:
...
...
2591
        if hasattr(win, "kill"):
2642
        if hasattr(win, "kill"):
2592
            win.kill()
2643
            win.kill()
2593
        if hasattr(win, 't'):
2644
        if hasattr(win, 't'):
2594
            win.t.Stop()
2645
            win.t.Stop()
2595
            win.t2.Stop()
2646
            win.t2.Stop()
2647
        pubsub.publish('document.close', stc_id=id(win))
2596
        self.control.DeletePage(wnum)
2648
        self.control.DeletePage(wnum)
2597
        self.updateWindowTitle()
2649
        self.updateWindowTitle()
2598
        self.docpanel._refresh()
2650
        self.docpanel._refresh()
2599
        wx.CallAfter(self._updateChecks)
2651
        wx.CallAfter(self._updateChecks)
2600
2652
...
...
2699
            return num, self.control.GetPage(num).GetWindow1()
2751
            return num, self.control.GetPage(num).GetWindow1()
2700
        if e:
2752
        if e:
2701
            e.Skip()
2753
            e.Skip()
2702
        raise cancelled
2754
        raise cancelled
2703
2755
2756
    def OnMiddleClickToggle(self, evt):
2757
        global MIDDLE_PASTE
2758
        MIDDLE_PASTE = not MIDDLE_PASTE
2759
2704
    def OnShowFindbar(self, evt):
2760
    def OnShowFindbar(self, evt):
2705
        num, win = self.getNumWin(evt)
2761
        num, win = self.getNumWin(evt)
2706
        if win.parent.IsSplit() and not isinstance(win.parent.GetWindow2(), findbar.FindBar):
2762
        if win.parent.IsSplit() and not isinstance(win.parent.GetWindow2(), findbar.FindBar):
2707
            win.parent.GetWindow2().close()
2763
            win.parent.GetWindow2().close()
2708
2764
...
...
2758
2814
2759
    def OnFindAgain(self, evt):
2815
    def OnFindAgain(self, evt):
2760
        num, win = self.getNumWin(evt)
2816
        num, win = self.getNumWin(evt)
2761
        if win.parent.IsSplit():
2817
        if win.parent.IsSplit():
2762
            win.parent.GetWindow2().OnFindN(evt)
2818
            win.parent.GetWindow2().OnFindN(evt)
2819
        else:
2820
            try:
2821
                prefs = win.findbarprefs
2822
            except:
2823
                prefs = {}
2824
            if prefs.get('find',[]):
2825
                bar = findbar.FindBar(win.parent, self)
2826
                win.parent.SplitHorizontally(win, bar, -(bar.GetBestSize())[1]-5, 1-findbar_location)
2827
                win.parent.GetWindow2().OnFindN(evt)
2763
        win.SetFocus()
2828
        win.SetFocus()
2764
2829
2765
#----------------------------- View Menu Methods -----------------------------
2830
#----------------------------- View Menu Methods -----------------------------
2766
    def OnZoom(self, e):
2831
    def OnZoom(self, e):
2767
        wnum, win = self.getNumWin(e)
2832
        wnum, win = self.getNumWin(e)
...
...
2794
    def OnRefresh(self, e, win=None):
2859
    def OnRefresh(self, e, win=None):
2795
        if win is None:
2860
        if win is None:
2796
            num, win = self.getNumWin(e)
2861
            num, win = self.getNumWin(e)
2797
        self.OnDocumentChange(win, True)
2862
        self.OnDocumentChange(win, True)
2798
2863
2799
    def OnToggleBookmark (self, e):
2864
    def OnToggleBookmark(self, e):
2800
        wnum, win = self.getNumWin(e)
2865
        wnum, win = self.getNumWin(e)
2801
        lineNo = win.GetCurrentLine()
2866
        lineNo = win.GetCurrentLine()
2867
        if win.MarkerGet(lineNo) & NOTIFICATIONMASK:
2868
            win.MarkerDelete(lineNo, NOTIFICATIONNUMBER)
2802
        if win.MarkerGet(lineNo) & BOOKMARKMASK:
2869
        elif win.MarkerGet(lineNo) & BOOKMARKMASK:
2803
            win.MarkerDelete(lineNo, BOOKMARKNUMBER)
2870
            win.MarkerDelete(lineNo, BOOKMARKNUMBER)
2804
        else:
2871
        else:
2805
            win.MarkerAdd(lineNo, BOOKMARKNUMBER)
2872
            win.MarkerAdd(lineNo, BOOKMARKNUMBER)
2806
2873
2807
    def OnNextBookmark  (self, e):
2874
    def OnNextBookmark(self, e):
2808
        wnum, win = self.getNumWin(e)
2875
        wnum, win = self.getNumWin(e)
2809
        lineNo = win.GetCurrentLine()
2876
        lineNo = win.GetCurrentLine()
2810
        newLineNo = win.MarkerNext(lineNo + 1, BOOKMARKMASK)
2877
        newLineNo = win.MarkerNext(lineNo + 1, BOOKMARKMASK)
2811
        if newLineNo != -1:
2878
        if newLineNo != -1:
2812
            win.GotoLine(newLineNo)
2879
            win.GotoLine(newLineNo)
...
...
2816
            if newLineNo != -1:
2883
            if newLineNo != -1:
2817
                win.GotoLine(newLineNo)
2884
                win.GotoLine(newLineNo)
2818
        win.EnsureVisible(win.GetCurrentLine())
2885
        win.EnsureVisible(win.GetCurrentLine())
2819
        win.EnsureCaretVisible()
2886
        win.EnsureCaretVisible()
2820
2887
2821
    def OnPreviousBookmark (self, e):
2888
    def OnPreviousBookmark(self, e):
2822
        wnum, win = self.getNumWin(e)
2889
        wnum, win = self.getNumWin(e)
2823
        lineNo = win.GetCurrentLine()
2890
        lineNo = win.GetCurrentLine()
2824
        newLineNo = win.MarkerPrevious(lineNo - 1, BOOKMARKMASK)
2891
        newLineNo = win.MarkerPrevious(lineNo - 1, BOOKMARKMASK)
2825
        if newLineNo != -1:
2892
        if newLineNo != -1:
2826
            win.GotoLine(newLineNo)
2893
            win.GotoLine(newLineNo)
...
...
2831
                win.GotoLine(newLineNo)
2898
                win.GotoLine(newLineNo)
2832
        win.EnsureVisible(win.GetCurrentLine())
2899
        win.EnsureVisible(win.GetCurrentLine())
2833
        win.EnsureCaretVisible()
2900
        win.EnsureCaretVisible()
2834
2901
2835
    def OnLeft(self, e):
2902
    def OnLeft(self, e):
2903
        if self.control.GetSelection() == 0:
2904
            self.control.SetSelection(self.control.GetPageCount() - 1)
2905
        else:
2836
        self.control.AdvanceSelection(False)
2906
            self.control.AdvanceSelection(False)
2837
2907
2838
    def OnRight(self, e):
2908
    def OnRight(self, e):
2909
        pc = self.control.GetPageCount()
2910
        if pc and self.control.GetSelection() == (pc - 1):
2911
            self.control.SetSelection(0)
2912
        else:
2839
        self.control.AdvanceSelection(True)
2913
           self.control.AdvanceSelection(True)
2840
2914
2841
    def OnFindDefn(self, e):
2915
    def OnFindDefn(self, e):
2842
        if 'filter' not in window_management.enabled:
2916
        if 'filter' not in window_management.enabled:
2843
            self.SetStatusText("Error: you must enable the filter in 'Options -> Tool Options' to use this feature")
2917
            self.SetStatusText("Error: you must enable the filter in 'Options -> Tool Options' to use this feature")
2844
            return
2918
            return
...
...
2938
        self.control.updateChecks(win)
3012
        self.control.updateChecks(win)
2939
3013
2940
    def OnUseMethodsToggle(self, e):
3014
    def OnUseMethodsToggle(self, e):
2941
        n, win = self.getNumWin(e)
3015
        n, win = self.getNumWin(e)
2942
        win.fetch_methods = not win.fetch_methods
3016
        win.fetch_methods = not win.fetch_methods
3017
3018
    def OnUseKeywordsToggle(self, e):
3019
        n, win = self.getNumWin(e)
3020
        win.use_keywords = not win.use_keywords
3021
3022
    def OnAutocompleteLength(self, e):
3023
        n, win = self.getNumWin(e)
3024
        rslt = self.getInt("Autocomplete Length",
3025
                           "How many characters must be typed in order for\n"\
3026
                           "autocomplete to offer suggestions? Enter an integer > 0.",
3027
                           win.ac_length)
3028
        
3029
        win.ac_length = rslt
2943
3030
2944
    def OnNumberToggle(self, e):
3031
    def OnNumberToggle(self, e):
2945
        n, win = self.getNumWin(e)
3032
        n, win = self.getNumWin(e)
2946
        win.SetMarginWidth(0, not win.GetMarginWidth(0))
3033
        win.SetMarginWidth(0, not win.GetMarginWidth(0))
2947
3034
...
...
3339
        self.menubar.Check(e.GetId(), 1)
3426
        self.menubar.Check(e.GetId(), 1)
3340
        global HOW_OFTEN2
3427
        global HOW_OFTEN2
3341
        HOW_OFTEN2 = REFRESH_DELAY_ID_TO_NUM[e.GetId()]
3428
        HOW_OFTEN2 = REFRESH_DELAY_ID_TO_NUM[e.GetId()]
3342
3429
3343
    def SharedCaret(self):
3430
    def SharedCaret(self):
3344
        _, flags = CARET_OPTION_TO_ID[caret_option]
3345
        for win in self.control:
3431
        for win in self.control:
3346
            win.SetXCaretPolicy(flags, caret_slop*caret_multiplier)
3432
            win.SetSlopPolicy()
3347
            win.SetYCaretPolicy(flags, caret_slop)
3348
            win.SetSelection(*win.GetSelection())
3349
3433
3350
    def OnFinbarDefault(self, e):
3434
    def OnFinbarDefault(self, e):
3351
        n, win = self.getNumWin()
3435
        n, win = self.getNumWin()
3352
        if win.GetParent().IsSplit():
3436
        if win.GetParent().IsSplit():
3353
            win.GetParent().GetWindow2().savePreferences()
3437
            win.GetParent().GetWindow2().savePreferences()
...
...
3514
    def keyboardShortcut(self, keypressed, evt=None):
3598
    def keyboardShortcut(self, keypressed, evt=None):
3515
        menuid = HOTKEY_TO_ID[keypressed]
3599
        menuid = HOTKEY_TO_ID[keypressed]
3516
        wx.PostEvent(self, wx.MenuEvent(wx.wxEVT_COMMAND_MENU_SELECTED, menuid))
3600
        wx.PostEvent(self, wx.MenuEvent(wx.wxEVT_COMMAND_MENU_SELECTED, menuid))
3517
3601
3518
    def OnKeyPressed(self, event):
3602
    def OnKeyPressed(self, event):
3519
        showpress=0
3603
        showpress = False
3520
        self._activity()
3604
        self._activity()
3521
        keypressed = GetKeyPress(event)
3605
        keypressed = GetKeyPress(event)
3522
3606
3523
        #fix for funky bug on OS X
3607
        #fix for funky bug on OS X
3524
        if not self.menubar.IsEnabled(wx.ID_UNDO):
3608
        if not self.menubar.IsEnabled(wx.ID_UNDO):
3525
            for menuid in (wx.ID_UNDO, wx.ID_REDO, wx.ID_CUT, wx.ID_COPY):
3609
            for menuid in (wx.ID_UNDO, wx.ID_REDO, wx.ID_CUT, wx.ID_COPY):
3526
                self.menubar.Enable(menuid, 1)
3610
                self.menubar.Enable(menuid, 1)
3527
3611
3612
        if showpress:
3528
        if showpress: print "keypressed", keypressed
3613
            print "keypressed", keypressed
3529
3614
3530
        if keypressed in HOTKEY_TO_ID:
3615
        if keypressed in HOTKEY_TO_ID:
3531
            return self.keyboardShortcut(keypressed, event)
3616
            return self.keyboardShortcut(keypressed, event)
3532
        if self.macropage.RunMacro(keypressed):
3617
        if self.macropage.RunMacro(keypressed):
3533
            return
3618
            return
...
...
3604
        ## else:
3689
        ## else:
3605
            ## print "no tip", repr(word)
3690
            ## print "no tip", repr(word)
3606
3691
3607
    def _ac(self, win):
3692
    def _ac(self, win):
3608
        cur, colpos, word, method = self.getLeftFunct(win)
3693
        cur, colpos, word, method = self.getLeftFunct(win)
3609
        if not word:
3694
        if not word or len(word) < win.ac_length:
3610
            return win.AutoCompCancel()
3695
            return win.AutoCompCancel()
3611
3696
3612
        ## print "got word:", word
3697
        ## print "got word:", word
3613
3698
3614
        words = None
3699
        words = None
3615
        if method and win.fetch_methods:
3700
        if method and win.fetch_methods:
3616
            ## print "found method!"
3617
            words = win._method_listing(win.lines.curlinei, cur, word) or []
3701
            words = win._method_listing(win.lines.curlinei, cur, word) or []
3618
        if not words:
3702
        if not words:
3619
            words = sorted([i for i in win.kw.split() if i.startswith(word)] + win._name_listing(win.lines.curlinei, cur, word))
3703
            words = win._name_listing(win.lines.curlinei, cur, word)
3704
            if win.use_keywords:
3705
                words.extend(i for i in win.kw.split() if i.startswith(word))
3706
            words.sort()
3620
3707
3621
        if len(words) == 0:
3708
        if len(words) == 0:
3622
            ## print 'no words!'
3709
            ## print 'no words!'
3623
            return win.AutoCompCancel()
3710
            return win.AutoCompCancel()
3624
        if len(words) == 1 and words[-1] == word:
3711
        if len(words) == 1 and words[-1] == word:
...
...
3718
        self.SetEndAtLastLine(False)
3805
        self.SetEndAtLastLine(False)
3719
        self.paste_rectangle = None
3806
        self.paste_rectangle = None
3720
        self.cached = None
3807
        self.cached = None
3721
        self.loaded = True
3808
        self.loaded = True
3722
        self.MarkerDefine(BOOKMARKNUMBER, BOOKMARKSYMBOL, 'blue', 'blue')
3809
        self.MarkerDefine(BOOKMARKNUMBER, BOOKMARKSYMBOL, 'blue', 'blue')
3810
        self.MarkerDefine(NOTIFICATIONNUMBER, NOTIFICATIONSYMBOL, 'green', 'green')
3723
3811
3724
        _, flags = CARET_OPTION_TO_ID[caret_option]
3812
        _, flags = CARET_OPTION_TO_ID[caret_option]
3725
        self.SetXCaretPolicy(flags, caret_slop*caret_multiplier)
3813
        self.SetXCaretPolicy(flags, caret_slop*caret_multiplier)
3726
        self.SetYCaretPolicy(flags, caret_slop)
3814
        self.SetYCaretPolicy(flags, caret_slop)
3727
3815
...
...
3744
        self.lexer = 'text'
3832
        self.lexer = 'text'
3745
        self.selep = None
3833
        self.selep = None
3746
        self.recording = 0
3834
        self.recording = 0
3747
        self.macro = []
3835
        self.macro = []
3748
        self.fetch_methods = 0
3836
        self.fetch_methods = 0
3837
        self.use_keywords = 0
3838
        self.ac_length = 1
3749
        self.fetch_methods_cache = [-1, 0, '', []]
3839
        self.fetch_methods_cache = [-1, 0, '', []]
3750
3840
3751
        #drop file and text support
3841
        #drop file and text support
3752
        self.SetDropTarget(FileDropTarget(self.root))
3842
        self.SetDropTarget(FileDropTarget(self.root))
3753
3843
...
...
3829
        #unavailable in 2.5.1.2, didn't work in previous versions of wxPython
3919
        #unavailable in 2.5.1.2, didn't work in previous versions of wxPython
3830
        # stc.EVT_STC_POSCHANGED(self, ID, self.pos)
3920
        # stc.EVT_STC_POSCHANGED(self, ID, self.pos)
3831
        stc.EVT_STC_SAVEPOINTREACHED(self, ID, self.MakeClean)
3921
        stc.EVT_STC_SAVEPOINTREACHED(self, ID, self.MakeClean)
3832
        stc.EVT_STC_SAVEPOINTLEFT(self, ID, self.MakeDirty)
3922
        stc.EVT_STC_SAVEPOINTLEFT(self, ID, self.MakeDirty)
3833
        stc.EVT_STC_NEEDSHOWN(self, ID, self.OnNeedShown)
3923
        stc.EVT_STC_NEEDSHOWN(self, ID, self.OnNeedShown)
3924
        self.Bind(wx.EVT_LEFT_UP, self.OnSelectionEnd)
3925
        if not isinstance(self, View):
3926
            self.Bind(wx.EVT_MIDDLE_UP, self.OnMousePaste)
3834
        self.Bind(stc.EVT_STC_MACRORECORD, self.GotEvent)
3927
        self.Bind(stc.EVT_STC_MACRORECORD, self.GotEvent)
3835
        self.SetModEventMask(stc.STC_MOD_INSERTTEXT|stc.STC_MOD_DELETETEXT|stc.STC_PERFORMED_USER|stc.STC_PERFORMED_UNDO|stc.STC_PERFORMED_REDO)
3928
        self.SetModEventMask(stc.STC_MOD_INSERTTEXT|stc.STC_MOD_DELETETEXT|stc.STC_PERFORMED_USER|stc.STC_PERFORMED_UNDO|stc.STC_PERFORMED_REDO)
3836
3929
3837
        if REM_SWAP:
3930
        if REM_SWAP:
3838
            self.CmdKeyClear(ord('T'), stc.STC_SCMOD_CTRL)
3931
            self.CmdKeyClear(ord('T'), stc.STC_SCMOD_CTRL)
...
...
3864
3957
3865
        try:
3958
        try:
3866
            self.IndicatorSetUnder(1)
3959
            self.IndicatorSetUnder(1)
3867
        except:
3960
        except:
3868
            pass
3961
            pass
3962
3963
    def SetSlopPolicy(self):
3964
        _, flags = CARET_OPTION_TO_ID[caret_option]
3965
        self.SetXCaretPolicy(flags, caret_slop*caret_multiplier)
3966
        self.SetYCaretPolicy(flags, caret_slop)
3967
        self.SetCaretWidth(CARET_WIDTH)
3869
3968
3870
    def gotcharacter(self):
3969
    def gotcharacter(self):
3871
        ## self._gotcharacter()
3970
        ## self._gotcharacter()
3872
        self.root._activity(self.lexer == 'python', self)
3971
        self.root._activity(self.lexer == 'python', self)
3873
3972
...
...
4196
                'show_line_ends':self.GetViewEOL(),
4295
                'show_line_ends':self.GetViewEOL(),
4197
                'sloppy':self.sloppy,
4296
                'sloppy':self.sloppy,
4198
                'smartpaste':self.smartpaste,
4297
                'smartpaste':self.smartpaste,
4199
                'showline':self.GetCaretLineVisible(),
4298
                'showline':self.GetCaretLineVisible(),
4200
                'fetch_methods':self.fetch_methods,
4299
                'fetch_methods':self.fetch_methods,
4300
                'use_keywords':self.use_keywords,
4301
                'ac_length':self.ac_length,
4201
               }
4302
               }
4202
        if not self.save_cursor and not scp:
4303
        if not self.save_cursor and not scp:
4203
            del ret['cursor_posn']
4304
            del ret['cursor_posn']
4204
        if self.GetTextLength() < MAX_SAVE_STATE_DOC_SIZE:
4305
        if self.GetTextLength() < MAX_SAVE_STATE_DOC_SIZE:
4205
            ret['checksum'] = md5.new(self.GetText(0)).hexdigest()
4306
            ret['checksum'] = md5.new(self.GetText(0)).hexdigest()
...
...
4227
        self.SetEdgeColumn(saved['col_line'])
4328
        self.SetEdgeColumn(saved['col_line'])
4228
        self.SetEdgeMode(saved['col_mode'])
4329
        self.SetEdgeMode(saved['col_mode'])
4229
        self.SetIndentationGuides(saved['indent_guide'])
4330
        self.SetIndentationGuides(saved['indent_guide'])
4230
        self.showautocomp = saved['showautocomp']
4331
        self.showautocomp = saved['showautocomp']
4231
        self.fetch_methods = saved['fetch_methods']
4332
        self.fetch_methods = saved['fetch_methods']
4333
        self.use_keywords = saved['use_keywords']
4334
        self.ac_length = saved['ac_length']
4232
        self.findbarprefs = dict(saved.get('findbarprefs', {}))
4335
        self.findbarprefs = dict(saved.get('findbarprefs', {}))
4233
        self.triggers = saved.get('triggers', {})
4336
        self.triggers = saved.get('triggers', {})
4234
        self.sloppy = saved['sloppy']
4337
        self.sloppy = saved['sloppy']
4235
        self.smartpaste = saved['smartpaste']
4338
        self.smartpaste = saved['smartpaste']
4236
        self.SetCaretLineVisible(saved['showline'])
4339
        self.SetCaretLineVisible(saved['showline'])
...
...
4541
    def do(self, funct, dirty=1):
4644
    def do(self, funct, dirty=1):
4542
        if dirty:
4645
        if dirty:
4543
            self.MakeDirty(None)
4646
            self.MakeDirty(None)
4544
        funct(self)
4647
        funct(self)
4545
        self.root.redrawvisible(self)
4648
        self.root.redrawvisible(self)
4649
4546
    def SelectLines(self, force=0):
4650
    def SelectLines(self, force=0):
4547
        x,y = self.GetSelection()
4651
        x,y = self.GetSelection()
4548
        if not force and x==y:
4652
        if not force and x==y:
4549
            return
4653
            return
4550
4654
...
...
4555
4659
4556
    def Cut(self):
4660
    def Cut(self):
4557
        if self.sloppy and not self.SelectionIsRectangle():
4661
        if self.sloppy and not self.SelectionIsRectangle():
4558
            self.SelectLines()
4662
            self.SelectLines()
4559
        interpreter.FutureCall(1, self.do, stc.StyledTextCtrl.Cut)
4663
        interpreter.FutureCall(1, self.do, stc.StyledTextCtrl.Cut)
4664
4560
    def Copy(self):
4665
    def Copy(self):
4561
        if self.sloppy and not self.SelectionIsRectangle():
4666
        if self.sloppy and not self.SelectionIsRectangle():
4562
            self.SelectLines()
4667
            self.SelectLines()
4563
        interpreter.FutureCall(1, self.do, stc.StyledTextCtrl.Copy, 0)
4668
        interpreter.FutureCall(1, self.do, stc.StyledTextCtrl.Copy, 0)
4564
4669
...
...
4596
                lw = lw.replace(repl, '\t')
4701
                lw = lw.replace(repl, '\t')
4597
            out.append(lw+lr)
4702
            out.append(lw+lr)
4598
4703
4599
        return self.format.join(out)
4704
        return self.format.join(out)
4600
4705
4601
    def Paste(self):
4706
    def Paste(self, use_primary=False):
4707
        d = GetClipboardText(use_primary)
4602
        while self.smartpaste:
4708
        while self.smartpaste:
4603
            if self.recording:
4709
            if self.recording:
4604
                self.macro.append((2179, 0, 0))
4710
                self.macro.append((2179, 0, 0))
4605
4711
4606
            x,y = self.GetSelection()
4712
            x,y = self.GetSelection()
4607
            dofirst = x != y
4713
            dofirst = x != y
4608
            d = GetClipboardText()
4609
            if d is None or '\n' not in d:
4714
            if d is None or '\n' not in d:
4610
                if self.recording:
4715
                if self.recording:
4611
                    _ = self.macro.pop()
4716
                    _ = self.macro.pop()
4612
                break
4717
                break
4613
4718
...
...
4634
                self.ReplaceSelection(x)
4739
                self.ReplaceSelection(x)
4635
            finally:
4740
            finally:
4636
                self.EndUndoAction()
4741
                self.EndUndoAction()
4637
            return
4742
            return
4638
4743
4639
        self.do(stc.StyledTextCtrl.Paste)
4744
        self.do((lambda slf, d=d: slf.ReplaceSelection(d)), True)
4640
4745
4641
    def PasteRectangular(self):
4746
    def PasteRectangular(self):
4642
        if self.recording:
4747
        if self.recording:
4643
            self.macro.append((None, '', 'PasteRectangular'))
4748
            self.macro.append((None, '', 'PasteRectangular'))
4644
        _, self.recording = self.recording, 0
4749
        _, self.recording = self.recording, 0
...
...
5466
                break
5571
                break
5467
        return cur_scope
5572
        return cur_scope
5468
5573
5469
    def _name_listing(self, curline, curcol, prefix=''):
5574
    def _name_listing(self, curline, curcol, prefix=''):
5470
        cur_scope = self.get_scope(curline, curcol)
5575
        cur_scope = self.get_scope(curline, curcol)
5576
        ## print cur_scope
5471
        available = set()
5577
        available = set()
5472
        while cur_scope:
5578
        while cur_scope:
5473
            ## print "using scope for the name listing", cur_scope.long, cur_scope.locals
5474
            available.update(name for name in cur_scope.locals if isinstance(name, basestring) and name.startswith(prefix))
5579
            available.update(name for name in cur_scope.locals if isinstance(name, basestring) and name.startswith(prefix))
5475
            cur_scope = cur_scope.search_list
5580
            cur_scope = cur_scope.search_list
5476
        return sorted(available)
5581
        return sorted(available)
5477
5582
5478
    def _method_listing(self, curline, curcol, prefix=''):
5583
    def _method_listing(self, curline, curcol, prefix=''):
...
...
5761
    def _invalidate_cache(self):
5866
    def _invalidate_cache(self):
5762
        self.cache = None
5867
        self.cache = None
5763
        self.m2 = None
5868
        self.m2 = None
5764
        self.gotcharacter()
5869
        self.gotcharacter()
5765
5870
5871
    def OnMousePaste(self, evt):
5872
        """Paste the primary selection (on unix) at the mouse cursor location
5873
        
5874
        This currently supports only the primary selection.
5875
        """
5876
        if sys.platform.startswith('win') and not MIDDLE_PASTE:
5877
            return evt.Skip()
5878
5879
        pos = self.PositionFromPoint(wx.Point(evt.GetX(), evt.GetY()))
5880
        if pos != stc.STC_INVALID_POSITION:
5881
            self.SetSelection(pos, pos)
5882
            self.Paste(True)
5883
5884
    def OnSelectionEnd(self, evt):
5885
        """Copy the selected region into the primary selection
5886
    
5887
        This currently supports unix only, because it depends on the primary
5888
        selection of the clipboard.
5889
        
5890
        Borrowed and mangled from peppy via the url:
5891
        http://markmail.org/message/qyvzus77xpjqmxtw
5892
        """
5893
        evt.Skip()
5894
        if MIDDLE_PASTE or sys.platform.startswith('win'):
5895
            wx.CallAfter(self._OnSelectionEnd)
5896
5897
    def _OnSelectionEnd(self):
5898
        start, end = self.GetSelection()
5899
        if start != end:
5900
            text = self.GetTextRange(start, end)
5901
            if self.sloppy and not self.SelectionIsRectangle():
5902
                x,y = self.lines.selectedlinesi
5903
                if y-x > 1:
5904
                    self.SelectLines()
5905
                    text = ''.join(self.lines.selectedlines)
5906
            SetClipboardText(text, True)
5907
5908
    def UpdateNotifications(self, lines):
5909
        lineno = self.MarkerNext(0, NOTIFICATIONMASK)
5910
        while lineno != -1:
5911
            self.MarkerDelete(lineno, NOTIFICATIONNUMBER)
5912
            lineno = self.MarkerNext(0, NOTIFICATIONMASK)
5913
        for lineno in lines:
5914
            self.MarkerAdd(lineno, NOTIFICATIONNUMBER)
5915
5766
class View(PythonSTC):
5916
class View(PythonSTC):
5767
    def __init__(self, *args):
5917
    def __init__(self, *args):
5768
        PythonSTC.__init__(self, *args)
5918
        PythonSTC.__init__(self, *args)
5769
        ## self.CmdKeyClearAll()
5919
        ## self.CmdKeyClearAll()
5770
5920
...
...
5944
        return wx.SplitterWindow.SetSashPosition(self, position, redraw)
6094
        return wx.SplitterWindow.SetSashPosition(self, position, redraw)
5945
6095
5946
VS = wx.VERSION_STRING
6096
VS = wx.VERSION_STRING
5947
6097
5948
def main():
6098
def main():
5949
    docs = [os.path.abspath(os.path.join(current_path, i))
6099
    docs = [os.path.abspath(os.path.join(current_path, i)) for i in _args]
5950
            for i in sys.argv[1:]]
5951
    if single_instance.send_documents(docs):
6100
    if single_instance.send_documents(docs):
5952
        return
6101
        return
5953
6102
5954
    global IMGLIST1, IMGLIST2, IMGLIST3, IMGLIST4, root, app
6103
    global IMGLIST1, IMGLIST2, IMGLIST3, IMGLIST4, root, app
5955
    app = wx.App(0)
6104
    app = wx.App(0)
...
...
5965
        IMGLIST3.append(bmp)
6114
        IMGLIST3.append(bmp)
5966
        for il in (IMGLIST1, IMGLIST2, IMGLIST4):
6115
        for il in (IMGLIST1, IMGLIST2, IMGLIST4):
5967
            il.AddIcon(wx.IconFromBitmap(bmp))
6116
            il.AddIcon(wx.IconFromBitmap(bmp))
5968
    IMGLIST3.append(IMGLIST3[0])
6117
    IMGLIST3.append(IMGLIST3[0])
5969
6118
5970
    opn=0
5971
    if len(sys.argv)>1 and ('--last' in sys.argv):
5972
        opn=1
5973
    filehistory.root = root = app.frame = MainWindow(None, -1, "PyPE", docs)
6119
    filehistory.root = root = app.frame = MainWindow(None, -1, "PyPE", docs)
5974
    root.updateWindowTitle()
6120
    root.updateWindowTitle()
5975
    app.SetTopWindow(app.frame)
6121
    app.SetTopWindow(app.frame)
5976
    app.frame.Show()
6122
    app.frame.Show()
5977
    app.frame.Hide() #to fix not showing problem on Windows
6123
    app.frame.Hide() #to fix not showing problem on Windows
5978
    app.frame.Show() #
6124
    app.frame.Show() #
5979
    if opn:
6125
    if _options.last:
5980
        app.frame.OnOpenPrevDocs(None)
6126
        app.frame.OnOpenPrevDocs(None)
5981
    app.frame.SendSizeEvent()
6127
    app.frame.SendSizeEvent()
5982
    app.MainLoop()
6128
    app.MainLoop()
5983
6129
5984
if __name__ == '__main__':
6130
if __name__ == '__main__':