##// END OF EJS Templates
Added ipy_render.py for template expansion
vivainio -
Show More
@@ -0,0 +1,45 b''
1 #!/usr/bin/env python
2
3 import IPython.ipapi
4
5 ip = IPython.ipapi.get()
6
7 from string import Template
8 import sys
9
10 def toclip_w32(s):
11 """ places contents of s to clipboard """
12 import win32clipboard as cl
13 import win32con
14 cl.OpenClipboard()
15 cl.EmptyClipboard()
16 cl.SetClipboardText( s )
17 cl.CloseClipboard()
18
19 if sys.platform == 'win32':
20 toclip = toclip_w32
21 else:
22 def toclip(s): pass
23
24
25 def render(tmpl):
26 """ Render a template (as specified in string.Template docs) from ipython variables
27
28 Example:
29
30 $ import ipy_render
31 $ my_name = 'Bob' # %store this for convenience
32 $ t_submission_form = "Submission report, author: $my_name" # %store also
33 $ render t_submission_form
34
35 => returns "Submission report, author: Bob" and copies to clipboard on win32
36
37 """
38
39 s = Template(tmpl)
40 res = s.substitute(ip.user_ns)
41 toclip(res)
42 return res
43
44 ip.user_ns['render'] = render
45 No newline at end of file
@@ -1,226 +1,226 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2
2
3 """ Implementations for various useful completers
3 """ Implementations for various useful completers
4
4
5 See Extensions/ipy_stock_completers.py on examples of how to enable a completer,
5 See Extensions/ipy_stock_completers.py on examples of how to enable a completer,
6 but the basic idea is to do:
6 but the basic idea is to do:
7
7
8 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
8 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
9
9
10 """
10 """
11
11
12 import IPython.ipapi
12 import IPython.ipapi
13 import glob,os,shlex,sys
13 import glob,os,shlex,sys
14
14
15 ip = IPython.ipapi.get()
15 ip = IPython.ipapi.get()
16
16
17 def vcs_completer(commands, event):
17 def vcs_completer(commands, event):
18 """ utility to make writing typical version control app completers easier
18 """ utility to make writing typical version control app completers easier
19
19
20 VCS command line apps typically have the format:
20 VCS command line apps typically have the format:
21
21
22 [sudo ]PROGNAME [help] [command] file file...
22 [sudo ]PROGNAME [help] [command] file file...
23
23
24 """
24 """
25
25
26
26
27 cmd_param = event.line.split()
27 cmd_param = event.line.split()
28 if event.line.endswith(' '):
28 if event.line.endswith(' '):
29 cmd_param.append('')
29 cmd_param.append('')
30
30
31 if cmd_param[0] == 'sudo':
31 if cmd_param[0] == 'sudo':
32 cmd_param = cmd_param[1:]
32 cmd_param = cmd_param[1:]
33
33
34 if len(cmd_param) == 2 or 'help' in cmd_param:
34 if len(cmd_param) == 2 or 'help' in cmd_param:
35 return commands.split()
35 return commands.split()
36
36
37 return ip.IP.Completer.file_matches(event.symbol)
37 return ip.IP.Completer.file_matches(event.symbol)
38
38
39
39
40
40
41 def apt_completers(self, event):
41 def apt_completers(self, event):
42 """ This should return a list of strings with possible completions.
42 """ This should return a list of strings with possible completions.
43
43
44 Note that all the included strings that don't start with event.symbol
44 Note that all the included strings that don't start with event.symbol
45 are removed, in order to not confuse readline.
45 are removed, in order to not confuse readline.
46
46
47 """
47 """
48 # print event # dbg
48 # print event # dbg
49
49
50 # commands are only suggested for the 'command' part of package manager
50 # commands are only suggested for the 'command' part of package manager
51 # invocation
51 # invocation
52
52
53 cmd = (event.line + "<placeholder>").rsplit(None,1)[0]
53 cmd = (event.line + "<placeholder>").rsplit(None,1)[0]
54 # print cmd
54 # print cmd
55 if cmd.endswith('apt-get') or cmd.endswith('yum'):
55 if cmd.endswith('apt-get') or cmd.endswith('yum'):
56 return ['update', 'upgrade', 'install', 'remove']
56 return ['update', 'upgrade', 'install', 'remove']
57
57
58 # later on, add dpkg -l / whatever to get list of possible
58 # later on, add dpkg -l / whatever to get list of possible
59 # packages, add switches etc. for the rest of command line
59 # packages, add switches etc. for the rest of command line
60 # filling
60 # filling
61
61
62 raise IPython.ipapi.TryNext
62 raise IPython.ipapi.TryNext
63
63
64
64
65
65
66 pkg_cache = None
66 pkg_cache = None
67
67
68 def module_completer(self,event):
68 def module_completer(self,event):
69 """ Give completions after user has typed 'import'.
69 """ Give completions after user has typed 'import'.
70
70
71 Note that only possible completions in the local directory are returned."""
71 Note that only possible completions in the local directory are returned."""
72
72
73 # This works in all versions of python. While 2.5 has
73 # This works in all versions of python. While 2.5 has
74 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
74 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
75 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
75 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
76 # of possibly problematic side effects. At some point we may implement
76 # of possibly problematic side effects. At some point we may implement
77 # something that searches sys.path in a saner/safer way, but for now we'll
77 # something that searches sys.path in a saner/safer way, but for now we'll
78 # restrict ourselves to local completions only.
78 # restrict ourselves to local completions only.
79 for el in [f[:-3] for f in glob.glob("*.py")]:
79 for el in [f[:-3] for f in glob.glob("*.py")]:
80 yield el
80 yield el
81 return
81 return
82
82
83
83
84 svn_commands = """\
84 svn_commands = """\
85 add blame praise annotate ann cat checkout co cleanup commit ci copy
85 add blame praise annotate ann cat checkout co cleanup commit ci copy
86 cp delete del remove rm diff di export help ? h import info list ls
86 cp delete del remove rm diff di export help ? h import info list ls
87 lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit
87 lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit
88 pe propget pget pg proplist plist pl propset pset ps resolved revert
88 pe propget pget pg proplist plist pl propset pset ps resolved revert
89 status stat st switch sw unlock update
89 status stat st switch sw unlock update
90 """
90 """
91
91
92 def svn_completer(self,event):
92 def svn_completer(self,event):
93 return vcs_completer(svn_commands, event)
93 return vcs_completer(svn_commands, event)
94
94
95
95
96 hg_commands = """
96 hg_commands = """
97 add addremove annotate archive backout branch branches bundle cat
97 add addremove annotate archive backout branch branches bundle cat
98 clone commit copy diff export grep heads help identify import incoming
98 clone commit copy diff export grep heads help identify import incoming
99 init locate log manifest merge outgoing parents paths pull push
99 init locate log manifest merge outgoing parents paths pull push
100 qapplied qclone qcommit qdelete qdiff qfold qguard qheader qimport
100 qapplied qclone qcommit qdelete qdiff qfold qguard qheader qimport
101 qinit qnew qnext qpop qprev qpush qrefresh qrename qrestore qsave
101 qinit qnew qnext qpop qprev qpush qrefresh qrename qrestore qsave
102 qselect qseries qtop qunapplied recover remove rename revert rollback
102 qselect qseries qtop qunapplied recover remove rename revert rollback
103 root serve showconfig status strip tag tags tip unbundle update verify
103 root serve showconfig status strip tag tags tip unbundle update verify
104 version
104 version
105 """
105 """
106
106
107 def hg_completer(self,event):
107 def hg_completer(self,event):
108 """ Completer for mercurial commands """
108 """ Completer for mercurial commands """
109
109
110 return vcs_completer(hg_commands, event)
110 return vcs_completer(hg_commands, event)
111
111
112
112
113
113
114 bzr_commands = """
114 bzr_commands = """
115 add annotate bind branch break-lock bundle-revisions cat check
115 add annotate bind branch break-lock bundle-revisions cat check
116 checkout commit conflicts deleted diff export gannotate gbranch
116 checkout commit conflicts deleted diff export gannotate gbranch
117 gcommit gdiff help ignore ignored info init init-repository inventory
117 gcommit gdiff help ignore ignored info init init-repository inventory
118 log merge missing mkdir mv nick pull push reconcile register-branch
118 log merge missing mkdir mv nick pull push reconcile register-branch
119 remerge remove renames resolve revert revno root serve sign-my-commits
119 remerge remove renames resolve revert revno root serve sign-my-commits
120 status testament unbind uncommit unknowns update upgrade version
120 status testament unbind uncommit unknowns update upgrade version
121 version-info visualise whoami
121 version-info visualise whoami
122 """
122 """
123
123
124 def bzr_completer(self,event):
124 def bzr_completer(self,event):
125 """ Completer for bazaar commands """
125 """ Completer for bazaar commands """
126 cmd_param = event.line.split()
126 cmd_param = event.line.split()
127 if event.line.endswith(' '):
127 if event.line.endswith(' '):
128 cmd_param.append('')
128 cmd_param.append('')
129
129
130 if len(cmd_param) > 2:
130 if len(cmd_param) > 2:
131 cmd = cmd_param[1]
131 cmd = cmd_param[1]
132 param = cmd_param[-1]
132 param = cmd_param[-1]
133 output_file = (param == '--output=')
133 output_file = (param == '--output=')
134 if cmd == 'help':
134 if cmd == 'help':
135 return bzr_commands.split()
135 return bzr_commands.split()
136 elif cmd in ['bundle-revisions','conflicts',
136 elif cmd in ['bundle-revisions','conflicts',
137 'deleted','nick','register-branch',
137 'deleted','nick','register-branch',
138 'serve','unbind','upgrade','version',
138 'serve','unbind','upgrade','version',
139 'whoami'] and not output_file:
139 'whoami'] and not output_file:
140 return []
140 return []
141 else:
141 else:
142 # the rest are probably file names
142 # the rest are probably file names
143 return ip.IP.Completer.file_matches(event.symbol)
143 return ip.IP.Completer.file_matches(event.symbol)
144
144
145 return bzr_commands.split()
145 return bzr_commands.split()
146
146
147
147
148 def shlex_split(x):
148 def shlex_split(x):
149 """Helper function to split lines into segments."""
149 """Helper function to split lines into segments."""
150 #shlex.split raise exception if syntax error in sh syntax
150 #shlex.split raise exception if syntax error in sh syntax
151 #for example if no closing " is found. This function keeps dropping
151 #for example if no closing " is found. This function keeps dropping
152 #the last character of the line until shlex.split does not raise
152 #the last character of the line until shlex.split does not raise
153 #exception. Adds end of the line to the result of shlex.split
153 #exception. Adds end of the line to the result of shlex.split
154 #example: %run "c:/python -> ['%run','"c:/python']
154 #example: %run "c:/python -> ['%run','"c:/python']
155 endofline=[]
155 endofline=[]
156 while x!="":
156 while x!="":
157 try:
157 try:
158 comps=shlex.split(x)
158 comps=shlex.split(x)
159 if len(endofline)>=1:
159 if len(endofline)>=1:
160 comps.append("".join(endofline))
160 comps.append("".join(endofline))
161 return comps
161 return comps
162 except ValueError:
162 except ValueError:
163 endofline=[x[-1:]]+endofline
163 endofline=[x[-1:]]+endofline
164 x=x[:-1]
164 x=x[:-1]
165 return ["".join(endofline)]
165 return ["".join(endofline)]
166
166
167 def runlistpy(self, event):
167 def runlistpy(self, event):
168 comps = shlex_split(event.line)
168 comps = shlex_split(event.line)
169 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
169 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
170
170
171 #print "\nev=",event # dbg
171 #print "\nev=",event # dbg
172 #print "rp=",relpath # dbg
172 #print "rp=",relpath # dbg
173 #print 'comps=',comps # dbg
173 #print 'comps=',comps # dbg
174
174
175 lglob = glob.glob
175 lglob = glob.glob
176 isdir = os.path.isdir
176 isdir = os.path.isdir
177 if relpath.startswith('~'):
177 if relpath.startswith('~'):
178 relpath = os.path.expanduser(relpath)
178 relpath = os.path.expanduser(relpath)
179 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*')
179 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*')
180 if isdir(f)]
180 if isdir(f)]
181
181
182 # Find if the user has already typed the first filename, after which we
182 # Find if the user has already typed the first filename, after which we
183 # should complete on all files, since after the first one other files may
183 # should complete on all files, since after the first one other files may
184 # be arguments to the input script.
184 # be arguments to the input script.
185 #filter(
185 #filter(
186 if filter(lambda f: f.endswith('.py') or f.endswith('.ipy'),comps):
186 if filter(lambda f: f.endswith('.py') or f.endswith('.ipy'),comps):
187 pys = [f.replace('\\','/') for f in lglob('*')]
187 pys = [f.replace('\\','/') for f in lglob('*')]
188 else:
188 else:
189 pys = [f.replace('\\','/')
189 pys = [f.replace('\\','/')
190 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy')]
190 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy')]
191 return dirs + pys
191 return dirs + pys
192
192
193
193
194 def cd_completer(self, event):
194 def cd_completer(self, event):
195 relpath = event.symbol
195 relpath = event.symbol
196 #print event # dbg
196 #print event # dbg
197 if '-b' in event.line:
197 if '-b' in event.line:
198 # return only bookmark completions
198 # return only bookmark completions
199 bkms = self.db.get('bookmarks',{})
199 bkms = self.db.get('bookmarks',{})
200 return bkms.keys()
200 return bkms.keys()
201
201
202
202
203 if event.symbol == '-':
203 if event.symbol == '-':
204 # jump in directory history by number
204 # jump in directory history by number
205 ents = ['-%d [%s]' % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
205 ents = ['-%d [%s]' % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
206 if len(ents) > 1:
206 if len(ents) > 1:
207 return ents
207 return ents
208 return []
208 return []
209
209
210 if relpath.startswith('~'):
210 if relpath.startswith('~'):
211 relpath = os.path.expanduser(relpath).replace('\\','/')
211 relpath = os.path.expanduser(relpath).replace('\\','/')
212 found = []
212 found = []
213 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
213 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
214 if os.path.isdir(f)]:
214 if os.path.isdir(f)]:
215 if ' ' in d:
215 if ' ' in d:
216 # we don't want to deal with any of that, complex code
216 # we don't want to deal with any of that, complex code
217 # for this is elsewhere
217 # for this is elsewhere
218 raise IPython.ipapi.TryNext
218 raise IPython.ipapi.TryNext
219 found.append( d )
219 found.append( d )
220
220
221 if not found:
221 if not found:
222 if os.path.isdir(relpath):
222 if os.path.isdir(relpath):
223 return [relpath]
223 return [relpath]
224 raise IPython.ipapi.TryNext
224 raise IPython.ipapi.TryNext
225 return found
225 return found
226
226
General Comments 0
You need to be logged in to leave comments. Login now