##// END OF EJS Templates
%cd completer now shows bookmark completions on %cd -b
vivainio -
Show More
@@ -1,119 +1,125 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 return py_std_modules.split()
77
77
78 ip.set_hook('complete_command', module_completer, str_key = 'import')
78 ip.set_hook('complete_command', module_completer, str_key = 'import')
79
79
80 svn_commands = """\
80 svn_commands = """\
81 add blame praise annotate ann cat checkout co cleanup commit ci copy
81 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
82 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
83 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
84 pe propget pget pg proplist plist pl propset pset ps resolved revert
85 status stat st switch sw unlock update
85 status stat st switch sw unlock update
86 """
86 """
87
87
88 def svn_completer(self,event):
88 def svn_completer(self,event):
89 if len((event.line + 'placeholder').split()) > 2:
89 if len((event.line + 'placeholder').split()) > 2:
90 # the rest are probably file names
90 # the rest are probably file names
91 return ip.IP.Completer.file_matches(event.symbol)
91 return ip.IP.Completer.file_matches(event.symbol)
92
92
93 return svn_commands.split()
93 return svn_commands.split()
94
94
95 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
95 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
96
96
97 def runlistpy(self, event):
97 def runlistpy(self, event):
98 comps = shlex.split(event.line)
98 comps = shlex.split(event.line)
99 relpath = (len(comps) > 1 and comps[-1] or '')
99 relpath = (len(comps) > 1 and comps[-1] or '')
100
100
101 print "rp",relpath
101 print "rp",relpath
102 if relpath.startswith('~'):
102 if relpath.startswith('~'):
103 relpath = os.path.expanduser(relpath)
103 relpath = os.path.expanduser(relpath)
104 dirs = [f.replace('\\','/') + "/" for f in glob.glob(relpath+'*') if os.path.isdir(f)]
104 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')]
105 pys = [f.replace('\\','/') for f in glob.glob(relpath+'*.py')]
106 return dirs + pys
106 return dirs + pys
107
107
108 ip.set_hook('complete_command', runlistpy, str_key = '%run')
108 ip.set_hook('complete_command', runlistpy, str_key = '%run')
109
109
110 def listdirs(self, event):
110 def listdirs(self, event):
111 relpath = event.symbol
111 relpath = event.symbol
112
113 if '-b' in event.line:
114 # return only bookmark completions
115 bkms = self.db.get('bookmarks',{})
116 return bkms.keys()
117
112 if relpath.startswith('~'):
118 if relpath.startswith('~'):
113 relpath = os.path.expanduser(relpath).replace('\\','/')
119 relpath = os.path.expanduser(relpath).replace('\\','/')
114 found = [f.replace('\\','/')+'/' for f in glob.glob(relpath+'*') if os.path.isdir(f)]
120 found = [f.replace('\\','/')+'/' for f in glob.glob(relpath+'*') if os.path.isdir(f)]
115 if not found:
121 if not found:
116 return [relpath]
122 return [relpath]
117 return found
123 return found
118
124
119 ip.set_hook('complete_command', listdirs, str_key = '%cd') No newline at end of file
125 ip.set_hook('complete_command', listdirs, str_key = '%cd')
General Comments 0
You need to be logged in to leave comments. Login now