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