PageRenderTime 99ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/IPython/frontend/qt/console/ipython_widget.py

https://github.com/cboos/ipython
Python | 563 lines | 542 code | 6 blank | 15 comment | 0 complexity | d19e81db63e64308bbb73dd51ebac196 MD5 | raw file
  1. """ A FrontendWidget that emulates the interface of the console IPython and
  2. supports the additional functionality provided by the IPython kernel.
  3. """
  4. #-----------------------------------------------------------------------------
  5. # Imports
  6. #-----------------------------------------------------------------------------
  7. # Standard library imports
  8. from collections import namedtuple
  9. import os.path
  10. import re
  11. from subprocess import Popen
  12. import sys
  13. import time
  14. from textwrap import dedent
  15. # System library imports
  16. from IPython.external.qt import QtCore, QtGui
  17. # Local imports
  18. from IPython.core.inputsplitter import IPythonInputSplitter, \
  19. transform_ipy_prompt
  20. from IPython.utils.traitlets import Bool, Unicode
  21. from frontend_widget import FrontendWidget
  22. import styles
  23. #-----------------------------------------------------------------------------
  24. # Constants
  25. #-----------------------------------------------------------------------------
  26. # Default strings to build and display input and output prompts (and separators
  27. # in between)
  28. default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: '
  29. default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: '
  30. default_input_sep = '\n'
  31. default_output_sep = ''
  32. default_output_sep2 = ''
  33. # Base path for most payload sources.
  34. zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell'
  35. if sys.platform.startswith('win'):
  36. default_editor = 'notepad'
  37. else:
  38. default_editor = ''
  39. #-----------------------------------------------------------------------------
  40. # IPythonWidget class
  41. #-----------------------------------------------------------------------------
  42. class IPythonWidget(FrontendWidget):
  43. """ A FrontendWidget for an IPython kernel.
  44. """
  45. # If set, the 'custom_edit_requested(str, int)' signal will be emitted when
  46. # an editor is needed for a file. This overrides 'editor' and 'editor_line'
  47. # settings.
  48. custom_edit = Bool(False)
  49. custom_edit_requested = QtCore.Signal(object, object)
  50. editor = Unicode(default_editor, config=True,
  51. help="""
  52. A command for invoking a system text editor. If the string contains a
  53. {filename} format specifier, it will be used. Otherwise, the filename
  54. will be appended to the end the command.
  55. """)
  56. editor_line = Unicode(config=True,
  57. help="""
  58. The editor command to use when a specific line number is requested. The
  59. string should contain two format specifiers: {line} and {filename}. If
  60. this parameter is not specified, the line number option to the %edit
  61. magic will be ignored.
  62. """)
  63. style_sheet = Unicode(config=True,
  64. help="""
  65. A CSS stylesheet. The stylesheet can contain classes for:
  66. 1. Qt: QPlainTextEdit, QFrame, QWidget, etc
  67. 2. Pygments: .c, .k, .o, etc. (see PygmentsHighlighter)
  68. 3. IPython: .error, .in-prompt, .out-prompt, etc
  69. """)
  70. syntax_style = Unicode(config=True,
  71. help="""
  72. If not empty, use this Pygments style for syntax highlighting.
  73. Otherwise, the style sheet is queried for Pygments style
  74. information.
  75. """)
  76. # Prompts.
  77. in_prompt = Unicode(default_in_prompt, config=True)
  78. out_prompt = Unicode(default_out_prompt, config=True)
  79. input_sep = Unicode(default_input_sep, config=True)
  80. output_sep = Unicode(default_output_sep, config=True)
  81. output_sep2 = Unicode(default_output_sep2, config=True)
  82. # FrontendWidget protected class variables.
  83. _input_splitter_class = IPythonInputSplitter
  84. # IPythonWidget protected class variables.
  85. _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number'])
  86. _payload_source_edit = zmq_shell_source + '.edit_magic'
  87. _payload_source_exit = zmq_shell_source + '.ask_exit'
  88. _payload_source_next_input = zmq_shell_source + '.set_next_input'
  89. _payload_source_page = 'IPython.zmq.page.page'
  90. _retrying_history_request = False
  91. #---------------------------------------------------------------------------
  92. # 'object' interface
  93. #---------------------------------------------------------------------------
  94. def __init__(self, *args, **kw):
  95. super(IPythonWidget, self).__init__(*args, **kw)
  96. # IPythonWidget protected variables.
  97. self._payload_handlers = {
  98. self._payload_source_edit : self._handle_payload_edit,
  99. self._payload_source_exit : self._handle_payload_exit,
  100. self._payload_source_page : self._handle_payload_page,
  101. self._payload_source_next_input : self._handle_payload_next_input }
  102. self._previous_prompt_obj = None
  103. self._keep_kernel_on_exit = None
  104. # Initialize widget styling.
  105. if self.style_sheet:
  106. self._style_sheet_changed()
  107. self._syntax_style_changed()
  108. else:
  109. self.set_default_style()
  110. #---------------------------------------------------------------------------
  111. # 'BaseFrontendMixin' abstract interface
  112. #---------------------------------------------------------------------------
  113. def _handle_complete_reply(self, rep):
  114. """ Reimplemented to support IPython's improved completion machinery.
  115. """
  116. self.log.debug("complete: %s", rep.get('content', ''))
  117. cursor = self._get_cursor()
  118. info = self._request_info.get('complete')
  119. if info and info.id == rep['parent_header']['msg_id'] and \
  120. info.pos == cursor.position():
  121. matches = rep['content']['matches']
  122. text = rep['content']['matched_text']
  123. offset = len(text)
  124. # Clean up matches with period and path separators if the matched
  125. # text has not been transformed. This is done by truncating all
  126. # but the last component and then suitably decreasing the offset
  127. # between the current cursor position and the start of completion.
  128. if len(matches) > 1 and matches[0][:offset] == text:
  129. parts = re.split(r'[./\\]', text)
  130. sep_count = len(parts) - 1
  131. if sep_count:
  132. chop_length = sum(map(len, parts[:sep_count])) + sep_count
  133. matches = [ match[chop_length:] for match in matches ]
  134. offset -= chop_length
  135. # Move the cursor to the start of the match and complete.
  136. cursor.movePosition(QtGui.QTextCursor.Left, n=offset)
  137. self._complete_with_items(cursor, matches)
  138. def _handle_execute_reply(self, msg):
  139. """ Reimplemented to support prompt requests.
  140. """
  141. msg_id = msg['parent_header'].get('msg_id')
  142. info = self._request_info['execute'].get(msg_id)
  143. if info and info.kind == 'prompt':
  144. number = msg['content']['execution_count'] + 1
  145. self._show_interpreter_prompt(number)
  146. self._request_info['execute'].pop(msg_id)
  147. else:
  148. super(IPythonWidget, self)._handle_execute_reply(msg)
  149. def _handle_history_reply(self, msg):
  150. """ Implemented to handle history tail replies, which are only supported
  151. by the IPython kernel.
  152. """
  153. self.log.debug("history: %s", msg.get('content', ''))
  154. content = msg['content']
  155. if 'history' not in content:
  156. self.log.error("History request failed: %r"%content)
  157. if content.get('status', '') == 'aborted' and \
  158. not self._retrying_history_request:
  159. # a *different* action caused this request to be aborted, so
  160. # we should try again.
  161. self.log.error("Retrying aborted history request")
  162. # prevent multiple retries of aborted requests:
  163. self._retrying_history_request = True
  164. # wait out the kernel's queue flush, which is currently timed at 0.1s
  165. time.sleep(0.25)
  166. self.kernel_manager.shell_channel.history(hist_access_type='tail',n=1000)
  167. else:
  168. self._retrying_history_request = False
  169. return
  170. # reset retry flag
  171. self._retrying_history_request = False
  172. history_items = content['history']
  173. items = []
  174. last_cell = u""
  175. for _, _, cell in history_items:
  176. cell = cell.rstrip()
  177. if cell != last_cell:
  178. items.append(cell)
  179. last_cell = cell
  180. self._set_history(items)
  181. def _handle_pyout(self, msg):
  182. """ Reimplemented for IPython-style "display hook".
  183. """
  184. self.log.debug("pyout: %s", msg.get('content', ''))
  185. if not self._hidden and self._is_from_this_session(msg):
  186. content = msg['content']
  187. prompt_number = content['execution_count']
  188. data = content['data']
  189. if data.has_key('text/html'):
  190. self._append_plain_text(self.output_sep, True)
  191. self._append_html(self._make_out_prompt(prompt_number), True)
  192. html = data['text/html']
  193. self._append_plain_text('\n', True)
  194. self._append_html(html + self.output_sep2, True)
  195. elif data.has_key('text/plain'):
  196. self._append_plain_text(self.output_sep, True)
  197. self._append_html(self._make_out_prompt(prompt_number), True)
  198. text = data['text/plain']
  199. # If the repr is multiline, make sure we start on a new line,
  200. # so that its lines are aligned.
  201. if "\n" in text and not self.output_sep.endswith("\n"):
  202. self._append_plain_text('\n', True)
  203. self._append_plain_text(text + self.output_sep2, True)
  204. def _handle_display_data(self, msg):
  205. """ The base handler for the ``display_data`` message.
  206. """
  207. self.log.debug("display: %s", msg.get('content', ''))
  208. # For now, we don't display data from other frontends, but we
  209. # eventually will as this allows all frontends to monitor the display
  210. # data. But we need to figure out how to handle this in the GUI.
  211. if not self._hidden and self._is_from_this_session(msg):
  212. source = msg['content']['source']
  213. data = msg['content']['data']
  214. metadata = msg['content']['metadata']
  215. # In the regular IPythonWidget, we simply print the plain text
  216. # representation.
  217. if data.has_key('text/html'):
  218. html = data['text/html']
  219. self._append_html(html, True)
  220. elif data.has_key('text/plain'):
  221. text = data['text/plain']
  222. self._append_plain_text(text, True)
  223. # This newline seems to be needed for text and html output.
  224. self._append_plain_text(u'\n', True)
  225. def _started_channels(self):
  226. """ Reimplemented to make a history request.
  227. """
  228. super(IPythonWidget, self)._started_channels()
  229. self.kernel_manager.shell_channel.history(hist_access_type='tail',
  230. n=1000)
  231. #---------------------------------------------------------------------------
  232. # 'ConsoleWidget' public interface
  233. #---------------------------------------------------------------------------
  234. def copy(self):
  235. """ Copy the currently selected text to the clipboard, removing prompts
  236. if possible.
  237. """
  238. text = self._control.textCursor().selection().toPlainText()
  239. if text:
  240. lines = map(transform_ipy_prompt, text.splitlines())
  241. text = '\n'.join(lines)
  242. QtGui.QApplication.clipboard().setText(text)
  243. #---------------------------------------------------------------------------
  244. # 'FrontendWidget' public interface
  245. #---------------------------------------------------------------------------
  246. def execute_file(self, path, hidden=False):
  247. """ Reimplemented to use the 'run' magic.
  248. """
  249. # Use forward slashes on Windows to avoid escaping each separator.
  250. if sys.platform == 'win32':
  251. path = os.path.normpath(path).replace('\\', '/')
  252. # Perhaps we should not be using %run directly, but while we
  253. # are, it is necessary to quote filenames containing spaces or quotes.
  254. # Escaping quotes in filename in %run seems tricky and inconsistent,
  255. # so not trying it at present.
  256. if '"' in path:
  257. if "'" in path:
  258. raise ValueError("Can't run filename containing both single "
  259. "and double quotes: %s" % path)
  260. path = "'%s'" % path
  261. elif ' ' in path or "'" in path:
  262. path = '"%s"' % path
  263. self.execute('%%run %s' % path, hidden=hidden)
  264. #---------------------------------------------------------------------------
  265. # 'FrontendWidget' protected interface
  266. #---------------------------------------------------------------------------
  267. def _complete(self):
  268. """ Reimplemented to support IPython's improved completion machinery.
  269. """
  270. # We let the kernel split the input line, so we *always* send an empty
  271. # text field. Readline-based frontends do get a real text field which
  272. # they can use.
  273. text = ''
  274. # Send the completion request to the kernel
  275. msg_id = self.kernel_manager.shell_channel.complete(
  276. text, # text
  277. self._get_input_buffer_cursor_line(), # line
  278. self._get_input_buffer_cursor_column(), # cursor_pos
  279. self.input_buffer) # block
  280. pos = self._get_cursor().position()
  281. info = self._CompletionRequest(msg_id, pos)
  282. self._request_info['complete'] = info
  283. def _process_execute_error(self, msg):
  284. """ Reimplemented for IPython-style traceback formatting.
  285. """
  286. content = msg['content']
  287. traceback = '\n'.join(content['traceback']) + '\n'
  288. if False:
  289. # FIXME: For now, tracebacks come as plain text, so we can't use
  290. # the html renderer yet. Once we refactor ultratb to produce
  291. # properly styled tracebacks, this branch should be the default
  292. traceback = traceback.replace(' ', '&nbsp;')
  293. traceback = traceback.replace('\n', '<br/>')
  294. ename = content['ename']
  295. ename_styled = '<span class="error">%s</span>' % ename
  296. traceback = traceback.replace(ename, ename_styled)
  297. self._append_html(traceback)
  298. else:
  299. # This is the fallback for now, using plain text with ansi escapes
  300. self._append_plain_text(traceback)
  301. def _process_execute_payload(self, item):
  302. """ Reimplemented to dispatch payloads to handler methods.
  303. """
  304. handler = self._payload_handlers.get(item['source'])
  305. if handler is None:
  306. # We have no handler for this type of payload, simply ignore it
  307. return False
  308. else:
  309. handler(item)
  310. return True
  311. def _show_interpreter_prompt(self, number=None):
  312. """ Reimplemented for IPython-style prompts.
  313. """
  314. # If a number was not specified, make a prompt number request.
  315. if number is None:
  316. msg_id = self.kernel_manager.shell_channel.execute('', silent=True)
  317. info = self._ExecutionRequest(msg_id, 'prompt')
  318. self._request_info['execute'][msg_id] = info
  319. return
  320. # Show a new prompt and save information about it so that it can be
  321. # updated later if the prompt number turns out to be wrong.
  322. self._prompt_sep = self.input_sep
  323. self._show_prompt(self._make_in_prompt(number), html=True)
  324. block = self._control.document().lastBlock()
  325. length = len(self._prompt)
  326. self._previous_prompt_obj = self._PromptBlock(block, length, number)
  327. # Update continuation prompt to reflect (possibly) new prompt length.
  328. self._set_continuation_prompt(
  329. self._make_continuation_prompt(self._prompt), html=True)
  330. def _show_interpreter_prompt_for_reply(self, msg):
  331. """ Reimplemented for IPython-style prompts.
  332. """
  333. # Update the old prompt number if necessary.
  334. content = msg['content']
  335. # abort replies do not have any keys:
  336. if content['status'] == 'aborted':
  337. if self._previous_prompt_obj:
  338. previous_prompt_number = self._previous_prompt_obj.number
  339. else:
  340. previous_prompt_number = 0
  341. else:
  342. previous_prompt_number = content['execution_count']
  343. if self._previous_prompt_obj and \
  344. self._previous_prompt_obj.number != previous_prompt_number:
  345. block = self._previous_prompt_obj.block
  346. # Make sure the prompt block has not been erased.
  347. if block.isValid() and block.text():
  348. # Remove the old prompt and insert a new prompt.
  349. cursor = QtGui.QTextCursor(block)
  350. cursor.movePosition(QtGui.QTextCursor.Right,
  351. QtGui.QTextCursor.KeepAnchor,
  352. self._previous_prompt_obj.length)
  353. prompt = self._make_in_prompt(previous_prompt_number)
  354. self._prompt = self._insert_html_fetching_plain_text(
  355. cursor, prompt)
  356. # When the HTML is inserted, Qt blows away the syntax
  357. # highlighting for the line, so we need to rehighlight it.
  358. self._highlighter.rehighlightBlock(cursor.block())
  359. self._previous_prompt_obj = None
  360. # Show a new prompt with the kernel's estimated prompt number.
  361. self._show_interpreter_prompt(previous_prompt_number + 1)
  362. #---------------------------------------------------------------------------
  363. # 'IPythonWidget' interface
  364. #---------------------------------------------------------------------------
  365. def set_default_style(self, colors='lightbg'):
  366. """ Sets the widget style to the class defaults.
  367. Parameters:
  368. -----------
  369. colors : str, optional (default lightbg)
  370. Whether to use the default IPython light background or dark
  371. background or B&W style.
  372. """
  373. colors = colors.lower()
  374. if colors=='lightbg':
  375. self.style_sheet = styles.default_light_style_sheet
  376. self.syntax_style = styles.default_light_syntax_style
  377. elif colors=='linux':
  378. self.style_sheet = styles.default_dark_style_sheet
  379. self.syntax_style = styles.default_dark_syntax_style
  380. elif colors=='nocolor':
  381. self.style_sheet = styles.default_bw_style_sheet
  382. self.syntax_style = styles.default_bw_syntax_style
  383. else:
  384. raise KeyError("No such color scheme: %s"%colors)
  385. #---------------------------------------------------------------------------
  386. # 'IPythonWidget' protected interface
  387. #---------------------------------------------------------------------------
  388. def _edit(self, filename, line=None):
  389. """ Opens a Python script for editing.
  390. Parameters:
  391. -----------
  392. filename : str
  393. A path to a local system file.
  394. line : int, optional
  395. A line of interest in the file.
  396. """
  397. if self.custom_edit:
  398. self.custom_edit_requested.emit(filename, line)
  399. elif not self.editor:
  400. self._append_plain_text('No default editor available.\n'
  401. 'Specify a GUI text editor in the `IPythonWidget.editor` '
  402. 'configurable to enable the %edit magic')
  403. else:
  404. try:
  405. filename = '"%s"' % filename
  406. if line and self.editor_line:
  407. command = self.editor_line.format(filename=filename,
  408. line=line)
  409. else:
  410. try:
  411. command = self.editor.format()
  412. except KeyError:
  413. command = self.editor.format(filename=filename)
  414. else:
  415. command += ' ' + filename
  416. except KeyError:
  417. self._append_plain_text('Invalid editor command.\n')
  418. else:
  419. try:
  420. Popen(command, shell=True)
  421. except OSError:
  422. msg = 'Opening editor with command "%s" failed.\n'
  423. self._append_plain_text(msg % command)
  424. def _make_in_prompt(self, number):
  425. """ Given a prompt number, returns an HTML In prompt.
  426. """
  427. try:
  428. body = self.in_prompt % number
  429. except TypeError:
  430. # allow in_prompt to leave out number, e.g. '>>> '
  431. body = self.in_prompt
  432. return '<span class="in-prompt">%s</span>' % body
  433. def _make_continuation_prompt(self, prompt):
  434. """ Given a plain text version of an In prompt, returns an HTML
  435. continuation prompt.
  436. """
  437. end_chars = '...: '
  438. space_count = len(prompt.lstrip('\n')) - len(end_chars)
  439. body = '&nbsp;' * space_count + end_chars
  440. return '<span class="in-prompt">%s</span>' % body
  441. def _make_out_prompt(self, number):
  442. """ Given a prompt number, returns an HTML Out prompt.
  443. """
  444. body = self.out_prompt % number
  445. return '<span class="out-prompt">%s</span>' % body
  446. #------ Payload handlers --------------------------------------------------
  447. # Payload handlers with a generic interface: each takes the opaque payload
  448. # dict, unpacks it and calls the underlying functions with the necessary
  449. # arguments.
  450. def _handle_payload_edit(self, item):
  451. self._edit(item['filename'], item['line_number'])
  452. def _handle_payload_exit(self, item):
  453. self._keep_kernel_on_exit = item['keepkernel']
  454. self.exit_requested.emit(self)
  455. def _handle_payload_next_input(self, item):
  456. self.input_buffer = dedent(item['text'].rstrip())
  457. def _handle_payload_page(self, item):
  458. # Since the plain text widget supports only a very small subset of HTML
  459. # and we have no control over the HTML source, we only page HTML
  460. # payloads in the rich text widget.
  461. if item['html'] and self.kind == 'rich':
  462. self._page(item['html'], html=True)
  463. else:
  464. self._page(item['text'], html=False)
  465. #------ Trait change handlers --------------------------------------------
  466. def _style_sheet_changed(self):
  467. """ Set the style sheets of the underlying widgets.
  468. """
  469. self.setStyleSheet(self.style_sheet)
  470. self._control.document().setDefaultStyleSheet(self.style_sheet)
  471. if self._page_control:
  472. self._page_control.document().setDefaultStyleSheet(self.style_sheet)
  473. bg_color = self._control.palette().window().color()
  474. self._ansi_processor.set_background_color(bg_color)
  475. def _syntax_style_changed(self):
  476. """ Set the style for the syntax highlighter.
  477. """
  478. if self._highlighter is None:
  479. # ignore premature calls
  480. return
  481. if self.syntax_style:
  482. self._highlighter.set_style(self.syntax_style)
  483. else:
  484. self._highlighter.set_style_sheet(self.style_sheet)
  485. #------ Trait default initializers -----------------------------------------
  486. def _banner_default(self):
  487. from IPython.core.usage import default_gui_banner
  488. return default_gui_banner