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
74 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
75 cin=None, cout=None,cerr=None, input_func=None):
78 @param self: this object
79 @param argv: Command line options
for IPython
80 @param user_ns: User namespace.
81 @param user_global_ns: User
global namespace.
82 @param cin: Console standard input.
83 @param cout: Console standard output.
84 @param cerr: Console standard error.
85 @param input_func: Replacement
for builtin raw_input()
89 if parse_version(IPython.release.version) >= parse_version(
"1.2.1"):
90 IPython.terminal.interactiveshell.raw_input_original = input_func
92 IPython.frontend.terminal.interactiveshell.raw_input_original = input_func
94 io.stdin = io.IOStream(cin)
96 io.stdout = io.IOStream(cout)
98 io.stderr = io.IOStream(cerr)
103 io.raw_input =
lambda x:
None
105 os.environ[
'TERM'] =
'dumb'
106 excepthook = sys.excepthook
108 from IPython.config.loader
import Config
110 cfg.InteractiveShell.colors =
"Linux"
115 old_stdout, old_stderr = sys.stdout, sys.stderr
116 sys.stdout, sys.stderr = io.stdout.stream, io.stderr.stream
120 if parse_version(IPython.release.version) >= parse_version(
"1.2.1"):
121 self.
IP = IPython.terminal.embed.InteractiveShellEmbed.instance(\
122 config=cfg, user_ns=user_ns)
124 self.
IP = IPython.frontend.terminal.embed.InteractiveShellEmbed.instance(\
125 config=cfg, user_ns=user_ns)
127 sys.stdout, sys.stderr = old_stdout, old_stderr
129 self.
IP.system =
lambda cmd: self.
shell(self.
IP.var_expand(cmd),
130 header=
'IPython system call: ')
135 self.
IP.raw_input = input_func
136 sys.excepthook = excepthook
142 self.
IP.readline_startup_hook(self.
IP.pre_readline)
149 Update self.IP namespace for autocompletion
with sys.modules
152 for k, v
in list(sys.modules.items()):
154 self.
IP.user_ns.update({k:v})
158 Executes the current line provided by the shell object.
162 orig_stdout = sys.stdout
163 sys.stdout = IPython.utils.io.stdout
165 orig_stdin = sys.stdin
166 sys.stdin = IPython.utils.io.stdin;
169 self.IP.hooks.pre_prompt_hook()
174 self.
IP.showtraceback()
175 if self.
IP.autoindent:
176 self.
IP.rl_do_indent =
True
179 line = self.
IP.raw_input(self.
prompt)
180 except KeyboardInterrupt:
181 self.
IP.write(
'\nKeyboardInterrupt\n')
182 self.
IP.input_splitter.reset()
184 self.
IP.showtraceback()
186 self.
IP.input_splitter.push(line)
187 self.
iter_more = self.
IP.input_splitter.push_accepts_more()
189 if (self.
IP.SyntaxTB.last_syntax_error
and
190 self.
IP.autoedit_syntax):
191 self.
IP.edit_syntax_error()
193 if parse_version(IPython.release.version) >= parse_version(
"2.0.0-dev"):
194 source_raw = self.
IP.input_splitter.raw_reset()
196 source_raw = self.
IP.input_splitter.source_raw_reset()[1]
197 self.
IP.run_cell(source_raw, store_history=
True)
198 self.
IP.rl_do_indent =
False
202 self.
IP.rl_do_indent =
True
205 sys.stdout = orig_stdout
206 sys.stdin = orig_stdin
210 Generate prompt depending on is_continuation value
212 @param is_continuation
213 @return: The prompt string representation
219 ver = IPython.__version__
221 prompt = self.
IP.hooks.generate_prompt(is_continuation)
224 prompt = self.
IP.prompt_manager.render(
'in2')
226 prompt = self.
IP.prompt_manager.render(
'in')
233 Provides one history command back.
235 @param self this object
236 @return: The command string.
245 Provides one history command forward.
247 @param self this object
248 @return: The command string.
256 Gets the command string of the current history level.
258 @param self this object
259 @return: Historic command string.
269 Add the current dictionary to the shell namespace.
271 @param ns_dict: A dictionary of symbol-values.
274 self.IP.user_ns.update(ns_dict)
278 Returns an auto completed line and/
or possibilities
for completion.
280 @param line: Given line so far.
281 @return: Line completed
as for as possible,
and possible further completions.
285 possibilities = self.
IP.
complete(split_line[-1])
288 possibilities = [
'', []]
290 def _commonPrefix(str1, str2):
292 Reduction function. returns common prefix of two given strings.
294 @param str1: First string.
295 @param str2: Second string
296 @return: Common prefix to both strings.
298 for i
in range(len(str1)):
299 if not str2.startswith(str1[:i+1]):
303 common_prefix = reduce(_commonPrefix, possibilities[1])
or line[-1]
304 completed = line[:-len(split_line[-1])]+common_prefix
309 return completed, possibilities[1]
312 def shell(self, cmd,verbose=0,debug=0,header=''):
314 Replacement method to allow shell commands without them blocking.
316 @param cmd: Shell command to execute.
317 @param verbose: Verbosity
318 @param debug: Debug level
319 @param header: Header to be printed before output
323 if verbose
or debug: print(header+cmd)
326 input, output = os.popen4(cmd)
344 Specialized text view for console-like workflow.
346 @cvar ANSI_COLORS: Mapping of terminal colors to X11 names.
347 @type ANSI_COLORS: dictionary
349 @ivar text_buffer: Widget
's text buffer. @type text_buffer: Gtk.TextBuffer
350 @ivar color_pat: Regex of terminal color pattern
351 @type color_pat: _sre.SRE_Pattern
352 @ivar mark: Scroll mark
for automatic scrolling on input.
353 @type mark: Gtk.TextMark
354 @ivar line_start: Start of command line mark.
355 @type line_start: Gtk.TextMark
357 ANSI_COLORS = {'0;30':
'Black',
'0;31':
'Red',
358 '0;32':
'Green',
'0;33':
'Brown',
359 '0;34':
'Blue',
'0;35':
'Purple',
360 '0;36':
'Cyan',
'0;37':
'LightGray',
361 '1;30':
'DarkGray',
'1;31':
'DarkRed',
362 '1;32':
'SeaGreen',
'1;33':
'Yellow',
363 '1;34':
'LightBlue',
'1;35':
'MediumPurple',
364 '1;36':
'LightCyan',
'1;37':
'White'}
368 Initialize console view.
370 GObject.GObject.__init__(self)
371 self.modify_font(Pango.FontDescription('Mono'))
372 self.set_cursor_visible(
True)
382 self.
text_buffer.create_tag(
'notouch', editable=
False)
383 self.
color_pat = re.compile(
'\x01?\x1b\[(.*?)m\x02?')
387 self.connect(
'key-press-event', self.
onKeyPress)
389 def write(self, text, editable=False):
391 Write given text to buffer.
393 @param text: Text to append.
394 @param editable: If true, added text
is editable.
397 GObject.idle_add(self._write, text, editable)
399 def _write(self, text, editable=False):
401 Write given text to buffer.
403 @param text: Text to append.
404 @param editable: If true, added text
is editable.
408 segment = segments.pop(0)
416 for tag
in ansi_tags:
417 i = segments.index(tag)
419 segments[i+1], str(tag))
426 self.scroll_mark_onscreen(self.
mark)
430 Prints prompt at start of line.
432 @param prompt: Prompt to
print.
439 Prints prompt at start of line.
441 @param prompt: Prompt to
print.
450 Replace currently entered command line with given text.
452 @param text: Text to use
as replacement.
459 Replace currently entered command line with given text.
461 @param text: Text to use
as replacement.
465 iter.forward_to_line_end()
471 Get text in current command line.
473 @return Text of current command line.
482 Show returned text from last command
and print new prompt.
484 @param text: Text to show.
491 Show returned text from last command
and print new prompt.
493 @param text: Text to show.
497 iter.forward_to_line_end()
509 if self.IP.rl_do_indent:
510 indentation = self.IP.input_splitter.indent_spaces *
' '
515 Key press callback used for correcting behavior
for console-like
516 interfaces. For example
'home' should go to prompt,
not to beginning of
519 @param widget: Widget that key press accored
in.
520 @param event: Event object
521 @return Return
True if event should
not trickle.
524 insert_iter = self.text_buffer.get_iter_at_mark(insert_mark)
525 selection_mark = self.text_buffer.get_selection_bound()
526 selection_iter = self.text_buffer.get_iter_at_mark(selection_mark)
528 if event.keyval == Gdk.KEY_Home:
529 if event.get_state() & Gdk.ModifierType.CONTROL_MASK
or event.get_state() & Gdk.ModifierType.MOD1_MASK:
531 elif event.get_state() & Gdk.ModifierType.SHIFT_MASK:
532 self.
text_buffer.move_mark(insert_mark, start_iter)
537 elif event.keyval == Gdk.KEY_Left:
538 insert_iter.backward_cursor_position()
539 if not insert_iter.editable(
True):
541 elif not event.string:
543 elif start_iter.compare(insert_iter) <= 0
and \
544 start_iter.compare(selection_iter) <= 0:
546 elif start_iter.compare(insert_iter) > 0
and \
547 start_iter.compare(selection_iter) > 0:
549 elif insert_iter.compare(selection_iter) < 0:
550 self.
text_buffer.move_mark(insert_mark, start_iter)
551 elif insert_iter.compare(selection_iter) > 0:
552 self.
text_buffer.move_mark(selection_mark, start_iter)
558 For some reason we can't extend onKeyPress directly (bug #500900).
559 @param event key press
581 Sub-class of both modified
IPython shell and L{ConsoleView} this makes
582 a GTK+ IPython console.
586 Initialize. Redirect I/O to console.
588 ConsoleView.__init__(self)
589 self.cout = StringIO()
590 IterableIPShell.__init__(self, cout=self.cout,cerr=self.cout,
600 Custom raw_input() replacement. Gets current line from console buffer.
602 @param prompt: Prompt to
print. Here
for compatibility
as replacement.
603 @return The current command line text.
607 raise KeyboardInterrupt
612 Key press callback with plenty of shell goodness, like history,
613 autocompletions, etc.
615 @param event: Event object.
616 @return True if event should
not trickle.
619 if event.get_state() & Gdk.ModifierType.CONTROL_MASK
and event.keyval == 99:
623 elif event.keyval == Gdk.KEY_Return:
626 elif event.keyval == Gdk.KEY_Up:
629 elif event.keyval == Gdk.KEY_Down:
632 elif event.keyval == Gdk.KEY_Tab:
636 if len(possibilities) > 1:
639 for symbol
in possibilities:
640 self.
write(symbol+
'\n')
647 Process current command line.
652 rv = self.cout.getvalue()
653 if rv: rv = rv.strip(
'\n')
655 self.
cout.truncate(0)
658if __name__ ==
"__main__":
659 window = Gtk.Window()
660 window.set_default_size(640, 320)
661 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.
dictionary 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.