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