##// END OF EJS Templates
Remove input_prefilter hook...
Thomas Kluyver -
Show More
@@ -0,0 +1,4 b''
1 * The ``input_prefilter`` hook has been removed, as it was never
2 actually used by the code. The input transformer system offers much
3 more powerful APIs to work with input code. See
4 :doc:`/config/inputtransforms` for details.
@@ -1,224 +1,209 b''
1 """Hooks for IPython.
1 """Hooks for IPython.
2
2
3 In Python, it is possible to overwrite any method of any object if you really
3 In Python, it is possible to overwrite any method of any object if you really
4 want to. But IPython exposes a few 'hooks', methods which are *designed* to
4 want to. But IPython exposes a few 'hooks', methods which are *designed* to
5 be overwritten by users for customization purposes. This module defines the
5 be overwritten by users for customization purposes. This module defines the
6 default versions of all such hooks, which get used by IPython if not
6 default versions of all such hooks, which get used by IPython if not
7 overridden by the user.
7 overridden by the user.
8
8
9 Hooks are simple functions, but they should be declared with ``self`` as their
9 Hooks are simple functions, but they should be declared with ``self`` as their
10 first argument, because when activated they are registered into IPython as
10 first argument, because when activated they are registered into IPython as
11 instance methods. The self argument will be the IPython running instance
11 instance methods. The self argument will be the IPython running instance
12 itself, so hooks have full access to the entire IPython object.
12 itself, so hooks have full access to the entire IPython object.
13
13
14 If you wish to define a new hook and activate it, you can make an :doc:`extension
14 If you wish to define a new hook and activate it, you can make an :doc:`extension
15 </config/extensions/index>` or a :ref:`startup script <startup_files>`. For
15 </config/extensions/index>` or a :ref:`startup script <startup_files>`. For
16 example, you could use a startup file like this::
16 example, you could use a startup file like this::
17
17
18 import os
18 import os
19
19
20 def calljed(self,filename, linenum):
20 def calljed(self,filename, linenum):
21 "My editor hook calls the jed editor directly."
21 "My editor hook calls the jed editor directly."
22 print "Calling my own editor, jed ..."
22 print "Calling my own editor, jed ..."
23 if os.system('jed +%d %s' % (linenum,filename)) != 0:
23 if os.system('jed +%d %s' % (linenum,filename)) != 0:
24 raise TryNext()
24 raise TryNext()
25
25
26 def load_ipython_extension(ip):
26 def load_ipython_extension(ip):
27 ip.set_hook('editor', calljed)
27 ip.set_hook('editor', calljed)
28
28
29 """
29 """
30
30
31 #*****************************************************************************
31 #*****************************************************************************
32 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
32 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
33 #
33 #
34 # Distributed under the terms of the BSD License. The full license is in
34 # Distributed under the terms of the BSD License. The full license is in
35 # the file COPYING, distributed as part of this software.
35 # the file COPYING, distributed as part of this software.
36 #*****************************************************************************
36 #*****************************************************************************
37
37
38 import os
38 import os
39 import subprocess
39 import subprocess
40 import sys
40 import sys
41
41
42 from IPython.core.error import TryNext
42 from IPython.core.error import TryNext
43
43
44 # List here all the default hooks. For now it's just the editor functions
44 # List here all the default hooks. For now it's just the editor functions
45 # but over time we'll move here all the public API for user-accessible things.
45 # but over time we'll move here all the public API for user-accessible things.
46
46
47 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
47 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
48 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
48 'shutdown_hook', 'late_startup_hook',
49 'show_in_pager','pre_prompt_hook',
49 'show_in_pager','pre_prompt_hook',
50 'pre_run_code_hook', 'clipboard_get']
50 'pre_run_code_hook', 'clipboard_get']
51
51
52 def editor(self, filename, linenum=None, wait=True):
52 def editor(self, filename, linenum=None, wait=True):
53 """Open the default editor at the given filename and linenumber.
53 """Open the default editor at the given filename and linenumber.
54
54
55 This is IPython's default editor hook, you can use it as an example to
55 This is IPython's default editor hook, you can use it as an example to
56 write your own modified one. To set your own editor function as the
56 write your own modified one. To set your own editor function as the
57 new editor hook, call ip.set_hook('editor',yourfunc)."""
57 new editor hook, call ip.set_hook('editor',yourfunc)."""
58
58
59 # IPython configures a default editor at startup by reading $EDITOR from
59 # IPython configures a default editor at startup by reading $EDITOR from
60 # the environment, and falling back on vi (unix) or notepad (win32).
60 # the environment, and falling back on vi (unix) or notepad (win32).
61 editor = self.editor
61 editor = self.editor
62
62
63 # marker for at which line to open the file (for existing objects)
63 # marker for at which line to open the file (for existing objects)
64 if linenum is None or editor=='notepad':
64 if linenum is None or editor=='notepad':
65 linemark = ''
65 linemark = ''
66 else:
66 else:
67 linemark = '+%d' % int(linenum)
67 linemark = '+%d' % int(linenum)
68
68
69 # Enclose in quotes if necessary and legal
69 # Enclose in quotes if necessary and legal
70 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
70 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
71 editor = '"%s"' % editor
71 editor = '"%s"' % editor
72
72
73 # Call the actual editor
73 # Call the actual editor
74 proc = subprocess.Popen('%s %s %s' % (editor, linemark, filename),
74 proc = subprocess.Popen('%s %s %s' % (editor, linemark, filename),
75 shell=True)
75 shell=True)
76 if wait and proc.wait() != 0:
76 if wait and proc.wait() != 0:
77 raise TryNext()
77 raise TryNext()
78
78
79 import tempfile
79 import tempfile
80 def fix_error_editor(self,filename,linenum,column,msg):
80 def fix_error_editor(self,filename,linenum,column,msg):
81 """Open the editor at the given filename, linenumber, column and
81 """Open the editor at the given filename, linenumber, column and
82 show an error message. This is used for correcting syntax errors.
82 show an error message. This is used for correcting syntax errors.
83 The current implementation only has special support for the VIM editor,
83 The current implementation only has special support for the VIM editor,
84 and falls back on the 'editor' hook if VIM is not used.
84 and falls back on the 'editor' hook if VIM is not used.
85
85
86 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
86 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
87 """
87 """
88 def vim_quickfix_file():
88 def vim_quickfix_file():
89 t = tempfile.NamedTemporaryFile()
89 t = tempfile.NamedTemporaryFile()
90 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
90 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
91 t.flush()
91 t.flush()
92 return t
92 return t
93 if os.path.basename(self.editor) != 'vim':
93 if os.path.basename(self.editor) != 'vim':
94 self.hooks.editor(filename,linenum)
94 self.hooks.editor(filename,linenum)
95 return
95 return
96 t = vim_quickfix_file()
96 t = vim_quickfix_file()
97 try:
97 try:
98 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
98 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
99 raise TryNext()
99 raise TryNext()
100 finally:
100 finally:
101 t.close()
101 t.close()
102
102
103
103
104 def synchronize_with_editor(self, filename, linenum, column):
104 def synchronize_with_editor(self, filename, linenum, column):
105 pass
105 pass
106
106
107
107
108 class CommandChainDispatcher:
108 class CommandChainDispatcher:
109 """ Dispatch calls to a chain of commands until some func can handle it
109 """ Dispatch calls to a chain of commands until some func can handle it
110
110
111 Usage: instantiate, execute "add" to add commands (with optional
111 Usage: instantiate, execute "add" to add commands (with optional
112 priority), execute normally via f() calling mechanism.
112 priority), execute normally via f() calling mechanism.
113
113
114 """
114 """
115 def __init__(self,commands=None):
115 def __init__(self,commands=None):
116 if commands is None:
116 if commands is None:
117 self.chain = []
117 self.chain = []
118 else:
118 else:
119 self.chain = commands
119 self.chain = commands
120
120
121
121
122 def __call__(self,*args, **kw):
122 def __call__(self,*args, **kw):
123 """ Command chain is called just like normal func.
123 """ Command chain is called just like normal func.
124
124
125 This will call all funcs in chain with the same args as were given to
125 This will call all funcs in chain with the same args as were given to
126 this function, and return the result of first func that didn't raise
126 this function, and return the result of first func that didn't raise
127 TryNext"""
127 TryNext"""
128 last_exc = TryNext()
128 last_exc = TryNext()
129 for prio,cmd in self.chain:
129 for prio,cmd in self.chain:
130 #print "prio",prio,"cmd",cmd #dbg
130 #print "prio",prio,"cmd",cmd #dbg
131 try:
131 try:
132 return cmd(*args, **kw)
132 return cmd(*args, **kw)
133 except TryNext as exc:
133 except TryNext as exc:
134 last_exc = exc
134 last_exc = exc
135 # if no function will accept it, raise TryNext up to the caller
135 # if no function will accept it, raise TryNext up to the caller
136 raise last_exc
136 raise last_exc
137
137
138 def __str__(self):
138 def __str__(self):
139 return str(self.chain)
139 return str(self.chain)
140
140
141 def add(self, func, priority=0):
141 def add(self, func, priority=0):
142 """ Add a func to the cmd chain with given priority """
142 """ Add a func to the cmd chain with given priority """
143 self.chain.append((priority, func))
143 self.chain.append((priority, func))
144 self.chain.sort(key=lambda x: x[0])
144 self.chain.sort(key=lambda x: x[0])
145
145
146 def __iter__(self):
146 def __iter__(self):
147 """ Return all objects in chain.
147 """ Return all objects in chain.
148
148
149 Handy if the objects are not callable.
149 Handy if the objects are not callable.
150 """
150 """
151 return iter(self.chain)
151 return iter(self.chain)
152
152
153
153
154 def input_prefilter(self,line):
155 """ Default input prefilter
156
157 This returns the line as unchanged, so that the interpreter
158 knows that nothing was done and proceeds with "classic" prefiltering
159 (%magics, !shell commands etc.).
160
161 Note that leading whitespace is not passed to this hook. Prefilter
162 can't alter indentation.
163
164 """
165 #print "attempt to rewrite",line #dbg
166 return line
167
168
169 def shutdown_hook(self):
154 def shutdown_hook(self):
170 """ default shutdown hook
155 """ default shutdown hook
171
156
172 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
157 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
173 """
158 """
174
159
175 #print "default shutdown hook ok" # dbg
160 #print "default shutdown hook ok" # dbg
176 return
161 return
177
162
178
163
179 def late_startup_hook(self):
164 def late_startup_hook(self):
180 """ Executed after ipython has been constructed and configured
165 """ Executed after ipython has been constructed and configured
181
166
182 """
167 """
183 #print "default startup hook ok" # dbg
168 #print "default startup hook ok" # dbg
184
169
185
170
186 def show_in_pager(self,s):
171 def show_in_pager(self,s):
187 """ Run a string through pager """
172 """ Run a string through pager """
188 # raising TryNext here will use the default paging functionality
173 # raising TryNext here will use the default paging functionality
189 raise TryNext
174 raise TryNext
190
175
191
176
192 def pre_prompt_hook(self):
177 def pre_prompt_hook(self):
193 """ Run before displaying the next prompt
178 """ Run before displaying the next prompt
194
179
195 Use this e.g. to display output from asynchronous operations (in order
180 Use this e.g. to display output from asynchronous operations (in order
196 to not mess up text entry)
181 to not mess up text entry)
197 """
182 """
198
183
199 return None
184 return None
200
185
201
186
202 def pre_run_code_hook(self):
187 def pre_run_code_hook(self):
203 """ Executed before running the (prefiltered) code in IPython """
188 """ Executed before running the (prefiltered) code in IPython """
204 return None
189 return None
205
190
206
191
207 def clipboard_get(self):
192 def clipboard_get(self):
208 """ Get text from the clipboard.
193 """ Get text from the clipboard.
209 """
194 """
210 from IPython.lib.clipboard import (
195 from IPython.lib.clipboard import (
211 osx_clipboard_get, tkinter_clipboard_get,
196 osx_clipboard_get, tkinter_clipboard_get,
212 win32_clipboard_get
197 win32_clipboard_get
213 )
198 )
214 if sys.platform == 'win32':
199 if sys.platform == 'win32':
215 chain = [win32_clipboard_get, tkinter_clipboard_get]
200 chain = [win32_clipboard_get, tkinter_clipboard_get]
216 elif sys.platform == 'darwin':
201 elif sys.platform == 'darwin':
217 chain = [osx_clipboard_get, tkinter_clipboard_get]
202 chain = [osx_clipboard_get, tkinter_clipboard_get]
218 else:
203 else:
219 chain = [tkinter_clipboard_get]
204 chain = [tkinter_clipboard_get]
220 dispatcher = CommandChainDispatcher()
205 dispatcher = CommandChainDispatcher()
221 for func in chain:
206 for func in chain:
222 dispatcher.add(func)
207 dispatcher.add(func)
223 text = dispatcher()
208 text = dispatcher()
224 return text
209 return text
General Comments 0
You need to be logged in to leave comments. Login now