Mark Hammond wrote:
Robert wrote:
want to put new functions (short python code) on keys like F1, F12, Ctrl-F1 and other keys.
Is there a mechanism/recipe ?


Look for the *.cfg files in the pythonwin directory.


Thanks.

maybe some of the following stuff is useful for somebody, or for future PythonWin default:

In attachment a patch for pywin/default.cfg, which does context (word) sensitive help from editor into Python Help and PythonWin Help

F1               = HelpPy
Ctrl+F1          = HelpPyWin
..

and allows for faster edit-run cycle: running/interacting with (auto-unindented) selected code lines from editor

Ctrl+K            = Interact_SelectedLines
Ctrl+E            = ExecGlobal_SelectedLines

( the little patch of scintilla/config.py enables correct line numbers for traceback and debugging of code in default.cfg )

-

Also CtrlEnter.patch (-> framework/interact.py), which enables ad-hoc debugging from interactive pane (Ctrl-Enter) into an interactive statement (without long-winded F5 running into breakpoints etc). I did not put the code into default.cfg, because a lot of pre-processing code is shared with normal interactive statement execution.


Robert
--- default.cfg.orig    Tue Jul 01 00:54:06 2008
+++ default.cfg Thu Apr 30 17:01:29 2009
@@ -66,6 +66,16 @@
 
 Ctrl+F3           = AutoFindNext
 
+# Context Sensitive Help
+F1               = HelpPy
+Ctrl+F1          = HelpPyWin
+Alt+F1           = HelpMSDN
+
+F12              = HelpWXIndex  
+Shift+F12        = HelpWXPYIndex
+Ctrl+F12         = HelpWXSearch
+Alt+F12          = HelpWXNakedIndex 
+Ctrl+Shift+F12   = HelpWXNet
 
 [Keys:Editor]
 # Key bindings specific to the editor
@@ -100,6 +110,10 @@
 Shift+Subtract    = FoldCollapseSecondLevel
 Multiply          = FoldTopLevel
 
+# Interact with selected lines
+Ctrl+K            = Interact_SelectedLines
+Ctrl+E            = ExecGlobal_SelectedLines
+
 [Keys:Interactive]
 # Key bindings specific to the interactive window.
 # History for the interactive window
@@ -213,3 +227,182 @@
        # Almost an "unbind" - allows Pythonwin/MFC to handle the keystroke
        return 1
 
+
+# Context Help
+
+def HelpPy(editor_window, event):
+    CtxHelp(editor_window, event, doc_ix=0)
+def HelpPyWin(editor_window, event):
+    CtxHelp(editor_window, event, doc_ix=1)
+def HelpMSDN(editor_window, event):
+    CtxHelp(editor_window, event, doc_ix=2)
+    
+def HelpWXIndex(editor_window, event):  
+    CtxHelp(editor_window, event, doc_ix=10)
+def HelpWXSearch(editor_window, event):
+    CtxHelp(editor_window, event, doc_ix=11)
+def HelpWXNakedIndex(editor_window, event):
+    CtxHelp(editor_window, event, doc_ix=12)
+def HelpWXPYIndex(editor_window, event): 
+    CtxHelp(editor_window, event, doc_ix=13)
+def HelpWXNet(editor_window, event):
+    CtxHelp(editor_window, event, doc_ix=14)
+
+def CtxHelp(editor_window,event,doc_ix=0):
+       """ context sensitive help for (relevant) word near cursor position
+       """
+       import sys,os,re,pywin,traceback
+       self=editor_window.edit
+       
+       # compute the relevant word ..
+       start,end=self.GetSel()
+       iline=self.LineFromChar(start)
+       line=self.GetLine(iline)
+       linestart=self.LineIndex(iline)
+       x=start-linestart
+       ix=0
+       word=""
+       m=1
+       while m:
+               m=re.search(r"\b\w+",line[ix:])
+               if m:
+                       if m.start()+ix>x:
+                               break
+                       ix+=m.end()
+                       ww=m.group()
+                       if re.match(r"\d+",ww):
+                               continue
+                       if ww in ("and","or","if","else","self","this",):
+                               continue
+                       word=ww
+
+       # fork into help files / web ..
+       if word:
+               import win32help
+               import regutil
+               if doc_ix==0: # F1
+                       hf = regutil.GetRegisteredHelpFile("Main Python 
Documentation")
+                       win32help.HtmlHelp(0, hf, win32help.HH_DISPLAY_INDEX, 
word)
+               elif doc_ix==1: # Ctrl-F1
+                       hf = regutil.GetRegisteredHelpFile("Pythonwin 
Reference")
+                       win32help.HtmlHelp(0, hf, win32help.HH_DISPLAY_INDEX, 
word)
+               elif doc_ix==2: # 
+                       hf = regutil.GetRegisteredHelpFile("MSDN")
+##                     if not os.path.exists(hf or ""):
+##                             hf=os.environ.get('ProgramFiles') + 
r"\Microsoft Visual Studio\MSDN98\98VSa\1033\msdnvs6a.col"
+                       if not os.path.exists(hf):
+                               
os.startfile("http://social.msdn.microsoft.com/Search/en-US/?Query=%s"; % word)
+                               return
+                       win32help.HtmlHelp(0, hf, win32help.HH_DISPLAY_INDEX, 
word)
+               elif doc_ix in (10,11,12,13,14):  #wxPython
+                       hf = regutil.GetRegisteredHelpFile("wx")
+                       if not hf:
+                               print "no chm HelpFile for wx configured in 
Pywin registry: Help/wx (Menu/Tools/EditPythonPath)"
+                               hf=r"C:\Programme\wxPython2.8 Docs and 
Demos\docs\wx.chm"
+                       if not os.path.exists(hf):
+                               traceback.print_stack()
+                               print "default.cfg/CtxHelp: not found:",hf
+                       if doc_ix == 10:  # F12
+                               win32help.HtmlHelp(0, hf, 
win32help.HH_DISPLAY_INDEX, 'wx'+word)
+                       elif doc_ix == 11:  #Ctrl+F12 
+                               
os.startfile(r"http://www.google.com/search?q=%s 
site:www.wxpython.org/docs/api/" % word)
+                               if 0:
+                                       # HH_DISPLAY_SEARCH doesn't transfer 
the string NOR execute; MSDN says: Bug!
+                                       q=win32help.HH_FTS_QUERY()
+                                       q.searchQuery=word
+                                       q.execute=True
+                                       win32help.HtmlHelp(0, hf, 
win32help.HH_DISPLAY_SEARCH, q)
+                       elif doc_ix == 12: # Alt+F12
+                               win32help.HtmlHelp(0, hf, 
win32help.HH_DISPLAY_INDEX, word)
+                       elif doc_ix == 13: # Shift+F12
+                               hfpy = regutil.GetRegisteredHelpFile("wxpy")
+                               if not hfpy:
+                                       print "default.cfg/CtxHelp: 
Documentation File Help/wxpy not found (Menu/Tools/EditPythonPath)"
+                               win32help.HtmlHelp(0, hfpy, 
win32help.HH_DISPLAY_INDEX, word)
+                       elif doc_ix == 14: # Ctrl+Shift+F12 # Net Search
+                               
os.startfile("http://www.google.com/search?q=wxpython+%s"; % word)
+                       else:
+                               raise AssertionError,"?"
+               else:
+                       print "unknown Help File; doc_ix=",doc_ix
+                       
+def Interact_SelectedLines(editor_window,event):
+       ExecGlobal_SelectedLines(editor_window,event, key='interact')
+def ExecGlobal_SelectedLines(editor_window, event, key=''):
+       """
+       Execute (auto-unindented) selected lines in global namespace
+       default key: Ctrl-E
+       """
+       import string,re,pywin
+       ##print "--ExecGlobal_SelectedLines--"
+       self=editor_window.edit
+       x,y=self.GetSel()
+       if y>x: y=y-1
+       start, end = map(self.LineFromChar,(x,y))
+       code=''
+
+       # get selected lines; compute minimal leading whitespace
+       l=[]            #the lines
+       minw=10000      #minimal leading whitespace of the lines
+       linecount=self.GetLineCount()
+       baselines=0
+       for i in range(start,end+1):
+               line=self.GetLine(i)
+               white=len(line)-len(string.lstrip(line))
+               if white<minw:
+                       minw=white
+                       baselines=1
+               elif white==minw:
+                       baselines=baselines+1
+               l.append(line)
+
+       # fetch indented lines of open statments (todo: use interpreter 
intelligence)
+       if line.strip().endswith(':'): 
+               white1=len(line)-len(string.lstrip(line))
+               while i<linecount:
+                       i=i+1
+                       line=self.GetLine(i)
+                       xline=string.lstrip(line)
+                       if not xline or xline.startswith('#'):
+                               continue
+                       white=len(line)-len(xline)
+                       if white<=white1:
+                               break
+                       l.append(line)
+                       
+       # print first + ..  + last line when executing snippet 
+       if key!='interact':
+               print '\r\n...',
+               print l[0][minw:-2]
+               if len(l)>1:
+                       if len(l)>2: print '    ..'
+                       print '...',l[-1][minw:-2]
+
+       # .. or serve snippet lines for interaction
+       i=0
+       if key=='interact' and baselines>1:
+               print '\r\n... if 1:',
+       for line in l:
+               code=code+line[minw:]
+               if key=='interact':
+                       if baselines>1:
+                               print '\r\n...     ',
+                       else:
+                               print '\r\n...',
+                       print line[minw:-2],
+               i=i+1
+       pywin.framework.interact.ShowInteractiveWindow()
+       if key=='interact':
+               ##pywin.framework.interact.edit.currentView.SetFocus()
+               return 0
+
+       #execute snippet lines  
+       print '--executing unindented lines globally ... --'
+       import __main__
+       from pywin.framework import interact
+       try:
+               exec re.sub(r'\r','',code) in __main__.__dict__
+       except:
+               import traceback; traceback.print_exc()
+       print '--lines executed. --\n>>> ',
+       return 0
--- scintilla/config.py.orig    Sat Nov 29 19:46:30 2003
+++ scintilla/config.py Wed Apr 29 17:58:10 2009
@@ -277,7 +277,7 @@
             if bBreak: break
             lines.append(line)
         try:
-            c = compile(string.join(lines, ""), self.filename, "exec")
+            c = compile("\n"*start_lineno + string.join(lines, ""), 
self.filename, "exec")
             self._save_data("extension code", c)
         except SyntaxError, details:
             msg = details[0]
--- framework/interact.py.orig  Tue Jul 01 00:54:08 2008
+++ framework/interact.py       Thu Apr 30 17:13:20 2009
@@ -466,7 +466,7 @@
                        return
 
                # If SHIFT held down, we want new code here and now!
-               bNeedIndent = win32api.GetKeyState(win32con.VK_SHIFT)<0 or 
win32api.GetKeyState(win32con.VK_CONTROL)<0
+               bNeedIndent = win32api.GetKeyState(win32con.VK_SHIFT)<0 # or 
win32api.GetKeyState(win32con.VK_CONTROL)<0
                if bNeedIndent:
                        self.ReplaceSel("\n")
                else:
@@ -477,7 +477,22 @@
                                source = source[:-1]
                        self.OutputGrab()       # grab the output for the 
command exec.
                        try:
-                               if self.interp.runsource(source, "<interactive 
input>"): # Need more input!
+                               if win32api.GetKeyState(win32con.VK_CONTROL)<0:
+                                       print "    -- debugging into statement 
... --"
+                                       import pywin.debugger
+                                       pywin.debugger.run #$pycheck_no
+                                       try:
+                                               pywin.debugger.run(source, 
self.interp.globals, self.interp.locals )
+                                       except:
+                                               import traceback
+                                               
traceback.print_exception(*sys.exc_info())
+                                               print "-- statement debugger 
exited with exception --"
+                                       print "--  statement debugger exit --"
+                                       if self.history is not None:
+                                               
self.history.history_store(source)
+                                       self.AppendToPrompt([])
+                                       win32ui.SetStatusText('Statement 
execution in debugger complete.')
+                               elif self.interp.runsource(source, 
"<interactive input>"): # Need more input!
                                        bNeedIndent = 1
                                else:
                                        # If the last line isnt empty, append a 
newline
_______________________________________________
python-win32 mailing list
python-win32@python.org
http://mail.python.org/mailman/listinfo/python-win32

Reply via email to