2 Backend to the console plugin.
4 @author: Eitan Isaacson
5 @organization: IBM Corporation
6 @copyright: Copyright (c) 2007 IBM Corporation
9 All rights reserved. This program and the accompanying materials are made
10 available under the terms of the BSD which accompanies this distribution, and
11 is available at U{http://www.opensource.org/licenses/bsd-license.php}
20 from gi.repository
import Pango
21 from StringIO
import StringIO
24 from 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.
IPIP = IPython.terminal.embed.InteractiveShellEmbed.instance(\
103 config=cfg, user_ns=user_ns)
105 self.
IPIP = IPython.frontend.terminal.embed.InteractiveShellEmbed.instance(\
106 config=cfg, user_ns=user_ns)
108 sys.stdout, sys.stderr = old_stdout, old_stderr
110 self.
IPIP.system =
lambda cmd: self.
shellshell(self.
IPIP.var_expand(cmd),
111 header=
'IPython system call: ')
116 self.
IPIP.raw_input = input_func
117 sys.excepthook = excepthook
123 self.
IPIP.readline_startup_hook(self.
IPIP.pre_readline)
130 Update self.IP namespace for autocompletion with sys.modules
133 for k, v
in list(sys.modules.items()):
135 self.
IPIP.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.
IPIP.hooks.pre_prompt_hook()
155 self.
IPIP.showtraceback()
156 if self.
IPIP.autoindent:
157 self.
IPIP.rl_do_indent =
True
160 line = self.
IPIP.raw_input(self.
promptprompt)
161 except KeyboardInterrupt:
162 self.
IPIP.write(
'\nKeyboardInterrupt\n')
163 self.
IPIP.input_splitter.reset()
165 self.
IPIP.showtraceback()
167 self.
IPIP.input_splitter.push(line)
168 self.
iter_moreiter_more = self.
IPIP.input_splitter.push_accepts_more()
170 if (self.
IPIP.SyntaxTB.last_syntax_error
and
171 self.
IPIP.autoedit_syntax):
172 self.
IPIP.edit_syntax_error()
174 if parse_version(IPython.release.version) >= parse_version(
"2.0.0-dev"):
175 source_raw = self.
IPIP.input_splitter.raw_reset()
177 source_raw = self.
IPIP.input_splitter.source_raw_reset()[1]
178 self.
IPIP.run_cell(source_raw, store_history=
True)
179 self.
IPIP.rl_do_indent =
False
183 self.
IPIP.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.
IPIP.hooks.generate_prompt(is_continuation)
205 prompt = self.
IPIP.prompt_manager.render(
'in2')
207 prompt = self.
IPIP.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.
243 rv = self.
IPIP.user_ns[
'In'][self.
history_levelhistory_level].strip(
'\n')
250 Add the current dictionary to the shell namespace.
252 @param ns_dict: A dictionary of symbol-values.
255 self.
IPIP.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.
IPIP.
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.
331 @type text_buffer: Gtk.TextBuffer
332 @ivar color_pat: Regex of terminal color pattern
333 @type color_pat: _sre.SRE_Pattern
334 @ivar mark: Scroll mark for automatic scrolling on input.
335 @type mark: Gtk.TextMark
336 @ivar line_start: Start of command line mark.
337 @type line_start: Gtk.TextMark
339 ANSI_COLORS = {
'0;30':
'Black',
'0;31':
'Red',
340 '0;32':
'Green',
'0;33':
'Brown',
341 '0;34':
'Blue',
'0;35':
'Purple',
342 '0;36':
'Cyan',
'0;37':
'LightGray',
343 '1;30':
'DarkGray',
'1;31':
'DarkRed',
344 '1;32':
'SeaGreen',
'1;33':
'Yellow',
345 '1;34':
'LightBlue',
'1;35':
'MediumPurple',
346 '1;36':
'LightCyan',
'1;37':
'White'}
350 Initialize console view.
352 GObject.GObject.__init__(self)
353 self.modify_font(Pango.FontDescription(
'Mono'))
354 self.set_cursor_visible(
True)
364 self.
text_buffertext_buffer.create_tag(
'notouch', editable=
False)
365 self.
color_patcolor_pat = re.compile(
'\x01?\x1b\[(.*?)m\x02?')
367 self.
text_buffertext_buffer.create_mark(
'line_start',
369 self.connect(
'key-press-event', self.
onKeyPressonKeyPress)
371 def write(self, text, editable=False):
373 Write given text to buffer.
375 @param text: Text to append.
376 @param editable: If true, added text is editable.
379 GObject.idle_add(self.
_write_write, text, editable)
383 Write given text to buffer.
385 @param text: Text to append.
386 @param editable: If true, added text is editable.
389 segments = self.
color_patcolor_pat.split(text)
390 segment = segments.pop(0)
391 start_mark = self.
text_buffertext_buffer.create_mark(
None,
397 ansi_tags = self.
color_patcolor_pat.findall(text)
398 for tag
in ansi_tags:
399 i = segments.index(tag)
401 segments[i+1], str(tag))
404 self.
text_buffertext_buffer.apply_tag_by_name(
'notouch',
405 self.
text_buffertext_buffer.get_iter_at_mark(start_mark),
407 self.
text_buffertext_buffer.delete_mark(start_mark)
408 self.scroll_mark_onscreen(self.
markmark)
412 Prints prompt at start of line.
414 @param prompt: Prompt to print.
417 GObject.idle_add(self.
_showPrompt_showPrompt, prompt)
421 Prints prompt at start of line.
423 @param prompt: Prompt to print.
432 Replace currently entered command line with given text.
434 @param text: Text to use as replacement.
437 GObject.idle_add(self.
_changeLine_changeLine, text)
441 Replace currently entered command line with given text.
443 @param text: Text to use as replacement.
447 iter.forward_to_line_end()
449 self.
_write_write(text,
True)
453 Get text in current command line.
455 @return Text of current command line.
464 Show returned text from last command and print new prompt.
466 @param text: Text to show.
473 Show returned text from last command and print new prompt.
475 @param text: Text to show.
479 iter.forward_to_line_end()
484 self.
_write_write(
'\n'+text)
491 if self.IP.rl_do_indent:
492 indentation = self.IP.input_splitter.indent_spaces *
' '
493 self.
text_buffertext_buffer.insert_at_cursor(indentation)
497 Key press callback used for correcting behavior for console-like
498 interfaces. For example 'home' should go to prompt, not to beginning of
501 @param widget: Widget that key press accored in.
502 @param event: Event object
503 @return Return True if event should not trickle.
505 insert_mark = self.
text_buffertext_buffer.get_insert()
506 insert_iter = self.
text_buffertext_buffer.get_iter_at_mark(insert_mark)
507 selection_mark = self.
text_buffertext_buffer.get_selection_bound()
508 selection_iter = self.
text_buffertext_buffer.get_iter_at_mark(selection_mark)
510 if event.keyval == Gdk.KEY_Home:
511 if event.get_state() & Gdk.ModifierType.CONTROL_MASK
or event.get_state() & Gdk.ModifierType.MOD1_MASK:
513 elif event.get_state() & Gdk.ModifierType.SHIFT_MASK:
514 self.
text_buffertext_buffer.move_mark(insert_mark, start_iter)
517 self.
text_buffertext_buffer.place_cursor(start_iter)
519 elif event.keyval == Gdk.KEY_Left:
520 insert_iter.backward_cursor_position()
521 if not insert_iter.editable(
True):
523 elif not event.string:
525 elif start_iter.compare(insert_iter) <= 0
and \
526 start_iter.compare(selection_iter) <= 0:
528 elif start_iter.compare(insert_iter) > 0
and \
529 start_iter.compare(selection_iter) > 0:
530 self.
text_buffertext_buffer.place_cursor(start_iter)
531 elif insert_iter.compare(selection_iter) < 0:
532 self.
text_buffertext_buffer.move_mark(insert_mark, start_iter)
533 elif insert_iter.compare(selection_iter) > 0:
534 self.
text_buffertext_buffer.move_mark(selection_mark, start_iter)
540 For some reason we can't extend onKeyPress directly (bug #500900).
541 @param event key press
547 class IPythonView(ConsoleView, IterableIPShell):
563 Sub-class of both modified IPython shell and L{ConsoleView} this makes
564 a GTK+ IPython console.
568 Initialize. Redirect I/O to console.
570 ConsoleView.__init__(self)
572 IterableIPShell.__init__(self, cout=self.
coutcout,cerr=self.
coutcout,
577 self.
coutcout.truncate(0)
582 Custom raw_input() replacement. Gets current line from console buffer.
584 @param prompt: Prompt to print. Here for compatibility as replacement.
585 @return The current command line text.
589 raise KeyboardInterrupt
594 Key press callback with plenty of shell goodness, like history,
595 autocompletions, etc.
597 @param event: Event object.
598 @return True if event should not trickle.
601 if event.get_state() & Gdk.ModifierType.CONTROL_MASK
and event.keyval == 99:
605 elif event.keyval == Gdk.KEY_Return:
608 elif event.keyval == Gdk.KEY_Up:
611 elif event.keyval == Gdk.KEY_Down:
614 elif event.keyval == Gdk.KEY_Tab:
618 if len(possibilities) > 1:
620 self.
writewrite(
'\n')
621 for symbol
in possibilities:
622 self.
writewrite(symbol+
'\n')
629 Process current command line.
634 rv = self.
coutcout.getvalue()
635 if rv: rv = rv.strip(
'\n')
637 self.
coutcout.truncate(0)
638 self.
coutcout.seek(0)
640 if __name__ ==
"__main__":
641 window = Gtk.Window()
642 window.set_default_size(640, 320)
643 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.