##// END OF EJS Templates
cd - now has completions too (show directory history entries)
vivainio -
Show More
@@ -1,125 +1,133 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 76 return py_std_modules.split()
77 77
78 78 ip.set_hook('complete_command', module_completer, str_key = 'import')
79 79
80 80 svn_commands = """\
81 81 add blame praise annotate ann cat checkout co cleanup commit ci copy
82 82 cp delete del remove rm diff di export help ? h import info list ls
83 83 lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit
84 84 pe propget pget pg proplist plist pl propset pset ps resolved revert
85 85 status stat st switch sw unlock update
86 86 """
87 87
88 88 def svn_completer(self,event):
89 89 if len((event.line + 'placeholder').split()) > 2:
90 90 # the rest are probably file names
91 91 return ip.IP.Completer.file_matches(event.symbol)
92 92
93 93 return svn_commands.split()
94 94
95 95 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
96 96
97 97 def runlistpy(self, event):
98 98 comps = shlex.split(event.line)
99 99 relpath = (len(comps) > 1 and comps[-1] or '')
100 100
101 101 print "rp",relpath
102 102 if relpath.startswith('~'):
103 103 relpath = os.path.expanduser(relpath)
104 104 dirs = [f.replace('\\','/') + "/" for f in glob.glob(relpath+'*') if os.path.isdir(f)]
105 105 pys = [f.replace('\\','/') for f in glob.glob(relpath+'*.py')]
106 106 return dirs + pys
107 107
108 108 ip.set_hook('complete_command', runlistpy, str_key = '%run')
109 109
110 110 def listdirs(self, event):
111 111 relpath = event.symbol
112 112
113 113 if '-b' in event.line:
114 114 # return only bookmark completions
115 115 bkms = self.db.get('bookmarks',{})
116 116 return bkms.keys()
117 117
118 if event.symbol == '-':
119 # jump in directory history by number
120 ents = ['-%d [%s]' % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
121 if len(ents) > 1:
122 return ents
123 return []
124
125
118 126 if relpath.startswith('~'):
119 127 relpath = os.path.expanduser(relpath).replace('\\','/')
120 128 found = [f.replace('\\','/')+'/' for f in glob.glob(relpath+'*') if os.path.isdir(f)]
121 129 if not found:
122 130 return [relpath]
123 131 return found
124 132
125 133 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