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