##// END OF EJS Templates
- set the default value of autoedit_syntax to be false. Too many complaints....
fperez -
Show More

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

@@ -1,296 +1,285 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Pdb debugger class.
4 4
5 5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 6 the command line completion of other programs which include this isn't
7 7 damaged.
8 8
9 9 In the future, this class will be expanded with improvements over the standard
10 10 pdb.
11 11
12 12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 13 changes. Licensing should therefore be under the standard Python terms. For
14 14 details on the PSF (Python Software Foundation) standard license, see:
15 15
16 16 http://www.python.org/2.2.3/license.html
17 17
18 $Id: Debugger.py 1029 2006-01-18 07:33:38Z fperez $"""
18 $Id: Debugger.py 1324 2006-05-24 20:25:11Z fperez $"""
19 19
20 20 #*****************************************************************************
21 21 #
22 22 # Since this file is essentially a modified copy of the pdb module which is
23 23 # part of the standard Python distribution, I assume that the proper procedure
24 24 # is to maintain its copyright as belonging to the Python Software Foundation
25 25 # (in addition to my own, for all new code).
26 26 #
27 27 # Copyright (C) 2001 Python Software Foundation, www.python.org
28 28 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
29 29 #
30 30 # Distributed under the terms of the BSD License. The full license is in
31 31 # the file COPYING, distributed as part of this software.
32 32 #
33 33 #*****************************************************************************
34 34
35
36 35 from IPython import Release
37 36 __author__ = '%s <%s>' % Release.authors['Fernando']
38 37 __license__ = 'Python'
39 38
40 39 import bdb
41 40 import cmd
42 41 import linecache
43 42 import os
44 43 import pdb
45 44 import sys
46 45
47 46 from IPython import PyColorize, ColorANSI
48 47 from IPython.genutils import Term
49 48 from IPython.excolors import ExceptionColors
50 49
51 50 def _file_lines(fname):
52 51 """Return the contents of a named file as a list of lines.
53 52
54 53 This function never raises an IOError exception: if the file can't be
55 54 read, it simply returns an empty list."""
56 55
57 56 try:
58 57 outfile = open(fname)
59 58 except IOError:
60 59 return []
61 60 else:
62 61 out = outfile.readlines()
63 62 outfile.close()
64 63 return out
65 64
66
67 65 class Pdb(pdb.Pdb):
68 66 """Modified Pdb class, does not load readline."""
69 67
70 68 # Ugly hack: we can't call the parent constructor, because it binds
71 69 # readline and breaks tab-completion. This means we have to COPY the
72 70 # constructor here, and that requires tracking various python versions.
73 71
74 72 def __init__(self,color_scheme='NoColor'):
75 73 bdb.Bdb.__init__(self)
76 74 cmd.Cmd.__init__(self,completekey=None) # don't load readline
77 75 self.prompt = 'ipdb> ' # The default prompt is '(Pdb)'
78 76 self.aliases = {}
79 77
80 78 # These two lines are part of the py2.4 constructor, let's put them
81 79 # unconditionally here as they won't cause any problems in 2.3.
82 80 self.mainpyfile = ''
83 81 self._wait_for_mainpyfile = 0
84 82
85 83 # Read $HOME/.pdbrc and ./.pdbrc
86 84 try:
87 85 self.rcLines = _file_lines(os.path.join(os.environ['HOME'],
88 86 ".pdbrc"))
89 87 except KeyError:
90 88 self.rcLines = []
91 89 self.rcLines.extend(_file_lines(".pdbrc"))
92 90
93 91 # Create color table: we copy the default one from the traceback
94 92 # module and add a few attributes needed for debugging
95 93 self.color_scheme_table = ExceptionColors.copy()
96 94
97 95 # shorthands
98 96 C = ColorANSI.TermColors
99 97 cst = self.color_scheme_table
100 98
101 99 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
102 100 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
103 101
104 102 cst['Linux'].colors.breakpoint_enabled = C.LightRed
105 103 cst['Linux'].colors.breakpoint_disabled = C.Red
106 104
107 105 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
108 106 cst['LightBG'].colors.breakpoint_disabled = C.Red
109 107
110 108 self.set_colors(color_scheme)
111 109
112 110 def set_colors(self, scheme):
113 111 """Shorthand access to the color table scheme selector method."""
114 112 self.color_scheme_table.set_active_scheme(scheme)
115 113
116
117 114 def interaction(self, frame, traceback):
118 115 __IPYTHON__.set_completer_frame(frame)
119 116 pdb.Pdb.interaction(self, frame, traceback)
120 117
121
122 118 def do_up(self, arg):
123 119 pdb.Pdb.do_up(self, arg)
124 120 __IPYTHON__.set_completer_frame(self.curframe)
125 121 do_u = do_up
126 122
127
128 123 def do_down(self, arg):
129 124 pdb.Pdb.do_down(self, arg)
130 125 __IPYTHON__.set_completer_frame(self.curframe)
131 126 do_d = do_down
132 127
133
134 128 def postloop(self):
135 129 __IPYTHON__.set_completer_frame(None)
136 130
137
138 131 def print_stack_trace(self):
139 132 try:
140 133 for frame_lineno in self.stack:
141 134 self.print_stack_entry(frame_lineno, context = 5)
142 135 except KeyboardInterrupt:
143 136 pass
144 137
145
146 138 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
147 139 context = 3):
148 140 frame, lineno = frame_lineno
149 141 print >>Term.cout, self.format_stack_entry(frame_lineno, '', context)
150 142
151
152 143 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
153 144 import linecache, repr
154 145
155 ret = ""
146 ret = []
156 147
157 148 Colors = self.color_scheme_table.active_colors
158 149 ColorsNormal = Colors.Normal
159 150 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
160 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
151 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
161 152 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
162 153 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
163 154 ColorsNormal)
164 155
165 156 frame, lineno = frame_lineno
166 157
167 158 return_value = ''
168 159 if '__return__' in frame.f_locals:
169 160 rv = frame.f_locals['__return__']
170 161 #return_value += '->'
171 162 return_value += repr.repr(rv) + '\n'
172 ret += return_value
163 ret.append(return_value)
173 164
174 165 #s = filename + '(' + `lineno` + ')'
175 166 filename = self.canonic(frame.f_code.co_filename)
176 167 link = tpl_link % filename
177 168
178 169 if frame.f_code.co_name:
179 170 func = frame.f_code.co_name
180 171 else:
181 172 func = "<lambda>"
182 173
183 174 call = ''
184 175 if func != '?':
185 176 if '__args__' in frame.f_locals:
186 177 args = repr.repr(frame.f_locals['__args__'])
187 178 else:
188 179 args = '()'
189 180 call = tpl_call % (func, args)
190
191 level = '%s %s\n' % (link, call)
192 ret += level
181
182 # The level info should be generated in the same format pdb uses, to
183 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
184 ret.append('> %s(%s)%s\n' % (link,lineno,call))
193 185
194 186 start = lineno - 1 - context//2
195 187 lines = linecache.getlines(filename)
196 188 start = max(start, 0)
197 189 start = min(start, len(lines) - context)
198 190 lines = lines[start : start + context]
199 191
200 for i in range(len(lines)):
201 line = lines[i]
202 if start + 1 + i == lineno:
203 ret += self.__format_line(tpl_line_em, filename, start + 1 + i, line, arrow = True)
204 else:
205 ret += self.__format_line(tpl_line, filename, start + 1 + i, line, arrow = False)
206
207 return ret
192 for i,line in enumerate(lines):
193 show_arrow = (start + 1 + i == lineno)
194 ret.append(self.__format_line(tpl_line_em, filename,
195 start + 1 + i, line,
196 arrow = show_arrow) )
208 197
198 return ''.join(ret)
209 199
210 200 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
211 201 bp_mark = ""
212 202 bp_mark_color = ""
213 203
214 204 bp = None
215 205 if lineno in self.get_file_breaks(filename):
216 206 bps = self.get_breaks(filename, lineno)
217 207 bp = bps[-1]
218 208
219 209 if bp:
220 210 Colors = self.color_scheme_table.active_colors
221 211 bp_mark = str(bp.number)
222 212 bp_mark_color = Colors.breakpoint_enabled
223 213 if not bp.enabled:
224 214 bp_mark_color = Colors.breakpoint_disabled
225 215
226 216 numbers_width = 7
227 217 if arrow:
228 218 # This is the line with the error
229 219 pad = numbers_width - len(str(lineno)) - len(bp_mark)
230 220 if pad >= 3:
231 221 marker = '-'*(pad-3) + '-> '
232 222 elif pad == 2:
233 223 marker = '> '
234 224 elif pad == 1:
235 225 marker = '>'
236 226 else:
237 227 marker = ''
238 228 num = '%s%s' % (marker, str(lineno))
239 229 line = tpl_line % (bp_mark_color + bp_mark, num, line)
240 230 else:
241 231 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
242 232 line = tpl_line % (bp_mark_color + bp_mark, num, line)
243 233
244 234 return line
245
246 235
247 236 def do_list(self, arg):
248 237 self.lastcmd = 'list'
249 238 last = None
250 239 if arg:
251 240 try:
252 241 x = eval(arg, {}, {})
253 242 if type(x) == type(()):
254 243 first, last = x
255 244 first = int(first)
256 245 last = int(last)
257 246 if last < first:
258 247 # Assume it's a count
259 248 last = first + last
260 249 else:
261 250 first = max(1, int(x) - 5)
262 251 except:
263 252 print '*** Error in argument:', `arg`
264 253 return
265 254 elif self.lineno is None:
266 255 first = max(1, self.curframe.f_lineno - 5)
267 256 else:
268 257 first = self.lineno + 1
269 258 if last is None:
270 259 last = first + 10
271 260 filename = self.curframe.f_code.co_filename
272 261 try:
273 262 Colors = self.color_scheme_table.active_colors
274 263 ColorsNormal = Colors.Normal
275 264 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
276 265 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
277 266 src = []
278 267 for lineno in range(first, last+1):
279 268 line = linecache.getline(filename, lineno)
280 269 if not line:
281 270 break
282 271
283 272 if lineno == self.curframe.f_lineno:
284 273 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
285 274 else:
286 275 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
287 276
288 277 src.append(line)
289 278 self.lineno = lineno
290 279
291 280 print >>Term.cout, ''.join(src)
292 281
293 282 except KeyboardInterrupt:
294 283 pass
295 284
296 285 do_l = do_list
@@ -1,31 +1,30 b''
1 1 """ User configuration file for IPython
2 2
3 3 This is a more flexible and safe way to configure ipython than *rc files
4 4 (ipythonrc, ipythonrc-pysh etc.)
5 5
6 6 This file is always imported on ipython startup. You can import the
7 7 ipython extensions you need here (see IPython/Extensions directory).
8 8
9 9 Feel free to edit this file to customize your ipython experience.
10 10
11 11 Note that as such this file does nothing, for backwards compatibility.
12 12 Consult e.g. file 'ipy_profile_sh.py' for an example of the things
13 13 you can do here.
14 14
15 15 """
16 16
17 17 # Most of your config files and extensions will probably start with this import
18 18
19 19 import IPython.ipapi
20 20 ip = IPython.ipapi.get()
21 21
22 22 # You probably want to uncomment this if you did %upgrade -nolegacy
23 23 # import ipy_defaults
24 24
25 25 def main():
26 26 o = ip.options
27 27 # An example on how to set options
28 28 #o.autocall = 1
29 29
30 30 main()
31
@@ -1,597 +1,597 b''
1 1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 # $Id: ipythonrc 1155 2006-02-12 01:21:00Z fperez $
2 # $Id: ipythonrc 1324 2006-05-24 20:25:11Z fperez $
3 3
4 4 #***************************************************************************
5 5 #
6 6 # Configuration file for IPython -- ipythonrc format
7 7 #
8 8 # The format of this file is simply one of 'key value' lines.
9 9 # Lines containing only whitespace at the beginning and then a # are ignored
10 10 # as comments. But comments can NOT be put on lines with data.
11 11
12 12 # The meaning and use of each key are explained below.
13 13
14 14 #---------------------------------------------------------------------------
15 15 # Section: included files
16 16
17 17 # Put one or more *config* files (with the syntax of this file) you want to
18 18 # include. For keys with a unique value the outermost file has precedence. For
19 19 # keys with multiple values, they all get assembled into a list which then
20 20 # gets loaded by IPython.
21 21
22 22 # In this file, all lists of things should simply be space-separated.
23 23
24 24 # This allows you to build hierarchies of files which recursively load
25 25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
26 26 # should only keep here basic things you always want available. Then you can
27 27 # include it in every other special-purpose config file you create.
28 28 include
29 29
30 30 #---------------------------------------------------------------------------
31 31 # Section: startup setup
32 32
33 33 # These are mostly things which parallel a command line option of the same
34 34 # name.
35 35
36 36 # Keys in this section should only appear once. If any key from this section
37 37 # is encountered more than once, the last value remains, all earlier ones get
38 38 # discarded.
39 39
40 40
41 41 # Automatic calling of callable objects. If set to 1 or 2, callable objects
42 42 # are automatically called when invoked at the command line, even if you don't
43 43 # type parentheses. IPython adds the parentheses for you. For example:
44 44
45 45 #In [1]: str 45
46 46 #------> str(45)
47 47 #Out[1]: '45'
48 48
49 49 # IPython reprints your line with '---->' indicating that it added
50 50 # parentheses. While this option is very convenient for interactive use, it
51 51 # may occasionally cause problems with objects which have side-effects if
52 52 # called unexpectedly.
53 53
54 54 # The valid values for autocall are:
55 55
56 56 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
57 57
58 58 # autocall 1 -> active, but do not apply if there are no arguments on the line.
59 59
60 60 # In this mode, you get:
61 61
62 62 #In [1]: callable
63 63 #Out[1]: <built-in function callable>
64 64
65 65 #In [2]: callable 'hello'
66 66 #------> callable('hello')
67 67 #Out[2]: False
68 68
69 69 # 2 -> Active always. Even if no arguments are present, the callable object
70 70 # is called:
71 71
72 72 #In [4]: callable
73 73 #------> callable()
74 74
75 75 # Note that even with autocall off, you can still use '/' at the start of a
76 76 # line to treat the first argument on the command line as a function and add
77 77 # parentheses to it:
78 78
79 79 #In [8]: /str 43
80 80 #------> str(43)
81 81 #Out[8]: '43'
82 82
83 83 autocall 1
84 84
85 85 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
86 86 # source code (see the 'editor' variable below), it is possible that you save
87 87 # a file with syntax errors in it. If this variable is true, IPython will ask
88 88 # you whether to re-open the editor immediately to correct such an error.
89 89
90 autoedit_syntax 1
90 autoedit_syntax 0
91 91
92 92 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
93 93 # line, while also un-indenting automatically after 'raise' or 'return'.
94 94
95 95 # This feature uses the readline library, so it will honor your ~/.inputrc
96 96 # configuration (or whatever file your INPUTRC variable points to). Adding
97 97 # the following lines to your .inputrc file can make indent/unindenting more
98 98 # convenient (M-i indents, M-u unindents):
99 99
100 100 # $if Python
101 101 # "\M-i": " "
102 102 # "\M-u": "\d\d\d\d"
103 103 # $endif
104 104
105 105 # The feature is potentially a bit dangerous, because it can cause problems
106 106 # with pasting of indented code (the pasted code gets re-indented on each
107 107 # line). But it's a huge time-saver when working interactively. The magic
108 108 # function %autoindent allows you to toggle it on/off at runtime.
109 109
110 110 autoindent 1
111 111
112 112 # Auto-magic. This gives you access to all the magic functions without having
113 113 # to prepend them with an % sign. If you define a variable with the same name
114 114 # as a magic function (say who=1), you will need to access the magic function
115 115 # with % (%who in this example). However, if later you delete your variable
116 116 # (del who), you'll recover the automagic calling form.
117 117
118 118 # Considering that many magic functions provide a lot of shell-like
119 119 # functionality, automagic gives you something close to a full Python+system
120 120 # shell environment (and you can extend it further if you want).
121 121
122 122 automagic 1
123 123
124 124 # Size of the output cache. After this many entries are stored, the cache will
125 125 # get flushed. Depending on the size of your intermediate calculations, you
126 126 # may have memory problems if you make it too big, since keeping things in the
127 127 # cache prevents Python from reclaiming the memory for old results. Experiment
128 128 # with a value that works well for you.
129 129
130 130 # If you choose cache_size 0 IPython will revert to python's regular >>>
131 131 # unnumbered prompt. You will still have _, __ and ___ for your last three
132 132 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
133 133 # you are running on a slow machine or with very limited memory, this may
134 134 # help.
135 135
136 136 cache_size 1000
137 137
138 138 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
139 139 # but that's your choice! Classic 1 -> same as IPython -classic.
140 140 # Note that this is _not_ the normal python interpreter, it's simply
141 141 # IPython emulating most of the classic interpreter's behavior.
142 142 classic 0
143 143
144 144 # colors - Coloring option for prompts and traceback printouts.
145 145
146 146 # Currently available schemes: NoColor, Linux, LightBG.
147 147
148 148 # This option allows coloring the prompts and traceback printouts. This
149 149 # requires a terminal which can properly handle color escape sequences. If you
150 150 # are having problems with this, use the NoColor scheme (uses no color escapes
151 151 # at all).
152 152
153 153 # The Linux option works well in linux console type environments: dark
154 154 # background with light fonts.
155 155
156 156 # LightBG is similar to Linux but swaps dark/light colors to be more readable
157 157 # in light background terminals.
158 158
159 159 # keep uncommented only the one you want:
160 160 colors Linux
161 161 #colors LightBG
162 162 #colors NoColor
163 163
164 164 ########################
165 165 # Note to Windows users
166 166 #
167 167 # Color and readline support is avaialble to Windows users via Gary Bishop's
168 168 # readline library. You can find Gary's tools at
169 169 # http://sourceforge.net/projects/uncpythontools.
170 170 # Note that his readline module requires in turn the ctypes library, available
171 171 # at http://starship.python.net/crew/theller/ctypes.
172 172 ########################
173 173
174 174 # color_info: IPython can display information about objects via a set of
175 175 # functions, and optionally can use colors for this, syntax highlighting
176 176 # source code and various other elements. This information is passed through a
177 177 # pager (it defaults to 'less' if $PAGER is not set).
178 178
179 179 # If your pager has problems, try to setting it to properly handle escapes
180 180 # (see the less manpage for detail), or disable this option. The magic
181 181 # function %color_info allows you to toggle this interactively for testing.
182 182
183 183 color_info 1
184 184
185 185 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
186 186 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
187 187 # the magic functions %Exit or %Quit you can force a direct exit, bypassing
188 188 # any confirmation.
189 189
190 190 confirm_exit 1
191 191
192 192 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
193 193 # still available as dreload() and appears as a builtin.
194 194
195 195 deep_reload 0
196 196
197 197 # Which editor to use with the %edit command. If you leave this at 0, IPython
198 198 # will honor your EDITOR environment variable. Since this editor is invoked on
199 199 # the fly by ipython and is meant for editing small code snippets, you may
200 200 # want to use a small, lightweight editor here.
201 201
202 202 # For Emacs users, setting up your Emacs server properly as described in the
203 203 # manual is a good idea. An alternative is to use jed, a very light editor
204 204 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
205 205
206 206 editor 0
207 207
208 208 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
209 209 log 0
210 210
211 211 # Same as ipython -Logfile YourLogfileName.
212 212 # Don't use with log 1 (use one or the other)
213 213 logfile ''
214 214
215 215 # banner 0 -> same as ipython -nobanner
216 216 banner 1
217 217
218 218 # messages 0 -> same as ipython -nomessages
219 219 messages 1
220 220
221 221 # Automatically call the pdb debugger after every uncaught exception. If you
222 222 # are used to debugging using pdb, this puts you automatically inside of it
223 223 # after any call (either in IPython or in code called by it) which triggers an
224 224 # exception which goes uncaught.
225 225 pdb 0
226 226
227 227 # Enable the pprint module for printing. pprint tends to give a more readable
228 228 # display (than print) for complex nested data structures.
229 229 pprint 1
230 230
231 231 # Prompt strings
232 232
233 233 # Most bash-like escapes can be used to customize IPython's prompts, as well as
234 234 # a few additional ones which are IPython-specific. All valid prompt escapes
235 235 # are described in detail in the Customization section of the IPython HTML/PDF
236 236 # manual.
237 237
238 238 # Use \# to represent the current prompt number, and quote them to protect
239 239 # spaces.
240 240 prompt_in1 'In [\#]: '
241 241
242 242 # \D is replaced by as many dots as there are digits in the
243 243 # current value of \#.
244 244 prompt_in2 ' .\D.: '
245 245
246 246 prompt_out 'Out[\#]: '
247 247
248 248 # Select whether to left-pad the output prompts to match the length of the
249 249 # input ones. This allows you for example to use a simple '>' as an output
250 250 # prompt, and yet have the output line up with the input. If set to false,
251 251 # the output prompts will be unpadded (flush left).
252 252 prompts_pad_left 1
253 253
254 254 # quick 1 -> same as ipython -quick
255 255 quick 0
256 256
257 257 # Use the readline library (1) or not (0). Most users will want this on, but
258 258 # if you experience strange problems with line management (mainly when using
259 259 # IPython inside Emacs buffers) you may try disabling it. Not having it on
260 260 # prevents you from getting command history with the arrow keys, searching and
261 261 # name completion using TAB.
262 262
263 263 readline 1
264 264
265 265 # Screen Length: number of lines of your screen. This is used to control
266 266 # printing of very long strings. Strings longer than this number of lines will
267 267 # be paged with the less command instead of directly printed.
268 268
269 269 # The default value for this is 0, which means IPython will auto-detect your
270 270 # screen size every time it needs to print. If for some reason this isn't
271 271 # working well (it needs curses support), specify it yourself. Otherwise don't
272 272 # change the default.
273 273
274 274 screen_length 0
275 275
276 276 # Prompt separators for input and output.
277 277 # Use \n for newline explicitly, without quotes.
278 278 # Use 0 (like at the cmd line) to turn off a given separator.
279 279
280 280 # The structure of prompt printing is:
281 281 # (SeparateIn)Input....
282 282 # (SeparateOut)Output...
283 283 # (SeparateOut2), # that is, no newline is printed after Out2
284 284 # By choosing these you can organize your output any way you want.
285 285
286 286 separate_in \n
287 287 separate_out 0
288 288 separate_out2 0
289 289
290 290 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
291 291 # Simply removes all input/output separators, overriding the choices above.
292 292 nosep 0
293 293
294 294 # Wildcard searches - IPython has a system for searching names using
295 295 # shell-like wildcards; type %psearch? for details. This variables sets
296 296 # whether by default such searches should be case sensitive or not. You can
297 297 # always override the default at the system command line or the IPython
298 298 # prompt.
299 299
300 300 wildcards_case_sensitive 1
301 301
302 302 # xmode - Exception reporting mode.
303 303
304 304 # Valid modes: Plain, Context and Verbose.
305 305
306 306 # Plain: similar to python's normal traceback printing.
307 307
308 308 # Context: prints 5 lines of context source code around each line in the
309 309 # traceback.
310 310
311 311 # Verbose: similar to Context, but additionally prints the variables currently
312 312 # visible where the exception happened (shortening their strings if too
313 313 # long). This can potentially be very slow, if you happen to have a huge data
314 314 # structure whose string representation is complex to compute. Your computer
315 315 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
316 316 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
317 317
318 318 #xmode Plain
319 319 xmode Context
320 320 #xmode Verbose
321 321
322 322 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
323 323 # !cmd) to be used in multi-line input (like for loops). For example, if you
324 324 # have this active, the following is valid in IPython:
325 325 #
326 326 #In [17]: for i in range(3):
327 327 # ....: mkdir $i
328 328 # ....: !touch $i/hello
329 329 # ....: ls -l $i
330 330
331 331 multi_line_specials 1
332 332
333 333 # wxversion: request a specific wxPython version (used for -wthread)
334 334
335 335 # Set this to the value of wxPython you want to use, but note that this
336 336 # feature requires you to have the wxversion Python module to work. If you
337 337 # don't have the wxversion module (try 'import wxversion' at the prompt to
338 338 # check) or simply want to leave the system to pick up the default, leave this
339 339 # variable at 0.
340 340
341 341 wxversion 0
342 342
343 343 #---------------------------------------------------------------------------
344 344 # Section: Readline configuration (readline is not available for MS-Windows)
345 345
346 346 # This is done via the following options:
347 347
348 348 # (i) readline_parse_and_bind: this option can appear as many times as you
349 349 # want, each time defining a string to be executed via a
350 350 # readline.parse_and_bind() command. The syntax for valid commands of this
351 351 # kind can be found by reading the documentation for the GNU readline library,
352 352 # as these commands are of the kind which readline accepts in its
353 353 # configuration file.
354 354
355 355 # The TAB key can be used to complete names at the command line in one of two
356 356 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
357 357 # completes as much as possible while 'menu-complete' cycles through all
358 358 # possible completions. Leave the one you prefer uncommented.
359 359
360 360 readline_parse_and_bind tab: complete
361 361 #readline_parse_and_bind tab: menu-complete
362 362
363 363 # This binds Control-l to printing the list of all possible completions when
364 364 # there is more than one (what 'complete' does when hitting TAB twice, or at
365 365 # the first TAB if show-all-if-ambiguous is on)
366 366 readline_parse_and_bind "\C-l": possible-completions
367 367
368 368 # This forces readline to automatically print the above list when tab
369 369 # completion is set to 'complete'. You can still get this list manually by
370 370 # using the key bound to 'possible-completions' (Control-l by default) or by
371 371 # hitting TAB twice. Turning this on makes the printing happen at the first
372 372 # TAB.
373 373 readline_parse_and_bind set show-all-if-ambiguous on
374 374
375 375 # If you have TAB set to complete names, you can rebind any key (Control-o by
376 376 # default) to insert a true TAB character.
377 377 readline_parse_and_bind "\C-o": tab-insert
378 378
379 379 # These commands allow you to indent/unindent easily, with the 4-space
380 380 # convention of the Python coding standards. Since IPython's internal
381 381 # auto-indent system also uses 4 spaces, you should not change the number of
382 382 # spaces in the code below.
383 383 readline_parse_and_bind "\M-i": " "
384 384 readline_parse_and_bind "\M-o": "\d\d\d\d"
385 385 readline_parse_and_bind "\M-I": "\d\d\d\d"
386 386
387 387 # Bindings for incremental searches in the history. These searches use the
388 388 # string typed so far on the command line and search anything in the previous
389 389 # input history containing them.
390 390 readline_parse_and_bind "\C-r": reverse-search-history
391 391 readline_parse_and_bind "\C-s": forward-search-history
392 392
393 393 # Bindings for completing the current line in the history of previous
394 394 # commands. This allows you to recall any previous command by typing its first
395 395 # few letters and hitting Control-p, bypassing all intermediate commands which
396 396 # may be in the history (much faster than hitting up-arrow 50 times!)
397 397 readline_parse_and_bind "\C-p": history-search-backward
398 398 readline_parse_and_bind "\C-n": history-search-forward
399 399
400 400 # I also like to have the same functionality on the plain arrow keys. If you'd
401 401 # rather have the arrows use all the history (and not just match what you've
402 402 # typed so far), comment out or delete the next two lines.
403 403 readline_parse_and_bind "\e[A": history-search-backward
404 404 readline_parse_and_bind "\e[B": history-search-forward
405 405
406 406 # These are typically on by default under *nix, but not win32.
407 407 readline_parse_and_bind "\C-k": kill-line
408 408 readline_parse_and_bind "\C-u": unix-line-discard
409 409
410 410 # (ii) readline_remove_delims: a string of characters to be removed from the
411 411 # default word-delimiters list used by readline, so that completions may be
412 412 # performed on strings which contain them.
413 413
414 414 readline_remove_delims -/~
415 415
416 416 # (iii) readline_merge_completions: whether to merge the result of all
417 417 # possible completions or not. If true, IPython will complete filenames,
418 418 # python names and aliases and return all possible completions. If you set it
419 419 # to false, each completer is used at a time, and only if it doesn't return
420 420 # any completions is the next one used.
421 421
422 422 # The default order is: [python_matches, file_matches, alias_matches]
423 423
424 424 readline_merge_completions 1
425 425
426 426 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
427 427 # will complete all attributes of an object, including all the special methods
428 428 # whose names start with single or double underscores (like __getitem__ or
429 429 # __class__).
430 430
431 431 # This variable allows you to control this completion behavior:
432 432
433 433 # readline_omit__names 1 -> completion will omit showing any names starting
434 434 # with two __, but it will still show names starting with one _.
435 435
436 436 # readline_omit__names 2 -> completion will omit all names beginning with one
437 437 # _ (which obviously means filtering out the double __ ones).
438 438
439 439 # Even when this option is set, you can still see those names by explicitly
440 440 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
441 441 # complete attribute names starting with '_'.
442 442
443 443 # This option is off by default so that new users see all attributes of any
444 444 # objects they are dealing with.
445 445
446 446 readline_omit__names 0
447 447
448 448 #---------------------------------------------------------------------------
449 449 # Section: modules to be loaded with 'import ...'
450 450
451 451 # List, separated by spaces, the names of the modules you want to import
452 452
453 453 # Example:
454 454 # import_mod sys os
455 455 # will produce internally the statements
456 456 # import sys
457 457 # import os
458 458
459 459 # Each import is executed in its own try/except block, so if one module
460 460 # fails to load the others will still be ok.
461 461
462 462 import_mod
463 463
464 464 #---------------------------------------------------------------------------
465 465 # Section: modules to import some functions from: 'from ... import ...'
466 466
467 467 # List, one per line, the modules for which you want only to import some
468 468 # functions. Give the module name first and then the name of functions to be
469 469 # imported from that module.
470 470
471 471 # Example:
472 472
473 473 # import_some IPython.genutils timing timings
474 474 # will produce internally the statement
475 475 # from IPython.genutils import timing, timings
476 476
477 477 # timing() and timings() are two IPython utilities for timing the execution of
478 478 # your own functions, which you may find useful. Just commment out the above
479 479 # line if you want to test them.
480 480
481 481 # If you have more than one modules_some line, each gets its own try/except
482 482 # block (like modules, see above).
483 483
484 484 import_some
485 485
486 486 #---------------------------------------------------------------------------
487 487 # Section: modules to import all from : 'from ... import *'
488 488
489 489 # List (same syntax as import_mod above) those modules for which you want to
490 490 # import all functions. Remember, this is a potentially dangerous thing to do,
491 491 # since it is very easy to overwrite names of things you need. Use with
492 492 # caution.
493 493
494 494 # Example:
495 495 # import_all sys os
496 496 # will produce internally the statements
497 497 # from sys import *
498 498 # from os import *
499 499
500 500 # As before, each will be called in a separate try/except block.
501 501
502 502 import_all
503 503
504 504 #---------------------------------------------------------------------------
505 505 # Section: Python code to execute.
506 506
507 507 # Put here code to be explicitly executed (keep it simple!)
508 508 # Put one line of python code per line. All whitespace is removed (this is a
509 509 # feature, not a bug), so don't get fancy building loops here.
510 510 # This is just for quick convenient creation of things you want available.
511 511
512 512 # Example:
513 513 # execute x = 1
514 514 # execute print 'hello world'; y = z = 'a'
515 515 # will produce internally
516 516 # x = 1
517 517 # print 'hello world'; y = z = 'a'
518 518 # and each *line* (not each statement, we don't do python syntax parsing) is
519 519 # executed in its own try/except block.
520 520
521 521 execute
522 522
523 523 # Note for the adventurous: you can use this to define your own names for the
524 524 # magic functions, by playing some namespace tricks:
525 525
526 526 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
527 527
528 528 # defines %pf as a new name for %profile.
529 529
530 530 #---------------------------------------------------------------------------
531 531 # Section: Pyhton files to load and execute.
532 532
533 533 # Put here the full names of files you want executed with execfile(file). If
534 534 # you want complicated initialization, just write whatever you want in a
535 535 # regular python file and load it from here.
536 536
537 537 # Filenames defined here (which *must* include the extension) are searched for
538 538 # through all of sys.path. Since IPython adds your .ipython directory to
539 539 # sys.path, they can also be placed in your .ipython dir and will be
540 540 # found. Otherwise (if you want to execute things not in .ipyton nor in
541 541 # sys.path) give a full path (you can use ~, it gets expanded)
542 542
543 543 # Example:
544 544 # execfile file1.py ~/file2.py
545 545 # will generate
546 546 # execfile('file1.py')
547 547 # execfile('_path_to_your_home/file2.py')
548 548
549 549 # As before, each file gets its own try/except block.
550 550
551 551 execfile
552 552
553 553 # If you are feeling adventurous, you can even add functionality to IPython
554 554 # through here. IPython works through a global variable called __ip which
555 555 # exists at the time when these files are read. If you know what you are doing
556 556 # (read the source) you can add functions to __ip in files loaded here.
557 557
558 558 # The file example-magic.py contains a simple but correct example. Try it:
559 559
560 560 # execfile example-magic.py
561 561
562 562 # Look at the examples in IPython/iplib.py for more details on how these magic
563 563 # functions need to process their arguments.
564 564
565 565 #---------------------------------------------------------------------------
566 566 # Section: aliases for system shell commands
567 567
568 568 # Here you can define your own names for system commands. The syntax is
569 569 # similar to that of the builtin %alias function:
570 570
571 571 # alias alias_name command_string
572 572
573 573 # The resulting aliases are auto-generated magic functions (hence usable as
574 574 # %alias_name)
575 575
576 576 # For example:
577 577
578 578 # alias myls ls -la
579 579
580 580 # will define 'myls' as an alias for executing the system command 'ls -la'.
581 581 # This allows you to customize IPython's environment to have the same aliases
582 582 # you are accustomed to from your own shell.
583 583
584 584 # You can also define aliases with parameters using %s specifiers (one per
585 585 # parameter):
586 586
587 587 # alias parts echo first %s second %s
588 588
589 589 # will give you in IPython:
590 590 # >>> %parts A B
591 591 # first A second B
592 592
593 593 # Use one 'alias' statement per alias you wish to define.
594 594
595 595 # alias
596 596
597 597 #************************* end of file <ipythonrc> ************************
@@ -1,750 +1,750 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or better.
6 6
7 7 This file contains the main make_IPython() starter function.
8 8
9 $Id: ipmaker.py 1260 2006-04-11 10:19:34Z vivainio $"""
9 $Id: ipmaker.py 1324 2006-05-24 20:25:11Z fperez $"""
10 10
11 11 #*****************************************************************************
12 12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #*****************************************************************************
17 17
18 18 from IPython import Release
19 19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 20 __license__ = Release.license
21 21 __version__ = Release.version
22 22
23 23 credits._Printer__data = """
24 24 Python: %s
25 25
26 26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 27 See http://ipython.scipy.org for more information.""" \
28 28 % credits._Printer__data
29 29
30 30 copyright._Printer__data += """
31 31
32 32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 33 All Rights Reserved."""
34 34
35 35 #****************************************************************************
36 36 # Required modules
37 37
38 38 # From the standard library
39 39 import __main__
40 40 import __builtin__
41 41 import os
42 42 import re
43 43 import sys
44 44 import types
45 45 from pprint import pprint,pformat
46 46
47 47 # Our own
48 48 from IPython import DPyGetOpt
49 49 from IPython.ipstruct import Struct
50 50 from IPython.OutputTrap import OutputTrap
51 51 from IPython.ConfigLoader import ConfigLoader
52 52 from IPython.iplib import InteractiveShell
53 53 from IPython.usage import cmd_line_usage,interactive_usage
54 54 from IPython.genutils import *
55 55
56 56 #-----------------------------------------------------------------------------
57 57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
58 58 rc_override=None,shell_class=InteractiveShell,
59 59 embedded=False,**kw):
60 60 """This is a dump of IPython into a single function.
61 61
62 62 Later it will have to be broken up in a sensible manner.
63 63
64 64 Arguments:
65 65
66 66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
67 67 script name, b/c DPyGetOpt strips the first argument only for the real
68 68 sys.argv.
69 69
70 70 - user_ns: a dict to be used as the user's namespace."""
71 71
72 72 #----------------------------------------------------------------------
73 73 # Defaults and initialization
74 74
75 75 # For developer debugging, deactivates crash handler and uses pdb.
76 76 DEVDEBUG = False
77 77
78 78 if argv is None:
79 79 argv = sys.argv
80 80
81 81 # __IP is the main global that lives throughout and represents the whole
82 82 # application. If the user redefines it, all bets are off as to what
83 83 # happens.
84 84
85 85 # __IP is the name of he global which the caller will have accessible as
86 86 # __IP.name. We set its name via the first parameter passed to
87 87 # InteractiveShell:
88 88
89 89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
90 90 embedded=embedded,**kw)
91 91
92 92 # Put 'help' in the user namespace
93 93 from site import _Helper
94 94 IP.user_ns['help'] = _Helper()
95 95
96 96
97 97 if DEVDEBUG:
98 98 # For developer debugging only (global flag)
99 99 from IPython import ultraTB
100 100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
101 101
102 102 IP.BANNER_PARTS = ['Python %s\n'
103 103 'Type "copyright", "credits" or "license" '
104 104 'for more information.\n'
105 105 % (sys.version.split('\n')[0],),
106 106 "IPython %s -- An enhanced Interactive Python."
107 107 % (__version__,),
108 108 """? -> Introduction to IPython's features.
109 109 %magic -> Information about IPython's 'magic' % functions.
110 110 help -> Python's own help system.
111 111 object? -> Details about 'object'. ?object also works, ?? prints more.
112 112 """ ]
113 113
114 114 IP.usage = interactive_usage
115 115
116 116 # Platform-dependent suffix and directory names. We use _ipython instead
117 117 # of .ipython under win32 b/c there's software that breaks with .named
118 118 # directories on that platform.
119 119 if os.name == 'posix':
120 120 rc_suffix = ''
121 121 ipdir_def = '.ipython'
122 122 else:
123 123 rc_suffix = '.ini'
124 124 ipdir_def = '_ipython'
125 125
126 126 # default directory for configuration
127 127 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
128 128 os.path.join(IP.home_dir,ipdir_def)))
129 129
130 130 # add personal .ipython dir to sys.path so that users can put things in
131 131 # there for customization
132 132 sys.path.append(ipythondir)
133 133
134 134 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
135 135
136 136 # we need the directory where IPython itself is installed
137 137 import IPython
138 138 IPython_dir = os.path.dirname(IPython.__file__)
139 139 del IPython
140 140
141 141 #-------------------------------------------------------------------------
142 142 # Command line handling
143 143
144 144 # Valid command line options (uses DPyGetOpt syntax, like Perl's
145 145 # GetOpt::Long)
146 146
147 147 # Any key not listed here gets deleted even if in the file (like session
148 148 # or profile). That's deliberate, to maintain the rc namespace clean.
149 149
150 150 # Each set of options appears twice: under _conv only the names are
151 151 # listed, indicating which type they must be converted to when reading the
152 152 # ipythonrc file. And under DPyGetOpt they are listed with the regular
153 153 # DPyGetOpt syntax (=s,=i,:f,etc).
154 154
155 155 # Make sure there's a space before each end of line (they get auto-joined!)
156 156 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
157 157 'c=s classic|cl color_info! colors=s confirm_exit! '
158 158 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
159 159 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
160 160 'quick screen_length|sl=i prompts_pad_left=i '
161 161 'logfile|lf=s logplay|lp=s profile|p=s '
162 162 'readline! readline_merge_completions! '
163 163 'readline_omit__names! '
164 164 'rcfile=s separate_in|si=s separate_out|so=s '
165 165 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
166 166 'magic_docstrings system_verbose! '
167 167 'multi_line_specials! '
168 168 'wxversion=s '
169 169 'autoedit_syntax!')
170 170
171 171 # Options that can *only* appear at the cmd line (not in rcfiles).
172 172
173 173 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
174 174 # the 'C-c !' command in emacs automatically appends a -i option at the end.
175 175 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
176 176 'gthread! qthread! wthread! pylab! tk!')
177 177
178 178 # Build the actual name list to be used by DPyGetOpt
179 179 opts_names = qw(cmdline_opts) + qw(cmdline_only)
180 180
181 181 # Set sensible command line defaults.
182 182 # This should have everything from cmdline_opts and cmdline_only
183 183 opts_def = Struct(autocall = 1,
184 autoedit_syntax = 1,
185 autoindent=0,
184 autoedit_syntax = 0,
185 autoindent = 0,
186 186 automagic = 1,
187 187 banner = 1,
188 188 cache_size = 1000,
189 189 c = '',
190 190 classic = 0,
191 191 colors = 'NoColor',
192 192 color_info = 0,
193 193 confirm_exit = 1,
194 194 debug = 0,
195 195 deep_reload = 0,
196 196 editor = '0',
197 197 help = 0,
198 198 ignore = 0,
199 199 ipythondir = ipythondir,
200 200 log = 0,
201 201 logfile = '',
202 202 logplay = '',
203 203 multi_line_specials = 1,
204 204 messages = 1,
205 205 nosep = 0,
206 206 pdb = 0,
207 207 pprint = 0,
208 208 profile = '',
209 209 prompt_in1 = 'In [\\#]: ',
210 210 prompt_in2 = ' .\\D.: ',
211 211 prompt_out = 'Out[\\#]: ',
212 212 prompts_pad_left = 1,
213 213 quick = 0,
214 214 readline = 1,
215 215 readline_merge_completions = 1,
216 216 readline_omit__names = 0,
217 217 rcfile = 'ipythonrc' + rc_suffix,
218 218 screen_length = 0,
219 219 separate_in = '\n',
220 220 separate_out = '\n',
221 221 separate_out2 = '',
222 222 system_verbose = 0,
223 223 gthread = 0,
224 224 qthread = 0,
225 225 wthread = 0,
226 226 pylab = 0,
227 227 tk = 0,
228 228 upgrade = 0,
229 229 Version = 0,
230 230 xmode = 'Verbose',
231 231 wildcards_case_sensitive = 1,
232 232 wxversion = '0',
233 233 magic_docstrings = 0, # undocumented, for doc generation
234 234 )
235 235
236 236 # Things that will *only* appear in rcfiles (not at the command line).
237 237 # Make sure there's a space before each end of line (they get auto-joined!)
238 238 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
239 239 qw_lol: 'import_some ',
240 240 # for things with embedded whitespace:
241 241 list_strings:'execute alias readline_parse_and_bind ',
242 242 # Regular strings need no conversion:
243 243 None:'readline_remove_delims ',
244 244 }
245 245 # Default values for these
246 246 rc_def = Struct(include = [],
247 247 import_mod = [],
248 248 import_all = [],
249 249 import_some = [[]],
250 250 execute = [],
251 251 execfile = [],
252 252 alias = [],
253 253 readline_parse_and_bind = [],
254 254 readline_remove_delims = '',
255 255 )
256 256
257 257 # Build the type conversion dictionary from the above tables:
258 258 typeconv = rcfile_opts.copy()
259 259 typeconv.update(optstr2types(cmdline_opts))
260 260
261 261 # FIXME: the None key appears in both, put that back together by hand. Ugly!
262 262 typeconv[None] += ' ' + rcfile_opts[None]
263 263
264 264 # Remove quotes at ends of all strings (used to protect spaces)
265 265 typeconv[unquote_ends] = typeconv[None]
266 266 del typeconv[None]
267 267
268 268 # Build the list we'll use to make all config decisions with defaults:
269 269 opts_all = opts_def.copy()
270 270 opts_all.update(rc_def)
271 271
272 272 # Build conflict resolver for recursive loading of config files:
273 273 # - preserve means the outermost file maintains the value, it is not
274 274 # overwritten if an included file has the same key.
275 275 # - add_flip applies + to the two values, so it better make sense to add
276 276 # those types of keys. But it flips them first so that things loaded
277 277 # deeper in the inclusion chain have lower precedence.
278 278 conflict = {'preserve': ' '.join([ typeconv[int],
279 279 typeconv[unquote_ends] ]),
280 280 'add_flip': ' '.join([ typeconv[qwflat],
281 281 typeconv[qw_lol],
282 282 typeconv[list_strings] ])
283 283 }
284 284
285 285 # Now actually process the command line
286 286 getopt = DPyGetOpt.DPyGetOpt()
287 287 getopt.setIgnoreCase(0)
288 288
289 289 getopt.parseConfiguration(opts_names)
290 290
291 291 try:
292 292 getopt.processArguments(argv)
293 293 except:
294 294 print cmd_line_usage
295 295 warn('\nError in Arguments: ' + `sys.exc_value`)
296 296 sys.exit(1)
297 297
298 298 # convert the options dict to a struct for much lighter syntax later
299 299 opts = Struct(getopt.optionValues)
300 300 args = getopt.freeValues
301 301
302 302 # this is the struct (which has default values at this point) with which
303 303 # we make all decisions:
304 304 opts_all.update(opts)
305 305
306 306 # Options that force an immediate exit
307 307 if opts_all.help:
308 308 page(cmd_line_usage)
309 309 sys.exit()
310 310
311 311 if opts_all.Version:
312 312 print __version__
313 313 sys.exit()
314 314
315 315 if opts_all.magic_docstrings:
316 316 IP.magic_magic('-latex')
317 317 sys.exit()
318 318
319 319 # Create user config directory if it doesn't exist. This must be done
320 320 # *after* getting the cmd line options.
321 321 if not os.path.isdir(opts_all.ipythondir):
322 322 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
323 323
324 324 # upgrade user config files while preserving a copy of the originals
325 325 if opts_all.upgrade:
326 326 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
327 327
328 328 # check mutually exclusive options in the *original* command line
329 329 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
330 330 qw('classic profile'),qw('classic rcfile')])
331 331
332 332 #---------------------------------------------------------------------------
333 333 # Log replay
334 334
335 335 # if -logplay, we need to 'become' the other session. That basically means
336 336 # replacing the current command line environment with that of the old
337 337 # session and moving on.
338 338
339 339 # this is needed so that later we know we're in session reload mode, as
340 340 # opts_all will get overwritten:
341 341 load_logplay = 0
342 342
343 343 if opts_all.logplay:
344 344 load_logplay = opts_all.logplay
345 345 opts_debug_save = opts_all.debug
346 346 try:
347 347 logplay = open(opts_all.logplay)
348 348 except IOError:
349 349 if opts_all.debug: IP.InteractiveTB()
350 350 warn('Could not open logplay file '+`opts_all.logplay`)
351 351 # restore state as if nothing had happened and move on, but make
352 352 # sure that later we don't try to actually load the session file
353 353 logplay = None
354 354 load_logplay = 0
355 355 del opts_all.logplay
356 356 else:
357 357 try:
358 358 logplay.readline()
359 359 logplay.readline();
360 360 # this reloads that session's command line
361 361 cmd = logplay.readline()[6:]
362 362 exec cmd
363 363 # restore the true debug flag given so that the process of
364 364 # session loading itself can be monitored.
365 365 opts.debug = opts_debug_save
366 366 # save the logplay flag so later we don't overwrite the log
367 367 opts.logplay = load_logplay
368 368 # now we must update our own structure with defaults
369 369 opts_all.update(opts)
370 370 # now load args
371 371 cmd = logplay.readline()[6:]
372 372 exec cmd
373 373 logplay.close()
374 374 except:
375 375 logplay.close()
376 376 if opts_all.debug: IP.InteractiveTB()
377 377 warn("Logplay file lacking full configuration information.\n"
378 378 "I'll try to read it, but some things may not work.")
379 379
380 380 #-------------------------------------------------------------------------
381 381 # set up output traps: catch all output from files, being run, modules
382 382 # loaded, etc. Then give it to the user in a clean form at the end.
383 383
384 384 msg_out = 'Output messages. '
385 385 msg_err = 'Error messages. '
386 386 msg_sep = '\n'
387 387 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
388 388 msg_err,msg_sep,debug,
389 389 quiet_out=1),
390 390 user_exec = OutputTrap('User File Execution',msg_out,
391 391 msg_err,msg_sep,debug),
392 392 logplay = OutputTrap('Log Loader',msg_out,
393 393 msg_err,msg_sep,debug),
394 394 summary = ''
395 395 )
396 396
397 397 #-------------------------------------------------------------------------
398 398 # Process user ipythonrc-type configuration files
399 399
400 400 # turn on output trapping and log to msg.config
401 401 # remember that with debug on, trapping is actually disabled
402 402 msg.config.trap_all()
403 403
404 404 # look for rcfile in current or default directory
405 405 try:
406 406 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
407 407 except IOError:
408 408 if opts_all.debug: IP.InteractiveTB()
409 409 warn('Configuration file %s not found. Ignoring request.'
410 410 % (opts_all.rcfile) )
411 411
412 412 # 'profiles' are a shorthand notation for config filenames
413 413 if opts_all.profile:
414 414
415 415 try:
416 416 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
417 417 + rc_suffix,
418 418 opts_all.ipythondir)
419 419 except IOError:
420 420 if opts_all.debug: IP.InteractiveTB()
421 421 opts.profile = '' # remove profile from options if invalid
422 422 # We won't warn anymore, primary method is ipy_profile_PROFNAME
423 423 # which does trigger a warning.
424 424
425 425 # load the config file
426 426 rcfiledata = None
427 427 if opts_all.quick:
428 428 print 'Launching IPython in quick mode. No config file read.'
429 429 elif opts_all.classic:
430 430 print 'Launching IPython in classic mode. No config file read.'
431 431 elif opts_all.rcfile:
432 432 try:
433 433 cfg_loader = ConfigLoader(conflict)
434 434 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
435 435 'include',opts_all.ipythondir,
436 436 purge = 1,
437 437 unique = conflict['preserve'])
438 438 except:
439 439 IP.InteractiveTB()
440 440 warn('Problems loading configuration file '+
441 441 `opts_all.rcfile`+
442 442 '\nStarting with default -bare bones- configuration.')
443 443 else:
444 444 warn('No valid configuration file found in either currrent directory\n'+
445 445 'or in the IPython config. directory: '+`opts_all.ipythondir`+
446 446 '\nProceeding with internal defaults.')
447 447
448 448 #------------------------------------------------------------------------
449 449 # Set exception handlers in mode requested by user.
450 450 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
451 451 IP.magic_xmode(opts_all.xmode)
452 452 otrap.release_out()
453 453
454 454 #------------------------------------------------------------------------
455 455 # Execute user config
456 456
457 457 # Create a valid config structure with the right precedence order:
458 458 # defaults < rcfile < command line. This needs to be in the instance, so
459 459 # that method calls below that rely on it find it.
460 460 IP.rc = rc_def.copy()
461 461
462 462 # Work with a local alias inside this routine to avoid unnecessary
463 463 # attribute lookups.
464 464 IP_rc = IP.rc
465 465
466 466 IP_rc.update(opts_def)
467 467 if rcfiledata:
468 468 # now we can update
469 469 IP_rc.update(rcfiledata)
470 470 IP_rc.update(opts)
471 471 IP_rc.update(rc_override)
472 472
473 473 # Store the original cmd line for reference:
474 474 IP_rc.opts = opts
475 475 IP_rc.args = args
476 476
477 477 # create a *runtime* Struct like rc for holding parameters which may be
478 478 # created and/or modified by runtime user extensions.
479 479 IP.runtime_rc = Struct()
480 480
481 481 # from this point on, all config should be handled through IP_rc,
482 482 # opts* shouldn't be used anymore.
483 483
484 484
485 485 # update IP_rc with some special things that need manual
486 486 # tweaks. Basically options which affect other options. I guess this
487 487 # should just be written so that options are fully orthogonal and we
488 488 # wouldn't worry about this stuff!
489 489
490 490 if IP_rc.classic:
491 491 IP_rc.quick = 1
492 492 IP_rc.cache_size = 0
493 493 IP_rc.pprint = 0
494 494 IP_rc.prompt_in1 = '>>> '
495 495 IP_rc.prompt_in2 = '... '
496 496 IP_rc.prompt_out = ''
497 497 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
498 498 IP_rc.colors = 'NoColor'
499 499 IP_rc.xmode = 'Plain'
500 500
501 501 IP.pre_config_initialization()
502 502 # configure readline
503 503 # Define the history file for saving commands in between sessions
504 504 if IP_rc.profile:
505 505 histfname = 'history-%s' % IP_rc.profile
506 506 else:
507 507 histfname = 'history'
508 508 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
509 509
510 510 # update exception handlers with rc file status
511 511 otrap.trap_out() # I don't want these messages ever.
512 512 IP.magic_xmode(IP_rc.xmode)
513 513 otrap.release_out()
514 514
515 515 # activate logging if requested and not reloading a log
516 516 if IP_rc.logplay:
517 517 IP.magic_logstart(IP_rc.logplay + ' append')
518 518 elif IP_rc.logfile:
519 519 IP.magic_logstart(IP_rc.logfile)
520 520 elif IP_rc.log:
521 521 IP.magic_logstart()
522 522
523 523 # find user editor so that it we don't have to look it up constantly
524 524 if IP_rc.editor.strip()=='0':
525 525 try:
526 526 ed = os.environ['EDITOR']
527 527 except KeyError:
528 528 if os.name == 'posix':
529 529 ed = 'vi' # the only one guaranteed to be there!
530 530 else:
531 531 ed = 'notepad' # same in Windows!
532 532 IP_rc.editor = ed
533 533
534 534 # Keep track of whether this is an embedded instance or not (useful for
535 535 # post-mortems).
536 536 IP_rc.embedded = IP.embedded
537 537
538 538 # Recursive reload
539 539 try:
540 540 from IPython import deep_reload
541 541 if IP_rc.deep_reload:
542 542 __builtin__.reload = deep_reload.reload
543 543 else:
544 544 __builtin__.dreload = deep_reload.reload
545 545 del deep_reload
546 546 except ImportError:
547 547 pass
548 548
549 549 # Save the current state of our namespace so that the interactive shell
550 550 # can later know which variables have been created by us from config files
551 551 # and loading. This way, loading a file (in any way) is treated just like
552 552 # defining things on the command line, and %who works as expected.
553 553
554 554 # DON'T do anything that affects the namespace beyond this point!
555 555 IP.internal_ns.update(__main__.__dict__)
556 556
557 557 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
558 558
559 559 # Now run through the different sections of the users's config
560 560 if IP_rc.debug:
561 561 print 'Trying to execute the following configuration structure:'
562 562 print '(Things listed first are deeper in the inclusion tree and get'
563 563 print 'loaded first).\n'
564 564 pprint(IP_rc.__dict__)
565 565
566 566 for mod in IP_rc.import_mod:
567 567 try:
568 568 exec 'import '+mod in IP.user_ns
569 569 except :
570 570 IP.InteractiveTB()
571 571 import_fail_info(mod)
572 572
573 573 for mod_fn in IP_rc.import_some:
574 574 if mod_fn == []: break
575 575 mod,fn = mod_fn[0],','.join(mod_fn[1:])
576 576 try:
577 577 exec 'from '+mod+' import '+fn in IP.user_ns
578 578 except :
579 579 IP.InteractiveTB()
580 580 import_fail_info(mod,fn)
581 581
582 582 for mod in IP_rc.import_all:
583 583 try:
584 584 exec 'from '+mod+' import *' in IP.user_ns
585 585 except :
586 586 IP.InteractiveTB()
587 587 import_fail_info(mod)
588 588
589 589 for code in IP_rc.execute:
590 590 try:
591 591 exec code in IP.user_ns
592 592 except:
593 593 IP.InteractiveTB()
594 594 warn('Failure executing code: ' + `code`)
595 595
596 596 # Execute the files the user wants in ipythonrc
597 597 for file in IP_rc.execfile:
598 598 try:
599 599 file = filefind(file,sys.path+[IPython_dir])
600 600 except IOError:
601 601 warn(itpl('File $file not found. Skipping it.'))
602 602 else:
603 603 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
604 604
605 605 # finally, try importing ipy_*_conf for final configuration
606 606 try:
607 607 import ipy_system_conf
608 608 except ImportError:
609 609 if opts_all.debug: IP.InteractiveTB()
610 610 warn("Could not import 'ipy_system_conf'")
611 611 except:
612 612 IP.InteractiveTB()
613 613 import_fail_info('ipy_system_conf')
614 614
615 615 if opts_all.profile:
616 616 profmodname = 'ipy_profile_' + opts_all.profile
617 617 try:
618 618 __import__(profmodname)
619 619 except ImportError:
620 620 # only warn if ipythonrc-PROFNAME didn't exist
621 621 if opts.profile =='':
622 622 warn("Could not start with profile '%s'!\n ('%s/%s.py' does not exist? run '%%upgrade')" % (
623 623 opts_all.profile, ipythondir, profmodname)
624 624
625 625 )
626 626 except:
627 627 print "Error importing",profmodname
628 628 IP.InteractiveTB()
629 629 import_fail_info(profmodname)
630 630
631 631 try:
632 632 import ipy_user_conf
633 633 except ImportError:
634 634 if opts_all.debug: IP.InteractiveTB()
635 635 warn("Could not import user config!\n ('%s/ipy_user_conf.py' does not exist? Please run '%%upgrade')\n" %
636 636 ipythondir)
637 637 except:
638 638 print "Error importing ipy_user_conf"
639 639 IP.InteractiveTB()
640 640 import_fail_info("ipy_user_conf")
641 641
642 642
643 643 # release stdout and stderr and save config log into a global summary
644 644 msg.config.release_all()
645 645 if IP_rc.messages:
646 646 msg.summary += msg.config.summary_all()
647 647
648 648 #------------------------------------------------------------------------
649 649 # Setup interactive session
650 650
651 651 # Now we should be fully configured. We can then execute files or load
652 652 # things only needed for interactive use. Then we'll open the shell.
653 653
654 654 # Take a snapshot of the user namespace before opening the shell. That way
655 655 # we'll be able to identify which things were interactively defined and
656 656 # which were defined through config files.
657 657 IP.user_config_ns = IP.user_ns.copy()
658 658
659 659 # Force reading a file as if it were a session log. Slower but safer.
660 660 if load_logplay:
661 661 print 'Replaying log...'
662 662 try:
663 663 if IP_rc.debug:
664 664 logplay_quiet = 0
665 665 else:
666 666 logplay_quiet = 1
667 667
668 668 msg.logplay.trap_all()
669 669 IP.safe_execfile(load_logplay,IP.user_ns,
670 670 islog = 1, quiet = logplay_quiet)
671 671 msg.logplay.release_all()
672 672 if IP_rc.messages:
673 673 msg.summary += msg.logplay.summary_all()
674 674 except:
675 675 warn('Problems replaying logfile %s.' % load_logplay)
676 676 IP.InteractiveTB()
677 677
678 678 # Load remaining files in command line
679 679 msg.user_exec.trap_all()
680 680
681 681 # Do NOT execute files named in the command line as scripts to be loaded
682 682 # by embedded instances. Doing so has the potential for an infinite
683 683 # recursion if there are exceptions thrown in the process.
684 684
685 685 # XXX FIXME: the execution of user files should be moved out to after
686 686 # ipython is fully initialized, just as if they were run via %run at the
687 687 # ipython prompt. This would also give them the benefit of ipython's
688 688 # nice tracebacks.
689 689
690 690 if (not embedded and IP_rc.args and
691 691 not IP_rc.args[0].lower().endswith('.ipy')):
692 692 name_save = IP.user_ns['__name__']
693 693 IP.user_ns['__name__'] = '__main__'
694 694 # Set our own excepthook in case the user code tries to call it
695 695 # directly. This prevents triggering the IPython crash handler.
696 696 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
697 697
698 698 save_argv = sys.argv[:] # save it for later restoring
699 699
700 700 sys.argv = args
701 701
702 702 try:
703 703 IP.safe_execfile(args[0], IP.user_ns)
704 704 finally:
705 705 # Reset our crash handler in place
706 706 sys.excepthook = old_excepthook
707 707 sys.argv = save_argv
708 708 IP.user_ns['__name__'] = name_save
709 709
710 710 msg.user_exec.release_all()
711 711 if IP_rc.messages:
712 712 msg.summary += msg.user_exec.summary_all()
713 713
714 714 # since we can't specify a null string on the cmd line, 0 is the equivalent:
715 715 if IP_rc.nosep:
716 716 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
717 717 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
718 718 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
719 719 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
720 720 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
721 721 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
722 722 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
723 723
724 724 # Determine how many lines at the bottom of the screen are needed for
725 725 # showing prompts, so we can know wheter long strings are to be printed or
726 726 # paged:
727 727 num_lines_bot = IP_rc.separate_in.count('\n')+1
728 728 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
729 729
730 730 # configure startup banner
731 731 if IP_rc.c: # regular python doesn't print the banner with -c
732 732 IP_rc.banner = 0
733 733 if IP_rc.banner:
734 734 BANN_P = IP.BANNER_PARTS
735 735 else:
736 736 BANN_P = []
737 737
738 738 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
739 739
740 740 # add message log (possibly empty)
741 741 if msg.summary: BANN_P.append(msg.summary)
742 742 # Final banner is a string
743 743 IP.BANNER = '\n'.join(BANN_P)
744 744
745 745 # Finalize the IPython instance. This assumes the rc structure is fully
746 746 # in place.
747 747 IP.post_config_initialization()
748 748
749 749 return IP
750 750 #************************ end of file <ipmaker.py> **************************
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,402 +1,408 b''
1 1 ;;; ipython.el --- Adds support for IPython to python-mode.el
2 2
3 3 ;; Copyright (C) 2002, 2003, 2004, 2005 Alexander Schmolck
4 4 ;; Author: Alexander Schmolck
5 5 ;; Keywords: ipython python languages oop
6 6 ;; URL: http://ipython.scipy.org
7 7 ;; Compatibility: Emacs21, XEmacs21
8 8 ;; FIXME: #$@! INPUT RING
9 (defconst ipython-version "$Revision: 1211 $"
9 (defconst ipython-version "$Revision: 1324 $"
10 10 "VC version number.")
11 11
12 12 ;;; Commentary
13 13 ;; This library makes all the functionality python-mode has when running with
14 14 ;; the normal python-interpreter available for ipython, too. It also enables a
15 15 ;; persistent py-shell command history accross sessions (if you exit python
16 16 ;; with C-d in py-shell) and defines the command `ipython-to-doctest', which
17 17 ;; can be used to convert bits of a ipython session into something that can be
18 18 ;; used for doctests. To install, put this file somewhere in your emacs
19 19 ;; `load-path' [1] and add the following line to your ~/.emacs file (the first
20 20 ;; line only needed if the default (``"ipython"``) is wrong)::
21 21 ;;
22 22 ;; (setq ipython-command "/SOME-PATH/ipython")
23 23 ;; (require 'ipython)
24 24 ;;
25 25 ;; Ipython will be set as the default python shell, but only if the ipython
26 26 ;; executable is in the path. For ipython sessions autocompletion with <tab>
27 27 ;; is also enabled (experimental feature!). Please also note that all the
28 28 ;; terminal functions in py-shell are handled by emacs's comint, **not** by
29 29 ;; (i)python, so importing readline etc. will have 0 effect.
30 30 ;;
31 31 ;; To start an interactive ipython session run `py-shell' with ``M-x py-shell``
32 32 ;; (or the default keybinding ``C-c C-!``).
33 33 ;;
34 34 ;; NOTE: This mode is currently somewhat alpha and although I hope that it
35 35 ;; will work fine for most cases, doing certain things (like the
36 36 ;; autocompletion and a decent scheme to switch between python interpreters)
37 37 ;; properly will also require changes to ipython that will likely have to wait
38 38 ;; for a larger rewrite scheduled some time in the future.
39 39 ;;
40 40 ;; Also note that you currently NEED THE CVS VERSION OF PYTHON.EL.
41 41 ;;
42 42 ;; Further note that I don't know whether this runs under windows or not and
43 43 ;; that if it doesn't I can't really help much, not being afflicted myself.
44 44 ;;
45 45 ;;
46 46 ;; Hints for effective usage
47 47 ;; -------------------------
48 48 ;;
49 49 ;; - IMO the best feature by far of the ipython/emacs combo is how much easier it
50 ;; makes it to find and fix bugs thanks to the ``@pdb on``/ pdbtrack combo. Try
51 ;; it: first in the ipython to shell do ``@pdb on`` then do something that will
50 ;; makes it to find and fix bugs thanks to the ``%pdb on``/ pdbtrack combo. Try
51 ;; it: first in the ipython to shell do ``%pdb on`` then do something that will
52 52 ;; raise an exception (FIXME nice example) -- and be amazed how easy it is to
53 53 ;; inspect the live objects in each stack frames and to jump to the
54 54 ;; corresponding sourcecode locations as you walk up and down the stack trace
55 55 ;; (even without ``%pdb on`` you can always use ``C-c -`` (`py-up-exception')
56 56 ;; to jump to the corresponding source code locations).
57 57 ;;
58 58 ;; - emacs gives you much more powerful commandline editing and output searching
59 59 ;; capabilities than ipython-standalone -- isearch is your friend if you
60 60 ;; quickly want to print 'DEBUG ...' to stdout out etc.
61 61 ;;
62 62 ;; - This is not really specific to ipython, but for more convenient history
63 63 ;; access you might want to add something like the following to *the beggining*
64 64 ;; of your ``.emacs`` (if you want behavior that's more similar to stand-alone
65 65 ;; ipython, you can change ``meta p`` etc. for ``control p``)::
66 66 ;;
67 67 ;; (require 'comint)
68 68 ;; (define-key comint-mode-map [(meta p)]
69 69 ;; 'comint-previous-matching-input-from-input)
70 70 ;; (define-key comint-mode-map [(meta n)]
71 71 ;; 'comint-next-matching-input-from-input)
72 72 ;; (define-key comint-mode-map [(control meta n)]
73 73 ;; 'comint-next-input)
74 74 ;; (define-key comint-mode-map [(control meta p)]
75 75 ;; 'comint-previous-input)
76 76 ;;
77 77 ;; - Be aware that if you customize py-python-command previously, this value
78 78 ;; will override what ipython.el does (because loading the customization
79 79 ;; variables comes later).
80 80 ;;
81 81 ;; Please send comments and feedback to the ipython-list
82 82 ;; (<ipython-user@scipy.net>) where I (a.s.) or someone else will try to
83 83 ;; answer them (it helps if you specify your emacs version, OS etc;
84 84 ;; familiarity with <http://www.catb.org/~esr/faqs/smart-questions.html> might
85 85 ;; speed up things further).
86 86 ;;
87 87 ;; Footnotes:
88 88 ;;
89 89 ;; [1] If you don't know what `load-path' is, C-h v load-path will tell
90 90 ;; you; if required you can also add a new directory. So assuming that
91 91 ;; ipython.el resides in ~/el/, put this in your emacs:
92 92 ;;
93 93 ;;
94 94 ;; (add-to-list 'load-path "~/el")
95 95 ;; (setq ipython-command "/some-path/ipython")
96 96 ;; (require 'ipython)
97 97 ;;
98 98 ;;
99 99 ;;
100 100 ;;
101 101 ;; TODO:
102 102 ;; - do autocompletion properly
103 103 ;; - implement a proper switching between python interpreters
104 104 ;;
105 105 ;; BUGS:
106 106 ;; - neither::
107 107 ;;
108 108 ;; (py-shell "-c print 'FOOBAR'")
109 109 ;;
110 110 ;; nor::
111 111 ;;
112 112 ;; (let ((py-python-command-args (append py-python-command-args
113 113 ;; '("-c" "print 'FOOBAR'"))))
114 114 ;; (py-shell))
115 115 ;;
116 116 ;; seem to print anything as they should
117 117 ;;
118 118 ;; - look into init priority issues with `py-python-command' (if it's set
119 119 ;; via custom)
120 120
121 121
122 122 ;;; Code
123 123 (require 'cl)
124 124 (require 'shell)
125 125 (require 'executable)
126 126 (require 'ansi-color)
127 127
128 128 (defcustom ipython-command "ipython"
129 129 "*Shell command used to start ipython."
130 130 :type 'string
131 131 :group 'python)
132 132
133 133 ;; Users can set this to nil
134 134 (defvar py-shell-initial-switch-buffers t
135 135 "If nil, don't switch to the *Python* buffer on the first call to
136 136 `py-shell'.")
137 137
138 138 (defvar ipython-backup-of-py-python-command nil
139 139 "HACK")
140 140
141 141
142 142 (defvar ipython-de-input-prompt-regexp "\\(?:
143 143 In \\[[0-9]+\\]: *.*
144 144 ----+> \\(.*
145 145 \\)[\n]?\\)\\|\\(?:
146 146 In \\[[0-9]+\\]: *\\(.*
147 147 \\)\\)\\|^[ ]\\{3\\}[.]\\{3,\\}: *\\(.*
148 148 \\)"
149 149 "A regular expression to match the IPython input prompt and the python
150 150 command after it. The first match group is for a command that is rewritten,
151 151 the second for a 'normal' command, and the third for a multiline command.")
152 152 (defvar ipython-de-output-prompt-regexp "^Out\\[[0-9]+\\]: "
153 153 "A regular expression to match the output prompt of IPython.")
154 154
155 155
156 156 (if (not (executable-find ipython-command))
157 157 (message (format "Can't find executable %s - ipython.el *NOT* activated!!!"
158 158 ipython-command))
159 159 ;; XXX load python-mode, so that we can screw around with its variables
160 160 ;; this has the disadvantage that python-mode is loaded even if no
161 161 ;; python-file is ever edited etc. but it means that `py-shell' works
162 162 ;; without loading a python-file first. Obviously screwing around with
163 163 ;; python-mode's variables like this is a mess, but well.
164 164 (require 'python-mode)
165 165 ;; turn on ansi colors for ipython and activate completion
166 166 (defun ipython-shell-hook ()
167 167 ;; the following is to synchronize dir-changes
168 168 (make-local-variable 'shell-dirstack)
169 169 (setq shell-dirstack nil)
170 170 (make-local-variable 'shell-last-dir)
171 171 (setq shell-last-dir nil)
172 172 (make-local-variable 'shell-dirtrackp)
173 173 (setq shell-dirtrackp t)
174 174 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
175 175
176 176 (ansi-color-for-comint-mode-on)
177 177 (define-key py-shell-map [tab] 'ipython-complete)
178 178 ;;XXX this is really just a cheap hack, it only completes symbols in the
179 179 ;;interactive session -- useful nonetheless.
180 (define-key py-mode-map [(meta tab)] 'ipython-complete))
180 (define-key py-mode-map [(meta tab)] 'ipython-complete)
181
182 )
181 183 (add-hook 'py-shell-hook 'ipython-shell-hook)
182 184 ;; Regular expression that describes tracebacks for IPython in context and
183 185 ;; verbose mode.
184 186
185 187 ;;Adapt python-mode settings for ipython.
186 188 ;; (this works for %xmode 'verbose' or 'context')
187 189
188 190 ;; XXX putative regexps for syntax errors; unfortunately the
189 191 ;; current python-mode traceback-line-re scheme is too primitive,
190 192 ;; so it's either matching syntax errors, *or* everything else
191 193 ;; (XXX: should ask Fernando for a change)
192 194 ;;"^ File \"\\(.*?\\)\", line \\([0-9]+\\).*\n.*\n.*\nSyntaxError:"
193 195 ;;^ File \"\\(.*?\\)\", line \\([0-9]+\\)"
196
194 197 (setq py-traceback-line-re
195 198 "\\(^[^\t ].+?\\.py\\).*\n +[0-9]+[^\00]*?\n-+> \\([0-9]+\\) +")
196
199
200 ;; Recognize the ipython pdb, whose prompt is 'ipdb>' instead of '(Pdb)'
201 (setq py-pdbtrack-input-prompt "\n[(<]*[Ii]?[Pp]db[>)]+ ")
202
197 203 (setq py-shell-input-prompt-1-regexp "^In \\[[0-9]+\\]: *"
198 204 py-shell-input-prompt-2-regexp "^ [.][.][.]+: *" )
199 205 ;; select a suitable color-scheme
200 206 (unless (member "-colors" py-python-command-args)
201 207 (setq py-python-command-args
202 208 (nconc py-python-command-args
203 209 (list "-colors"
204 210 (cond
205 211 ((eq frame-background-mode 'dark)
206 212 "DarkBG")
207 213 ((eq frame-background-mode 'light)
208 214 "LightBG")
209 215 (t ; default (backg-mode isn't always set by XEmacs)
210 216 "LightBG"))))))
211 217 (unless (equal ipython-backup-of-py-python-command py-python-command)
212 218 (setq ipython-backup-of-py-python-command py-python-command))
213 219 (setq py-python-command ipython-command))
214 220
215 221
216 222 ;; MODIFY py-shell so that it loads the editing history
217 223 (defadvice py-shell (around py-shell-with-history)
218 224 "Add persistent command-history support (in
219 225 $PYTHONHISTORY (or \"~/.ipython/history\", if we use IPython)). Also, if
220 226 `py-shell-initial-switch-buffers' is nil, it only switches to *Python* if that
221 227 buffer already exists."
222 228 (if (comint-check-proc "*Python*")
223 229 ad-do-it
224 230 (setq comint-input-ring-file-name
225 231 (if (string-equal py-python-command ipython-command)
226 232 (concat (or (getenv "IPYTHONDIR") "~/.ipython") "/history")
227 233 (or (getenv "PYTHONHISTORY") "~/.python-history.py")))
228 234 (comint-read-input-ring t)
229 235 (let ((buf (current-buffer)))
230 236 ad-do-it
231 237 (unless py-shell-initial-switch-buffers
232 238 (switch-to-buffer-other-window buf)))))
233 239 (ad-activate 'py-shell)
234 240 ;; (defadvice py-execute-region (before py-execute-buffer-ensure-process)
235 241 ;; "HACK: test that ipython is already running before executing something.
236 242 ;; Doing this properly seems not worth the bother (unless people actually
237 243 ;; request it)."
238 244 ;; (unless (comint-check-proc "*Python*")
239 245 ;; (error "Sorry you have to first do M-x py-shell to send something to ipython.")))
240 246 ;; (ad-activate 'py-execute-region)
241 247
242 248 (defadvice py-execute-region (around py-execute-buffer-ensure-process)
243 249 "HACK: if `py-shell' is not active or ASYNC is explicitly desired, fall back
244 250 to python instead of ipython."
245 251 (let ((py-python-command (if (and (comint-check-proc "*Python*") (not async))
246 252 py-python-command
247 253 ipython-backup-of-py-python-command)))
248 254 ad-do-it))
249 255 (ad-activate 'py-execute-region)
250 256
251 257 (defun ipython-to-doctest (start end)
252 258 "Transform a cut-and-pasted bit from an IPython session into something that
253 259 looks like it came from a normal interactive python session, so that it can
254 260 be used in doctests. Example:
255 261
256 262
257 263 In [1]: import sys
258 264
259 265 In [2]: sys.stdout.write 'Hi!\n'
260 266 ------> sys.stdout.write ('Hi!\n')
261 267 Hi!
262 268
263 269 In [3]: 3 + 4
264 270 Out[3]: 7
265 271
266 272 gets converted to:
267 273
268 274 >>> import sys
269 275 >>> sys.stdout.write ('Hi!\n')
270 276 Hi!
271 277 >>> 3 + 4
272 278 7
273 279
274 280 "
275 281 (interactive "*r\n")
276 282 ;(message (format "###DEBUG s:%de:%d" start end))
277 283 (save-excursion
278 284 (save-match-data
279 285 ;; replace ``In [3]: bla`` with ``>>> bla`` and
280 286 ;; ``... : bla`` with ``... bla``
281 287 (goto-char start)
282 288 (while (re-search-forward ipython-de-input-prompt-regexp end t)
283 289 ;(message "finding 1")
284 290 (cond ((match-string 3) ;continued
285 291 (replace-match "... \\3" t nil))
286 292 (t
287 293 (replace-match ">>> \\1\\2" t nil))))
288 294 ;; replace ``
289 295 (goto-char start)
290 296 (while (re-search-forward ipython-de-output-prompt-regexp end t)
291 297 (replace-match "" t nil)))))
292 298
293 299 (defvar ipython-completion-command-string
294 300 "print ';'.join(__IP.Completer.all_completions('%s')) #PYTHON-MODE SILENT\n"
295 301 "The string send to ipython to query for all possible completions")
296 302
297 303
298 304 ;; xemacs doesn't have `comint-preoutput-filter-functions' so we'll try the
299 305 ;; following wonderful hack to work around this case
300 306 (if (featurep 'xemacs)
301 307 ;;xemacs
302 308 (defun ipython-complete ()
303 309 "Try to complete the python symbol before point. Only knows about the stuff
304 310 in the current *Python* session."
305 311 (interactive)
306 312 (let* ((ugly-return nil)
307 313 (sep ";")
308 314 (python-process (or (get-buffer-process (current-buffer))
309 315 ;XXX hack for .py buffers
310 316 (get-process py-which-bufname)))
311 317 ;; XXX currently we go backwards to find the beginning of an
312 318 ;; expression part; a more powerful approach in the future might be
313 319 ;; to let ipython have the complete line, so that context can be used
314 320 ;; to do things like filename completion etc.
315 321 (beg (save-excursion (skip-chars-backward "a-z0-9A-Z_." (point-at-bol))
316 322 (point)))
317 323 (end (point))
318 324 (pattern (buffer-substring-no-properties beg end))
319 325 (completions nil)
320 326 (completion-table nil)
321 327 completion
322 328 (comint-output-filter-functions
323 329 (append comint-output-filter-functions
324 330 '(ansi-color-filter-apply
325 331 (lambda (string)
326 332 ;(message (format "DEBUG filtering: %s" string))
327 333 (setq ugly-return (concat ugly-return string))
328 334 (delete-region comint-last-output-start
329 335 (process-mark (get-buffer-process (current-buffer)))))))))
330 336 ;(message (format "#DEBUG pattern: '%s'" pattern))
331 337 (process-send-string python-process
332 338 (format ipython-completion-command-string pattern))
333 339 (accept-process-output python-process)
334 340 ;(message (format "DEBUG return: %s" ugly-return))
335 341 (setq completions
336 342 (split-string (substring ugly-return 0 (position ?\n ugly-return)) sep))
337 343 (setq completion-table (loop for str in completions
338 344 collect (list str nil)))
339 345 (setq completion (try-completion pattern completion-table))
340 346 (cond ((eq completion t))
341 347 ((null completion)
342 348 (message "Can't find completion for \"%s\"" pattern)
343 349 (ding))
344 350 ((not (string= pattern completion))
345 351 (delete-region beg end)
346 352 (insert completion))
347 353 (t
348 354 (message "Making completion list...")
349 355 (with-output-to-temp-buffer "*Python Completions*"
350 356 (display-completion-list (all-completions pattern completion-table)))
351 357 (message "Making completion list...%s" "done")))))
352 358 ;; emacs
353 359 (defun ipython-complete ()
354 360 "Try to complete the python symbol before point. Only knows about the stuff
355 361 in the current *Python* session."
356 362 (interactive)
357 363 (let* ((ugly-return nil)
358 364 (sep ";")
359 365 (python-process (or (get-buffer-process (current-buffer))
360 366 ;XXX hack for .py buffers
361 367 (get-process py-which-bufname)))
362 368 ;; XXX currently we go backwards to find the beginning of an
363 369 ;; expression part; a more powerful approach in the future might be
364 370 ;; to let ipython have the complete line, so that context can be used
365 371 ;; to do things like filename completion etc.
366 372 (beg (save-excursion (skip-chars-backward "a-z0-9A-Z_." (point-at-bol))
367 373 (point)))
368 374 (end (point))
369 375 (pattern (buffer-substring-no-properties beg end))
370 376 (completions nil)
371 377 (completion-table nil)
372 378 completion
373 379 (comint-preoutput-filter-functions
374 380 (append comint-preoutput-filter-functions
375 381 '(ansi-color-filter-apply
376 382 (lambda (string)
377 383 (setq ugly-return (concat ugly-return string))
378 384 "")))))
379 385 (process-send-string python-process
380 386 (format ipython-completion-command-string pattern))
381 387 (accept-process-output python-process)
382 388 (setq completions
383 389 (split-string (substring ugly-return 0 (position ?\n ugly-return)) sep))
384 390 ;(message (format "DEBUG completions: %S" completions))
385 391 (setq completion-table (loop for str in completions
386 392 collect (list str nil)))
387 393 (setq completion (try-completion pattern completion-table))
388 394 (cond ((eq completion t))
389 395 ((null completion)
390 396 (message "Can't find completion for \"%s\"" pattern)
391 397 (ding))
392 398 ((not (string= pattern completion))
393 399 (delete-region beg end)
394 400 (insert completion))
395 401 (t
396 402 (message "Making completion list...")
397 403 (with-output-to-temp-buffer "*IPython Completions*"
398 404 (display-completion-list (all-completions pattern completion-table)))
399 405 (message "Making completion list...%s" "done")))))
400 406 )
401 407
402 408 (provide 'ipython)
General Comments 0
You need to be logged in to leave comments. Login now