[Idle-dev] Auto Completion extension
Changjune Kim
Changjune Kim" <juneaftn@removethis.krpost.net
Mon, 16 Jun 2003 03:16:30 +0900
Hello.
I made this extension because I had to type in the same code template again
and again -- I practice TDD, where you have to write down the test code first.
Hope some people find this useful.
You type in a specific keyword, which you've defined in your
config-template.def/cfg file, and press a specific key, like ctrl-space, then
the predefined code template will be replaced, optionally with the cursor
located at the intended position.
# AutoCompletion.py
#
# Copyright 2003 June Kim <juneaftn at hanmail dot net>
#
#
import os
from configHandler import idleConf
def _updateWithFile(aDict,aPath):
if os.path.isfile(aPath):
tmp=open(aPath,'rt').read()
aDict.update(eval(tmp))
return aDict
def initTemplate():
d={}
if __name__ != '__main__': # we were imported
idleDir=os.path.dirname(__file__)
else: # we were exec'ed (for testing only)
idleDir=os.path.abspath(sys.path[0])
userDir=idleConf.GetUserCfgDir()
_updateWithFile(d,os.path.join(idleDir,'config-template.def'))
_updateWithFile(d,os.path.join(userDir,'config-template.cfg'))
return d
tempdict=initTemplate()
class AutoCompletion:
menudefs = [
('edit', [
('Auto Completio_n', '<<auto-completion>>'),
])
]
def __init__(self, editwin):
self.editwin = editwin
self.tempdict=initTemplate()
def getSelection(self,text):
sel1,sel2=text.index("insert-1c wordstart"),text.index("insert
wordend")
return text.get(sel1,sel2).strip(),sel1,sel2
def auto_completion_event(self, event):
text=self.editwin.text
sel,sel_start,sel_end=self.getSelection(text)
replaced=self.tempdict.get(sel)
if not replaced:
return
cursor=replaced.find('^!')
if cursor==-1: cursor=0
text.delete(sel_start,sel_end)
text.insert("insert",replaced.replace('^!',''))
text.mark_set("insert",sel_start+"+%dc"%cursor)
text.see("insert")
---------------------
This is the config-template.def or cfg file. "^!" is the mark for the cursor
position after replacement. If omitted, the cursor will remain still at the
start of the replaced code.
{'unittest':'''\
import unittest
class Test(unittest.TestCase):
def test1(self)
^!pass
if __name__=='__main__'
unittest.main()
''',
'foreach':'''\
for each in ^!:
''',
}
--------------------
Lastly, config-extension.def or cfg should contain the following:
[AutoCompletion]
enable=1
[AutoCompletion_cfgBindings]
auto-completion=<Control-Key-space>