|
@@
-1,584
+1,588
b''
|
|
1
|
1
|
# -*- coding: utf-8 -*-
|
|
2
|
2
|
"""
|
|
3
|
3
|
Classes for handling input/output prompts.
|
|
4
|
4
|
|
|
5
|
|
$Id: Prompts.py 1076 2006-01-24 17:27:05Z vivainio $"""
|
|
|
5
|
$Id: Prompts.py 1261 2006-04-11 14:37:02Z vivainio $"""
|
|
6
|
6
|
|
|
7
|
7
|
#*****************************************************************************
|
|
8
|
8
|
# Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
|
|
9
|
9
|
#
|
|
10
|
10
|
# Distributed under the terms of the BSD License. The full license is in
|
|
11
|
11
|
# the file COPYING, distributed as part of this software.
|
|
12
|
12
|
#*****************************************************************************
|
|
13
|
13
|
|
|
14
|
14
|
from IPython import Release
|
|
15
|
15
|
__author__ = '%s <%s>' % Release.authors['Fernando']
|
|
16
|
16
|
__license__ = Release.license
|
|
17
|
17
|
__version__ = Release.version
|
|
18
|
18
|
|
|
19
|
19
|
#****************************************************************************
|
|
20
|
20
|
# Required modules
|
|
21
|
21
|
import __builtin__
|
|
22
|
22
|
import os
|
|
23
|
23
|
import socket
|
|
24
|
24
|
import sys
|
|
25
|
25
|
import time
|
|
26
|
26
|
from pprint import pprint,pformat
|
|
27
|
27
|
|
|
28
|
28
|
# IPython's own
|
|
29
|
29
|
from IPython import ColorANSI
|
|
30
|
30
|
from IPython.Itpl import ItplNS
|
|
31
|
31
|
from IPython.ipstruct import Struct
|
|
32
|
32
|
from IPython.macro import Macro
|
|
33
|
33
|
from IPython.genutils import *
|
|
34
|
34
|
|
|
35
|
35
|
#****************************************************************************
|
|
36
|
36
|
#Color schemes for Prompts.
|
|
37
|
37
|
|
|
38
|
38
|
PromptColors = ColorANSI.ColorSchemeTable()
|
|
39
|
39
|
InputColors = ColorANSI.InputTermColors # just a shorthand
|
|
40
|
40
|
Colors = ColorANSI.TermColors # just a shorthand
|
|
41
|
41
|
|
|
42
|
42
|
PromptColors.add_scheme(ColorANSI.ColorScheme(
|
|
43
|
43
|
'NoColor',
|
|
44
|
44
|
in_prompt = InputColors.NoColor, # Input prompt
|
|
45
|
45
|
in_number = InputColors.NoColor, # Input prompt number
|
|
46
|
46
|
in_prompt2 = InputColors.NoColor, # Continuation prompt
|
|
47
|
47
|
in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
|
|
48
|
48
|
|
|
49
|
49
|
out_prompt = Colors.NoColor, # Output prompt
|
|
50
|
50
|
out_number = Colors.NoColor, # Output prompt number
|
|
51
|
51
|
|
|
52
|
52
|
normal = Colors.NoColor # color off (usu. Colors.Normal)
|
|
53
|
53
|
))
|
|
54
|
54
|
|
|
55
|
55
|
# make some schemes as instances so we can copy them for modification easily:
|
|
56
|
56
|
__PColLinux = ColorANSI.ColorScheme(
|
|
57
|
57
|
'Linux',
|
|
58
|
58
|
in_prompt = InputColors.Green,
|
|
59
|
59
|
in_number = InputColors.LightGreen,
|
|
60
|
60
|
in_prompt2 = InputColors.Green,
|
|
61
|
61
|
in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
|
|
62
|
62
|
|
|
63
|
63
|
out_prompt = Colors.Red,
|
|
64
|
64
|
out_number = Colors.LightRed,
|
|
65
|
65
|
|
|
66
|
66
|
normal = Colors.Normal
|
|
67
|
67
|
)
|
|
68
|
68
|
# Don't forget to enter it into the table!
|
|
69
|
69
|
PromptColors.add_scheme(__PColLinux)
|
|
70
|
70
|
|
|
71
|
71
|
# Slightly modified Linux for light backgrounds
|
|
72
|
72
|
__PColLightBG = __PColLinux.copy('LightBG')
|
|
73
|
73
|
|
|
74
|
74
|
__PColLightBG.colors.update(
|
|
75
|
75
|
in_prompt = InputColors.Blue,
|
|
76
|
76
|
in_number = InputColors.LightBlue,
|
|
77
|
77
|
in_prompt2 = InputColors.Blue
|
|
78
|
78
|
)
|
|
79
|
79
|
PromptColors.add_scheme(__PColLightBG)
|
|
80
|
80
|
|
|
81
|
81
|
del Colors,InputColors
|
|
82
|
82
|
|
|
83
|
83
|
#-----------------------------------------------------------------------------
|
|
84
|
84
|
def multiple_replace(dict, text):
|
|
85
|
85
|
""" Replace in 'text' all occurences of any key in the given
|
|
86
|
86
|
dictionary by its corresponding value. Returns the new string."""
|
|
87
|
87
|
|
|
88
|
88
|
# Function by Xavier Defrang, originally found at:
|
|
89
|
89
|
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
|
|
90
|
90
|
|
|
91
|
91
|
# Create a regular expression from the dictionary keys
|
|
92
|
92
|
regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
|
|
93
|
93
|
# For each match, look-up corresponding value in dictionary
|
|
94
|
94
|
return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
|
|
95
|
95
|
|
|
96
|
96
|
#-----------------------------------------------------------------------------
|
|
97
|
97
|
# Special characters that can be used in prompt templates, mainly bash-like
|
|
98
|
98
|
|
|
99
|
99
|
# If $HOME isn't defined (Windows), make it an absurd string so that it can
|
|
100
|
100
|
# never be expanded out into '~'. Basically anything which can never be a
|
|
101
|
101
|
# reasonable directory name will do, we just want the $HOME -> '~' operation
|
|
102
|
102
|
# to become a no-op. We pre-compute $HOME here so it's not done on every
|
|
103
|
103
|
# prompt call.
|
|
104
|
104
|
|
|
105
|
105
|
# FIXME:
|
|
106
|
106
|
|
|
107
|
107
|
# - This should be turned into a class which does proper namespace management,
|
|
108
|
108
|
# since the prompt specials need to be evaluated in a certain namespace.
|
|
109
|
109
|
# Currently it's just globals, which need to be managed manually by code
|
|
110
|
110
|
# below.
|
|
111
|
111
|
|
|
112
|
112
|
# - I also need to split up the color schemes from the prompt specials
|
|
113
|
113
|
# somehow. I don't have a clean design for that quite yet.
|
|
114
|
114
|
|
|
115
|
115
|
HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
|
|
116
|
116
|
|
|
117
|
117
|
# We precompute a few more strings here for the prompt_specials, which are
|
|
118
|
118
|
# fixed once ipython starts. This reduces the runtime overhead of computing
|
|
119
|
119
|
# prompt strings.
|
|
120
|
120
|
USER = os.environ.get("USER")
|
|
121
|
121
|
HOSTNAME = socket.gethostname()
|
|
122
|
122
|
HOSTNAME_SHORT = HOSTNAME.split(".")[0]
|
|
123
|
123
|
ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
|
|
124
|
124
|
|
|
125
|
125
|
prompt_specials_color = {
|
|
126
|
126
|
# Prompt/history count
|
|
127
|
127
|
'%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
|
|
128
|
128
|
'\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
|
|
129
|
129
|
# Prompt/history count, with the actual digits replaced by dots. Used
|
|
130
|
130
|
# mainly in continuation prompts (prompt_in2)
|
|
131
|
131
|
'\\D': '${"."*len(str(self.cache.prompt_count))}',
|
|
132
|
132
|
# Current working directory
|
|
133
|
133
|
'\\w': '${os.getcwd()}',
|
|
134
|
134
|
# Current time
|
|
135
|
135
|
'\\t' : '${time.strftime("%H:%M:%S")}',
|
|
136
|
136
|
# Basename of current working directory.
|
|
137
|
137
|
# (use os.sep to make this portable across OSes)
|
|
138
|
138
|
'\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
|
|
139
|
139
|
# These X<N> are an extension to the normal bash prompts. They return
|
|
140
|
140
|
# N terms of the path, after replacing $HOME with '~'
|
|
141
|
141
|
'\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
|
|
142
|
142
|
'\\X1': '${self.cwd_filt(1)}',
|
|
143
|
143
|
'\\X2': '${self.cwd_filt(2)}',
|
|
144
|
144
|
'\\X3': '${self.cwd_filt(3)}',
|
|
145
|
145
|
'\\X4': '${self.cwd_filt(4)}',
|
|
146
|
146
|
'\\X5': '${self.cwd_filt(5)}',
|
|
147
|
147
|
# Y<N> are similar to X<N>, but they show '~' if it's the directory
|
|
148
|
148
|
# N+1 in the list. Somewhat like %cN in tcsh.
|
|
149
|
149
|
'\\Y0': '${self.cwd_filt2(0)}',
|
|
150
|
150
|
'\\Y1': '${self.cwd_filt2(1)}',
|
|
151
|
151
|
'\\Y2': '${self.cwd_filt2(2)}',
|
|
152
|
152
|
'\\Y3': '${self.cwd_filt2(3)}',
|
|
153
|
153
|
'\\Y4': '${self.cwd_filt2(4)}',
|
|
154
|
154
|
'\\Y5': '${self.cwd_filt2(5)}',
|
|
155
|
155
|
# Hostname up to first .
|
|
156
|
156
|
'\\h': HOSTNAME_SHORT,
|
|
157
|
157
|
# Full hostname
|
|
158
|
158
|
'\\H': HOSTNAME,
|
|
159
|
159
|
# Username of current user
|
|
160
|
160
|
'\\u': USER,
|
|
161
|
161
|
# Escaped '\'
|
|
162
|
162
|
'\\\\': '\\',
|
|
163
|
163
|
# Newline
|
|
164
|
164
|
'\\n': '\n',
|
|
165
|
165
|
# Carriage return
|
|
166
|
166
|
'\\r': '\r',
|
|
167
|
167
|
# Release version
|
|
168
|
168
|
'\\v': __version__,
|
|
169
|
169
|
# Root symbol ($ or #)
|
|
170
|
170
|
'\\$': ROOT_SYMBOL,
|
|
171
|
171
|
}
|
|
172
|
172
|
|
|
173
|
173
|
# A copy of the prompt_specials dictionary but with all color escapes removed,
|
|
174
|
174
|
# so we can correctly compute the prompt length for the auto_rewrite method.
|
|
175
|
175
|
prompt_specials_nocolor = prompt_specials_color.copy()
|
|
176
|
176
|
prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
|
|
177
|
177
|
prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
|
|
178
|
178
|
|
|
179
|
179
|
# Add in all the InputTermColors color escapes as valid prompt characters.
|
|
180
|
180
|
# They all get added as \\C_COLORNAME, so that we don't have any conflicts
|
|
181
|
181
|
# with a color name which may begin with a letter used by any other of the
|
|
182
|
182
|
# allowed specials. This of course means that \\C will never be allowed for
|
|
183
|
183
|
# anything else.
|
|
184
|
184
|
input_colors = ColorANSI.InputTermColors
|
|
185
|
185
|
for _color in dir(input_colors):
|
|
186
|
186
|
if _color[0] != '_':
|
|
187
|
187
|
c_name = '\\C_'+_color
|
|
188
|
188
|
prompt_specials_color[c_name] = getattr(input_colors,_color)
|
|
189
|
189
|
prompt_specials_nocolor[c_name] = ''
|
|
190
|
190
|
|
|
191
|
191
|
# we default to no color for safety. Note that prompt_specials is a global
|
|
192
|
192
|
# variable used by all prompt objects.
|
|
193
|
193
|
prompt_specials = prompt_specials_nocolor
|
|
194
|
194
|
|
|
195
|
195
|
#-----------------------------------------------------------------------------
|
|
196
|
196
|
def str_safe(arg):
|
|
197
|
197
|
"""Convert to a string, without ever raising an exception.
|
|
198
|
198
|
|
|
199
|
199
|
If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
|
|
200
|
200
|
error message."""
|
|
201
|
201
|
|
|
202
|
202
|
try:
|
|
203
|
203
|
out = str(arg)
|
|
204
|
204
|
except UnicodeError:
|
|
205
|
205
|
try:
|
|
206
|
206
|
out = arg.encode('utf_8','replace')
|
|
207
|
207
|
except Exception,msg:
|
|
208
|
208
|
# let's keep this little duplication here, so that the most common
|
|
209
|
209
|
# case doesn't suffer from a double try wrapping.
|
|
210
|
210
|
out = '<ERROR: %s>' % msg
|
|
211
|
211
|
except Exception,msg:
|
|
212
|
212
|
out = '<ERROR: %s>' % msg
|
|
213
|
213
|
return out
|
|
214
|
214
|
|
|
215
|
215
|
class BasePrompt:
|
|
216
|
216
|
"""Interactive prompt similar to Mathematica's."""
|
|
217
|
217
|
def __init__(self,cache,sep,prompt,pad_left=False):
|
|
218
|
218
|
|
|
219
|
219
|
# Hack: we access information about the primary prompt through the
|
|
220
|
220
|
# cache argument. We need this, because we want the secondary prompt
|
|
221
|
221
|
# to be aligned with the primary one. Color table info is also shared
|
|
222
|
222
|
# by all prompt classes through the cache. Nice OO spaghetti code!
|
|
223
|
223
|
self.cache = cache
|
|
224
|
224
|
self.sep = sep
|
|
225
|
225
|
|
|
226
|
226
|
# regexp to count the number of spaces at the end of a prompt
|
|
227
|
227
|
# expression, useful for prompt auto-rewriting
|
|
228
|
228
|
self.rspace = re.compile(r'(\s*)$')
|
|
229
|
229
|
# Flag to left-pad prompt strings to match the length of the primary
|
|
230
|
230
|
# prompt
|
|
231
|
231
|
self.pad_left = pad_left
|
|
232
|
232
|
# Set template to create each actual prompt (where numbers change)
|
|
233
|
233
|
self.p_template = prompt
|
|
234
|
234
|
self.set_p_str()
|
|
235
|
235
|
|
|
236
|
236
|
def set_p_str(self):
|
|
237
|
237
|
""" Set the interpolating prompt strings.
|
|
238
|
238
|
|
|
239
|
239
|
This must be called every time the color settings change, because the
|
|
240
|
240
|
prompt_specials global may have changed."""
|
|
241
|
241
|
|
|
242
|
242
|
import os,time # needed in locals for prompt string handling
|
|
243
|
243
|
loc = locals()
|
|
244
|
244
|
self.p_str = ItplNS('%s%s%s' %
|
|
245
|
245
|
('${self.sep}${self.col_p}',
|
|
246
|
246
|
multiple_replace(prompt_specials, self.p_template),
|
|
247
|
247
|
'${self.col_norm}'),self.cache.user_ns,loc)
|
|
248
|
248
|
|
|
249
|
249
|
self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
|
|
250
|
250
|
self.p_template),
|
|
251
|
251
|
self.cache.user_ns,loc)
|
|
252
|
252
|
|
|
253
|
253
|
def write(self,msg): # dbg
|
|
254
|
254
|
sys.stdout.write(msg)
|
|
255
|
255
|
return ''
|
|
256
|
256
|
|
|
257
|
257
|
def __str__(self):
|
|
258
|
258
|
"""Return a string form of the prompt.
|
|
259
|
259
|
|
|
260
|
260
|
This for is useful for continuation and output prompts, since it is
|
|
261
|
261
|
left-padded to match lengths with the primary one (if the
|
|
262
|
262
|
self.pad_left attribute is set)."""
|
|
263
|
263
|
|
|
264
|
264
|
out_str = str_safe(self.p_str)
|
|
265
|
265
|
if self.pad_left:
|
|
266
|
266
|
# We must find the amount of padding required to match lengths,
|
|
267
|
267
|
# taking the color escapes (which are invisible on-screen) into
|
|
268
|
268
|
# account.
|
|
269
|
269
|
esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
|
|
270
|
270
|
format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
|
|
271
|
271
|
return format % out_str
|
|
272
|
272
|
else:
|
|
273
|
273
|
return out_str
|
|
274
|
274
|
|
|
275
|
275
|
# these path filters are put in as methods so that we can control the
|
|
276
|
276
|
# namespace where the prompt strings get evaluated
|
|
277
|
277
|
def cwd_filt(self,depth):
|
|
278
|
278
|
"""Return the last depth elements of the current working directory.
|
|
279
|
279
|
|
|
280
|
280
|
$HOME is always replaced with '~'.
|
|
281
|
281
|
If depth==0, the full path is returned."""
|
|
282
|
282
|
|
|
283
|
283
|
cwd = os.getcwd().replace(HOME,"~")
|
|
284
|
284
|
out = os.sep.join(cwd.split(os.sep)[-depth:])
|
|
285
|
285
|
if out:
|
|
286
|
286
|
return out
|
|
287
|
287
|
else:
|
|
288
|
288
|
return os.sep
|
|
289
|
289
|
|
|
290
|
290
|
def cwd_filt2(self,depth):
|
|
291
|
291
|
"""Return the last depth elements of the current working directory.
|
|
292
|
292
|
|
|
293
|
293
|
$HOME is always replaced with '~'.
|
|
294
|
294
|
If depth==0, the full path is returned."""
|
|
295
|
295
|
|
|
296
|
296
|
cwd = os.getcwd().replace(HOME,"~").split(os.sep)
|
|
297
|
297
|
if '~' in cwd and len(cwd) == depth+1:
|
|
298
|
298
|
depth += 1
|
|
299
|
299
|
out = os.sep.join(cwd[-depth:])
|
|
300
|
300
|
if out:
|
|
301
|
301
|
return out
|
|
302
|
302
|
else:
|
|
303
|
303
|
return os.sep
|
|
304
|
304
|
|
|
305
|
305
|
class Prompt1(BasePrompt):
|
|
306
|
306
|
"""Input interactive prompt similar to Mathematica's."""
|
|
307
|
307
|
|
|
308
|
308
|
def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
|
|
309
|
309
|
BasePrompt.__init__(self,cache,sep,prompt,pad_left)
|
|
310
|
310
|
|
|
311
|
311
|
def set_colors(self):
|
|
312
|
312
|
self.set_p_str()
|
|
313
|
313
|
Colors = self.cache.color_table.active_colors # shorthand
|
|
314
|
314
|
self.col_p = Colors.in_prompt
|
|
315
|
315
|
self.col_num = Colors.in_number
|
|
316
|
316
|
self.col_norm = Colors.in_normal
|
|
317
|
317
|
# We need a non-input version of these escapes for the '--->'
|
|
318
|
318
|
# auto-call prompts used in the auto_rewrite() method.
|
|
319
|
319
|
self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
|
|
320
|
320
|
self.col_norm_ni = Colors.normal
|
|
321
|
321
|
|
|
322
|
322
|
def __str__(self):
|
|
323
|
323
|
self.cache.prompt_count += 1
|
|
324
|
324
|
self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
|
|
325
|
325
|
return str_safe(self.p_str)
|
|
326
|
326
|
|
|
327
|
327
|
def auto_rewrite(self):
|
|
328
|
328
|
"""Print a string of the form '--->' which lines up with the previous
|
|
329
|
329
|
input string. Useful for systems which re-write the user input when
|
|
330
|
330
|
handling automatically special syntaxes."""
|
|
331
|
331
|
|
|
332
|
332
|
curr = str(self.cache.last_prompt)
|
|
333
|
333
|
nrspaces = len(self.rspace.search(curr).group())
|
|
334
|
334
|
return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
|
|
335
|
335
|
' '*nrspaces,self.col_norm_ni)
|
|
336
|
336
|
|
|
337
|
337
|
class PromptOut(BasePrompt):
|
|
338
|
338
|
"""Output interactive prompt similar to Mathematica's."""
|
|
339
|
339
|
|
|
340
|
340
|
def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
|
|
341
|
341
|
BasePrompt.__init__(self,cache,sep,prompt,pad_left)
|
|
342
|
342
|
if not self.p_template:
|
|
343
|
343
|
self.__str__ = lambda: ''
|
|
344
|
344
|
|
|
345
|
345
|
def set_colors(self):
|
|
346
|
346
|
self.set_p_str()
|
|
347
|
347
|
Colors = self.cache.color_table.active_colors # shorthand
|
|
348
|
348
|
self.col_p = Colors.out_prompt
|
|
349
|
349
|
self.col_num = Colors.out_number
|
|
350
|
350
|
self.col_norm = Colors.normal
|
|
351
|
351
|
|
|
352
|
352
|
class Prompt2(BasePrompt):
|
|
353
|
353
|
"""Interactive continuation prompt."""
|
|
354
|
354
|
|
|
355
|
355
|
def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
|
|
356
|
356
|
self.cache = cache
|
|
357
|
357
|
self.p_template = prompt
|
|
358
|
358
|
self.pad_left = pad_left
|
|
359
|
359
|
self.set_p_str()
|
|
360
|
360
|
|
|
361
|
361
|
def set_p_str(self):
|
|
362
|
362
|
import os,time # needed in locals for prompt string handling
|
|
363
|
363
|
loc = locals()
|
|
364
|
364
|
self.p_str = ItplNS('%s%s%s' %
|
|
365
|
365
|
('${self.col_p2}',
|
|
366
|
366
|
multiple_replace(prompt_specials, self.p_template),
|
|
367
|
367
|
'$self.col_norm'),
|
|
368
|
368
|
self.cache.user_ns,loc)
|
|
369
|
369
|
self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
|
|
370
|
370
|
self.p_template),
|
|
371
|
371
|
self.cache.user_ns,loc)
|
|
372
|
372
|
|
|
373
|
373
|
def set_colors(self):
|
|
374
|
374
|
self.set_p_str()
|
|
375
|
375
|
Colors = self.cache.color_table.active_colors
|
|
376
|
376
|
self.col_p2 = Colors.in_prompt2
|
|
377
|
377
|
self.col_norm = Colors.in_normal
|
|
378
|
378
|
# FIXME (2004-06-16) HACK: prevent crashes for users who haven't
|
|
379
|
379
|
# updated their prompt_in2 definitions. Remove eventually.
|
|
380
|
380
|
self.col_p = Colors.out_prompt
|
|
381
|
381
|
self.col_num = Colors.out_number
|
|
382
|
382
|
|
|
383
|
383
|
#-----------------------------------------------------------------------------
|
|
384
|
384
|
class CachedOutput:
|
|
385
|
385
|
"""Class for printing output from calculations while keeping a cache of
|
|
386
|
386
|
reults. It dynamically creates global variables prefixed with _ which
|
|
387
|
387
|
contain these results.
|
|
388
|
388
|
|
|
389
|
389
|
Meant to be used as a sys.displayhook replacement, providing numbered
|
|
390
|
390
|
prompts and cache services.
|
|
391
|
391
|
|
|
392
|
392
|
Initialize with initial and final values for cache counter (this defines
|
|
393
|
393
|
the maximum size of the cache."""
|
|
394
|
394
|
|
|
395
|
395
|
def __init__(self,shell,cache_size,Pprint,
|
|
396
|
396
|
colors='NoColor',input_sep='\n',
|
|
397
|
397
|
output_sep='\n',output_sep2='',
|
|
398
|
398
|
ps1 = None, ps2 = None,ps_out = None,pad_left=True):
|
|
399
|
399
|
|
|
400
|
400
|
cache_size_min = 20
|
|
401
|
401
|
if cache_size <= 0:
|
|
402
|
402
|
self.do_full_cache = 0
|
|
403
|
403
|
cache_size = 0
|
|
404
|
404
|
elif cache_size < cache_size_min:
|
|
405
|
405
|
self.do_full_cache = 0
|
|
406
|
406
|
cache_size = 0
|
|
407
|
407
|
warn('caching was disabled (min value for cache size is %s).' %
|
|
408
|
408
|
cache_size_min,level=3)
|
|
409
|
409
|
else:
|
|
410
|
410
|
self.do_full_cache = 1
|
|
411
|
411
|
|
|
412
|
412
|
self.cache_size = cache_size
|
|
413
|
413
|
self.input_sep = input_sep
|
|
414
|
414
|
|
|
415
|
415
|
# we need a reference to the user-level namespace
|
|
416
|
416
|
self.shell = shell
|
|
417
|
417
|
self.user_ns = shell.user_ns
|
|
418
|
418
|
# and to the user's input
|
|
419
|
419
|
self.input_hist = shell.input_hist
|
|
420
|
420
|
# and to the user's logger, for logging output
|
|
421
|
421
|
self.logger = shell.logger
|
|
422
|
422
|
|
|
423
|
423
|
# Set input prompt strings and colors
|
|
424
|
424
|
if cache_size == 0:
|
|
425
|
425
|
if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
|
|
426
|
426
|
if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
|
|
427
|
427
|
self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
|
|
428
|
428
|
self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
|
|
429
|
429
|
self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
|
|
430
|
430
|
|
|
431
|
431
|
self.color_table = PromptColors
|
|
432
|
432
|
self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
|
|
433
|
433
|
pad_left=pad_left)
|
|
434
|
434
|
self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
|
|
435
|
435
|
self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
|
|
436
|
436
|
pad_left=pad_left)
|
|
437
|
437
|
self.set_colors(colors)
|
|
438
|
438
|
|
|
439
|
439
|
# other more normal stuff
|
|
440
|
440
|
# b/c each call to the In[] prompt raises it by 1, even the first.
|
|
441
|
441
|
self.prompt_count = 0
|
|
442
|
|
self.cache_count = 1
|
|
443
|
442
|
# Store the last prompt string each time, we need it for aligning
|
|
444
|
443
|
# continuation and auto-rewrite prompts
|
|
445
|
444
|
self.last_prompt = ''
|
|
446
|
445
|
self.entries = [None] # output counter starts at 1 for the user
|
|
447
|
446
|
self.Pprint = Pprint
|
|
448
|
447
|
self.output_sep = output_sep
|
|
449
|
448
|
self.output_sep2 = output_sep2
|
|
450
|
449
|
self._,self.__,self.___ = '','',''
|
|
451
|
450
|
self.pprint_types = map(type,[(),[],{}])
|
|
452
|
451
|
|
|
453
|
452
|
# these are deliberately global:
|
|
454
|
453
|
to_user_ns = {'_':self._,'__':self.__,'___':self.___}
|
|
455
|
454
|
self.user_ns.update(to_user_ns)
|
|
456
|
455
|
|
|
457
|
456
|
def _set_prompt_str(self,p_str,cache_def,no_cache_def):
|
|
458
|
457
|
if p_str is None:
|
|
459
|
458
|
if self.do_full_cache:
|
|
460
|
459
|
return cache_def
|
|
461
|
460
|
else:
|
|
462
|
461
|
return no_cache_def
|
|
463
|
462
|
else:
|
|
464
|
463
|
return p_str
|
|
465
|
464
|
|
|
466
|
465
|
def set_colors(self,colors):
|
|
467
|
466
|
"""Set the active color scheme and configure colors for the three
|
|
468
|
467
|
prompt subsystems."""
|
|
469
|
468
|
|
|
470
|
469
|
# FIXME: the prompt_specials global should be gobbled inside this
|
|
471
|
470
|
# class instead. Do it when cleaning up the whole 3-prompt system.
|
|
472
|
471
|
global prompt_specials
|
|
473
|
472
|
if colors.lower()=='nocolor':
|
|
474
|
473
|
prompt_specials = prompt_specials_nocolor
|
|
475
|
474
|
else:
|
|
476
|
475
|
prompt_specials = prompt_specials_color
|
|
477
|
476
|
|
|
478
|
477
|
self.color_table.set_active_scheme(colors)
|
|
479
|
478
|
self.prompt1.set_colors()
|
|
480
|
479
|
self.prompt2.set_colors()
|
|
481
|
480
|
self.prompt_out.set_colors()
|
|
482
|
481
|
|
|
483
|
482
|
def __call__(self,arg=None):
|
|
484
|
483
|
"""Printing with history cache management.
|
|
485
|
484
|
|
|
486
|
485
|
This is invoked everytime the interpreter needs to print, and is
|
|
487
|
486
|
activated by setting the variable sys.displayhook to it."""
|
|
488
|
487
|
|
|
489
|
488
|
# If something injected a '_' variable in __builtin__, delete
|
|
490
|
489
|
# ipython's automatic one so we don't clobber that. gettext() in
|
|
491
|
490
|
# particular uses _, so we need to stay away from it.
|
|
492
|
491
|
if '_' in __builtin__.__dict__:
|
|
493
|
492
|
try:
|
|
494
|
493
|
del self.user_ns['_']
|
|
495
|
494
|
except KeyError:
|
|
496
|
495
|
pass
|
|
497
|
496
|
if arg is not None:
|
|
498
|
497
|
cout_write = Term.cout.write # fast lookup
|
|
499
|
498
|
# first handle the cache and counters
|
|
500
|
499
|
|
|
501
|
500
|
# do not print output if input ends in ';'
|
|
502
|
501
|
if self.input_hist[self.prompt_count].endswith(';\n'):
|
|
503
|
502
|
return
|
|
504
|
503
|
# don't use print, puts an extra space
|
|
505
|
504
|
cout_write(self.output_sep)
|
|
506
|
505
|
if self.do_full_cache:
|
|
507
|
506
|
cout_write(str(self.prompt_out))
|
|
508
|
507
|
|
|
509
|
508
|
if isinstance(arg,Macro):
|
|
510
|
509
|
print 'Executing Macro...'
|
|
511
|
510
|
# in case the macro takes a long time to execute
|
|
512
|
511
|
Term.cout.flush()
|
|
513
|
512
|
self.shell.runlines(arg.value)
|
|
514
|
513
|
return None
|
|
515
|
514
|
|
|
516
|
515
|
# and now call a possibly user-defined print mechanism
|
|
517
|
516
|
manipulated_val = self.display(arg)
|
|
518
|
517
|
|
|
519
|
518
|
# user display hooks can change the variable to be stored in
|
|
520
|
519
|
# output history
|
|
521
|
520
|
|
|
522
|
521
|
if manipulated_val is not None:
|
|
523
|
522
|
arg = manipulated_val
|
|
524
|
523
|
|
|
525
|
524
|
# avoid recursive reference when displaying _oh/Out
|
|
526
|
525
|
if arg is not self.user_ns['_oh']:
|
|
527
|
526
|
self.update(arg)
|
|
528
|
527
|
|
|
529
|
528
|
if self.logger.log_output:
|
|
530
|
529
|
self.logger.log_write(repr(arg),'output')
|
|
531
|
530
|
cout_write(self.output_sep2)
|
|
532
|
531
|
Term.cout.flush()
|
|
533
|
532
|
|
|
534
|
533
|
def _display(self,arg):
|
|
535
|
534
|
"""Default printer method, uses pprint.
|
|
536
|
535
|
|
|
537
|
536
|
Do ip.set_hook("result_display", my_displayhook) for custom result
|
|
538
|
537
|
display, e.g. when your own objects need special formatting.
|
|
539
|
538
|
"""
|
|
540
|
539
|
|
|
541
|
540
|
return self.shell.hooks.result_display(arg)
|
|
542
|
541
|
|
|
543
|
542
|
# Assign the default display method:
|
|
544
|
543
|
display = _display
|
|
545
|
544
|
|
|
546
|
545
|
def update(self,arg):
|
|
547
|
546
|
#print '***cache_count', self.cache_count # dbg
|
|
548
|
|
if self.cache_count >= self.cache_size and self.do_full_cache:
|
|
|
547
|
if len(self.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
|
|
|
548
|
warn('Output cache limit (currently '+\
|
|
|
549
|
`self.cache_count`+' entries) hit.\n'
|
|
|
550
|
'Flushing cache and resetting history counter...\n'
|
|
|
551
|
'The only history variables available will be _,__,___ and _1\n'
|
|
|
552
|
'with the current result.')
|
|
|
553
|
|
|
549
|
554
|
self.flush()
|
|
550
|
555
|
# Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
|
|
551
|
556
|
# we cause buggy behavior for things like gettext).
|
|
552
|
557
|
if '_' not in __builtin__.__dict__:
|
|
553
|
558
|
self.___ = self.__
|
|
554
|
559
|
self.__ = self._
|
|
555
|
560
|
self._ = arg
|
|
556
|
561
|
self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
|
|
557
|
562
|
|
|
558
|
563
|
# hackish access to top-level namespace to create _1,_2... dynamically
|
|
559
|
564
|
to_main = {}
|
|
560
|
565
|
if self.do_full_cache:
|
|
561
|
|
self.cache_count += 1
|
|
562
|
566
|
self.entries.append(arg)
|
|
563
|
567
|
new_result = '_'+`self.prompt_count`
|
|
564
|
568
|
to_main[new_result] = self.entries[-1]
|
|
565
|
569
|
self.user_ns.update(to_main)
|
|
566
|
570
|
self.user_ns['_oh'][self.prompt_count] = arg
|
|
567
|
571
|
|
|
568
|
572
|
def flush(self):
|
|
569
|
573
|
if not self.do_full_cache:
|
|
570
|
574
|
raise ValueError,"You shouldn't have reached the cache flush "\
|
|
571
|
575
|
"if full caching is not enabled!"
|
|
572
|
|
warn('Output cache limit (currently '+\
|
|
573
|
|
`self.cache_count`+' entries) hit.\n'
|
|
574
|
|
'Flushing cache and resetting history counter...\n'
|
|
575
|
|
'The only history variables available will be _,__,___ and _1\n'
|
|
576
|
|
'with the current result.')
|
|
577
|
576
|
# delete auto-generated vars from global namespace
|
|
|
577
|
|
|
578
|
578
|
for n in range(1,self.prompt_count + 1):
|
|
579
|
579
|
key = '_'+`n`
|
|
580
|
580
|
try:
|
|
581
|
581
|
del self.user_ns[key]
|
|
582
|
582
|
except: pass
|
|
583
|
|
self.prompt_count = 1
|
|
584
|
|
self.cache_count = 1
|
|
|
583
|
self.user_ns['_oh'].clear()
|
|
|
584
|
|
|
|
585
|
if '_' not in __builtin__.__dict__:
|
|
|
586
|
self.user_ns.update({'_':None,'__':None, '___':None})
|
|
|
587
|
import gc
|
|
|
588
|
gc.collect() # xxx needed?
|