##// END OF EJS Templates
crlf normalization
vivainio -
Show More
@@ -1,21 +1,21 b''
1 """ Install various IPython completers
1 """ Install various IPython completers
2
2
3 IPython extension that installs the completers related to external apps.
3 IPython extension that installs the completers related to external apps.
4
4
5 The actual implementations are in Extensions/ipy_completers.py
5 The actual implementations are in Extensions/ipy_completers.py
6
6
7 """
7 """
8 import IPython.ipapi
8 import IPython.ipapi
9
9
10 ip = IPython.ipapi.get()
10 ip = IPython.ipapi.get()
11
11
12 from ipy_completers import *
12 from ipy_completers import *
13
13
14 ip.set_hook('complete_command', apt_completers, re_key = '.*apt-get')
14 ip.set_hook('complete_command', apt_completers, re_key = '.*apt-get')
15 ip.set_hook('complete_command', apt_completers, re_key = '.*yum')
15 ip.set_hook('complete_command', apt_completers, re_key = '.*yum')
16
16
17 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
17 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
18
18
19 ip.set_hook('complete_command', hg_completer, str_key = 'hg')
19 ip.set_hook('complete_command', hg_completer, str_key = 'hg')
20
20
21 ip.set_hook('complete_command', bzr_completer, str_key = 'bzr')
21 ip.set_hook('complete_command', bzr_completer, str_key = 'bzr')
@@ -1,80 +1,80 b''
1 """ 'editor' hooks for common editors that work well with ipython
1 """ 'editor' hooks for common editors that work well with ipython
2
2
3 They should honor the line number argument, at least.
3 They should honor the line number argument, at least.
4
4
5 Contributions are *very* welcome.
5 Contributions are *very* welcome.
6 """
6 """
7
7
8 import IPython.ipapi
8 import IPython.ipapi
9 ip = IPython.ipapi.get()
9 ip = IPython.ipapi.get()
10
10
11 from IPython.Itpl import itplns
11 from IPython.Itpl import itplns
12 import os
12 import os
13
13
14 def install_editor(run_template, wait = False):
14 def install_editor(run_template, wait = False):
15 """ Gets a template in format "myeditor bah bah $file bah bah $line"
15 """ Gets a template in format "myeditor bah bah $file bah bah $line"
16
16
17 $file will be replaced by file name, $line by line number (or 0).
17 $file will be replaced by file name, $line by line number (or 0).
18 Installs the editor that is called by IPython, instead of the default
18 Installs the editor that is called by IPython, instead of the default
19 notepad or vi.
19 notepad or vi.
20
20
21 If wait is true, wait until the user presses enter before returning,
21 If wait is true, wait until the user presses enter before returning,
22 to facilitate non-blocking editors that exit immediately after
22 to facilitate non-blocking editors that exit immediately after
23 the call.
23 the call.
24 """
24 """
25
25
26 def call_editor(self, file, line):
26 def call_editor(self, file, line):
27 if line is None:
27 if line is None:
28 line = 0
28 line = 0
29 cmd = itplns(run_template, locals())
29 cmd = itplns(run_template, locals())
30 print ">",cmd
30 print ">",cmd
31 os.system(cmd)
31 os.system(cmd)
32 if wait:
32 if wait:
33 raw_input("Press Enter when done editing:")
33 raw_input("Press Enter when done editing:")
34
34
35 ip.set_hook('editor',call_editor)
35 ip.set_hook('editor',call_editor)
36
36
37
37
38 # in these, exe is always the path/name of the executable. Useful
38 # in these, exe is always the path/name of the executable. Useful
39 # if you don't have the editor directory in your path
39 # if you don't have the editor directory in your path
40
40
41 def komodo(exe = 'komodo'):
41 def komodo(exe = 'komodo'):
42 """ Activestate Komodo [Edit] """
42 """ Activestate Komodo [Edit] """
43 install_editor(exe + ' -l $line "$file"', wait = True)
43 install_editor(exe + ' -l $line "$file"', wait = True)
44
44
45 def scite(exe = "scite"):
45 def scite(exe = "scite"):
46 """ SciTE or Sc1 """
46 """ SciTE or Sc1 """
47 install_editor(exe + ' "$file" -goto:$line')
47 install_editor(exe + ' "$file" -goto:$line')
48
48
49 def notepadplusplus(exe = 'notepad++'):
49 def notepadplusplus(exe = 'notepad++'):
50 """ Notepad++ http://notepad-plus.sourceforge.net """
50 """ Notepad++ http://notepad-plus.sourceforge.net """
51 install_editor(exe + ' -n$line "$file"')
51 install_editor(exe + ' -n$line "$file"')
52
52
53 def jed(exe = 'jed'):
53 def jed(exe = 'jed'):
54 """ JED, the lightweight emacsish editor """
54 """ JED, the lightweight emacsish editor """
55 install_editor(exe + ' +$line "$file"')
55 install_editor(exe + ' +$line "$file"')
56
56
57 def idle(exe = None):
57 def idle(exe = None):
58 """ Idle, the editor bundled with python
58 """ Idle, the editor bundled with python
59
59
60 Should be pretty smart about finding the executable.
60 Should be pretty smart about finding the executable.
61 """
61 """
62 if exe is None:
62 if exe is None:
63 import idlelib
63 import idlelib
64 p = os.path.dirname(idlelib.__file__)
64 p = os.path.dirname(idlelib.__file__)
65 exe = p + '/idle.py'
65 exe = p + '/idle.py'
66 install_editor(exe + ' "$file"')
66 install_editor(exe + ' "$file"')
67
67
68
68
69 # these are untested, report any problems
69 # these are untested, report any problems
70
70
71 def emacs(exe = 'emacs'):
71 def emacs(exe = 'emacs'):
72 install_editor(exe + ' +$line "$file"')
72 install_editor(exe + ' +$line "$file"')
73
73
74 def gnuclient(exe= 'gnuclient'):
74 def gnuclient(exe= 'gnuclient'):
75 install_editor(exe + ' -nw +$line "$file"')
75 install_editor(exe + ' -nw +$line "$file"')
76
76
77 def crimson_editor(exe = 'cedt.exe'):
77 def crimson_editor(exe = 'cedt.exe'):
78 install_editor(exe + ' /L:%line "$file"')
78 install_editor(exe + ' /L:%line "$file"')
79
79
80 No newline at end of file
80
@@ -1,173 +1,173 b''
1 """ File system operations
1 """ File system operations
2
2
3 Contains: Simple variants of normal unix shell commands (icp, imv, irm,
3 Contains: Simple variants of normal unix shell commands (icp, imv, irm,
4 imkdir, igrep).
4 imkdir, igrep).
5
5
6 Some "otherwise handy" utils ('collect' for gathering files to
6 Some "otherwise handy" utils ('collect' for gathering files to
7 ~/_ipython/collect, 'inote' for collecting single note lines to
7 ~/_ipython/collect, 'inote' for collecting single note lines to
8 ~/_ipython/note.txt)
8 ~/_ipython/note.txt)
9
9
10 Mostly of use for bare windows installations where cygwin/equivalent is not
10 Mostly of use for bare windows installations where cygwin/equivalent is not
11 installed and you would otherwise need to deal with dos versions of the
11 installed and you would otherwise need to deal with dos versions of the
12 commands (that e.g. don't understand / as path separator). These can
12 commands (that e.g. don't understand / as path separator). These can
13 do some useful tricks on their own, though (like use 'mglob' patterns).
13 do some useful tricks on their own, though (like use 'mglob' patterns).
14
14
15 Not to be confused with ipipe commands (ils etc.) that also start with i.
15 Not to be confused with ipipe commands (ils etc.) that also start with i.
16 """
16 """
17
17
18 import IPython.ipapi
18 import IPython.ipapi
19 ip = IPython.ipapi.get()
19 ip = IPython.ipapi.get()
20
20
21 import shutil,os,shlex
21 import shutil,os,shlex
22 from IPython.external import mglob
22 from IPython.external import mglob
23 class IpyShellCmdException(Exception):
23 class IpyShellCmdException(Exception):
24 pass
24 pass
25
25
26 def parse_args(args):
26 def parse_args(args):
27 """ Given arg string 'CMD files... target', return ([files], target) """
27 """ Given arg string 'CMD files... target', return ([files], target) """
28
28
29 tup = args.split(None, 1)
29 tup = args.split(None, 1)
30 if len(tup) == 1:
30 if len(tup) == 1:
31 raise IpyShellCmdException("Expected arguments for " + tup[0])
31 raise IpyShellCmdException("Expected arguments for " + tup[0])
32
32
33 tup2 = shlex.split(tup[1])
33 tup2 = shlex.split(tup[1])
34
34
35 flist, trg = mglob.expand(tup2[0:-1]), tup2[-1]
35 flist, trg = mglob.expand(tup2[0:-1]), tup2[-1]
36 if not flist:
36 if not flist:
37 raise IpyShellCmdException("No files found:" + str(tup2[0:-1]))
37 raise IpyShellCmdException("No files found:" + str(tup2[0:-1]))
38 return flist, trg
38 return flist, trg
39
39
40 def icp(ip,arg):
40 def icp(ip,arg):
41 """ icp files... targetdir
41 """ icp files... targetdir
42
42
43 Copy all files to target, creating dirs for target if necessary
43 Copy all files to target, creating dirs for target if necessary
44
44
45 icp srcdir dstdir
45 icp srcdir dstdir
46
46
47 Copy srcdir to distdir
47 Copy srcdir to distdir
48
48
49 """
49 """
50 import distutils.dir_util
50 import distutils.dir_util
51
51
52 fs, targetdir = parse_args(arg)
52 fs, targetdir = parse_args(arg)
53 if not os.path.isdir(targetdir):
53 if not os.path.isdir(targetdir):
54 distutils.dir_util.mkpath(targetdir,verbose =1)
54 distutils.dir_util.mkpath(targetdir,verbose =1)
55 for f in fs:
55 for f in fs:
56 shutil.copy2(f,targetdir)
56 shutil.copy2(f,targetdir)
57 return fs
57 return fs
58 ip.defalias("icp",icp)
58 ip.defalias("icp",icp)
59
59
60 def imv(ip,arg):
60 def imv(ip,arg):
61 """ imv src tgt
61 """ imv src tgt
62
62
63 Move source to target.
63 Move source to target.
64 """
64 """
65
65
66 fs, target = parse_args(arg)
66 fs, target = parse_args(arg)
67 if len(fs) > 1:
67 if len(fs) > 1:
68 assert os.path.isdir(target)
68 assert os.path.isdir(target)
69 for f in fs:
69 for f in fs:
70 shutil.move(f, target)
70 shutil.move(f, target)
71 return fs
71 return fs
72 ip.defalias("imv",imv)
72 ip.defalias("imv",imv)
73
73
74 def irm(ip,arg):
74 def irm(ip,arg):
75 """ irm path[s]...
75 """ irm path[s]...
76
76
77 Remove file[s] or dir[s] path. Dirs are deleted recursively.
77 Remove file[s] or dir[s] path. Dirs are deleted recursively.
78 """
78 """
79 paths = mglob.expand(arg.split(None,1)[1])
79 paths = mglob.expand(arg.split(None,1)[1])
80 import distutils.dir_util
80 import distutils.dir_util
81 for p in paths:
81 for p in paths:
82 print "rm",p
82 print "rm",p
83 if os.path.isdir(p):
83 if os.path.isdir(p):
84 distutils.dir_util.remove_tree(p, verbose = 1)
84 distutils.dir_util.remove_tree(p, verbose = 1)
85 else:
85 else:
86 os.remove(p)
86 os.remove(p)
87
87
88 ip.defalias("irm",irm)
88 ip.defalias("irm",irm)
89
89
90 def imkdir(ip,arg):
90 def imkdir(ip,arg):
91 """ imkdir path
91 """ imkdir path
92
92
93 Creates dir path, and all dirs on the road
93 Creates dir path, and all dirs on the road
94 """
94 """
95 import distutils.dir_util
95 import distutils.dir_util
96 targetdir = arg.split(None,1)[1]
96 targetdir = arg.split(None,1)[1]
97 distutils.dir_util.mkpath(targetdir,verbose =1)
97 distutils.dir_util.mkpath(targetdir,verbose =1)
98
98
99 ip.defalias("imkdir",imkdir)
99 ip.defalias("imkdir",imkdir)
100
100
101 def igrep(ip,arg):
101 def igrep(ip,arg):
102 """ igrep PAT files...
102 """ igrep PAT files...
103
103
104 Very dumb file scan, case-insensitive.
104 Very dumb file scan, case-insensitive.
105
105
106 e.g.
106 e.g.
107
107
108 igrep "test this" rec:*.py
108 igrep "test this" rec:*.py
109
109
110 """
110 """
111 elems = shlex.split(arg)
111 elems = shlex.split(arg)
112 dummy, pat, fs = elems[0], elems[1], mglob.expand(elems[2:])
112 dummy, pat, fs = elems[0], elems[1], mglob.expand(elems[2:])
113 res = []
113 res = []
114 for f in fs:
114 for f in fs:
115 found = False
115 found = False
116 for l in open(f):
116 for l in open(f):
117 if pat.lower() in l.lower():
117 if pat.lower() in l.lower():
118 if not found:
118 if not found:
119 print "[[",f,"]]"
119 print "[[",f,"]]"
120 found = True
120 found = True
121 res.append(f)
121 res.append(f)
122 print l.rstrip()
122 print l.rstrip()
123 return res
123 return res
124
124
125 ip.defalias("igrep",igrep)
125 ip.defalias("igrep",igrep)
126
126
127 def collect(ip,arg):
127 def collect(ip,arg):
128 """ collect foo/a.txt rec:bar=*.py
128 """ collect foo/a.txt rec:bar=*.py
129
129
130 Copies foo/a.txt to ~/_ipython/collect/foo/a.txt and *.py from bar,
130 Copies foo/a.txt to ~/_ipython/collect/foo/a.txt and *.py from bar,
131 likewise
131 likewise
132
132
133 Without args, try to open ~/_ipython/collect dir (in win32 at least).
133 Without args, try to open ~/_ipython/collect dir (in win32 at least).
134 """
134 """
135 from path import path
135 from path import path
136 basedir = path(ip.options.ipythondir + '/collect')
136 basedir = path(ip.options.ipythondir + '/collect')
137 try:
137 try:
138 fs = mglob.expand(arg.split(None,1)[1])
138 fs = mglob.expand(arg.split(None,1)[1])
139 except IndexError:
139 except IndexError:
140 os.startfile(basedir)
140 os.startfile(basedir)
141 return
141 return
142 for f in fs:
142 for f in fs:
143 f = path(f)
143 f = path(f)
144 trg = basedir / f.splitdrive()[1].lstrip('/\\')
144 trg = basedir / f.splitdrive()[1].lstrip('/\\')
145 if f.isdir():
145 if f.isdir():
146 print "mkdir",trg
146 print "mkdir",trg
147 trg.makedirs()
147 trg.makedirs()
148 continue
148 continue
149 dname = trg.dirname()
149 dname = trg.dirname()
150 if not dname.isdir():
150 if not dname.isdir():
151 dname.makedirs()
151 dname.makedirs()
152 print f,"=>",trg
152 print f,"=>",trg
153 shutil.copy2(f,trg)
153 shutil.copy2(f,trg)
154
154
155 ip.defalias("collect",collect)
155 ip.defalias("collect",collect)
156
156
157 def inote(ip,arg):
157 def inote(ip,arg):
158 """ inote Hello world
158 """ inote Hello world
159
159
160 Adds timestamp and Hello world to ~/_ipython/notes.txt
160 Adds timestamp and Hello world to ~/_ipython/notes.txt
161
161
162 Without args, opens notes.txt for editing.
162 Without args, opens notes.txt for editing.
163 """
163 """
164 import time
164 import time
165 fname = ip.options.ipythondir + '/notes.txt'
165 fname = ip.options.ipythondir + '/notes.txt'
166
166
167 try:
167 try:
168 entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '\n'
168 entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '\n'
169 f= open(fname, 'a').write(entry)
169 f= open(fname, 'a').write(entry)
170 except IndexError:
170 except IndexError:
171 ip.IP.hooks.editor(fname)
171 ip.IP.hooks.editor(fname)
172
172
173 ip.defalias("inote",inote)
173 ip.defalias("inote",inote)
@@ -1,56 +1,56 b''
1 import os,sys
1 import os,sys
2
2
3 import ipy_rehashdir,glob
3 import ipy_rehashdir,glob
4 from ipy_rehashdir import selflaunch, PyLauncher
4 from ipy_rehashdir import selflaunch, PyLauncher
5
5
6 def pylaunchers():
6 def pylaunchers():
7 """Create launchers for python scripts in cwd and store them in alias table
7 """Create launchers for python scripts in cwd and store them in alias table
8
8
9 This is useful if you want to invoke .py scripts from ipykit session,
9 This is useful if you want to invoke .py scripts from ipykit session,
10 just adding .py files in PATH does not work without file association.
10 just adding .py files in PATH does not work without file association.
11
11
12 .ipy files will be run like macros.
12 .ipy files will be run like macros.
13
13
14 """
14 """
15 fs = glob.glob('*.?py*')
15 fs = glob.glob('*.?py*')
16 for f in fs:
16 for f in fs:
17 l = PyLauncher(f)
17 l = PyLauncher(f)
18 n = os.path.splitext(f)[0]
18 n = os.path.splitext(f)[0]
19 ip.defalias(n, l)
19 ip.defalias(n, l)
20 ip.magic('store '+n)
20 ip.magic('store '+n)
21
21
22
22
23 def exta_imports():
23 def exta_imports():
24 # add some modules that you'd want to be bundled in the ipykit
24 # add some modules that you'd want to be bundled in the ipykit
25 # library zip file here. Do this if you get ImportErrors from scripts you
25 # library zip file here. Do this if you get ImportErrors from scripts you
26 # try to launch with 'py' or pylaunchers. In theory you could include
26 # try to launch with 'py' or pylaunchers. In theory you could include
27 # the whole stdlib here for full script coverage
27 # the whole stdlib here for full script coverage
28
28
29 # note that this is never run, it's just here for py2exe
29 # note that this is never run, it's just here for py2exe
30 import distutils.dir_util
30 import distutils.dir_util
31
31
32 def main():
32 def main():
33 root = os.environ.get('IPYKITROOT', None)
33 root = os.environ.get('IPYKITROOT', None)
34 if not root:
34 if not root:
35 print "Can't configure ipykit, IPYKITROOT should be set."
35 print "Can't configure ipykit, IPYKITROOT should be set."
36 return
36 return
37
37
38 os.environ["PATH"] = os.environ["PATH"] + ";" + root + "\\bin;"
38 os.environ["PATH"] = os.environ["PATH"] + ";" + root + "\\bin;"
39 ip.to_user_ns("pylaunchers")
39 ip.to_user_ns("pylaunchers")
40
40
41
41
42 def ipython_firstrun(ip):
42 def ipython_firstrun(ip):
43 print "First run of ipykit - configuring"
43 print "First run of ipykit - configuring"
44 ip.defalias('py',selflaunch)
44 ip.defalias('py',selflaunch)
45 ip.defalias('d','ls -F')
45 ip.defalias('d','ls -F')
46 ip.defalias('ls','ls')
46 ip.defalias('ls','ls')
47 ip.magic('store py')
47 ip.magic('store py')
48 ip.magic('store d')
48 ip.magic('store d')
49 ip.magic('store ls')
49 ip.magic('store ls')
50
50
51 def init_ipython(ipy):
51 def init_ipython(ipy):
52 global ip
52 global ip
53 ip = ipy
53 ip = ipy
54 main()
54 main()
55
55
56
56
@@ -1,43 +1,43 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2
2
3 import IPython.ipapi
3 import IPython.ipapi
4 ip = IPython.ipapi.get()
4 ip = IPython.ipapi.get()
5
5
6 import os, subprocess
6 import os, subprocess
7
7
8 workdir = None
8 workdir = None
9 def workdir_f(ip,line):
9 def workdir_f(ip,line):
10 """ Exceute commands residing in cwd elsewhere
10 """ Exceute commands residing in cwd elsewhere
11
11
12 Example::
12 Example::
13
13
14 workdir /myfiles
14 workdir /myfiles
15 cd bin
15 cd bin
16 workdir myscript.py
16 workdir myscript.py
17
17
18 executes myscript.py (stored in bin, but not in path) in /myfiles
18 executes myscript.py (stored in bin, but not in path) in /myfiles
19 """
19 """
20 global workdir
20 global workdir
21 dummy,cmd = line.split(None,1)
21 dummy,cmd = line.split(None,1)
22 if os.path.isdir(cmd):
22 if os.path.isdir(cmd):
23 workdir = os.path.abspath(cmd)
23 workdir = os.path.abspath(cmd)
24 print "Set workdir",workdir
24 print "Set workdir",workdir
25 elif workdir is None:
25 elif workdir is None:
26 print "Please set workdir first by doing e.g. 'workdir q:/'"
26 print "Please set workdir first by doing e.g. 'workdir q:/'"
27 else:
27 else:
28 sp = cmd.split(None,1)
28 sp = cmd.split(None,1)
29 if len(sp) == 1:
29 if len(sp) == 1:
30 head, tail = cmd, ''
30 head, tail = cmd, ''
31 else:
31 else:
32 head, tail = sp
32 head, tail = sp
33 if os.path.isfile(head):
33 if os.path.isfile(head):
34 cmd = os.path.abspath(head) + ' ' + tail
34 cmd = os.path.abspath(head) + ' ' + tail
35 print "Execute command '" + cmd+ "' in",workdir
35 print "Execute command '" + cmd+ "' in",workdir
36 olddir = os.getcwd()
36 olddir = os.getcwd()
37 os.chdir(workdir)
37 os.chdir(workdir)
38 try:
38 try:
39 os.system(cmd)
39 os.system(cmd)
40 finally:
40 finally:
41 os.chdir(olddir)
41 os.chdir(olddir)
42
42
43 ip.defalias("workdir",workdir_f)
43 ip.defalias("workdir",workdir_f)
@@ -1,30 +1,30 b''
1 from IPython.ipapi import TryNext
1 from IPython.ipapi import TryNext
2 from IPython.external.simplegeneric import generic
2 from IPython.external.simplegeneric import generic
3
3
4 ''' 'Generic' functions for extending IPython
4 ''' 'Generic' functions for extending IPython
5
5
6 See http://cheeseshop.python.org/pypi/simplegeneric
6 See http://cheeseshop.python.org/pypi/simplegeneric
7
7
8 Here's an example from genutils.py:
8 Here's an example from genutils.py:
9
9
10 def print_lsstring(arg):
10 def print_lsstring(arg):
11 """ Prettier (non-repr-like) and more informative printer for LSString """
11 """ Prettier (non-repr-like) and more informative printer for LSString """
12 print "LSString (.p, .n, .l, .s available). Value:"
12 print "LSString (.p, .n, .l, .s available). Value:"
13 print arg
13 print arg
14
14
15 print_lsstring = result_display.when_type(LSString)(print_lsstring)
15 print_lsstring = result_display.when_type(LSString)(print_lsstring)
16
16
17 (Yes, the nasty syntax is for python 2.3 compatibility. Your own extensions
17 (Yes, the nasty syntax is for python 2.3 compatibility. Your own extensions
18 can use the niftier decorator syntax)
18 can use the niftier decorator syntax)
19
19
20 '''
20 '''
21
21
22 def result_display(result):
22 def result_display(result):
23 """ print the result of computation """
23 """ print the result of computation """
24 raise TryNext
24 raise TryNext
25
25
26 result_display = generic(result_display)
26 result_display = generic(result_display)
27
27
28 def inspect_object(obj):
28 def inspect_object(obj):
29 """ Called when you do obj? """
29 """ Called when you do obj? """
30 raise TryNext
30 raise TryNext
@@ -1,241 +1,241 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 """ History related magics and functionality """
3 """ History related magics and functionality """
4
4
5 import fnmatch
5 import fnmatch
6
6
7 def magic_history(self, parameter_s = ''):
7 def magic_history(self, parameter_s = ''):
8 """Print input history (_i<n> variables), with most recent last.
8 """Print input history (_i<n> variables), with most recent last.
9
9
10 %history -> print at most 40 inputs (some may be multi-line)\\
10 %history -> print at most 40 inputs (some may be multi-line)\\
11 %history n -> print at most n inputs\\
11 %history n -> print at most n inputs\\
12 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
12 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
13
13
14 Each input's number <n> is shown, and is accessible as the
14 Each input's number <n> is shown, and is accessible as the
15 automatically generated variable _i<n>. Multi-line statements are
15 automatically generated variable _i<n>. Multi-line statements are
16 printed starting at a new line for easy copy/paste.
16 printed starting at a new line for easy copy/paste.
17
17
18
18
19 Options:
19 Options:
20
20
21 -n: do NOT print line numbers. This is useful if you want to get a
21 -n: do NOT print line numbers. This is useful if you want to get a
22 printout of many lines which can be directly pasted into a text
22 printout of many lines which can be directly pasted into a text
23 editor.
23 editor.
24
24
25 This feature is only available if numbered prompts are in use.
25 This feature is only available if numbered prompts are in use.
26
26
27 -t: (default) print the 'translated' history, as IPython understands it.
27 -t: (default) print the 'translated' history, as IPython understands it.
28 IPython filters your input and converts it all into valid Python source
28 IPython filters your input and converts it all into valid Python source
29 before executing it (things like magics or aliases are turned into
29 before executing it (things like magics or aliases are turned into
30 function calls, for example). With this option, you'll see the native
30 function calls, for example). With this option, you'll see the native
31 history instead of the user-entered version: '%cd /' will be seen as
31 history instead of the user-entered version: '%cd /' will be seen as
32 '_ip.magic("%cd /")' instead of '%cd /'.
32 '_ip.magic("%cd /")' instead of '%cd /'.
33
33
34 -r: print the 'raw' history, i.e. the actual commands you typed.
34 -r: print the 'raw' history, i.e. the actual commands you typed.
35
35
36 -g: treat the arg as a pattern to grep for in (full) history.
36 -g: treat the arg as a pattern to grep for in (full) history.
37 This includes the "shadow history" (almost all commands ever written).
37 This includes the "shadow history" (almost all commands ever written).
38 Use '%hist -g' to show full shadow history (may be very long).
38 Use '%hist -g' to show full shadow history (may be very long).
39 In shadow history, every index nuwber starts with 0.
39 In shadow history, every index nuwber starts with 0.
40
40
41
41
42 """
42 """
43
43
44 ip = self.api
44 ip = self.api
45 shell = self.shell
45 shell = self.shell
46 if not shell.outputcache.do_full_cache:
46 if not shell.outputcache.do_full_cache:
47 print 'This feature is only available if numbered prompts are in use.'
47 print 'This feature is only available if numbered prompts are in use.'
48 return
48 return
49 opts,args = self.parse_options(parameter_s,'gntsr',mode='list')
49 opts,args = self.parse_options(parameter_s,'gntsr',mode='list')
50
50
51 if opts.has_key('t'):
51 if opts.has_key('t'):
52 input_hist = shell.input_hist
52 input_hist = shell.input_hist
53 elif opts.has_key('r'):
53 elif opts.has_key('r'):
54 input_hist = shell.input_hist_raw
54 input_hist = shell.input_hist_raw
55 else:
55 else:
56 input_hist = shell.input_hist
56 input_hist = shell.input_hist
57
57
58
58
59 default_length = 40
59 default_length = 40
60 pattern = None
60 pattern = None
61 if opts.has_key('g'):
61 if opts.has_key('g'):
62 init = 1
62 init = 1
63 final = len(input_hist)
63 final = len(input_hist)
64 parts = parameter_s.split(None,1)
64 parts = parameter_s.split(None,1)
65 if len(parts) == 1:
65 if len(parts) == 1:
66 parts += '*'
66 parts += '*'
67 head, pattern = parts
67 head, pattern = parts
68 pattern = "*" + pattern + "*"
68 pattern = "*" + pattern + "*"
69 elif len(args) == 0:
69 elif len(args) == 0:
70 final = len(input_hist)
70 final = len(input_hist)
71 init = max(1,final-default_length)
71 init = max(1,final-default_length)
72 elif len(args) == 1:
72 elif len(args) == 1:
73 final = len(input_hist)
73 final = len(input_hist)
74 init = max(1,final-int(args[0]))
74 init = max(1,final-int(args[0]))
75 elif len(args) == 2:
75 elif len(args) == 2:
76 init,final = map(int,args)
76 init,final = map(int,args)
77 else:
77 else:
78 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
78 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
79 print self.magic_hist.__doc__
79 print self.magic_hist.__doc__
80 return
80 return
81 width = len(str(final))
81 width = len(str(final))
82 line_sep = ['','\n']
82 line_sep = ['','\n']
83 print_nums = not opts.has_key('n')
83 print_nums = not opts.has_key('n')
84
84
85 found = False
85 found = False
86 if pattern is not None:
86 if pattern is not None:
87 sh = ip.IP.shadowhist.all()
87 sh = ip.IP.shadowhist.all()
88 for idx, s in sh:
88 for idx, s in sh:
89 if fnmatch.fnmatch(s, pattern):
89 if fnmatch.fnmatch(s, pattern):
90 print "0%d: %s" %(idx, s)
90 print "0%d: %s" %(idx, s)
91 found = True
91 found = True
92
92
93 if found:
93 if found:
94 print "==="
94 print "==="
95 print "^shadow history ends, fetch by %rep <number> (must start with 0)"
95 print "^shadow history ends, fetch by %rep <number> (must start with 0)"
96 print "=== start of normal history ==="
96 print "=== start of normal history ==="
97
97
98 for in_num in range(init,final):
98 for in_num in range(init,final):
99 inline = input_hist[in_num]
99 inline = input_hist[in_num]
100 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
100 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
101 continue
101 continue
102
102
103 multiline = int(inline.count('\n') > 1)
103 multiline = int(inline.count('\n') > 1)
104 if print_nums:
104 if print_nums:
105 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
105 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
106 print inline,
106 print inline,
107
107
108
108
109
109
110 def magic_hist(self, parameter_s=''):
110 def magic_hist(self, parameter_s=''):
111 """Alternate name for %history."""
111 """Alternate name for %history."""
112 return self.magic_history(parameter_s)
112 return self.magic_history(parameter_s)
113
113
114
114
115
115
116 def rep_f(self, arg):
116 def rep_f(self, arg):
117 r""" Repeat a command, or get command to input line for editing
117 r""" Repeat a command, or get command to input line for editing
118
118
119 - %rep (no arguments):
119 - %rep (no arguments):
120
120
121 Place a string version of last computation result (stored in the special '_'
121 Place a string version of last computation result (stored in the special '_'
122 variable) to the next input prompt. Allows you to create elaborate command
122 variable) to the next input prompt. Allows you to create elaborate command
123 lines without using copy-paste::
123 lines without using copy-paste::
124
124
125 $ l = ["hei", "vaan"]
125 $ l = ["hei", "vaan"]
126 $ "".join(l)
126 $ "".join(l)
127 ==> heivaan
127 ==> heivaan
128 $ %rep
128 $ %rep
129 $ heivaan_ <== cursor blinking
129 $ heivaan_ <== cursor blinking
130
130
131 %rep 45
131 %rep 45
132
132
133 Place history line 45 to next input prompt. Use %hist to find out the
133 Place history line 45 to next input prompt. Use %hist to find out the
134 number.
134 number.
135
135
136 %rep 1-4 6-7 3
136 %rep 1-4 6-7 3
137
137
138 Repeat the specified lines immediately. Input slice syntax is the same as
138 Repeat the specified lines immediately. Input slice syntax is the same as
139 in %macro and %save.
139 in %macro and %save.
140
140
141 %rep foo
141 %rep foo
142
142
143 Place the most recent line that has the substring "foo" to next input.
143 Place the most recent line that has the substring "foo" to next input.
144 (e.g. 'svn ci -m foobar').
144 (e.g. 'svn ci -m foobar').
145
145
146 """
146 """
147
147
148
148
149 opts,args = self.parse_options(arg,'',mode='list')
149 opts,args = self.parse_options(arg,'',mode='list')
150 ip = self.api
150 ip = self.api
151 if not args:
151 if not args:
152 ip.set_next_input(str(ip.user_ns["_"]))
152 ip.set_next_input(str(ip.user_ns["_"]))
153 return
153 return
154
154
155 if len(args) == 1 and not '-' in args[0]:
155 if len(args) == 1 and not '-' in args[0]:
156 arg = args[0]
156 arg = args[0]
157 if len(arg) > 1 and arg.startswith('0'):
157 if len(arg) > 1 and arg.startswith('0'):
158 # get from shadow hist
158 # get from shadow hist
159 num = int(arg[1:])
159 num = int(arg[1:])
160 line = self.shadowhist.get(num)
160 line = self.shadowhist.get(num)
161 ip.set_next_input(str(line))
161 ip.set_next_input(str(line))
162 return
162 return
163 try:
163 try:
164 num = int(args[0])
164 num = int(args[0])
165 ip.set_next_input(str(ip.IP.input_hist_raw[num]).rstrip())
165 ip.set_next_input(str(ip.IP.input_hist_raw[num]).rstrip())
166 return
166 return
167 except ValueError:
167 except ValueError:
168 pass
168 pass
169
169
170 for h in reversed(self.shell.input_hist_raw):
170 for h in reversed(self.shell.input_hist_raw):
171 if 'rep' in h:
171 if 'rep' in h:
172 continue
172 continue
173 if fnmatch.fnmatch(h,'*' + arg + '*'):
173 if fnmatch.fnmatch(h,'*' + arg + '*'):
174 ip.set_next_input(str(h).rstrip())
174 ip.set_next_input(str(h).rstrip())
175 return
175 return
176
176
177
177
178 try:
178 try:
179 lines = self.extract_input_slices(args, True)
179 lines = self.extract_input_slices(args, True)
180 print "lines",lines
180 print "lines",lines
181 ip.runlines(lines)
181 ip.runlines(lines)
182 except ValueError:
182 except ValueError:
183 print "Not found in recent history:", args
183 print "Not found in recent history:", args
184
184
185
185
186
186
187 _sentinel = object()
187 _sentinel = object()
188
188
189 class ShadowHist:
189 class ShadowHist:
190 def __init__(self,db):
190 def __init__(self,db):
191 # cmd => idx mapping
191 # cmd => idx mapping
192 self.curidx = 0
192 self.curidx = 0
193 self.db = db
193 self.db = db
194
194
195 def inc_idx(self):
195 def inc_idx(self):
196 idx = self.db.get('shadowhist_idx', 1)
196 idx = self.db.get('shadowhist_idx', 1)
197 self.db['shadowhist_idx'] = idx + 1
197 self.db['shadowhist_idx'] = idx + 1
198 return idx
198 return idx
199
199
200 def add(self, ent):
200 def add(self, ent):
201 old = self.db.hget('shadowhist', ent, _sentinel)
201 old = self.db.hget('shadowhist', ent, _sentinel)
202 if old is not _sentinel:
202 if old is not _sentinel:
203 return
203 return
204 newidx = self.inc_idx()
204 newidx = self.inc_idx()
205 #print "new",newidx # dbg
205 #print "new",newidx # dbg
206 self.db.hset('shadowhist',ent, newidx)
206 self.db.hset('shadowhist',ent, newidx)
207
207
208 def all(self):
208 def all(self):
209 d = self.db.hdict('shadowhist')
209 d = self.db.hdict('shadowhist')
210 items = [(i,s) for (s,i) in d.items()]
210 items = [(i,s) for (s,i) in d.items()]
211 items.sort()
211 items.sort()
212 return items
212 return items
213
213
214 def get(self, idx):
214 def get(self, idx):
215 all = self.all()
215 all = self.all()
216
216
217 for k, v in all:
217 for k, v in all:
218 #print k,v
218 #print k,v
219 if k == idx:
219 if k == idx:
220 return v
220 return v
221
221
222 def test_shist():
222 def test_shist():
223 from IPython.Extensions import pickleshare
223 from IPython.Extensions import pickleshare
224 db = pickleshare.PickleShareDB('~/shist')
224 db = pickleshare.PickleShareDB('~/shist')
225 s = ShadowHist(db)
225 s = ShadowHist(db)
226 s.add('hello')
226 s.add('hello')
227 s.add('world')
227 s.add('world')
228 s.add('hello')
228 s.add('hello')
229 s.add('hello')
229 s.add('hello')
230 s.add('karhu')
230 s.add('karhu')
231 print "all",s.all()
231 print "all",s.all()
232 print s.get(2)
232 print s.get(2)
233
233
234 def init_ipython(ip):
234 def init_ipython(ip):
235 ip.expose_magic("rep",rep_f)
235 ip.expose_magic("rep",rep_f)
236 ip.expose_magic("hist",magic_hist)
236 ip.expose_magic("hist",magic_hist)
237 ip.expose_magic("history",magic_history)
237 ip.expose_magic("history",magic_history)
238
238
239 import ipy_completers
239 import ipy_completers
240 ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
240 ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
241 #test_shist()
241 #test_shist()
General Comments 0
You need to be logged in to leave comments. Login now