##// END OF EJS Templates
doc, changelog fixes
vivainio -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,56 +1,58 b''
1 1 # -*- coding: utf-8 -*-
2 2 """ IPython extension: add %clear magic """
3 3
4 4 import IPython.ipapi
5 5 import gc
6 6 ip = IPython.ipapi.get()
7 7
8 8
9 9 def clear_f(self,arg):
10 10 """ Clear various data (e.g. stored history data)
11 11
12 12 %clear out - clear output history
13 13 %clear in - clear input history
14 %clear shadow_compress - Compresses shadow history (to speed up ipython)
15 %clear shadow_nuke - permanently erase all entries in shadow history
14 16 """
15 17
16 18 api = self.getapi()
17 19 for target in arg.split():
18 20 if target == 'out':
19 21 print "Flushing output cache (%d entries)" % len(api.user_ns['_oh'])
20 22 self.outputcache.flush()
21 23 elif target == 'in':
22 24 print "Flushing input history"
23 25 from IPython import iplib
24 26 del self.input_hist[:]
25 27 del self.input_hist_raw[:]
26 28 for n in range(1,self.outputcache.prompt_count + 1):
27 29 key = '_i'+`n`
28 30 try:
29 31 del self.user_ns[key]
30 32 except: pass
31 33 elif target == 'array':
32 34 try:
33 35 pylab=ip.IP.pylab
34 36 for x in self.user_ns.keys():
35 37 if isinstance(self.user_ns[x],pylab.arraytype):
36 38 del self.user_ns[x]
37 39 except AttributeError:
38 40 print "Clear array only available in -pylab mode"
39 41 gc.collect()
40 42
41 43 elif target == 'shadow_compress':
42 44 print "Compressing shadow history"
43 45 api.db.hcompress('shadowhist')
44 46
45 47 elif target == 'shadow_nuke':
46 48 print "Erased all keys from shadow history "
47 49 for k in ip.db.keys('shadowhist/*'):
48 50 del ip.db[k]
49 51
50 52 ip.expose_magic("clear",clear_f)
51 53 import ipy_completers
52 54 ipy_completers.quick_completer('clear','in out shadow_nuke shadow_compress')
53 55
54 56
55 57
56 58
@@ -1,346 +1,345 b''
1 1 #!/usr/bin/env python
2 2
3 3 """ Implementations for various useful completers
4 4
5 5 See Extensions/ipy_stock_completers.py on examples of how to enable a completer,
6 6 but the basic idea is to do:
7 7
8 8 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
9 9
10 10 """
11 11 import IPython.ipapi
12 12 import glob,os,shlex,sys
13 13 import inspect
14 14 from time import time
15 15 ip = IPython.ipapi.get()
16 16
17 17 TIMEOUT_STORAGE = 3 #Time in seconds after which the rootmodules will be stored
18 18 TIMEOUT_GIVEUP = 20 #Time in seconds after which we give up
19 19
20 20 def quick_completer(cmd, completions):
21 """ Easily create a completer a trivial completer for a command.
21 """ Easily create a trivial completer for a command.
22 22
23 23 Takes either a list of completions, or all completions in string
24 24 (that will be split on whitespace)
25 25
26 26 Example::
27 27
28 28 [d:\ipython]|1> import ipy_completers
29 29 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
30 [d:\ipython]|3> foo boooo
31
30 [d:\ipython]|3> foo b<TAB>
32 31 bar baz
33 32 [d:\ipython]|3> foo ba
34 33 """
35 34 if isinstance(completions, basestring):
36 35
37 36 completions = completions.split()
38 37 def do_complete(self,event):
39 38 return completions
40 39
41 40 ip.set_hook('complete_command',do_complete, str_key = cmd)
42 41
43 42 def getRootModules():
44 43 """
45 44 Returns a list containing the names of all the modules available in the
46 45 folders of the pythonpath.
47 46 """
48 47 modules = []
49 48 if ip.db.has_key('rootmodules'):
50 49 return ip.db['rootmodules']
51 50 t = time()
52 51 store = False
53 52 for path in sys.path:
54 53 modules += moduleList(path)
55 54 if time() - t >= TIMEOUT_STORAGE and not store:
56 55 store = True
57 56 print "\nCaching the list of root modules, please wait!"
58 57 print "(This will only be done once - type '%rehashx' to " + \
59 58 "reset cache!)"
60 59 print
61 60 if time() - t > TIMEOUT_GIVEUP:
62 61 print "This is taking too long, we give up."
63 62 print
64 63 ip.db['rootmodules'] = []
65 64 return []
66 65
67 66 modules += sys.builtin_module_names
68 67 modules = list(set(modules))
69 68 if '__init__' in modules:
70 69 modules.remove('__init__')
71 70 modules = list(set(modules))
72 71 if store:
73 72 ip.db['rootmodules'] = modules
74 73 return modules
75 74
76 75 def moduleList(path):
77 76 """
78 77 Return the list containing the names of the modules available in the given
79 78 folder.
80 79 """
81 80 if os.path.isdir(path):
82 81 folder_list = os.listdir(path)
83 82 else:
84 83 folder_list = []
85 84 #folder_list = glob.glob(os.path.join(path,'*'))
86 85 folder_list = [path for path in folder_list \
87 86 if os.path.exists(os.path.join(path,'__init__.py'))\
88 87 or path[-3:] in ('.py','.so')\
89 88 or path[-4:] in ('.pyc','.pyo')]
90 89 folder_list += folder_list
91 90 folder_list = [os.path.basename(path).split('.')[0] for path in folder_list]
92 91 return folder_list
93 92
94 93 def moduleCompletion(line):
95 94 """
96 95 Returns a list containing the completion possibilities for an import line.
97 96 The line looks like this :
98 97 'import xml.d'
99 98 'from xml.dom import'
100 99 """
101 100 def tryImport(mod, only_modules=False):
102 101 def isImportable(module, attr):
103 102 if only_modules:
104 103 return inspect.ismodule(getattr(module, attr))
105 104 else:
106 105 return not(attr[:2] == '__' and attr[-2:] == '__')
107 106 try:
108 107 m = __import__(mod)
109 108 except:
110 109 return []
111 110 mods = mod.split('.')
112 111 for module in mods[1:]:
113 112 m = getattr(m,module)
114 113 if (not hasattr(m, '__file__')) or (not only_modules) or\
115 114 (hasattr(m, '__file__') and '__init__' in m.__file__):
116 115 completion_list = [attr for attr in dir(m) if isImportable(m, attr)]
117 116 completion_list.extend(getattr(m,'__all__',[]))
118 117 if hasattr(m, '__file__') and '__init__' in m.__file__:
119 118 completion_list.extend(moduleList(os.path.dirname(m.__file__)))
120 119 completion_list = list(set(completion_list))
121 120 if '__init__' in completion_list:
122 121 completion_list.remove('__init__')
123 122 return completion_list
124 123
125 124 words = line.split(' ')
126 125 if len(words) == 3 and words[0] == 'from':
127 126 return ['import ']
128 127 if len(words) < 3 and (words[0] in ['import','from']) :
129 128 if len(words) == 1:
130 129 return getRootModules()
131 130 mod = words[1].split('.')
132 131 if len(mod) < 2:
133 132 return getRootModules()
134 133 completion_list = tryImport('.'.join(mod[:-1]), True)
135 134 completion_list = ['.'.join(mod[:-1] + [el]) for el in completion_list]
136 135 return completion_list
137 136 if len(words) >= 3 and words[0] == 'from':
138 137 mod = words[1]
139 138 return tryImport(mod)
140 139
141 140 def vcs_completer(commands, event):
142 141 """ utility to make writing typical version control app completers easier
143 142
144 143 VCS command line apps typically have the format:
145 144
146 145 [sudo ]PROGNAME [help] [command] file file...
147 146
148 147 """
149 148
150 149
151 150 cmd_param = event.line.split()
152 151 if event.line.endswith(' '):
153 152 cmd_param.append('')
154 153
155 154 if cmd_param[0] == 'sudo':
156 155 cmd_param = cmd_param[1:]
157 156
158 157 if len(cmd_param) == 2 or 'help' in cmd_param:
159 158 return commands.split()
160 159
161 160 return ip.IP.Completer.file_matches(event.symbol)
162 161
163 162
164 163
165 164 def apt_completers(self, event):
166 165 """ This should return a list of strings with possible completions.
167 166
168 167 Note that all the included strings that don't start with event.symbol
169 168 are removed, in order to not confuse readline.
170 169
171 170 """
172 171 # print event # dbg
173 172
174 173 # commands are only suggested for the 'command' part of package manager
175 174 # invocation
176 175
177 176 cmd = (event.line + "<placeholder>").rsplit(None,1)[0]
178 177 # print cmd
179 178 if cmd.endswith('apt-get') or cmd.endswith('yum'):
180 179 return ['update', 'upgrade', 'install', 'remove']
181 180
182 181 # later on, add dpkg -l / whatever to get list of possible
183 182 # packages, add switches etc. for the rest of command line
184 183 # filling
185 184
186 185 raise IPython.ipapi.TryNext
187 186
188 187
189 188
190 189 pkg_cache = None
191 190
192 191 def module_completer(self,event):
193 192 """ Give completions after user has typed 'import ...' or 'from ...'"""
194 193
195 194 # This works in all versions of python. While 2.5 has
196 195 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
197 196 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
198 197 # of possibly problematic side effects.
199 198 # This search the folders in the sys.path for available modules.
200 199
201 200 return moduleCompletion(event.line)
202 201
203 202
204 203 svn_commands = """\
205 204 add blame praise annotate ann cat checkout co cleanup commit ci copy
206 205 cp delete del remove rm diff di export help ? h import info list ls
207 206 lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit
208 207 pe propget pget pg proplist plist pl propset pset ps resolved revert
209 208 status stat st switch sw unlock update
210 209 """
211 210
212 211 def svn_completer(self,event):
213 212 return vcs_completer(svn_commands, event)
214 213
215 214
216 215 hg_commands = """
217 216 add addremove annotate archive backout branch branches bundle cat
218 217 clone commit copy diff export grep heads help identify import incoming
219 218 init locate log manifest merge outgoing parents paths pull push
220 219 qapplied qclone qcommit qdelete qdiff qfold qguard qheader qimport
221 220 qinit qnew qnext qpop qprev qpush qrefresh qrename qrestore qsave
222 221 qselect qseries qtop qunapplied recover remove rename revert rollback
223 222 root serve showconfig status strip tag tags tip unbundle update verify
224 223 version
225 224 """
226 225
227 226 def hg_completer(self,event):
228 227 """ Completer for mercurial commands """
229 228
230 229 return vcs_completer(hg_commands, event)
231 230
232 231
233 232
234 233 bzr_commands = """
235 234 add annotate bind branch break-lock bundle-revisions cat check
236 235 checkout commit conflicts deleted diff export gannotate gbranch
237 236 gcommit gdiff help ignore ignored info init init-repository inventory
238 237 log merge missing mkdir mv nick pull push reconcile register-branch
239 238 remerge remove renames resolve revert revno root serve sign-my-commits
240 239 status testament unbind uncommit unknowns update upgrade version
241 240 version-info visualise whoami
242 241 """
243 242
244 243 def bzr_completer(self,event):
245 244 """ Completer for bazaar commands """
246 245 cmd_param = event.line.split()
247 246 if event.line.endswith(' '):
248 247 cmd_param.append('')
249 248
250 249 if len(cmd_param) > 2:
251 250 cmd = cmd_param[1]
252 251 param = cmd_param[-1]
253 252 output_file = (param == '--output=')
254 253 if cmd == 'help':
255 254 return bzr_commands.split()
256 255 elif cmd in ['bundle-revisions','conflicts',
257 256 'deleted','nick','register-branch',
258 257 'serve','unbind','upgrade','version',
259 258 'whoami'] and not output_file:
260 259 return []
261 260 else:
262 261 # the rest are probably file names
263 262 return ip.IP.Completer.file_matches(event.symbol)
264 263
265 264 return bzr_commands.split()
266 265
267 266
268 267 def shlex_split(x):
269 268 """Helper function to split lines into segments."""
270 269 #shlex.split raise exception if syntax error in sh syntax
271 270 #for example if no closing " is found. This function keeps dropping
272 271 #the last character of the line until shlex.split does not raise
273 272 #exception. Adds end of the line to the result of shlex.split
274 273 #example: %run "c:/python -> ['%run','"c:/python']
275 274 endofline=[]
276 275 while x!="":
277 276 try:
278 277 comps=shlex.split(x)
279 278 if len(endofline)>=1:
280 279 comps.append("".join(endofline))
281 280 return comps
282 281 except ValueError:
283 282 endofline=[x[-1:]]+endofline
284 283 x=x[:-1]
285 284 return ["".join(endofline)]
286 285
287 286 def runlistpy(self, event):
288 287 comps = shlex_split(event.line)
289 288 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
290 289
291 290 #print "\nev=",event # dbg
292 291 #print "rp=",relpath # dbg
293 292 #print 'comps=',comps # dbg
294 293
295 294 lglob = glob.glob
296 295 isdir = os.path.isdir
297 296 if relpath.startswith('~'):
298 297 relpath = os.path.expanduser(relpath)
299 298 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*')
300 299 if isdir(f)]
301 300
302 301 # Find if the user has already typed the first filename, after which we
303 302 # should complete on all files, since after the first one other files may
304 303 # be arguments to the input script.
305 304 #filter(
306 305 if filter(lambda f: f.endswith('.py') or f.endswith('.ipy'),comps):
307 306 pys = [f.replace('\\','/') for f in lglob('*')]
308 307 else:
309 308 pys = [f.replace('\\','/')
310 309 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy')]
311 310 return dirs + pys
312 311
313 312
314 313 def cd_completer(self, event):
315 314 relpath = event.symbol
316 315 #print event # dbg
317 316 if '-b' in event.line:
318 317 # return only bookmark completions
319 318 bkms = self.db.get('bookmarks',{})
320 319 return bkms.keys()
321 320
322 321
323 322 if event.symbol == '-':
324 323 # jump in directory history by number
325 324 ents = ['-%d [%s]' % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
326 325 if len(ents) > 1:
327 326 return ents
328 327 return []
329 328
330 329 if relpath.startswith('~'):
331 330 relpath = os.path.expanduser(relpath).replace('\\','/')
332 331 found = []
333 332 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
334 333 if os.path.isdir(f)]:
335 334 if ' ' in d:
336 335 # we don't want to deal with any of that, complex code
337 336 # for this is elsewhere
338 337 raise IPython.ipapi.TryNext
339 338 found.append( d )
340 339
341 340 if not found:
342 341 if os.path.isdir(relpath):
343 342 return [relpath]
344 343 raise IPython.ipapi.TryNext
345 344 return found
346 345
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now