PageRenderTime 57ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://github.com/tinyclues/ipython
Python | 549 lines | 528 code | 6 blank | 15 comment | 0 complexity | 45919ad855495b467a8b5a6efa773298 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. info = self._request_info.get('execute')
  142. if info and info.id == msg['parent_header']['msg_id']:
  143. if info.kind == 'prompt':
  144. number = msg['content']['execution_count'] + 1
  145. self._show_interpreter_prompt(number)
  146. else:
  147. super(IPythonWidget, self)._handle_execute_reply(msg)
  148. def _handle_history_reply(self, msg):
  149. """ Implemented to handle history tail replies, which are only supported
  150. by the IPython kernel.
  151. """
  152. self.log.debug("history: %s", msg.get('content', ''))
  153. content = msg['content']
  154. if 'history' not in content:
  155. self.log.error("History request failed: %r"%content)
  156. if content.get('status', '') == 'aborted' and \
  157. not self._retrying_history_request:
  158. # a *different* action caused this request to be aborted, so
  159. # we should try again.
  160. self.log.error("Retrying aborted history request")
  161. # prevent multiple retries of aborted requests:
  162. self._retrying_history_request = True
  163. # wait out the kernel's queue flush, which is currently timed at 0.1s
  164. time.sleep(0.25)
  165. self.kernel_manager.shell_channel.history(hist_access_type='tail',n=1000)
  166. else:
  167. self._retrying_history_request = False
  168. return
  169. # reset retry flag
  170. self._retrying_history_request = False
  171. history_items = content['history']
  172. items = [ line.rstrip() for _, _, line in history_items ]
  173. self._set_history(items)
  174. def _handle_pyout(self, msg):
  175. """ Reimplemented for IPython-style "display hook".
  176. """
  177. self.log.debug("pyout: %s", msg.get('content', ''))
  178. if not self._hidden and self._is_from_this_session(msg):
  179. content = msg['content']
  180. prompt_number = content['execution_count']
  181. data = content['data']
  182. if data.has_key('text/html'):
  183. self._append_plain_text(self.output_sep, True)
  184. self._append_html(self._make_out_prompt(prompt_number), True)
  185. html = data['text/html']
  186. self._append_plain_text('\n', True)
  187. self._append_html(html + self.output_sep2, True)
  188. elif data.has_key('text/plain'):
  189. self._append_plain_text(self.output_sep, True)
  190. self._append_html(self._make_out_prompt(prompt_number), True)
  191. text = data['text/plain']
  192. # If the repr is multiline, make sure we start on a new line,
  193. # so that its lines are aligned.
  194. if "\n" in text and not self.output_sep.endswith("\n"):
  195. self._append_plain_text('\n', True)
  196. self._append_plain_text(text + self.output_sep2, True)
  197. def _handle_display_data(self, msg):
  198. """ The base handler for the ``display_data`` message.
  199. """
  200. self.log.debug("display: %s", msg.get('content', ''))
  201. # For now, we don't display data from other frontends, but we
  202. # eventually will as this allows all frontends to monitor the display
  203. # data. But we need to figure out how to handle this in the GUI.
  204. if not self._hidden and self._is_from_this_session(msg):
  205. source = msg['content']['source']
  206. data = msg['content']['data']
  207. metadata = msg['content']['metadata']
  208. # In the regular IPythonWidget, we simply print the plain text
  209. # representation.
  210. if data.has_key('text/html'):
  211. html = data['text/html']
  212. self._append_html(html, True)
  213. elif data.has_key('text/plain'):
  214. text = data['text/plain']
  215. self._append_plain_text(text, True)
  216. # This newline seems to be needed for text and html output.
  217. self._append_plain_text(u'\n', True)
  218. def _started_channels(self):
  219. """ Reimplemented to make a history request.
  220. """
  221. super(IPythonWidget, self)._started_channels()
  222. self.kernel_manager.shell_channel.history(hist_access_type='tail',
  223. n=1000)
  224. #---------------------------------------------------------------------------
  225. # 'ConsoleWidget' public interface
  226. #---------------------------------------------------------------------------
  227. def copy(self):
  228. """ Copy the currently selected text to the clipboard, removing prompts
  229. if possible.
  230. """
  231. text = self._control.textCursor().selection().toPlainText()
  232. if text:
  233. lines = map(transform_ipy_prompt, text.splitlines())
  234. text = '\n'.join(lines)
  235. QtGui.QApplication.clipboard().setText(text)
  236. #---------------------------------------------------------------------------
  237. # 'FrontendWidget' public interface
  238. #---------------------------------------------------------------------------
  239. def execute_file(self, path, hidden=False):
  240. """ Reimplemented to use the 'run' magic.
  241. """
  242. # Use forward slashes on Windows to avoid escaping each separator.
  243. if sys.platform == 'win32':
  244. path = os.path.normpath(path).replace('\\', '/')
  245. # Perhaps we should not be using %run directly, but while we
  246. # are, it is necessary to quote filenames containing spaces or quotes.
  247. # Escaping quotes in filename in %run seems tricky and inconsistent,
  248. # so not trying it at present.
  249. if '"' in path:
  250. if "'" in path:
  251. raise ValueError("Can't run filename containing both single "
  252. "and double quotes: %s" % path)
  253. path = "'%s'" % path
  254. elif ' ' in path or "'" in path:
  255. path = '"%s"' % path
  256. self.execute('%%run %s' % path, hidden=hidden)
  257. #---------------------------------------------------------------------------
  258. # 'FrontendWidget' protected interface
  259. #---------------------------------------------------------------------------
  260. def _complete(self):
  261. """ Reimplemented to support IPython's improved completion machinery.
  262. """
  263. # We let the kernel split the input line, so we *always* send an empty
  264. # text field. Readline-based frontends do get a real text field which
  265. # they can use.
  266. text = ''
  267. # Send the completion request to the kernel
  268. msg_id = self.kernel_manager.shell_channel.complete(
  269. text, # text
  270. self._get_input_buffer_cursor_line(), # line
  271. self._get_input_buffer_cursor_column(), # cursor_pos
  272. self.input_buffer) # block
  273. pos = self._get_cursor().position()
  274. info = self._CompletionRequest(msg_id, pos)
  275. self._request_info['complete'] = info
  276. def _process_execute_error(self, msg):
  277. """ Reimplemented for IPython-style traceback formatting.
  278. """
  279. content = msg['content']
  280. traceback = '\n'.join(content['traceback']) + '\n'
  281. if False:
  282. # FIXME: For now, tracebacks come as plain text, so we can't use
  283. # the html renderer yet. Once we refactor ultratb to produce
  284. # properly styled tracebacks, this branch should be the default
  285. traceback = traceback.replace(' ', '&nbsp;')
  286. traceback = traceback.replace('\n', '<br/>')
  287. ename = content['ename']
  288. ename_styled = '<span class="error">%s</span>' % ename
  289. traceback = traceback.replace(ename, ename_styled)
  290. self._append_html(traceback)
  291. else:
  292. # This is the fallback for now, using plain text with ansi escapes
  293. self._append_plain_text(traceback)
  294. def _process_execute_payload(self, item):
  295. """ Reimplemented to dispatch payloads to handler methods.
  296. """
  297. handler = self._payload_handlers.get(item['source'])
  298. if handler is None:
  299. # We have no handler for this type of payload, simply ignore it
  300. return False
  301. else:
  302. handler(item)
  303. return True
  304. def _show_interpreter_prompt(self, number=None):
  305. """ Reimplemented for IPython-style prompts.
  306. """
  307. # If a number was not specified, make a prompt number request.
  308. if number is None:
  309. msg_id = self.kernel_manager.shell_channel.execute('', silent=True)
  310. info = self._ExecutionRequest(msg_id, 'prompt')
  311. self._request_info['execute'] = info
  312. return
  313. # Show a new prompt and save information about it so that it can be
  314. # updated later if the prompt number turns out to be wrong.
  315. self._prompt_sep = self.input_sep
  316. self._show_prompt(self._make_in_prompt(number), html=True)
  317. block = self._control.document().lastBlock()
  318. length = len(self._prompt)
  319. self._previous_prompt_obj = self._PromptBlock(block, length, number)
  320. # Update continuation prompt to reflect (possibly) new prompt length.
  321. self._set_continuation_prompt(
  322. self._make_continuation_prompt(self._prompt), html=True)
  323. def _show_interpreter_prompt_for_reply(self, msg):
  324. """ Reimplemented for IPython-style prompts.
  325. """
  326. # Update the old prompt number if necessary.
  327. content = msg['content']
  328. previous_prompt_number = content['execution_count']
  329. if self._previous_prompt_obj and \
  330. self._previous_prompt_obj.number != previous_prompt_number:
  331. block = self._previous_prompt_obj.block
  332. # Make sure the prompt block has not been erased.
  333. if block.isValid() and block.text():
  334. # Remove the old prompt and insert a new prompt.
  335. cursor = QtGui.QTextCursor(block)
  336. cursor.movePosition(QtGui.QTextCursor.Right,
  337. QtGui.QTextCursor.KeepAnchor,
  338. self._previous_prompt_obj.length)
  339. prompt = self._make_in_prompt(previous_prompt_number)
  340. self._prompt = self._insert_html_fetching_plain_text(
  341. cursor, prompt)
  342. # When the HTML is inserted, Qt blows away the syntax
  343. # highlighting for the line, so we need to rehighlight it.
  344. self._highlighter.rehighlightBlock(cursor.block())
  345. self._previous_prompt_obj = None
  346. # Show a new prompt with the kernel's estimated prompt number.
  347. self._show_interpreter_prompt(previous_prompt_number + 1)
  348. #---------------------------------------------------------------------------
  349. # 'IPythonWidget' interface
  350. #---------------------------------------------------------------------------
  351. def set_default_style(self, colors='lightbg'):
  352. """ Sets the widget style to the class defaults.
  353. Parameters:
  354. -----------
  355. colors : str, optional (default lightbg)
  356. Whether to use the default IPython light background or dark
  357. background or B&W style.
  358. """
  359. colors = colors.lower()
  360. if colors=='lightbg':
  361. self.style_sheet = styles.default_light_style_sheet
  362. self.syntax_style = styles.default_light_syntax_style
  363. elif colors=='linux':
  364. self.style_sheet = styles.default_dark_style_sheet
  365. self.syntax_style = styles.default_dark_syntax_style
  366. elif colors=='nocolor':
  367. self.style_sheet = styles.default_bw_style_sheet
  368. self.syntax_style = styles.default_bw_syntax_style
  369. else:
  370. raise KeyError("No such color scheme: %s"%colors)
  371. #---------------------------------------------------------------------------
  372. # 'IPythonWidget' protected interface
  373. #---------------------------------------------------------------------------
  374. def _edit(self, filename, line=None):
  375. """ Opens a Python script for editing.
  376. Parameters:
  377. -----------
  378. filename : str
  379. A path to a local system file.
  380. line : int, optional
  381. A line of interest in the file.
  382. """
  383. if self.custom_edit:
  384. self.custom_edit_requested.emit(filename, line)
  385. elif not self.editor:
  386. self._append_plain_text('No default editor available.\n'
  387. 'Specify a GUI text editor in the `IPythonWidget.editor` '
  388. 'configurable to enable the %edit magic')
  389. else:
  390. try:
  391. filename = '"%s"' % filename
  392. if line and self.editor_line:
  393. command = self.editor_line.format(filename=filename,
  394. line=line)
  395. else:
  396. try:
  397. command = self.editor.format()
  398. except KeyError:
  399. command = self.editor.format(filename=filename)
  400. else:
  401. command += ' ' + filename
  402. except KeyError:
  403. self._append_plain_text('Invalid editor command.\n')
  404. else:
  405. try:
  406. Popen(command, shell=True)
  407. except OSError:
  408. msg = 'Opening editor with command "%s" failed.\n'
  409. self._append_plain_text(msg % command)
  410. def _make_in_prompt(self, number):
  411. """ Given a prompt number, returns an HTML In prompt.
  412. """
  413. try:
  414. body = self.in_prompt % number
  415. except TypeError:
  416. # allow in_prompt to leave out number, e.g. '>>> '
  417. body = self.in_prompt
  418. return '<span class="in-prompt">%s</span>' % body
  419. def _make_continuation_prompt(self, prompt):
  420. """ Given a plain text version of an In prompt, returns an HTML
  421. continuation prompt.
  422. """
  423. end_chars = '...: '
  424. space_count = len(prompt.lstrip('\n')) - len(end_chars)
  425. body = '&nbsp;' * space_count + end_chars
  426. return '<span class="in-prompt">%s</span>' % body
  427. def _make_out_prompt(self, number):
  428. """ Given a prompt number, returns an HTML Out prompt.
  429. """
  430. body = self.out_prompt % number
  431. return '<span class="out-prompt">%s</span>' % body
  432. #------ Payload handlers --------------------------------------------------
  433. # Payload handlers with a generic interface: each takes the opaque payload
  434. # dict, unpacks it and calls the underlying functions with the necessary
  435. # arguments.
  436. def _handle_payload_edit(self, item):
  437. self._edit(item['filename'], item['line_number'])
  438. def _handle_payload_exit(self, item):
  439. self._keep_kernel_on_exit = item['keepkernel']
  440. self.exit_requested.emit()
  441. def _handle_payload_next_input(self, item):
  442. self.input_buffer = dedent(item['text'].rstrip())
  443. def _handle_payload_page(self, item):
  444. # Since the plain text widget supports only a very small subset of HTML
  445. # and we have no control over the HTML source, we only page HTML
  446. # payloads in the rich text widget.
  447. if item['html'] and self.kind == 'rich':
  448. self._page(item['html'], html=True)
  449. else:
  450. self._page(item['text'], html=False)
  451. #------ Trait change handlers --------------------------------------------
  452. def _style_sheet_changed(self):
  453. """ Set the style sheets of the underlying widgets.
  454. """
  455. self.setStyleSheet(self.style_sheet)
  456. self._control.document().setDefaultStyleSheet(self.style_sheet)
  457. if self._page_control:
  458. self._page_control.document().setDefaultStyleSheet(self.style_sheet)
  459. bg_color = self._control.palette().window().color()
  460. self._ansi_processor.set_background_color(bg_color)
  461. def _syntax_style_changed(self):
  462. """ Set the style for the syntax highlighter.
  463. """
  464. if self._highlighter is None:
  465. # ignore premature calls
  466. return
  467. if self.syntax_style:
  468. self._highlighter.set_style(self.syntax_style)
  469. else:
  470. self._highlighter.set_style_sheet(self.style_sheet)
  471. #------ Trait default initializers -----------------------------------------
  472. def _banner_default(self):
  473. from IPython.core.usage import default_gui_banner
  474. return default_gui_banner