##// END OF EJS Templates
module completer now uses pkgutil.iter_modules()
vivainio -
Show More
@@ -1,133 +1,135 b''
1 """ Tab completion support for a couple of linux package managers
1 """ Tab completion support for a couple of linux package managers
2
2
3 This is also an example of how to write custom completer plugins
3 This is also an example of how to write custom completer plugins
4 or hooks.
4 or hooks.
5
5
6 Practical use:
6 Practical use:
7
7
8 [ipython]|1> import ipy_linux_package_managers
8 [ipython]|1> import ipy_linux_package_managers
9 [ipython]|2> apt-get u<<< press tab here >>>
9 [ipython]|2> apt-get u<<< press tab here >>>
10 update upgrade
10 update upgrade
11 [ipython]|2> apt-get up
11 [ipython]|2> apt-get up
12
12
13 """
13 """
14 import IPython.ipapi
14 import IPython.ipapi
15 import glob,os,shlex
15 import glob,os,shlex
16
16
17 ip = IPython.ipapi.get()
17 ip = IPython.ipapi.get()
18
18
19 def apt_completers(self, event):
19 def apt_completers(self, event):
20 """ This should return a list of strings with possible completions.
20 """ This should return a list of strings with possible completions.
21
21
22 Note that all the included strings that don't start with event.symbol
22 Note that all the included strings that don't start with event.symbol
23 are removed, in order to not confuse readline.
23 are removed, in order to not confuse readline.
24
24
25 """
25 """
26 # print event # dbg
26 # print event # dbg
27
27
28 # commands are only suggested for the 'command' part of package manager
28 # commands are only suggested for the 'command' part of package manager
29 # invocation
29 # invocation
30
30
31 cmd = (event.line + "<placeholder>").rsplit(None,1)[0]
31 cmd = (event.line + "<placeholder>").rsplit(None,1)[0]
32 # print cmd
32 # print cmd
33 if cmd.endswith('apt-get') or cmd.endswith('yum'):
33 if cmd.endswith('apt-get') or cmd.endswith('yum'):
34 return ['update', 'upgrade', 'install', 'remove']
34 return ['update', 'upgrade', 'install', 'remove']
35
35
36 # later on, add dpkg -l / whatever to get list of possible
36 # later on, add dpkg -l / whatever to get list of possible
37 # packages, add switches etc. for the rest of command line
37 # packages, add switches etc. for the rest of command line
38 # filling
38 # filling
39
39
40 raise IPython.ipapi.TryNext
40 raise IPython.ipapi.TryNext
41
41
42
42
43 # re_key specifies the regexp that triggers the specified completer
43 # re_key specifies the regexp that triggers the specified completer
44
44
45 ip.set_hook('complete_command', apt_completers, re_key = '.*apt-get')
45 ip.set_hook('complete_command', apt_completers, re_key = '.*apt-get')
46 ip.set_hook('complete_command', apt_completers, re_key = '.*yum')
46 ip.set_hook('complete_command', apt_completers, re_key = '.*yum')
47
47
48 py_std_modules = """\
48 py_std_modules = """\
49 BaseHTTPServer Bastion CGIHTTPServer ConfigParser Cookie
49 BaseHTTPServer Bastion CGIHTTPServer ConfigParser Cookie
50 DocXMLRPCServer HTMLParser MimeWriter Queue SimpleHTTPServer
50 DocXMLRPCServer HTMLParser MimeWriter Queue SimpleHTTPServer
51 SimpleXMLRPCServer SocketServer StringIO UserDict UserList UserString
51 SimpleXMLRPCServer SocketServer StringIO UserDict UserList UserString
52 _LWPCookieJar _MozillaCookieJar __future__ __phello__.foo _strptime
52 _LWPCookieJar _MozillaCookieJar __future__ __phello__.foo _strptime
53 _threading_local aifc anydbm asynchat asyncore atexit audiodev base64
53 _threading_local aifc anydbm asynchat asyncore atexit audiodev base64
54 bdb binhex bisect cProfile calendar cgi cgitb chunk cmd code codecs
54 bdb binhex bisect cProfile calendar cgi cgitb chunk cmd code codecs
55 codeop colorsys commands compileall contextlib cookielib copy copy_reg
55 codeop colorsys commands compileall contextlib cookielib copy copy_reg
56 csv dbhash decimal difflib dircache dis doctest dumbdbm dummy_thread
56 csv dbhash decimal difflib dircache dis doctest dumbdbm dummy_thread
57 dummy_threading filecmp fileinput fnmatch formatter fpformat ftplib
57 dummy_threading filecmp fileinput fnmatch formatter fpformat ftplib
58 functools getopt getpass gettext glob gopherlib gzip hashlib heapq
58 functools getopt getpass gettext glob gopherlib gzip hashlib heapq
59 hmac htmlentitydefs htmllib httplib ihooks imaplib imghdr imputil
59 hmac htmlentitydefs htmllib httplib ihooks imaplib imghdr imputil
60 inspect keyword linecache locale macpath macurl2path mailbox mailcap
60 inspect keyword linecache locale macpath macurl2path mailbox mailcap
61 markupbase md5 mhlib mimetools mimetypes mimify modulefinder multifile
61 markupbase md5 mhlib mimetools mimetypes mimify modulefinder multifile
62 mutex netrc new nntplib ntpath nturl2path opcode optparse os
62 mutex netrc new nntplib ntpath nturl2path opcode optparse os
63 os2emxpath pdb pickle pickletools pipes pkgutil platform popen2 poplib
63 os2emxpath pdb pickle pickletools pipes pkgutil platform popen2 poplib
64 posixfile posixpath pprint profile pstats pty py_compile pyclbr pydoc
64 posixfile posixpath pprint profile pstats pty py_compile pyclbr pydoc
65 quopri random re repr rexec rfc822 rlcompleter robotparser runpy sched
65 quopri random re repr rexec rfc822 rlcompleter robotparser runpy sched
66 sets sgmllib sha shelve shlex shutil site smtpd smtplib sndhdr socket
66 sets sgmllib sha shelve shlex shutil site smtpd smtplib sndhdr socket
67 sre sre_compile sre_constants sre_parse stat statvfs string stringold
67 sre sre_compile sre_constants sre_parse stat statvfs string stringold
68 stringprep struct subprocess sunau sunaudio symbol symtable tabnanny
68 stringprep struct subprocess sunau sunaudio symbol symtable tabnanny
69 tarfile telnetlib tempfile textwrap this threading timeit toaiff token
69 tarfile telnetlib tempfile textwrap this threading timeit toaiff token
70 tokenize trace traceback tty types unittest urllib urllib2 urlparse
70 tokenize trace traceback tty types unittest urllib urllib2 urlparse
71 user uu uuid warnings wave weakref webbrowser whichdb xdrlib xmllib
71 user uu uuid warnings wave weakref webbrowser whichdb xdrlib xmllib
72 xmlrpclib zipfile"""
72 xmlrpclib zipfile"""
73
73
74 def module_completer(self,event):
74 def module_completer(self,event):
75 """ Give completions after user has typed 'import' """
75 """ Give completions after user has typed 'import' """
76 return py_std_modules.split()
76
77 import pkgutil
78 return [m[1] for m in pkgutil.iter_modules()]
77
79
78 ip.set_hook('complete_command', module_completer, str_key = 'import')
80 ip.set_hook('complete_command', module_completer, str_key = 'import')
79
81
80 svn_commands = """\
82 svn_commands = """\
81 add blame praise annotate ann cat checkout co cleanup commit ci copy
83 add blame praise annotate ann cat checkout co cleanup commit ci copy
82 cp delete del remove rm diff di export help ? h import info list ls
84 cp delete del remove rm diff di export help ? h import info list ls
83 lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit
85 lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit
84 pe propget pget pg proplist plist pl propset pset ps resolved revert
86 pe propget pget pg proplist plist pl propset pset ps resolved revert
85 status stat st switch sw unlock update
87 status stat st switch sw unlock update
86 """
88 """
87
89
88 def svn_completer(self,event):
90 def svn_completer(self,event):
89 if len((event.line + 'placeholder').split()) > 2:
91 if len((event.line + 'placeholder').split()) > 2:
90 # the rest are probably file names
92 # the rest are probably file names
91 return ip.IP.Completer.file_matches(event.symbol)
93 return ip.IP.Completer.file_matches(event.symbol)
92
94
93 return svn_commands.split()
95 return svn_commands.split()
94
96
95 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
97 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
96
98
97 def runlistpy(self, event):
99 def runlistpy(self, event):
98 comps = shlex.split(event.line)
100 comps = shlex.split(event.line)
99 relpath = (len(comps) > 1 and comps[-1] or '')
101 relpath = (len(comps) > 1 and comps[-1] or '')
100
102
101 print "rp",relpath
103 print "rp",relpath
102 if relpath.startswith('~'):
104 if relpath.startswith('~'):
103 relpath = os.path.expanduser(relpath)
105 relpath = os.path.expanduser(relpath)
104 dirs = [f.replace('\\','/') + "/" for f in glob.glob(relpath+'*') if os.path.isdir(f)]
106 dirs = [f.replace('\\','/') + "/" for f in glob.glob(relpath+'*') if os.path.isdir(f)]
105 pys = [f.replace('\\','/') for f in glob.glob(relpath+'*.py')]
107 pys = [f.replace('\\','/') for f in glob.glob(relpath+'*.py')]
106 return dirs + pys
108 return dirs + pys
107
109
108 ip.set_hook('complete_command', runlistpy, str_key = '%run')
110 ip.set_hook('complete_command', runlistpy, str_key = '%run')
109
111
110 def listdirs(self, event):
112 def listdirs(self, event):
111 relpath = event.symbol
113 relpath = event.symbol
112
114
113 if '-b' in event.line:
115 if '-b' in event.line:
114 # return only bookmark completions
116 # return only bookmark completions
115 bkms = self.db.get('bookmarks',{})
117 bkms = self.db.get('bookmarks',{})
116 return bkms.keys()
118 return bkms.keys()
117
119
118 if event.symbol == '-':
120 if event.symbol == '-':
119 # jump in directory history by number
121 # jump in directory history by number
120 ents = ['-%d [%s]' % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
122 ents = ['-%d [%s]' % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
121 if len(ents) > 1:
123 if len(ents) > 1:
122 return ents
124 return ents
123 return []
125 return []
124
126
125
127
126 if relpath.startswith('~'):
128 if relpath.startswith('~'):
127 relpath = os.path.expanduser(relpath).replace('\\','/')
129 relpath = os.path.expanduser(relpath).replace('\\','/')
128 found = [f.replace('\\','/')+'/' for f in glob.glob(relpath+'*') if os.path.isdir(f)]
130 found = [f.replace('\\','/')+'/' for f in glob.glob(relpath+'*') if os.path.isdir(f)]
129 if not found:
131 if not found:
130 return [relpath]
132 return [relpath]
131 return found
133 return found
132
134
133 ip.set_hook('complete_command', listdirs, str_key = '%cd') No newline at end of file
135 ip.set_hook('complete_command', listdirs, str_key = '%cd')
General Comments 0
You need to be logged in to leave comments. Login now