2Backend to the console plugin.
5@organization: IBM Corporation
6@copyright: Copyright (c) 2007 IBM Corporation
9All rights reserved. This program and the accompanying materials are made
10available under the terms of the BSD which accompanies this distribution, and
11is available at U{http://www.opensource.org/licenses/bsd-license.php}
20from gi.repository
import Pango
21from StringIO
import StringIO
24from pkg_resources
import parse_version
55 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
56 cin=None, cout=None,cerr=None, input_func=None):
59 @param self: this object
60 @param argv: Command line options
for IPython
61 @param user_ns: User namespace.
62 @param user_global_ns: User
global namespace.
63 @param cin: Console standard input.
64 @param cout: Console standard output.
65 @param cerr: Console standard error.
66 @param input_func: Replacement
for builtin raw_input()
70 if parse_version(IPython.release.version) >= parse_version(
"1.2.1"):
71 IPython.terminal.interactiveshell.raw_input_original = input_func
73 IPython.frontend.terminal.interactiveshell.raw_input_original = input_func
75 io.stdin = io.IOStream(cin)
77 io.stdout = io.IOStream(cout)
79 io.stderr = io.IOStream(cerr)
84 io.raw_input =
lambda x:
None
86 os.environ[
'TERM'] =
'dumb'
87 excepthook = sys.excepthook
89 from IPython.config.loader
import Config
91 cfg.InteractiveShell.colors =
"Linux"
96 old_stdout, old_stderr = sys.stdout, sys.stderr
97 sys.stdout, sys.stderr = io.stdout.stream, io.stderr.stream
101 if parse_version(IPython.release.version) >= parse_version(
"1.2.1"):
102 self.
IP = IPython.terminal.embed.InteractiveShellEmbed.instance(\
103 config=cfg, user_ns=user_ns)
105 self.
IP = IPython.frontend.terminal.embed.InteractiveShellEmbed.instance(\
106 config=cfg, user_ns=user_ns)
108 sys.stdout, sys.stderr = old_stdout, old_stderr
110 self.
IP.system =
lambda cmd: self.
shell(self.
IP.var_expand(cmd),
111 header=
'IPython system call: ')
116 self.
IP.raw_input = input_func
117 sys.excepthook = excepthook
123 self.
IP.readline_startup_hook(self.
IP.pre_readline)
130 Update self.IP namespace for autocompletion
with sys.modules
133 for k, v
in list(sys.modules.items()):
135 self.
IP.user_ns.update({k:v})
139 Executes the current line provided by the shell object.
143 orig_stdout = sys.stdout
144 sys.stdout = IPython.utils.io.stdout
146 orig_stdin = sys.stdin
147 sys.stdin = IPython.utils.io.stdin;
150 self.IP.hooks.pre_prompt_hook()
155 self.
IP.showtraceback()
156 if self.
IP.autoindent:
157 self.
IP.rl_do_indent =
True
160 line = self.
IP.raw_input(self.
prompt)
161 except KeyboardInterrupt:
162 self.
IP.write(
'\nKeyboardInterrupt\n')
163 self.
IP.input_splitter.reset()
165 self.
IP.showtraceback()
167 self.
IP.input_splitter.push(line)
168 self.
iter_more = self.
IP.input_splitter.push_accepts_more()
170 if (self.
IP.SyntaxTB.last_syntax_error
and
171 self.
IP.autoedit_syntax):
172 self.
IP.edit_syntax_error()
174 if parse_version(IPython.release.version) >= parse_version(
"2.0.0-dev"):
175 source_raw = self.
IP.input_splitter.raw_reset()
177 source_raw = self.
IP.input_splitter.source_raw_reset()[1]
178 self.
IP.run_cell(source_raw, store_history=
True)
179 self.
IP.rl_do_indent =
False
183 self.
IP.rl_do_indent =
True
186 sys.stdout = orig_stdout
187 sys.stdin = orig_stdin
191 Generate prompt depending on is_continuation value
193 @param is_continuation
194 @return: The prompt string representation
200 ver = IPython.__version__
202 prompt = self.
IP.hooks.generate_prompt(is_continuation)
205 prompt = self.
IP.prompt_manager.render(
'in2')
207 prompt = self.
IP.prompt_manager.render(
'in')
214 Provides one history command back.
216 @param self this object
217 @return: The command string.
226 Provides one history command forward.
228 @param self this object
229 @return: The command string.
237 Gets the command string of the current history level.
239 @param self this object
240 @return: Historic command string.
250 Add the current dictionary to the shell namespace.
252 @param ns_dict: A dictionary of symbol-values.
255 self.IP.user_ns.update(ns_dict)
259 Returns an auto completed line and/
or possibilities
for completion.
261 @param line: Given line so far.
262 @return: Line completed
as for as possible,
and possible further completions.
266 possibilities = self.
IP.
complete(split_line[-1])
269 possibilities = [
'', []]
271 def _commonPrefix(str1, str2):
273 Reduction function. returns common prefix of two given strings.
275 @param str1: First string.
276 @param str2: Second string
277 @return: Common prefix to both strings.
279 for i
in range(len(str1)):
280 if not str2.startswith(str1[:i+1]):
284 common_prefix = reduce(_commonPrefix, possibilities[1])
or line[-1]
285 completed = line[:-len(split_line[-1])]+common_prefix
290 return completed, possibilities[1]
293 def shell(self, cmd,verbose=0,debug=0,header=''):
295 Replacement method to allow shell commands without them blocking.
297 @param cmd: Shell command to execute.
298 @param verbose: Verbosity
299 @param debug: Debug level
300 @param header: Header to be printed before output
304 if verbose
or debug: print(header+cmd)
307 input, output = os.popen4(cmd)
325 Specialized text view for console-like workflow.
327 @cvar ANSI_COLORS: Mapping of terminal colors to X11 names.
328 @type ANSI_COLORS: dictionary
330 @ivar text_buffer: Widget
's text buffer. @type text_buffer: Gtk.TextBuffer
331 @ivar color_pat: Regex of terminal color pattern
332 @type color_pat: _sre.SRE_Pattern
333 @ivar mark: Scroll mark
for automatic scrolling on input.
334 @type mark: Gtk.TextMark
335 @ivar line_start: Start of command line mark.
336 @type line_start: Gtk.TextMark
338 ANSI_COLORS = {'0;30':
'Black',
'0;31':
'Red',
339 '0;32':
'Green',
'0;33':
'Brown',
340 '0;34':
'Blue',
'0;35':
'Purple',
341 '0;36':
'Cyan',
'0;37':
'LightGray',
342 '1;30':
'DarkGray',
'1;31':
'DarkRed',
343 '1;32':
'SeaGreen',
'1;33':
'Yellow',
344 '1;34':
'LightBlue',
'1;35':
'MediumPurple',
345 '1;36':
'LightCyan',
'1;37':
'White'}
349 Initialize console view.
351 GObject.GObject.__init__(self)
352 self.modify_font(Pango.FontDescription('Mono'))
353 self.set_cursor_visible(
True)
363 self.
text_buffer.create_tag(
'notouch', editable=
False)
364 self.
color_pat = re.compile(
'\x01?\x1b\[(.*?)m\x02?')
368 self.connect(
'key-press-event', self.
onKeyPress)
370 def write(self, text, editable=False):
372 Write given text to buffer.
374 @param text: Text to append.
375 @param editable: If true, added text
is editable.
378 GObject.idle_add(self._write, text, editable)
380 def _write(self, text, editable=False):
382 Write given text to buffer.
384 @param text: Text to append.
385 @param editable: If true, added text
is editable.
389 segment = segments.pop(0)
397 for tag
in ansi_tags:
398 i = segments.index(tag)
400 segments[i+1], str(tag))
407 self.scroll_mark_onscreen(self.
mark)
411 Prints prompt at start of line.
413 @param prompt: Prompt to
print.
420 Prints prompt at start of line.
422 @param prompt: Prompt to
print.
431 Replace currently entered command line with given text.
433 @param text: Text to use
as replacement.
440 Replace currently entered command line with given text.
442 @param text: Text to use
as replacement.
446 iter.forward_to_line_end()
452 Get text in current command line.
454 @return Text of current command line.
463 Show returned text from last command
and print new prompt.
465 @param text: Text to show.
472 Show returned text from last command
and print new prompt.
474 @param text: Text to show.
478 iter.forward_to_line_end()
490 if self.IP.rl_do_indent:
491 indentation = self.IP.input_splitter.indent_spaces *
' '
496 Key press callback used for correcting behavior
for console-like
497 interfaces. For example
'home' should go to prompt,
not to beginning of
500 @param widget: Widget that key press accored
in.
501 @param event: Event object
502 @return Return
True if event should
not trickle.
505 insert_iter = self.text_buffer.get_iter_at_mark(insert_mark)
506 selection_mark = self.text_buffer.get_selection_bound()
507 selection_iter = self.text_buffer.get_iter_at_mark(selection_mark)
509 if event.keyval == Gdk.KEY_Home:
510 if event.get_state() & Gdk.ModifierType.CONTROL_MASK
or event.get_state() & Gdk.ModifierType.MOD1_MASK:
512 elif event.get_state() & Gdk.ModifierType.SHIFT_MASK:
513 self.
text_buffer.move_mark(insert_mark, start_iter)
518 elif event.keyval == Gdk.KEY_Left:
519 insert_iter.backward_cursor_position()
520 if not insert_iter.editable(
True):
522 elif not event.string:
524 elif start_iter.compare(insert_iter) <= 0
and \
525 start_iter.compare(selection_iter) <= 0:
527 elif start_iter.compare(insert_iter) > 0
and \
528 start_iter.compare(selection_iter) > 0:
530 elif insert_iter.compare(selection_iter) < 0:
531 self.
text_buffer.move_mark(insert_mark, start_iter)
532 elif insert_iter.compare(selection_iter) > 0:
533 self.
text_buffer.move_mark(selection_mark, start_iter)
539 For some reason we can't extend onKeyPress directly (bug #500900).
540 @param event key press
562 Sub-class of both modified IPython
shell and L{ConsoleView} this makes
563 a GTK+ IPython console.
567 Initialize. Redirect I/O to console.
569 ConsoleView.__init__(self)
570 self.cout = StringIO()
571 IterableIPShell.__init__(self, cout=self.cout,cerr=self.cout,
581 Custom raw_input() replacement. Gets current line from console buffer.
583 @param prompt: Prompt to
print. Here
for compatibility
as replacement.
584 @return The current command line text.
588 raise KeyboardInterrupt
593 Key press callback with plenty of shell goodness, like history,
594 autocompletions, etc.
596 @param event: Event object.
597 @return True if event should
not trickle.
600 if event.get_state() & Gdk.ModifierType.CONTROL_MASK
and event.keyval == 99:
604 elif event.keyval == Gdk.KEY_Return:
607 elif event.keyval == Gdk.KEY_Up:
610 elif event.keyval == Gdk.KEY_Down:
613 elif event.keyval == Gdk.KEY_Tab:
617 if len(possibilities) > 1:
620 for symbol
in possibilities:
621 self.
write(symbol+
'\n')
628 Process current command line.
633 rv = self.cout.getvalue()
634 if rv: rv = rv.strip(
'\n')
636 self.
cout.truncate(0)
639if __name__ ==
"__main__":
640 window = Gtk.Window()
641 window.set_default_size(640, 320)
642 window.connect(
'delete-event',
lambda x, y: Gtk.main_quit())
def write(self, text, editable=False)
Write given text to buffer.
def changeLine(self, text)
Replace currently entered command line with given text.
dict ANSI_COLORS
color list
def _showPrompt(self, prompt)
Prints prompt at start of line.
def _showReturned(self, text)
Show returned text from last command and print new prompt.
def getCurrentLine(self)
Get text in current command line.
def onKeyPressExtend(self, event)
For some reason we can't extend onKeyPress directly (bug #500900).
def _write(self, text, editable=False)
Write given text to buffer.
def _changeLine(self, text)
Replace currently entered command line with given text.
def showPrompt(self, prompt)
Prints prompt at start of line.
def showReturned(self, text)
Show returned text from last command and print new prompt.
def onKeyPress(self, widget, event)
Key press callback used for correcting behavior for console-like interfaces.
def onKeyPressExtend(self, event)
Key press callback with plenty of shell goodness, like history, autocompletions, etc.
def raw_input(self, prompt='')
Custom raw_input() replacement.
def _processLine(self)
Process current command line.
def updateNamespace(self, ns_dict)
Add the current dictionary to the shell namespace.
def __init__(self, argv=None, user_ns=None, user_global_ns=None, cin=None, cout=None, cerr=None, input_func=None)
Initializer.
def _getHistory(self)
Gets the command string of the current history level.
def __update_namespace(self)
Update self.IP namespace for autocompletion with sys.modules.
def historyBack(self)
Provides one history command back.
history_level
history level
def generatePrompt(self, is_continuation)
Generate prompt depending on is_continuation value.
def historyForward(self)
Provides one history command forward.
def shell(self, cmd, verbose=0, debug=0, header='')
Replacement method to allow shell commands without them blocking.
def execute(self)
Executes the current line provided by the shell object.
def complete(self, line)
Returns an auto completed line and/or possibilities for completion.