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