console_widget.py 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458
  1. """An abstract base class for console-type widgets."""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from functools import partial
  5. import os
  6. import os.path
  7. import re
  8. import sys
  9. from textwrap import dedent
  10. import time
  11. from unicodedata import category
  12. import webbrowser
  13. from qtpy import QtCore, QtGui, QtPrintSupport, QtWidgets
  14. from traitlets.config.configurable import LoggingConfigurable
  15. from qtconsole.rich_text import HtmlExporter
  16. from qtconsole.util import MetaQObjectHasTraits, get_font, superQ
  17. from ipython_genutils.text import columnize
  18. from traitlets import Bool, Enum, Integer, Unicode
  19. from .ansi_code_processor import QtAnsiCodeProcessor
  20. from .completion_widget import CompletionWidget
  21. from .completion_html import CompletionHtml
  22. from .completion_plain import CompletionPlain
  23. from .kill_ring import QtKillRing
  24. def is_letter_or_number(char):
  25. """ Returns whether the specified unicode character is a letter or a number.
  26. """
  27. cat = category(char)
  28. return cat.startswith('L') or cat.startswith('N')
  29. def is_whitespace(char):
  30. """Check whether a given char counts as white space."""
  31. return category(char).startswith('Z')
  32. #-----------------------------------------------------------------------------
  33. # Classes
  34. #-----------------------------------------------------------------------------
  35. class ConsoleWidget(MetaQObjectHasTraits('NewBase', (LoggingConfigurable, superQ(QtWidgets.QWidget)), {})):
  36. """ An abstract base class for console-type widgets. This class has
  37. functionality for:
  38. * Maintaining a prompt and editing region
  39. * Providing the traditional Unix-style console keyboard shortcuts
  40. * Performing tab completion
  41. * Paging text
  42. * Handling ANSI escape codes
  43. ConsoleWidget also provides a number of utility methods that will be
  44. convenient to implementors of a console-style widget.
  45. """
  46. #------ Configuration ------------------------------------------------------
  47. ansi_codes = Bool(True, config=True,
  48. help="Whether to process ANSI escape codes."
  49. )
  50. buffer_size = Integer(500, config=True,
  51. help="""
  52. The maximum number of lines of text before truncation. Specifying a
  53. non-positive number disables text truncation (not recommended).
  54. """
  55. )
  56. execute_on_complete_input = Bool(True, config=True,
  57. help="""Whether to automatically execute on syntactically complete input.
  58. If False, Shift-Enter is required to submit each execution.
  59. Disabling this is mainly useful for non-Python kernels,
  60. where the completion check would be wrong.
  61. """
  62. )
  63. gui_completion = Enum(['plain', 'droplist', 'ncurses'], config=True,
  64. default_value = 'ncurses',
  65. help="""
  66. The type of completer to use. Valid values are:
  67. 'plain' : Show the available completion as a text list
  68. Below the editing area.
  69. 'droplist': Show the completion in a drop down list navigable
  70. by the arrow keys, and from which you can select
  71. completion by pressing Return.
  72. 'ncurses' : Show the completion as a text list which is navigable by
  73. `tab` and arrow keys.
  74. """
  75. )
  76. # NOTE: this value can only be specified during initialization.
  77. kind = Enum(['plain', 'rich'], default_value='plain', config=True,
  78. help="""
  79. The type of underlying text widget to use. Valid values are 'plain',
  80. which specifies a QPlainTextEdit, and 'rich', which specifies a
  81. QTextEdit.
  82. """
  83. )
  84. # NOTE: this value can only be specified during initialization.
  85. paging = Enum(['inside', 'hsplit', 'vsplit', 'custom', 'none'],
  86. default_value='inside', config=True,
  87. help="""
  88. The type of paging to use. Valid values are:
  89. 'inside'
  90. The widget pages like a traditional terminal.
  91. 'hsplit'
  92. When paging is requested, the widget is split horizontally. The top
  93. pane contains the console, and the bottom pane contains the paged text.
  94. 'vsplit'
  95. Similar to 'hsplit', except that a vertical splitter is used.
  96. 'custom'
  97. No action is taken by the widget beyond emitting a
  98. 'custom_page_requested(str)' signal.
  99. 'none'
  100. The text is written directly to the console.
  101. """)
  102. scrollbar_visibility = Bool(True, config=True,
  103. help="""The visibility of the scrollar. If False then the scrollbar will be
  104. invisible."""
  105. )
  106. font_family = Unicode(config=True,
  107. help="""The font family to use for the console.
  108. On OSX this defaults to Monaco, on Windows the default is
  109. Consolas with fallback of Courier, and on other platforms
  110. the default is Monospace.
  111. """)
  112. def _font_family_default(self):
  113. if sys.platform == 'win32':
  114. # Consolas ships with Vista/Win7, fallback to Courier if needed
  115. return 'Consolas'
  116. elif sys.platform == 'darwin':
  117. # OSX always has Monaco, no need for a fallback
  118. return 'Monaco'
  119. else:
  120. # Monospace should always exist, no need for a fallback
  121. return 'Monospace'
  122. font_size = Integer(config=True,
  123. help="""The font size. If unconfigured, Qt will be entrusted
  124. with the size of the font.
  125. """)
  126. console_width = Integer(81, config=True,
  127. help="""The width of the console at start time in number
  128. of characters (will double with `hsplit` paging)
  129. """)
  130. console_height = Integer(25, config=True,
  131. help="""The height of the console at start time in number
  132. of characters (will double with `vsplit` paging)
  133. """)
  134. # Whether to override ShortcutEvents for the keybindings defined by this
  135. # widget (Ctrl+n, Ctrl+a, etc). Enable this if you want this widget to take
  136. # priority (when it has focus) over, e.g., window-level menu shortcuts.
  137. override_shortcuts = Bool(False)
  138. # ------ Custom Qt Widgets -------------------------------------------------
  139. # For other projects to easily override the Qt widgets used by the console
  140. # (e.g. Spyder)
  141. custom_control = None
  142. custom_page_control = None
  143. #------ Signals ------------------------------------------------------------
  144. # Signals that indicate ConsoleWidget state.
  145. copy_available = QtCore.Signal(bool)
  146. redo_available = QtCore.Signal(bool)
  147. undo_available = QtCore.Signal(bool)
  148. # Signal emitted when paging is needed and the paging style has been
  149. # specified as 'custom'.
  150. custom_page_requested = QtCore.Signal(object)
  151. # Signal emitted when the font is changed.
  152. font_changed = QtCore.Signal(QtGui.QFont)
  153. #------ Protected class variables ------------------------------------------
  154. # control handles
  155. _control = None
  156. _page_control = None
  157. _splitter = None
  158. # When the control key is down, these keys are mapped.
  159. _ctrl_down_remap = { QtCore.Qt.Key_B : QtCore.Qt.Key_Left,
  160. QtCore.Qt.Key_F : QtCore.Qt.Key_Right,
  161. QtCore.Qt.Key_A : QtCore.Qt.Key_Home,
  162. QtCore.Qt.Key_P : QtCore.Qt.Key_Up,
  163. QtCore.Qt.Key_N : QtCore.Qt.Key_Down,
  164. QtCore.Qt.Key_H : QtCore.Qt.Key_Backspace, }
  165. if not sys.platform == 'darwin':
  166. # On OS X, Ctrl-E already does the right thing, whereas End moves the
  167. # cursor to the bottom of the buffer.
  168. _ctrl_down_remap[QtCore.Qt.Key_E] = QtCore.Qt.Key_End
  169. # The shortcuts defined by this widget. We need to keep track of these to
  170. # support 'override_shortcuts' above.
  171. _shortcuts = set(_ctrl_down_remap.keys()) | \
  172. { QtCore.Qt.Key_C, QtCore.Qt.Key_G, QtCore.Qt.Key_O,
  173. QtCore.Qt.Key_V }
  174. _temp_buffer_filled = False
  175. #---------------------------------------------------------------------------
  176. # 'QObject' interface
  177. #---------------------------------------------------------------------------
  178. def __init__(self, parent=None, **kw):
  179. """ Create a ConsoleWidget.
  180. Parameters
  181. ----------
  182. parent : QWidget, optional [default None]
  183. The parent for this widget.
  184. """
  185. super(ConsoleWidget, self).__init__(**kw)
  186. if parent:
  187. self.setParent(parent)
  188. self._is_complete_msg_id = None
  189. self._is_complete_timeout = 0.1
  190. self._is_complete_max_time = None
  191. # While scrolling the pager on Mac OS X, it tears badly. The
  192. # NativeGesture is platform and perhaps build-specific hence
  193. # we take adequate precautions here.
  194. self._pager_scroll_events = [QtCore.QEvent.Wheel]
  195. if hasattr(QtCore.QEvent, 'NativeGesture'):
  196. self._pager_scroll_events.append(QtCore.QEvent.NativeGesture)
  197. # Create the layout and underlying text widget.
  198. layout = QtWidgets.QStackedLayout(self)
  199. layout.setContentsMargins(0, 0, 0, 0)
  200. self._control = self._create_control()
  201. if self.paging in ('hsplit', 'vsplit'):
  202. self._splitter = QtWidgets.QSplitter()
  203. if self.paging == 'hsplit':
  204. self._splitter.setOrientation(QtCore.Qt.Horizontal)
  205. else:
  206. self._splitter.setOrientation(QtCore.Qt.Vertical)
  207. self._splitter.addWidget(self._control)
  208. layout.addWidget(self._splitter)
  209. else:
  210. layout.addWidget(self._control)
  211. # Create the paging widget, if necessary.
  212. if self.paging in ('inside', 'hsplit', 'vsplit'):
  213. self._page_control = self._create_page_control()
  214. if self._splitter:
  215. self._page_control.hide()
  216. self._splitter.addWidget(self._page_control)
  217. else:
  218. layout.addWidget(self._page_control)
  219. # Initialize protected variables. Some variables contain useful state
  220. # information for subclasses; they should be considered read-only.
  221. self._append_before_prompt_cursor = self._control.textCursor()
  222. self._ansi_processor = QtAnsiCodeProcessor()
  223. if self.gui_completion == 'ncurses':
  224. self._completion_widget = CompletionHtml(self)
  225. elif self.gui_completion == 'droplist':
  226. self._completion_widget = CompletionWidget(self)
  227. elif self.gui_completion == 'plain':
  228. self._completion_widget = CompletionPlain(self)
  229. self._continuation_prompt = '> '
  230. self._continuation_prompt_html = None
  231. self._executing = False
  232. self._filter_resize = False
  233. self._html_exporter = HtmlExporter(self._control)
  234. self._input_buffer_executing = ''
  235. self._input_buffer_pending = ''
  236. self._kill_ring = QtKillRing(self._control)
  237. self._prompt = ''
  238. self._prompt_html = None
  239. self._prompt_cursor = self._control.textCursor()
  240. self._prompt_sep = ''
  241. self._reading = False
  242. self._reading_callback = None
  243. self._tab_width = 4
  244. # List of strings pending to be appended as plain text in the widget.
  245. # The text is not immediately inserted when available to not
  246. # choke the Qt event loop with paint events for the widget in
  247. # case of lots of output from kernel.
  248. self._pending_insert_text = []
  249. # Timer to flush the pending stream messages. The interval is adjusted
  250. # later based on actual time taken for flushing a screen (buffer_size)
  251. # of output text.
  252. self._pending_text_flush_interval = QtCore.QTimer(self._control)
  253. self._pending_text_flush_interval.setInterval(100)
  254. self._pending_text_flush_interval.setSingleShot(True)
  255. self._pending_text_flush_interval.timeout.connect(
  256. self._on_flush_pending_stream_timer)
  257. # Set a monospaced font.
  258. self.reset_font()
  259. # Configure actions.
  260. action = QtWidgets.QAction('Print', None)
  261. action.setEnabled(True)
  262. printkey = QtGui.QKeySequence(QtGui.QKeySequence.Print)
  263. if printkey.matches("Ctrl+P") and sys.platform != 'darwin':
  264. # Only override the default if there is a collision.
  265. # Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
  266. printkey = "Ctrl+Shift+P"
  267. action.setShortcut(printkey)
  268. action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
  269. action.triggered.connect(self.print_)
  270. self.addAction(action)
  271. self.print_action = action
  272. action = QtWidgets.QAction('Save as HTML/XML', None)
  273. action.setShortcut(QtGui.QKeySequence.Save)
  274. action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
  275. action.triggered.connect(self.export_html)
  276. self.addAction(action)
  277. self.export_action = action
  278. action = QtWidgets.QAction('Select All', None)
  279. action.setEnabled(True)
  280. selectall = QtGui.QKeySequence(QtGui.QKeySequence.SelectAll)
  281. if selectall.matches("Ctrl+A") and sys.platform != 'darwin':
  282. # Only override the default if there is a collision.
  283. # Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
  284. selectall = "Ctrl+Shift+A"
  285. action.setShortcut(selectall)
  286. action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
  287. action.triggered.connect(self.select_all_smart)
  288. self.addAction(action)
  289. self.select_all_action = action
  290. self.increase_font_size = QtWidgets.QAction("Bigger Font",
  291. self,
  292. shortcut=QtGui.QKeySequence.ZoomIn,
  293. shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
  294. statusTip="Increase the font size by one point",
  295. triggered=self._increase_font_size)
  296. self.addAction(self.increase_font_size)
  297. self.decrease_font_size = QtWidgets.QAction("Smaller Font",
  298. self,
  299. shortcut=QtGui.QKeySequence.ZoomOut,
  300. shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
  301. statusTip="Decrease the font size by one point",
  302. triggered=self._decrease_font_size)
  303. self.addAction(self.decrease_font_size)
  304. self.reset_font_size = QtWidgets.QAction("Normal Font",
  305. self,
  306. shortcut="Ctrl+0",
  307. shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
  308. statusTip="Restore the Normal font size",
  309. triggered=self.reset_font)
  310. self.addAction(self.reset_font_size)
  311. # Accept drag and drop events here. Drops were already turned off
  312. # in self._control when that widget was created.
  313. self.setAcceptDrops(True)
  314. #---------------------------------------------------------------------------
  315. # Drag and drop support
  316. #---------------------------------------------------------------------------
  317. def dragEnterEvent(self, e):
  318. if e.mimeData().hasUrls():
  319. # The link action should indicate to that the drop will insert
  320. # the file anme.
  321. e.setDropAction(QtCore.Qt.LinkAction)
  322. e.accept()
  323. elif e.mimeData().hasText():
  324. # By changing the action to copy we don't need to worry about
  325. # the user accidentally moving text around in the widget.
  326. e.setDropAction(QtCore.Qt.CopyAction)
  327. e.accept()
  328. def dragMoveEvent(self, e):
  329. if e.mimeData().hasUrls():
  330. pass
  331. elif e.mimeData().hasText():
  332. cursor = self._control.cursorForPosition(e.pos())
  333. if self._in_buffer(cursor.position()):
  334. e.setDropAction(QtCore.Qt.CopyAction)
  335. self._control.setTextCursor(cursor)
  336. else:
  337. e.setDropAction(QtCore.Qt.IgnoreAction)
  338. e.accept()
  339. def dropEvent(self, e):
  340. if e.mimeData().hasUrls():
  341. self._keep_cursor_in_buffer()
  342. cursor = self._control.textCursor()
  343. filenames = [url.toLocalFile() for url in e.mimeData().urls()]
  344. text = ', '.join("'" + f.replace("'", "'\"'\"'") + "'"
  345. for f in filenames)
  346. self._insert_plain_text_into_buffer(cursor, text)
  347. elif e.mimeData().hasText():
  348. cursor = self._control.cursorForPosition(e.pos())
  349. if self._in_buffer(cursor.position()):
  350. text = e.mimeData().text()
  351. self._insert_plain_text_into_buffer(cursor, text)
  352. def eventFilter(self, obj, event):
  353. """ Reimplemented to ensure a console-like behavior in the underlying
  354. text widgets.
  355. """
  356. etype = event.type()
  357. if etype == QtCore.QEvent.KeyPress:
  358. # Re-map keys for all filtered widgets.
  359. key = event.key()
  360. if self._control_key_down(event.modifiers()) and \
  361. key in self._ctrl_down_remap:
  362. new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
  363. self._ctrl_down_remap[key],
  364. QtCore.Qt.NoModifier)
  365. QtWidgets.qApp.sendEvent(obj, new_event)
  366. return True
  367. elif obj == self._control:
  368. return self._event_filter_console_keypress(event)
  369. elif obj == self._page_control:
  370. return self._event_filter_page_keypress(event)
  371. # Make middle-click paste safe.
  372. elif getattr(event, 'button', False) and \
  373. etype == QtCore.QEvent.MouseButtonRelease and \
  374. event.button() == QtCore.Qt.MidButton and \
  375. obj == self._control.viewport():
  376. cursor = self._control.cursorForPosition(event.pos())
  377. self._control.setTextCursor(cursor)
  378. self.paste(QtGui.QClipboard.Selection)
  379. return True
  380. # Manually adjust the scrollbars *after* a resize event is dispatched.
  381. elif etype == QtCore.QEvent.Resize and not self._filter_resize:
  382. self._filter_resize = True
  383. QtWidgets.QApplication.instance().sendEvent(obj, event)
  384. self._adjust_scrollbars()
  385. self._filter_resize = False
  386. return True
  387. # Override shortcuts for all filtered widgets.
  388. elif etype == QtCore.QEvent.ShortcutOverride and \
  389. self.override_shortcuts and \
  390. self._control_key_down(event.modifiers()) and \
  391. event.key() in self._shortcuts:
  392. event.accept()
  393. # Handle scrolling of the vsplit pager. This hack attempts to solve
  394. # problems with tearing of the help text inside the pager window. This
  395. # happens only on Mac OS X with both PySide and PyQt. This fix isn't
  396. # perfect but makes the pager more usable.
  397. elif etype in self._pager_scroll_events and \
  398. obj == self._page_control:
  399. self._page_control.repaint()
  400. return True
  401. elif etype == QtCore.QEvent.MouseMove:
  402. anchor = self._control.anchorAt(event.pos())
  403. QtWidgets.QToolTip.showText(event.globalPos(), anchor)
  404. return super(ConsoleWidget, self).eventFilter(obj, event)
  405. #---------------------------------------------------------------------------
  406. # 'QWidget' interface
  407. #---------------------------------------------------------------------------
  408. def sizeHint(self):
  409. """ Reimplemented to suggest a size that is 80 characters wide and
  410. 25 lines high.
  411. """
  412. font_metrics = QtGui.QFontMetrics(self.font)
  413. margin = (self._control.frameWidth() +
  414. self._control.document().documentMargin()) * 2
  415. style = self.style()
  416. splitwidth = style.pixelMetric(QtWidgets.QStyle.PM_SplitterWidth)
  417. # Note 1: Despite my best efforts to take the various margins into
  418. # account, the width is still coming out a bit too small, so we include
  419. # a fudge factor of one character here.
  420. # Note 2: QFontMetrics.maxWidth is not used here or anywhere else due
  421. # to a Qt bug on certain Mac OS systems where it returns 0.
  422. width = font_metrics.width(' ') * self.console_width + margin
  423. width += style.pixelMetric(QtWidgets.QStyle.PM_ScrollBarExtent)
  424. if self.paging == 'hsplit':
  425. width = width * 2 + splitwidth
  426. height = font_metrics.height() * self.console_height + margin
  427. if self.paging == 'vsplit':
  428. height = height * 2 + splitwidth
  429. return QtCore.QSize(int(width), int(height))
  430. #---------------------------------------------------------------------------
  431. # 'ConsoleWidget' public interface
  432. #---------------------------------------------------------------------------
  433. include_other_output = Bool(False, config=True,
  434. help="""Whether to include output from clients
  435. other than this one sharing the same kernel.
  436. Outputs are not displayed until enter is pressed.
  437. """
  438. )
  439. other_output_prefix = Unicode('[remote] ', config=True,
  440. help="""Prefix to add to outputs coming from clients other than this one.
  441. Only relevant if include_other_output is True.
  442. """
  443. )
  444. def can_copy(self):
  445. """ Returns whether text can be copied to the clipboard.
  446. """
  447. return self._control.textCursor().hasSelection()
  448. def can_cut(self):
  449. """ Returns whether text can be cut to the clipboard.
  450. """
  451. cursor = self._control.textCursor()
  452. return (cursor.hasSelection() and
  453. self._in_buffer(cursor.anchor()) and
  454. self._in_buffer(cursor.position()))
  455. def can_paste(self):
  456. """ Returns whether text can be pasted from the clipboard.
  457. """
  458. if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
  459. return bool(QtWidgets.QApplication.clipboard().text())
  460. return False
  461. def clear(self, keep_input=True):
  462. """ Clear the console.
  463. Parameters
  464. ----------
  465. keep_input : bool, optional (default True)
  466. If set, restores the old input buffer if a new prompt is written.
  467. """
  468. if self._executing:
  469. self._control.clear()
  470. else:
  471. if keep_input:
  472. input_buffer = self.input_buffer
  473. self._control.clear()
  474. self._show_prompt()
  475. if keep_input:
  476. self.input_buffer = input_buffer
  477. def copy(self):
  478. """ Copy the currently selected text to the clipboard.
  479. """
  480. self.layout().currentWidget().copy()
  481. def copy_anchor(self, anchor):
  482. """ Copy anchor text to the clipboard
  483. """
  484. QtWidgets.QApplication.clipboard().setText(anchor)
  485. def cut(self):
  486. """ Copy the currently selected text to the clipboard and delete it
  487. if it's inside the input buffer.
  488. """
  489. self.copy()
  490. if self.can_cut():
  491. self._control.textCursor().removeSelectedText()
  492. def _handle_is_complete_reply(self, msg):
  493. if msg['parent_header'].get('msg_id', 0) != self._is_complete_msg_id:
  494. return
  495. status = msg['content'].get('status', u'complete')
  496. indent = msg['content'].get('indent', u'')
  497. self._trigger_is_complete_callback(status != 'incomplete', indent)
  498. def _trigger_is_complete_callback(self, complete=False, indent=u''):
  499. if self._is_complete_msg_id is not None:
  500. self._is_complete_msg_id = None
  501. self._is_complete_callback(complete, indent)
  502. def _register_is_complete_callback(self, source, callback):
  503. if self._is_complete_msg_id is not None:
  504. if self._is_complete_max_time < time.time():
  505. # Second return while waiting for is_complete
  506. return
  507. else:
  508. # request timed out
  509. self._trigger_is_complete_callback()
  510. self._is_complete_max_time = time.time() + self._is_complete_timeout
  511. self._is_complete_callback = callback
  512. self._is_complete_msg_id = self.kernel_client.is_complete(source)
  513. def execute(self, source=None, hidden=False, interactive=False):
  514. """ Executes source or the input buffer, possibly prompting for more
  515. input.
  516. Parameters
  517. ----------
  518. source : str, optional
  519. The source to execute. If not specified, the input buffer will be
  520. used. If specified and 'hidden' is False, the input buffer will be
  521. replaced with the source before execution.
  522. hidden : bool, optional (default False)
  523. If set, no output will be shown and the prompt will not be modified.
  524. In other words, it will be completely invisible to the user that
  525. an execution has occurred.
  526. interactive : bool, optional (default False)
  527. Whether the console is to treat the source as having been manually
  528. entered by the user. The effect of this parameter depends on the
  529. subclass implementation.
  530. Raises
  531. ------
  532. RuntimeError
  533. If incomplete input is given and 'hidden' is True. In this case,
  534. it is not possible to prompt for more input.
  535. Returns
  536. -------
  537. A boolean indicating whether the source was executed.
  538. """
  539. # WARNING: The order in which things happen here is very particular, in
  540. # large part because our syntax highlighting is fragile. If you change
  541. # something, test carefully!
  542. # Decide what to execute.
  543. if source is None:
  544. source = self.input_buffer
  545. elif not hidden:
  546. self.input_buffer = source
  547. if hidden:
  548. self._execute(source, hidden)
  549. # Execute the source or show a continuation prompt if it is incomplete.
  550. elif interactive and self.execute_on_complete_input:
  551. self._register_is_complete_callback(
  552. source, partial(self.do_execute, source))
  553. else:
  554. self.do_execute(source, True, '')
  555. def do_execute(self, source, complete, indent):
  556. if complete:
  557. self._append_plain_text('\n')
  558. self._input_buffer_executing = self.input_buffer
  559. self._executing = True
  560. self._finalize_input_request()
  561. # Perform actual execution.
  562. self._execute(source, False)
  563. else:
  564. # Do this inside an edit block so continuation prompts are
  565. # removed seamlessly via undo/redo.
  566. cursor = self._get_end_cursor()
  567. cursor.beginEditBlock()
  568. try:
  569. cursor.insertText('\n')
  570. self._insert_continuation_prompt(cursor, indent)
  571. finally:
  572. cursor.endEditBlock()
  573. # Do not do this inside the edit block. It works as expected
  574. # when using a QPlainTextEdit control, but does not have an
  575. # effect when using a QTextEdit. I believe this is a Qt bug.
  576. self._control.moveCursor(QtGui.QTextCursor.End)
  577. def export_html(self):
  578. """ Shows a dialog to export HTML/XML in various formats.
  579. """
  580. self._html_exporter.export()
  581. def _finalize_input_request(self):
  582. """
  583. Set the widget to a non-reading state.
  584. """
  585. # Must set _reading to False before calling _prompt_finished
  586. self._reading = False
  587. self._prompt_finished()
  588. # There is no prompt now, so before_prompt_position is eof
  589. self._append_before_prompt_cursor.setPosition(
  590. self._get_end_cursor().position())
  591. # The maximum block count is only in effect during execution.
  592. # This ensures that _prompt_pos does not become invalid due to
  593. # text truncation.
  594. self._control.document().setMaximumBlockCount(self.buffer_size)
  595. # Setting a positive maximum block count will automatically
  596. # disable the undo/redo history, but just to be safe:
  597. self._control.setUndoRedoEnabled(False)
  598. def _get_input_buffer(self, force=False):
  599. """ The text that the user has entered entered at the current prompt.
  600. If the console is currently executing, the text that is executing will
  601. always be returned.
  602. """
  603. # If we're executing, the input buffer may not even exist anymore due to
  604. # the limit imposed by 'buffer_size'. Therefore, we store it.
  605. if self._executing and not force:
  606. return self._input_buffer_executing
  607. cursor = self._get_end_cursor()
  608. cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
  609. input_buffer = cursor.selection().toPlainText()
  610. # Strip out continuation prompts.
  611. return input_buffer.replace('\n' + self._continuation_prompt, '\n')
  612. def _set_input_buffer(self, string):
  613. """ Sets the text in the input buffer.
  614. If the console is currently executing, this call has no *immediate*
  615. effect. When the execution is finished, the input buffer will be updated
  616. appropriately.
  617. """
  618. # If we're executing, store the text for later.
  619. if self._executing:
  620. self._input_buffer_pending = string
  621. return
  622. # Remove old text.
  623. cursor = self._get_end_cursor()
  624. cursor.beginEditBlock()
  625. cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
  626. cursor.removeSelectedText()
  627. # Insert new text with continuation prompts.
  628. self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string)
  629. cursor.endEditBlock()
  630. self._control.moveCursor(QtGui.QTextCursor.End)
  631. input_buffer = property(_get_input_buffer, _set_input_buffer)
  632. def _get_font(self):
  633. """ The base font being used by the ConsoleWidget.
  634. """
  635. return self._control.document().defaultFont()
  636. def _set_font(self, font):
  637. """ Sets the base font for the ConsoleWidget to the specified QFont.
  638. """
  639. font_metrics = QtGui.QFontMetrics(font)
  640. self._control.setTabStopWidth(self.tab_width * font_metrics.width(' '))
  641. self._completion_widget.setFont(font)
  642. self._control.document().setDefaultFont(font)
  643. if self._page_control:
  644. self._page_control.document().setDefaultFont(font)
  645. self.font_changed.emit(font)
  646. font = property(_get_font, _set_font)
  647. def open_anchor(self, anchor):
  648. """ Open selected anchor in the default webbrowser
  649. """
  650. webbrowser.open( anchor )
  651. def paste(self, mode=QtGui.QClipboard.Clipboard):
  652. """ Paste the contents of the clipboard into the input region.
  653. Parameters
  654. ----------
  655. mode : QClipboard::Mode, optional [default QClipboard::Clipboard]
  656. Controls which part of the system clipboard is used. This can be
  657. used to access the selection clipboard in X11 and the Find buffer
  658. in Mac OS. By default, the regular clipboard is used.
  659. """
  660. if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
  661. # Make sure the paste is safe.
  662. self._keep_cursor_in_buffer()
  663. cursor = self._control.textCursor()
  664. # Remove any trailing newline, which confuses the GUI and forces the
  665. # user to backspace.
  666. text = QtWidgets.QApplication.clipboard().text(mode).rstrip()
  667. # dedent removes "common leading whitespace" but to preserve relative
  668. # indent of multiline code, we have to compensate for any
  669. # leading space on the first line, if we're pasting into
  670. # an indented position.
  671. cursor_offset = cursor.position() - self._get_line_start_pos()
  672. if text.startswith(' ' * cursor_offset):
  673. text = text[cursor_offset:]
  674. self._insert_plain_text_into_buffer(cursor, dedent(text))
  675. def print_(self, printer = None):
  676. """ Print the contents of the ConsoleWidget to the specified QPrinter.
  677. """
  678. if (not printer):
  679. printer = QtPrintSupport.QPrinter()
  680. if(QtPrintSupport.QPrintDialog(printer).exec_() != QtPrintSupport.QPrintDialog.Accepted):
  681. return
  682. self._control.print_(printer)
  683. def prompt_to_top(self):
  684. """ Moves the prompt to the top of the viewport.
  685. """
  686. if not self._executing:
  687. prompt_cursor = self._get_prompt_cursor()
  688. if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():
  689. self._set_cursor(prompt_cursor)
  690. self._set_top_cursor(prompt_cursor)
  691. def redo(self):
  692. """ Redo the last operation. If there is no operation to redo, nothing
  693. happens.
  694. """
  695. self._control.redo()
  696. def reset_font(self):
  697. """ Sets the font to the default fixed-width font for this platform.
  698. """
  699. if sys.platform == 'win32':
  700. # Consolas ships with Vista/Win7, fallback to Courier if needed
  701. fallback = 'Courier'
  702. elif sys.platform == 'darwin':
  703. # OSX always has Monaco
  704. fallback = 'Monaco'
  705. else:
  706. # Monospace should always exist
  707. fallback = 'Monospace'
  708. font = get_font(self.font_family, fallback)
  709. if self.font_size:
  710. font.setPointSize(self.font_size)
  711. else:
  712. font.setPointSize(QtWidgets.QApplication.instance().font().pointSize())
  713. font.setStyleHint(QtGui.QFont.TypeWriter)
  714. self._set_font(font)
  715. def change_font_size(self, delta):
  716. """Change the font size by the specified amount (in points).
  717. """
  718. font = self.font
  719. size = max(font.pointSize() + delta, 1) # minimum 1 point
  720. font.setPointSize(size)
  721. self._set_font(font)
  722. def _increase_font_size(self):
  723. self.change_font_size(1)
  724. def _decrease_font_size(self):
  725. self.change_font_size(-1)
  726. def select_all_smart(self):
  727. """ Select current cell, or, if already selected, the whole document.
  728. """
  729. c = self._get_cursor()
  730. sel_range = c.selectionStart(), c.selectionEnd()
  731. c.clearSelection()
  732. c.setPosition(self._get_prompt_cursor().position())
  733. c.setPosition(self._get_end_pos(),
  734. mode=QtGui.QTextCursor.KeepAnchor)
  735. new_sel_range = c.selectionStart(), c.selectionEnd()
  736. if sel_range == new_sel_range:
  737. # cell already selected, expand selection to whole document
  738. self.select_document()
  739. else:
  740. # set cell selection as active selection
  741. self._control.setTextCursor(c)
  742. def select_document(self):
  743. """ Selects all the text in the buffer.
  744. """
  745. self._control.selectAll()
  746. def _get_tab_width(self):
  747. """ The width (in terms of space characters) for tab characters.
  748. """
  749. return self._tab_width
  750. def _set_tab_width(self, tab_width):
  751. """ Sets the width (in terms of space characters) for tab characters.
  752. """
  753. font_metrics = QtGui.QFontMetrics(self.font)
  754. self._control.setTabStopWidth(tab_width * font_metrics.width(' '))
  755. self._tab_width = tab_width
  756. tab_width = property(_get_tab_width, _set_tab_width)
  757. def undo(self):
  758. """ Undo the last operation. If there is no operation to undo, nothing
  759. happens.
  760. """
  761. self._control.undo()
  762. #---------------------------------------------------------------------------
  763. # 'ConsoleWidget' abstract interface
  764. #---------------------------------------------------------------------------
  765. def _is_complete(self, source, interactive):
  766. """ Returns whether 'source' can be executed. When triggered by an
  767. Enter/Return key press, 'interactive' is True; otherwise, it is
  768. False.
  769. """
  770. raise NotImplementedError
  771. def _execute(self, source, hidden):
  772. """ Execute 'source'. If 'hidden', do not show any output.
  773. """
  774. raise NotImplementedError
  775. def _prompt_started_hook(self):
  776. """ Called immediately after a new prompt is displayed.
  777. """
  778. pass
  779. def _prompt_finished_hook(self):
  780. """ Called immediately after a prompt is finished, i.e. when some input
  781. will be processed and a new prompt displayed.
  782. """
  783. pass
  784. def _up_pressed(self, shift_modifier):
  785. """ Called when the up key is pressed. Returns whether to continue
  786. processing the event.
  787. """
  788. return True
  789. def _down_pressed(self, shift_modifier):
  790. """ Called when the down key is pressed. Returns whether to continue
  791. processing the event.
  792. """
  793. return True
  794. def _tab_pressed(self):
  795. """ Called when the tab key is pressed. Returns whether to continue
  796. processing the event.
  797. """
  798. return True
  799. #--------------------------------------------------------------------------
  800. # 'ConsoleWidget' protected interface
  801. #--------------------------------------------------------------------------
  802. def _append_custom(self, insert, input, before_prompt=False, *args, **kwargs):
  803. """ A low-level method for appending content to the end of the buffer.
  804. If 'before_prompt' is enabled, the content will be inserted before the
  805. current prompt, if there is one.
  806. """
  807. # Determine where to insert the content.
  808. cursor = self._control.textCursor()
  809. if before_prompt and (self._reading or not self._executing):
  810. self._flush_pending_stream()
  811. cursor.setPosition(self._append_before_prompt_pos)
  812. else:
  813. if insert != self._insert_plain_text:
  814. self._flush_pending_stream()
  815. cursor.movePosition(QtGui.QTextCursor.End)
  816. # Perform the insertion.
  817. result = insert(cursor, input, *args, **kwargs)
  818. return result
  819. def _append_block(self, block_format=None, before_prompt=False):
  820. """ Appends an new QTextBlock to the end of the console buffer.
  821. """
  822. self._append_custom(self._insert_block, block_format, before_prompt)
  823. def _append_html(self, html, before_prompt=False):
  824. """ Appends HTML at the end of the console buffer.
  825. """
  826. self._append_custom(self._insert_html, html, before_prompt)
  827. def _append_html_fetching_plain_text(self, html, before_prompt=False):
  828. """ Appends HTML, then returns the plain text version of it.
  829. """
  830. return self._append_custom(self._insert_html_fetching_plain_text,
  831. html, before_prompt)
  832. def _append_plain_text(self, text, before_prompt=False):
  833. """ Appends plain text, processing ANSI codes if enabled.
  834. """
  835. self._append_custom(self._insert_plain_text, text, before_prompt)
  836. def _cancel_completion(self):
  837. """ If text completion is progress, cancel it.
  838. """
  839. self._completion_widget.cancel_completion()
  840. def _clear_temporary_buffer(self):
  841. """ Clears the "temporary text" buffer, i.e. all the text following
  842. the prompt region.
  843. """
  844. # Select and remove all text below the input buffer.
  845. cursor = self._get_prompt_cursor()
  846. prompt = self._continuation_prompt.lstrip()
  847. if(self._temp_buffer_filled):
  848. self._temp_buffer_filled = False
  849. while cursor.movePosition(QtGui.QTextCursor.NextBlock):
  850. temp_cursor = QtGui.QTextCursor(cursor)
  851. temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor)
  852. text = temp_cursor.selection().toPlainText().lstrip()
  853. if not text.startswith(prompt):
  854. break
  855. else:
  856. # We've reached the end of the input buffer and no text follows.
  857. return
  858. cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline.
  859. cursor.movePosition(QtGui.QTextCursor.End,
  860. QtGui.QTextCursor.KeepAnchor)
  861. cursor.removeSelectedText()
  862. # After doing this, we have no choice but to clear the undo/redo
  863. # history. Otherwise, the text is not "temporary" at all, because it
  864. # can be recalled with undo/redo. Unfortunately, Qt does not expose
  865. # fine-grained control to the undo/redo system.
  866. if self._control.isUndoRedoEnabled():
  867. self._control.setUndoRedoEnabled(False)
  868. self._control.setUndoRedoEnabled(True)
  869. def _complete_with_items(self, cursor, items):
  870. """ Performs completion with 'items' at the specified cursor location.
  871. """
  872. self._cancel_completion()
  873. if len(items) == 1:
  874. cursor.setPosition(self._control.textCursor().position(),
  875. QtGui.QTextCursor.KeepAnchor)
  876. cursor.insertText(items[0])
  877. elif len(items) > 1:
  878. current_pos = self._control.textCursor().position()
  879. prefix = os.path.commonprefix(items)
  880. if prefix:
  881. cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor)
  882. cursor.insertText(prefix)
  883. current_pos = cursor.position()
  884. self._completion_widget.show_items(cursor, items,
  885. prefix_length=len(prefix))
  886. def _fill_temporary_buffer(self, cursor, text, html=False):
  887. """fill the area below the active editting zone with text"""
  888. current_pos = self._control.textCursor().position()
  889. cursor.beginEditBlock()
  890. self._append_plain_text('\n')
  891. self._page(text, html=html)
  892. cursor.endEditBlock()
  893. cursor.setPosition(current_pos)
  894. self._control.moveCursor(QtGui.QTextCursor.End)
  895. self._control.setTextCursor(cursor)
  896. self._temp_buffer_filled = True
  897. def _context_menu_make(self, pos):
  898. """ Creates a context menu for the given QPoint (in widget coordinates).
  899. """
  900. menu = QtWidgets.QMenu(self)
  901. self.cut_action = menu.addAction('Cut', self.cut)
  902. self.cut_action.setEnabled(self.can_cut())
  903. self.cut_action.setShortcut(QtGui.QKeySequence.Cut)
  904. self.copy_action = menu.addAction('Copy', self.copy)
  905. self.copy_action.setEnabled(self.can_copy())
  906. self.copy_action.setShortcut(QtGui.QKeySequence.Copy)
  907. self.paste_action = menu.addAction('Paste', self.paste)
  908. self.paste_action.setEnabled(self.can_paste())
  909. self.paste_action.setShortcut(QtGui.QKeySequence.Paste)
  910. anchor = self._control.anchorAt(pos)
  911. if anchor:
  912. menu.addSeparator()
  913. self.copy_link_action = menu.addAction(
  914. 'Copy Link Address', lambda: self.copy_anchor(anchor=anchor))
  915. self.open_link_action = menu.addAction(
  916. 'Open Link', lambda: self.open_anchor(anchor=anchor))
  917. menu.addSeparator()
  918. menu.addAction(self.select_all_action)
  919. menu.addSeparator()
  920. menu.addAction(self.export_action)
  921. menu.addAction(self.print_action)
  922. return menu
  923. def _control_key_down(self, modifiers, include_command=False):
  924. """ Given a KeyboardModifiers flags object, return whether the Control
  925. key is down.
  926. Parameters
  927. ----------
  928. include_command : bool, optional (default True)
  929. Whether to treat the Command key as a (mutually exclusive) synonym
  930. for Control when in Mac OS.
  931. """
  932. # Note that on Mac OS, ControlModifier corresponds to the Command key
  933. # while MetaModifier corresponds to the Control key.
  934. if sys.platform == 'darwin':
  935. down = include_command and (modifiers & QtCore.Qt.ControlModifier)
  936. return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier)
  937. else:
  938. return bool(modifiers & QtCore.Qt.ControlModifier)
  939. def _create_control(self):
  940. """ Creates and connects the underlying text widget.
  941. """
  942. # Create the underlying control.
  943. if self.custom_control:
  944. control = self.custom_control()
  945. elif self.kind == 'plain':
  946. control = QtWidgets.QPlainTextEdit()
  947. elif self.kind == 'rich':
  948. control = QtWidgets.QTextEdit()
  949. control.setAcceptRichText(False)
  950. control.setMouseTracking(True)
  951. # Prevent the widget from handling drops, as we already provide
  952. # the logic in this class.
  953. control.setAcceptDrops(False)
  954. # Install event filters. The filter on the viewport is needed for
  955. # mouse events.
  956. control.installEventFilter(self)
  957. control.viewport().installEventFilter(self)
  958. # Connect signals.
  959. control.customContextMenuRequested.connect(
  960. self._custom_context_menu_requested)
  961. control.copyAvailable.connect(self.copy_available)
  962. control.redoAvailable.connect(self.redo_available)
  963. control.undoAvailable.connect(self.undo_available)
  964. # Hijack the document size change signal to prevent Qt from adjusting
  965. # the viewport's scrollbar. We are relying on an implementation detail
  966. # of Q(Plain)TextEdit here, which is potentially dangerous, but without
  967. # this functionality we cannot create a nice terminal interface.
  968. layout = control.document().documentLayout()
  969. layout.documentSizeChanged.disconnect()
  970. layout.documentSizeChanged.connect(self._adjust_scrollbars)
  971. # Configure the scrollbar policy
  972. if self.scrollbar_visibility:
  973. scrollbar_policy = QtCore.Qt.ScrollBarAlwaysOn
  974. else :
  975. scrollbar_policy = QtCore.Qt.ScrollBarAlwaysOff
  976. # Configure the control.
  977. control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
  978. control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
  979. control.setReadOnly(True)
  980. control.setUndoRedoEnabled(False)
  981. control.setVerticalScrollBarPolicy(scrollbar_policy)
  982. return control
  983. def _create_page_control(self):
  984. """ Creates and connects the underlying paging widget.
  985. """
  986. if self.custom_page_control:
  987. control = self.custom_page_control()
  988. elif self.kind == 'plain':
  989. control = QtWidgets.QPlainTextEdit()
  990. elif self.kind == 'rich':
  991. control = QtWidgets.QTextEdit()
  992. control.installEventFilter(self)
  993. viewport = control.viewport()
  994. viewport.installEventFilter(self)
  995. control.setReadOnly(True)
  996. control.setUndoRedoEnabled(False)
  997. # Configure the scrollbar policy
  998. if self.scrollbar_visibility:
  999. scrollbar_policy = QtCore.Qt.ScrollBarAlwaysOn
  1000. else :
  1001. scrollbar_policy = QtCore.Qt.ScrollBarAlwaysOff
  1002. control.setVerticalScrollBarPolicy(scrollbar_policy)
  1003. return control
  1004. def _event_filter_console_keypress(self, event):
  1005. """ Filter key events for the underlying text widget to create a
  1006. console-like interface.
  1007. """
  1008. intercepted = False
  1009. cursor = self._control.textCursor()
  1010. position = cursor.position()
  1011. key = event.key()
  1012. ctrl_down = self._control_key_down(event.modifiers())
  1013. alt_down = event.modifiers() & QtCore.Qt.AltModifier
  1014. shift_down = event.modifiers() & QtCore.Qt.ShiftModifier
  1015. #------ Special modifier logic -----------------------------------------
  1016. if key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
  1017. intercepted = True
  1018. # Special handling when tab completing in text mode.
  1019. self._cancel_completion()
  1020. if self._in_buffer(position):
  1021. # Special handling when a reading a line of raw input.
  1022. if self._reading:
  1023. self._append_plain_text('\n')
  1024. self._reading = False
  1025. if self._reading_callback:
  1026. self._reading_callback()
  1027. # If the input buffer is a single line or there is only
  1028. # whitespace after the cursor, execute. Otherwise, split the
  1029. # line with a continuation prompt.
  1030. elif not self._executing:
  1031. cursor.movePosition(QtGui.QTextCursor.End,
  1032. QtGui.QTextCursor.KeepAnchor)
  1033. at_end = len(cursor.selectedText().strip()) == 0
  1034. single_line = (self._get_end_cursor().blockNumber() ==
  1035. self._get_prompt_cursor().blockNumber())
  1036. if (at_end or shift_down or single_line) and not ctrl_down:
  1037. self.execute(interactive = not shift_down)
  1038. else:
  1039. # Do this inside an edit block for clean undo/redo.
  1040. pos = self._get_input_buffer_cursor_pos()
  1041. def callback(complete, indent):
  1042. try:
  1043. cursor.beginEditBlock()
  1044. cursor.setPosition(position)
  1045. cursor.insertText('\n')
  1046. self._insert_continuation_prompt(cursor)
  1047. if indent:
  1048. cursor.insertText(indent)
  1049. finally:
  1050. cursor.endEditBlock()
  1051. # Ensure that the whole input buffer is visible.
  1052. # FIXME: This will not be usable if the input buffer is
  1053. # taller than the console widget.
  1054. self._control.moveCursor(QtGui.QTextCursor.End)
  1055. self._control.setTextCursor(cursor)
  1056. self._register_is_complete_callback(
  1057. self._get_input_buffer()[:pos], callback)
  1058. #------ Control/Cmd modifier -------------------------------------------
  1059. elif ctrl_down:
  1060. if key == QtCore.Qt.Key_G:
  1061. self._keyboard_quit()
  1062. intercepted = True
  1063. elif key == QtCore.Qt.Key_K:
  1064. if self._in_buffer(position):
  1065. cursor.clearSelection()
  1066. cursor.movePosition(QtGui.QTextCursor.EndOfLine,
  1067. QtGui.QTextCursor.KeepAnchor)
  1068. if not cursor.hasSelection():
  1069. # Line deletion (remove continuation prompt)
  1070. cursor.movePosition(QtGui.QTextCursor.NextBlock,
  1071. QtGui.QTextCursor.KeepAnchor)
  1072. cursor.movePosition(QtGui.QTextCursor.Right,
  1073. QtGui.QTextCursor.KeepAnchor,
  1074. len(self._continuation_prompt))
  1075. self._kill_ring.kill_cursor(cursor)
  1076. self._set_cursor(cursor)
  1077. intercepted = True
  1078. elif key == QtCore.Qt.Key_L:
  1079. self.prompt_to_top()
  1080. intercepted = True
  1081. elif key == QtCore.Qt.Key_O:
  1082. if self._page_control and self._page_control.isVisible():
  1083. self._page_control.setFocus()
  1084. intercepted = True
  1085. elif key == QtCore.Qt.Key_U:
  1086. if self._in_buffer(position):
  1087. cursor.clearSelection()
  1088. start_line = cursor.blockNumber()
  1089. if start_line == self._get_prompt_cursor().blockNumber():
  1090. offset = len(self._prompt)
  1091. else:
  1092. offset = len(self._continuation_prompt)
  1093. cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
  1094. QtGui.QTextCursor.KeepAnchor)
  1095. cursor.movePosition(QtGui.QTextCursor.Right,
  1096. QtGui.QTextCursor.KeepAnchor, offset)
  1097. self._kill_ring.kill_cursor(cursor)
  1098. self._set_cursor(cursor)
  1099. intercepted = True
  1100. elif key == QtCore.Qt.Key_Y:
  1101. self._keep_cursor_in_buffer()
  1102. self._kill_ring.yank()
  1103. intercepted = True
  1104. elif key in (QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete):
  1105. if key == QtCore.Qt.Key_Backspace:
  1106. cursor = self._get_word_start_cursor(position)
  1107. else: # key == QtCore.Qt.Key_Delete
  1108. cursor = self._get_word_end_cursor(position)
  1109. cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
  1110. self._kill_ring.kill_cursor(cursor)
  1111. intercepted = True
  1112. elif key == QtCore.Qt.Key_D:
  1113. if len(self.input_buffer) == 0 and not self._executing:
  1114. self.exit_requested.emit(self)
  1115. # if executing and input buffer empty
  1116. elif len(self._get_input_buffer(force=True)) == 0:
  1117. # input a EOT ansi control character
  1118. self._control.textCursor().insertText(chr(4))
  1119. new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
  1120. QtCore.Qt.Key_Return,
  1121. QtCore.Qt.NoModifier)
  1122. QtWidgets.qApp.sendEvent(self._control, new_event)
  1123. intercepted = True
  1124. else:
  1125. new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
  1126. QtCore.Qt.Key_Delete,
  1127. QtCore.Qt.NoModifier)
  1128. QtWidgets.qApp.sendEvent(self._control, new_event)
  1129. intercepted = True
  1130. #------ Alt modifier ---------------------------------------------------
  1131. elif alt_down:
  1132. if key == QtCore.Qt.Key_B:
  1133. self._set_cursor(self._get_word_start_cursor(position))
  1134. intercepted = True
  1135. elif key == QtCore.Qt.Key_F:
  1136. self._set_cursor(self._get_word_end_cursor(position))
  1137. intercepted = True
  1138. elif key == QtCore.Qt.Key_Y:
  1139. self._kill_ring.rotate()
  1140. intercepted = True
  1141. elif key == QtCore.Qt.Key_Backspace:
  1142. cursor = self._get_word_start_cursor(position)
  1143. cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
  1144. self._kill_ring.kill_cursor(cursor)
  1145. intercepted = True
  1146. elif key == QtCore.Qt.Key_D:
  1147. cursor = self._get_word_end_cursor(position)
  1148. cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
  1149. self._kill_ring.kill_cursor(cursor)
  1150. intercepted = True
  1151. elif key == QtCore.Qt.Key_Delete:
  1152. intercepted = True
  1153. elif key == QtCore.Qt.Key_Greater:
  1154. self._control.moveCursor(QtGui.QTextCursor.End)
  1155. intercepted = True
  1156. elif key == QtCore.Qt.Key_Less:
  1157. self._control.setTextCursor(self._get_prompt_cursor())
  1158. intercepted = True
  1159. #------ No modifiers ---------------------------------------------------
  1160. else:
  1161. self._trigger_is_complete_callback()
  1162. if shift_down:
  1163. anchormode = QtGui.QTextCursor.KeepAnchor
  1164. else:
  1165. anchormode = QtGui.QTextCursor.MoveAnchor
  1166. if key == QtCore.Qt.Key_Escape:
  1167. self._keyboard_quit()
  1168. intercepted = True
  1169. elif key == QtCore.Qt.Key_Up:
  1170. if self._reading or not self._up_pressed(shift_down):
  1171. intercepted = True
  1172. else:
  1173. prompt_line = self._get_prompt_cursor().blockNumber()
  1174. intercepted = cursor.blockNumber() <= prompt_line
  1175. elif key == QtCore.Qt.Key_Down:
  1176. if self._reading or not self._down_pressed(shift_down):
  1177. intercepted = True
  1178. else:
  1179. end_line = self._get_end_cursor().blockNumber()
  1180. intercepted = cursor.blockNumber() == end_line
  1181. elif key == QtCore.Qt.Key_Tab:
  1182. if not self._reading:
  1183. if self._tab_pressed():
  1184. self._indent(dedent=False)
  1185. intercepted = True
  1186. elif key == QtCore.Qt.Key_Backtab:
  1187. self._indent(dedent=True)
  1188. intercepted = True
  1189. elif key == QtCore.Qt.Key_Left:
  1190. # Move to the previous line
  1191. line, col = cursor.blockNumber(), cursor.columnNumber()
  1192. if line > self._get_prompt_cursor().blockNumber() and \
  1193. col == len(self._continuation_prompt):
  1194. self._control.moveCursor(QtGui.QTextCursor.PreviousBlock,
  1195. mode=anchormode)
  1196. self._control.moveCursor(QtGui.QTextCursor.EndOfBlock,
  1197. mode=anchormode)
  1198. intercepted = True
  1199. # Regular left movement
  1200. else:
  1201. intercepted = not self._in_buffer(position - 1)
  1202. elif key == QtCore.Qt.Key_Right:
  1203. #original_block_number = cursor.blockNumber()
  1204. if position == self._get_line_end_pos():
  1205. cursor.movePosition(QtGui.QTextCursor.NextBlock, mode=anchormode)
  1206. cursor.movePosition(QtGui.QTextCursor.Right,
  1207. mode=anchormode,
  1208. n=len(self._continuation_prompt))
  1209. self._control.setTextCursor(cursor)
  1210. else:
  1211. self._control.moveCursor(QtGui.QTextCursor.Right,
  1212. mode=anchormode)
  1213. intercepted = True
  1214. elif key == QtCore.Qt.Key_Home:
  1215. start_pos = self._get_line_start_pos()
  1216. c = self._get_cursor()
  1217. spaces = self._get_leading_spaces()
  1218. if (c.position() > start_pos + spaces or
  1219. c.columnNumber() == len(self._continuation_prompt)):
  1220. start_pos += spaces # Beginning of text
  1221. if shift_down and self._in_buffer(position):
  1222. if c.selectedText():
  1223. sel_max = max(c.selectionStart(), c.selectionEnd())
  1224. cursor.setPosition(sel_max,
  1225. QtGui.QTextCursor.MoveAnchor)
  1226. cursor.setPosition(start_pos, QtGui.QTextCursor.KeepAnchor)
  1227. else:
  1228. cursor.setPosition(start_pos)
  1229. self._set_cursor(cursor)
  1230. intercepted = True
  1231. elif key == QtCore.Qt.Key_Backspace:
  1232. # Line deletion (remove continuation prompt)
  1233. line, col = cursor.blockNumber(), cursor.columnNumber()
  1234. if not self._reading and \
  1235. col == len(self._continuation_prompt) and \
  1236. line > self._get_prompt_cursor().blockNumber():
  1237. cursor.beginEditBlock()
  1238. cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
  1239. QtGui.QTextCursor.KeepAnchor)
  1240. cursor.removeSelectedText()
  1241. cursor.deletePreviousChar()
  1242. cursor.endEditBlock()
  1243. intercepted = True
  1244. # Regular backwards deletion
  1245. else:
  1246. anchor = cursor.anchor()
  1247. if anchor == position:
  1248. intercepted = not self._in_buffer(position - 1)
  1249. else:
  1250. intercepted = not self._in_buffer(min(anchor, position))
  1251. elif key == QtCore.Qt.Key_Delete:
  1252. # Line deletion (remove continuation prompt)
  1253. if not self._reading and self._in_buffer(position) and \
  1254. cursor.atBlockEnd() and not cursor.hasSelection():
  1255. cursor.movePosition(QtGui.QTextCursor.NextBlock,
  1256. QtGui.QTextCursor.KeepAnchor)
  1257. cursor.movePosition(QtGui.QTextCursor.Right,
  1258. QtGui.QTextCursor.KeepAnchor,
  1259. len(self._continuation_prompt))
  1260. cursor.removeSelectedText()
  1261. intercepted = True
  1262. # Regular forwards deletion:
  1263. else:
  1264. anchor = cursor.anchor()
  1265. intercepted = (not self._in_buffer(anchor) or
  1266. not self._in_buffer(position))
  1267. #------ Special sequences ----------------------------------------------
  1268. if not intercepted:
  1269. if event.matches(QtGui.QKeySequence.Copy):
  1270. self.copy()
  1271. intercepted = True
  1272. elif event.matches(QtGui.QKeySequence.Cut):
  1273. self.cut()
  1274. intercepted = True
  1275. elif event.matches(QtGui.QKeySequence.Paste):
  1276. self.paste()
  1277. intercepted = True
  1278. # Don't move the cursor if Control/Cmd is pressed to allow copy-paste
  1279. # using the keyboard in any part of the buffer. Also, permit scrolling
  1280. # with Page Up/Down keys. Finally, if we're executing, don't move the
  1281. # cursor (if even this made sense, we can't guarantee that the prompt
  1282. # position is still valid due to text truncation).
  1283. if not (self._control_key_down(event.modifiers(), include_command=True)
  1284. or key in (QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown)
  1285. or (self._executing and not self._reading)):
  1286. self._keep_cursor_in_buffer()
  1287. return intercepted
  1288. def _event_filter_page_keypress(self, event):
  1289. """ Filter key events for the paging widget to create console-like
  1290. interface.
  1291. """
  1292. key = event.key()
  1293. ctrl_down = self._control_key_down(event.modifiers())
  1294. alt_down = event.modifiers() & QtCore.Qt.AltModifier
  1295. if ctrl_down:
  1296. if key == QtCore.Qt.Key_O:
  1297. self._control.setFocus()
  1298. return True
  1299. elif alt_down:
  1300. if key == QtCore.Qt.Key_Greater:
  1301. self._page_control.moveCursor(QtGui.QTextCursor.End)
  1302. return True
  1303. elif key == QtCore.Qt.Key_Less:
  1304. self._page_control.moveCursor(QtGui.QTextCursor.Start)
  1305. return True
  1306. elif key in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape):
  1307. if self._splitter:
  1308. self._page_control.hide()
  1309. self._control.setFocus()
  1310. else:
  1311. self.layout().setCurrentWidget(self._control)
  1312. # re-enable buffer truncation after paging
  1313. self._control.document().setMaximumBlockCount(self.buffer_size)
  1314. return True
  1315. elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return,
  1316. QtCore.Qt.Key_Tab):
  1317. new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
  1318. QtCore.Qt.Key_PageDown,
  1319. QtCore.Qt.NoModifier)
  1320. QtWidgets.qApp.sendEvent(self._page_control, new_event)
  1321. return True
  1322. elif key == QtCore.Qt.Key_Backspace:
  1323. new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
  1324. QtCore.Qt.Key_PageUp,
  1325. QtCore.Qt.NoModifier)
  1326. QtWidgets.qApp.sendEvent(self._page_control, new_event)
  1327. return True
  1328. # vi/less -like key bindings
  1329. elif key == QtCore.Qt.Key_J:
  1330. new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
  1331. QtCore.Qt.Key_Down,
  1332. QtCore.Qt.NoModifier)
  1333. QtWidgets.qApp.sendEvent(self._page_control, new_event)
  1334. return True
  1335. # vi/less -like key bindings
  1336. elif key == QtCore.Qt.Key_K:
  1337. new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
  1338. QtCore.Qt.Key_Up,
  1339. QtCore.Qt.NoModifier)
  1340. QtWidgets.qApp.sendEvent(self._page_control, new_event)
  1341. return True
  1342. return False
  1343. def _on_flush_pending_stream_timer(self):
  1344. """ Flush the pending stream output and change the
  1345. prompt position appropriately.
  1346. """
  1347. cursor = self._control.textCursor()
  1348. cursor.movePosition(QtGui.QTextCursor.End)
  1349. self._flush_pending_stream()
  1350. cursor.movePosition(QtGui.QTextCursor.End)
  1351. def _flush_pending_stream(self):
  1352. """ Flush out pending text into the widget. """
  1353. text = self._pending_insert_text
  1354. self._pending_insert_text = []
  1355. buffer_size = self._control.document().maximumBlockCount()
  1356. if buffer_size > 0:
  1357. text = self._get_last_lines_from_list(text, buffer_size)
  1358. text = ''.join(text)
  1359. t = time.time()
  1360. self._insert_plain_text(self._get_end_cursor(), text, flush=True)
  1361. # Set the flush interval to equal the maximum time to update text.
  1362. self._pending_text_flush_interval.setInterval(max(100,
  1363. (time.time()-t)*1000))
  1364. def _format_as_columns(self, items, separator=' '):
  1365. """ Transform a list of strings into a single string with columns.
  1366. Parameters
  1367. ----------
  1368. items : sequence of strings
  1369. The strings to process.
  1370. separator : str, optional [default is two spaces]
  1371. The string that separates columns.
  1372. Returns
  1373. -------
  1374. The formatted string.
  1375. """
  1376. # Calculate the number of characters available.
  1377. width = self._control.document().textWidth()
  1378. char_width = QtGui.QFontMetrics(self.font).width(' ')
  1379. displaywidth = max(10, (width / char_width) - 1)
  1380. return columnize(items, separator, displaywidth)
  1381. def _get_block_plain_text(self, block):
  1382. """ Given a QTextBlock, return its unformatted text.
  1383. """
  1384. cursor = QtGui.QTextCursor(block)
  1385. cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
  1386. cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
  1387. QtGui.QTextCursor.KeepAnchor)
  1388. return cursor.selection().toPlainText()
  1389. def _get_cursor(self):
  1390. """ Get a cursor at the current insert position.
  1391. """
  1392. return self._control.textCursor()
  1393. def _get_end_cursor(self):
  1394. """ Get a cursor at the last character of the current cell.
  1395. """
  1396. cursor = self._control.textCursor()
  1397. cursor.movePosition(QtGui.QTextCursor.End)
  1398. return cursor
  1399. def _get_end_pos(self):
  1400. """ Get the position of the last character of the current cell.
  1401. """
  1402. return self._get_end_cursor().position()
  1403. def _get_line_start_cursor(self):
  1404. """ Get a cursor at the first character of the current line.
  1405. """
  1406. cursor = self._control.textCursor()
  1407. start_line = cursor.blockNumber()
  1408. if start_line == self._get_prompt_cursor().blockNumber():
  1409. cursor.setPosition(self._prompt_pos)
  1410. else:
  1411. cursor.movePosition(QtGui.QTextCursor.StartOfLine)
  1412. cursor.setPosition(cursor.position() +
  1413. len(self._continuation_prompt))
  1414. return cursor
  1415. def _get_line_start_pos(self):
  1416. """ Get the position of the first character of the current line.
  1417. """
  1418. return self._get_line_start_cursor().position()
  1419. def _get_line_end_cursor(self):
  1420. """ Get a cursor at the last character of the current line.
  1421. """
  1422. cursor = self._control.textCursor()
  1423. cursor.movePosition(QtGui.QTextCursor.EndOfLine)
  1424. return cursor
  1425. def _get_line_end_pos(self):
  1426. """ Get the position of the last character of the current line.
  1427. """
  1428. return self._get_line_end_cursor().position()
  1429. def _get_input_buffer_cursor_column(self):
  1430. """ Get the column of the cursor in the input buffer, excluding the
  1431. contribution by the prompt, or -1 if there is no such column.
  1432. """
  1433. prompt = self._get_input_buffer_cursor_prompt()
  1434. if prompt is None:
  1435. return -1
  1436. else:
  1437. cursor = self._control.textCursor()
  1438. return cursor.columnNumber() - len(prompt)
  1439. def _get_input_buffer_cursor_line(self):
  1440. """ Get the text of the line of the input buffer that contains the
  1441. cursor, or None if there is no such line.
  1442. """
  1443. prompt = self._get_input_buffer_cursor_prompt()
  1444. if prompt is None:
  1445. return None
  1446. else:
  1447. cursor = self._control.textCursor()
  1448. text = self._get_block_plain_text(cursor.block())
  1449. return text[len(prompt):]
  1450. def _get_input_buffer_cursor_pos(self):
  1451. """Get the cursor position within the input buffer."""
  1452. cursor = self._control.textCursor()
  1453. cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
  1454. input_buffer = cursor.selection().toPlainText()
  1455. # Don't count continuation prompts
  1456. return len(input_buffer.replace('\n' + self._continuation_prompt, '\n'))
  1457. def _get_input_buffer_cursor_prompt(self):
  1458. """ Returns the (plain text) prompt for line of the input buffer that
  1459. contains the cursor, or None if there is no such line.
  1460. """
  1461. if self._executing:
  1462. return None
  1463. cursor = self._control.textCursor()
  1464. if cursor.position() >= self._prompt_pos:
  1465. if cursor.blockNumber() == self._get_prompt_cursor().blockNumber():
  1466. return self._prompt
  1467. else:
  1468. return self._continuation_prompt
  1469. else:
  1470. return None
  1471. def _get_last_lines(self, text, num_lines, return_count=False):
  1472. """ Get the last specified number of lines of text (like `tail -n`).
  1473. If return_count is True, returns a tuple of clipped text and the
  1474. number of lines in the clipped text.
  1475. """
  1476. pos = len(text)
  1477. if pos < num_lines:
  1478. if return_count:
  1479. return text, text.count('\n') if return_count else text
  1480. else:
  1481. return text
  1482. i = 0
  1483. while i < num_lines:
  1484. pos = text.rfind('\n', None, pos)
  1485. if pos == -1:
  1486. pos = None
  1487. break
  1488. i += 1
  1489. if return_count:
  1490. return text[pos:], i
  1491. else:
  1492. return text[pos:]
  1493. def _get_last_lines_from_list(self, text_list, num_lines):
  1494. """ Get the list of text clipped to last specified lines.
  1495. """
  1496. ret = []
  1497. lines_pending = num_lines
  1498. for text in reversed(text_list):
  1499. text, lines_added = self._get_last_lines(text, lines_pending,
  1500. return_count=True)
  1501. ret.append(text)
  1502. lines_pending -= lines_added
  1503. if lines_pending <= 0:
  1504. break
  1505. return ret[::-1]
  1506. def _get_leading_spaces(self):
  1507. """ Get the number of leading spaces of the current line.
  1508. """
  1509. cursor = self._get_cursor()
  1510. start_line = cursor.blockNumber()
  1511. if start_line == self._get_prompt_cursor().blockNumber():
  1512. # first line
  1513. offset = len(self._prompt)
  1514. else:
  1515. # continuation
  1516. offset = len(self._continuation_prompt)
  1517. cursor.select(QtGui.QTextCursor.LineUnderCursor)
  1518. text = cursor.selectedText()[offset:]
  1519. return len(text) - len(text.lstrip())
  1520. @property
  1521. def _prompt_pos(self):
  1522. """ Find the position in the text right after the prompt.
  1523. """
  1524. return min(self._prompt_cursor.position() + 1, self._get_end_pos())
  1525. @property
  1526. def _append_before_prompt_pos(self):
  1527. """ Find the position in the text right before the prompt.
  1528. """
  1529. return min(self._append_before_prompt_cursor.position(),
  1530. self._get_end_pos())
  1531. def _get_prompt_cursor(self):
  1532. """ Get a cursor at the prompt position of the current cell.
  1533. """
  1534. cursor = self._control.textCursor()
  1535. cursor.setPosition(self._prompt_pos)
  1536. return cursor
  1537. def _get_selection_cursor(self, start, end):
  1538. """ Get a cursor with text selected between the positions 'start' and
  1539. 'end'.
  1540. """
  1541. cursor = self._control.textCursor()
  1542. cursor.setPosition(start)
  1543. cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
  1544. return cursor
  1545. def _get_word_start_cursor(self, position):
  1546. """ Find the start of the word to the left the given position. If a
  1547. sequence of non-word characters precedes the first word, skip over
  1548. them. (This emulates the behavior of bash, emacs, etc.)
  1549. """
  1550. document = self._control.document()
  1551. cursor = self._control.textCursor()
  1552. line_start_pos = self._get_line_start_pos()
  1553. if position == self._prompt_pos:
  1554. return cursor
  1555. elif position == line_start_pos:
  1556. # Cursor is at the beginning of a line, move to the last
  1557. # non-whitespace character of the previous line
  1558. cursor = self._control.textCursor()
  1559. cursor.setPosition(position)
  1560. cursor.movePosition(QtGui.QTextCursor.PreviousBlock)
  1561. cursor.movePosition(QtGui.QTextCursor.EndOfBlock)
  1562. position = cursor.position()
  1563. while (
  1564. position >= self._prompt_pos and
  1565. is_whitespace(document.characterAt(position))
  1566. ):
  1567. position -= 1
  1568. cursor.setPosition(position + 1)
  1569. else:
  1570. position -= 1
  1571. # Find the last alphanumeric char, but don't move across lines
  1572. while (
  1573. position >= self._prompt_pos and
  1574. position >= line_start_pos and
  1575. not is_letter_or_number(document.characterAt(position))
  1576. ):
  1577. position -= 1
  1578. # Find the first alphanumeric char, but don't move across lines
  1579. while (
  1580. position >= self._prompt_pos and
  1581. position >= line_start_pos and
  1582. is_letter_or_number(document.characterAt(position))
  1583. ):
  1584. position -= 1
  1585. cursor.setPosition(position + 1)
  1586. return cursor
  1587. def _get_word_end_cursor(self, position):
  1588. """ Find the end of the word to the right the given position. If a
  1589. sequence of non-word characters precedes the first word, skip over
  1590. them. (This emulates the behavior of bash, emacs, etc.)
  1591. """
  1592. document = self._control.document()
  1593. cursor = self._control.textCursor()
  1594. end_pos = self._get_end_pos()
  1595. line_end_pos = self._get_line_end_pos()
  1596. if position == end_pos:
  1597. # Cursor is at the very end of the buffer
  1598. return cursor
  1599. elif position == line_end_pos:
  1600. # Cursor is at the end of a line, move to the first
  1601. # non-whitespace character of the next line
  1602. cursor = self._control.textCursor()
  1603. cursor.setPosition(position)
  1604. cursor.movePosition(QtGui.QTextCursor.NextBlock)
  1605. position = cursor.position() + len(self._continuation_prompt)
  1606. while (
  1607. position < end_pos and
  1608. is_whitespace(document.characterAt(position))
  1609. ):
  1610. position += 1
  1611. cursor.setPosition(position)
  1612. else:
  1613. if is_whitespace(document.characterAt(position)):
  1614. # The next character is whitespace. If this is part of
  1615. # indentation whitespace, skip to the first non-whitespace
  1616. # character.
  1617. is_indentation_whitespace = True
  1618. back_pos = position - 1
  1619. line_start_pos = self._get_line_start_pos()
  1620. while back_pos >= line_start_pos:
  1621. if not is_whitespace(document.characterAt(back_pos)):
  1622. is_indentation_whitespace = False
  1623. break
  1624. back_pos -= 1
  1625. if is_indentation_whitespace:
  1626. # Skip to the first non-whitespace character
  1627. while (
  1628. position < end_pos and
  1629. position < line_end_pos and
  1630. is_whitespace(document.characterAt(position))
  1631. ):
  1632. position += 1
  1633. cursor.setPosition(position)
  1634. return cursor
  1635. while (
  1636. position < end_pos and
  1637. position < line_end_pos and
  1638. not is_letter_or_number(document.characterAt(position))
  1639. ):
  1640. position += 1
  1641. while (
  1642. position < end_pos and
  1643. position < line_end_pos and
  1644. is_letter_or_number(document.characterAt(position))
  1645. ):
  1646. position += 1
  1647. cursor.setPosition(position)
  1648. return cursor
  1649. def _indent(self, dedent=True):
  1650. """ Indent/Dedent current line or current text selection.
  1651. """
  1652. num_newlines = self._get_cursor().selectedText().count(u"\u2029")
  1653. save_cur = self._get_cursor()
  1654. cur = self._get_cursor()
  1655. # move to first line of selection, if present
  1656. cur.setPosition(cur.selectionStart())
  1657. self._control.setTextCursor(cur)
  1658. spaces = self._get_leading_spaces()
  1659. # calculate number of spaces neded to align/indent to 4-space multiple
  1660. step = self._tab_width - (spaces % self._tab_width)
  1661. # insertText shouldn't replace if selection is active
  1662. cur.clearSelection()
  1663. # indent all lines in selection (ir just current) by `step`
  1664. for _ in range(num_newlines+1):
  1665. # update underlying cursor for _get_line_start_pos
  1666. self._control.setTextCursor(cur)
  1667. # move to first non-ws char on line
  1668. cur.setPosition(self._get_line_start_pos())
  1669. if dedent:
  1670. spaces = min(step, self._get_leading_spaces())
  1671. safe_step = spaces % self._tab_width
  1672. cur.movePosition(QtGui.QTextCursor.Right,
  1673. QtGui.QTextCursor.KeepAnchor,
  1674. min(spaces, safe_step if safe_step != 0
  1675. else self._tab_width))
  1676. cur.removeSelectedText()
  1677. else:
  1678. cur.insertText(' '*step)
  1679. cur.movePosition(QtGui.QTextCursor.Down)
  1680. # restore cursor
  1681. self._control.setTextCursor(save_cur)
  1682. def _insert_continuation_prompt(self, cursor, indent=''):
  1683. """ Inserts new continuation prompt using the specified cursor.
  1684. """
  1685. if self._continuation_prompt_html is None:
  1686. self._insert_plain_text(cursor, self._continuation_prompt)
  1687. else:
  1688. self._continuation_prompt = self._insert_html_fetching_plain_text(
  1689. cursor, self._continuation_prompt_html)
  1690. if indent:
  1691. cursor.insertText(indent)
  1692. def _insert_block(self, cursor, block_format=None):
  1693. """ Inserts an empty QTextBlock using the specified cursor.
  1694. """
  1695. if block_format is None:
  1696. block_format = QtGui.QTextBlockFormat()
  1697. cursor.insertBlock(block_format)
  1698. def _insert_html(self, cursor, html):
  1699. """ Inserts HTML using the specified cursor in such a way that future
  1700. formatting is unaffected.
  1701. """
  1702. cursor.beginEditBlock()
  1703. cursor.insertHtml(html)
  1704. # After inserting HTML, the text document "remembers" it's in "html
  1705. # mode", which means that subsequent calls adding plain text will result
  1706. # in unwanted formatting, lost tab characters, etc. The following code
  1707. # hacks around this behavior, which I consider to be a bug in Qt, by
  1708. # (crudely) resetting the document's style state.
  1709. cursor.movePosition(QtGui.QTextCursor.Left,
  1710. QtGui.QTextCursor.KeepAnchor)
  1711. if cursor.selection().toPlainText() == ' ':
  1712. cursor.removeSelectedText()
  1713. else:
  1714. cursor.movePosition(QtGui.QTextCursor.Right)
  1715. cursor.insertText(' ', QtGui.QTextCharFormat())
  1716. cursor.endEditBlock()
  1717. def _insert_html_fetching_plain_text(self, cursor, html):
  1718. """ Inserts HTML using the specified cursor, then returns its plain text
  1719. version.
  1720. """
  1721. cursor.beginEditBlock()
  1722. cursor.removeSelectedText()
  1723. start = cursor.position()
  1724. self._insert_html(cursor, html)
  1725. end = cursor.position()
  1726. cursor.setPosition(start, QtGui.QTextCursor.KeepAnchor)
  1727. text = cursor.selection().toPlainText()
  1728. cursor.setPosition(end)
  1729. cursor.endEditBlock()
  1730. return text
  1731. def _insert_plain_text(self, cursor, text, flush=False):
  1732. """ Inserts plain text using the specified cursor, processing ANSI codes
  1733. if enabled.
  1734. """
  1735. # maximumBlockCount() can be different from self.buffer_size in
  1736. # case input prompt is active.
  1737. buffer_size = self._control.document().maximumBlockCount()
  1738. if (self._executing and not flush and
  1739. self._pending_text_flush_interval.isActive() and
  1740. cursor.position() == self._get_end_pos()):
  1741. # Queue the text to insert in case it is being inserted at end
  1742. self._pending_insert_text.append(text)
  1743. if buffer_size > 0:
  1744. self._pending_insert_text = self._get_last_lines_from_list(
  1745. self._pending_insert_text, buffer_size)
  1746. return
  1747. if self._executing and not self._pending_text_flush_interval.isActive():
  1748. self._pending_text_flush_interval.start()
  1749. # Clip the text to last `buffer_size` lines.
  1750. if buffer_size > 0:
  1751. text = self._get_last_lines(text, buffer_size)
  1752. viewport = self._control.viewport()
  1753. end_scroll_pos = self._control.cursorForPosition(
  1754. QtCore.QPoint(viewport.width()-1, viewport.height()-1)
  1755. ).position()
  1756. end_doc_pos = self._get_end_pos()
  1757. cursor.beginEditBlock()
  1758. if self.ansi_codes:
  1759. for substring in self._ansi_processor.split_string(text):
  1760. for act in self._ansi_processor.actions:
  1761. # Unlike real terminal emulators, we don't distinguish
  1762. # between the screen and the scrollback buffer. A screen
  1763. # erase request clears everything.
  1764. if act.action == 'erase' and act.area == 'screen':
  1765. cursor.select(QtGui.QTextCursor.Document)
  1766. cursor.removeSelectedText()
  1767. # Simulate a form feed by scrolling just past the last line.
  1768. elif act.action == 'scroll' and act.unit == 'page':
  1769. cursor.insertText('\n')
  1770. cursor.endEditBlock()
  1771. self._set_top_cursor(cursor)
  1772. cursor.joinPreviousEditBlock()
  1773. cursor.deletePreviousChar()
  1774. if os.name == 'nt':
  1775. cursor.select(QtGui.QTextCursor.Document)
  1776. cursor.removeSelectedText()
  1777. elif act.action == 'carriage-return':
  1778. cursor.movePosition(
  1779. cursor.StartOfLine, cursor.KeepAnchor)
  1780. elif act.action == 'beep':
  1781. QtWidgets.qApp.beep()
  1782. elif act.action == 'backspace':
  1783. if not cursor.atBlockStart():
  1784. cursor.movePosition(
  1785. cursor.PreviousCharacter, cursor.KeepAnchor)
  1786. elif act.action == 'newline':
  1787. cursor.movePosition(cursor.EndOfLine)
  1788. format = self._ansi_processor.get_format()
  1789. selection = cursor.selectedText()
  1790. if len(selection) == 0:
  1791. cursor.insertText(substring, format)
  1792. elif substring is not None:
  1793. # BS and CR are treated as a change in print
  1794. # position, rather than a backwards character
  1795. # deletion for output equivalence with (I)Python
  1796. # terminal.
  1797. if len(substring) >= len(selection):
  1798. cursor.insertText(substring, format)
  1799. else:
  1800. old_text = selection[len(substring):]
  1801. cursor.insertText(substring + old_text, format)
  1802. cursor.movePosition(cursor.PreviousCharacter,
  1803. cursor.KeepAnchor, len(old_text))
  1804. else:
  1805. cursor.insertText(text)
  1806. cursor.endEditBlock()
  1807. if end_doc_pos - end_scroll_pos <= 1:
  1808. end_scroll = (self._control.verticalScrollBar().maximum()
  1809. - self._control.verticalScrollBar().pageStep())
  1810. # Only scroll down
  1811. if end_scroll > self._control.verticalScrollBar().value():
  1812. self._control.verticalScrollBar().setValue(end_scroll)
  1813. def _insert_plain_text_into_buffer(self, cursor, text):
  1814. """ Inserts text into the input buffer using the specified cursor (which
  1815. must be in the input buffer), ensuring that continuation prompts are
  1816. inserted as necessary.
  1817. """
  1818. lines = text.splitlines(True)
  1819. if lines:
  1820. if lines[-1].endswith('\n'):
  1821. # If the text ends with a newline, add a blank line so a new
  1822. # continuation prompt is produced.
  1823. lines.append('')
  1824. cursor.beginEditBlock()
  1825. cursor.insertText(lines[0])
  1826. for line in lines[1:]:
  1827. if self._continuation_prompt_html is None:
  1828. cursor.insertText(self._continuation_prompt)
  1829. else:
  1830. self._continuation_prompt = \
  1831. self._insert_html_fetching_plain_text(
  1832. cursor, self._continuation_prompt_html)
  1833. cursor.insertText(line)
  1834. cursor.endEditBlock()
  1835. def _in_buffer(self, position=None):
  1836. """ Returns whether the current cursor (or, if specified, a position) is
  1837. inside the editing region.
  1838. """
  1839. cursor = self._control.textCursor()
  1840. if position is None:
  1841. position = cursor.position()
  1842. else:
  1843. cursor.setPosition(position)
  1844. line = cursor.blockNumber()
  1845. prompt_line = self._get_prompt_cursor().blockNumber()
  1846. if line == prompt_line:
  1847. return position >= self._prompt_pos
  1848. elif line > prompt_line:
  1849. cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
  1850. prompt_pos = cursor.position() + len(self._continuation_prompt)
  1851. return position >= prompt_pos
  1852. return False
  1853. def _keep_cursor_in_buffer(self):
  1854. """ Ensures that the cursor is inside the editing region. Returns
  1855. whether the cursor was moved.
  1856. """
  1857. moved = not self._in_buffer()
  1858. if moved:
  1859. cursor = self._control.textCursor()
  1860. cursor.movePosition(QtGui.QTextCursor.End)
  1861. self._control.setTextCursor(cursor)
  1862. return moved
  1863. def _keyboard_quit(self):
  1864. """ Cancels the current editing task ala Ctrl-G in Emacs.
  1865. """
  1866. if self._temp_buffer_filled :
  1867. self._cancel_completion()
  1868. self._clear_temporary_buffer()
  1869. else:
  1870. self.input_buffer = ''
  1871. def _page(self, text, html=False):
  1872. """ Displays text using the pager if it exceeds the height of the
  1873. viewport.
  1874. Parameters
  1875. ----------
  1876. html : bool, optional (default False)
  1877. If set, the text will be interpreted as HTML instead of plain text.
  1878. """
  1879. line_height = QtGui.QFontMetrics(self.font).height()
  1880. minlines = self._control.viewport().height() / line_height
  1881. if self.paging != 'none' and \
  1882. re.match("(?:[^\n]*\n){%i}" % minlines, text):
  1883. if self.paging == 'custom':
  1884. self.custom_page_requested.emit(text)
  1885. else:
  1886. # disable buffer truncation during paging
  1887. self._control.document().setMaximumBlockCount(0)
  1888. self._page_control.clear()
  1889. cursor = self._page_control.textCursor()
  1890. if html:
  1891. self._insert_html(cursor, text)
  1892. else:
  1893. self._insert_plain_text(cursor, text)
  1894. self._page_control.moveCursor(QtGui.QTextCursor.Start)
  1895. self._page_control.viewport().resize(self._control.size())
  1896. if self._splitter:
  1897. self._page_control.show()
  1898. self._page_control.setFocus()
  1899. else:
  1900. self.layout().setCurrentWidget(self._page_control)
  1901. elif html:
  1902. self._append_html(text)
  1903. else:
  1904. self._append_plain_text(text)
  1905. def _set_paging(self, paging):
  1906. """
  1907. Change the pager to `paging` style.
  1908. Parameters
  1909. ----------
  1910. paging : string
  1911. Either "hsplit", "vsplit", or "inside"
  1912. """
  1913. if self._splitter is None:
  1914. raise NotImplementedError("""can only switch if --paging=hsplit or
  1915. --paging=vsplit is used.""")
  1916. if paging == 'hsplit':
  1917. self._splitter.setOrientation(QtCore.Qt.Horizontal)
  1918. elif paging == 'vsplit':
  1919. self._splitter.setOrientation(QtCore.Qt.Vertical)
  1920. elif paging == 'inside':
  1921. raise NotImplementedError("""switching to 'inside' paging not
  1922. supported yet.""")
  1923. else:
  1924. raise ValueError("unknown paging method '%s'" % paging)
  1925. self.paging = paging
  1926. def _prompt_finished(self):
  1927. """ Called immediately after a prompt is finished, i.e. when some input
  1928. will be processed and a new prompt displayed.
  1929. """
  1930. self._control.setReadOnly(True)
  1931. self._prompt_finished_hook()
  1932. def _prompt_started(self):
  1933. """ Called immediately after a new prompt is displayed.
  1934. """
  1935. # Temporarily disable the maximum block count to permit undo/redo and
  1936. # to ensure that the prompt position does not change due to truncation.
  1937. self._control.document().setMaximumBlockCount(0)
  1938. self._control.setUndoRedoEnabled(True)
  1939. # Work around bug in QPlainTextEdit: input method is not re-enabled
  1940. # when read-only is disabled.
  1941. self._control.setReadOnly(False)
  1942. self._control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
  1943. if not self._reading:
  1944. self._executing = False
  1945. self._prompt_started_hook()
  1946. # If the input buffer has changed while executing, load it.
  1947. if self._input_buffer_pending:
  1948. self.input_buffer = self._input_buffer_pending
  1949. self._input_buffer_pending = ''
  1950. self._control.moveCursor(QtGui.QTextCursor.End)
  1951. def _readline(self, prompt='', callback=None, password=False):
  1952. """ Reads one line of input from the user.
  1953. Parameters
  1954. ----------
  1955. prompt : str, optional
  1956. The prompt to print before reading the line.
  1957. callback : callable, optional
  1958. A callback to execute with the read line. If not specified, input is
  1959. read *synchronously* and this method does not return until it has
  1960. been read.
  1961. Returns
  1962. -------
  1963. If a callback is specified, returns nothing. Otherwise, returns the
  1964. input string with the trailing newline stripped.
  1965. """
  1966. if self._reading:
  1967. raise RuntimeError('Cannot read a line. Widget is already reading.')
  1968. if not callback and not self.isVisible():
  1969. # If the user cannot see the widget, this function cannot return.
  1970. raise RuntimeError('Cannot synchronously read a line if the widget '
  1971. 'is not visible!')
  1972. self._reading = True
  1973. if password:
  1974. self._show_prompt('Warning: QtConsole does not support password mode, '\
  1975. 'the text you type will be visible.', newline=True)
  1976. self._show_prompt(prompt, newline=False)
  1977. if callback is None:
  1978. self._reading_callback = None
  1979. while self._reading:
  1980. QtCore.QCoreApplication.processEvents()
  1981. return self._get_input_buffer(force=True).rstrip('\n')
  1982. else:
  1983. self._reading_callback = lambda: \
  1984. callback(self._get_input_buffer(force=True).rstrip('\n'))
  1985. def _set_continuation_prompt(self, prompt, html=False):
  1986. """ Sets the continuation prompt.
  1987. Parameters
  1988. ----------
  1989. prompt : str
  1990. The prompt to show when more input is needed.
  1991. html : bool, optional (default False)
  1992. If set, the prompt will be inserted as formatted HTML. Otherwise,
  1993. the prompt will be treated as plain text, though ANSI color codes
  1994. will be handled.
  1995. """
  1996. if html:
  1997. self._continuation_prompt_html = prompt
  1998. else:
  1999. self._continuation_prompt = prompt
  2000. self._continuation_prompt_html = None
  2001. def _set_cursor(self, cursor):
  2002. """ Convenience method to set the current cursor.
  2003. """
  2004. self._control.setTextCursor(cursor)
  2005. def _set_top_cursor(self, cursor):
  2006. """ Scrolls the viewport so that the specified cursor is at the top.
  2007. """
  2008. scrollbar = self._control.verticalScrollBar()
  2009. scrollbar.setValue(scrollbar.maximum())
  2010. original_cursor = self._control.textCursor()
  2011. self._control.setTextCursor(cursor)
  2012. self._control.ensureCursorVisible()
  2013. self._control.setTextCursor(original_cursor)
  2014. def _show_prompt(self, prompt=None, html=False, newline=True):
  2015. """ Writes a new prompt at the end of the buffer.
  2016. Parameters
  2017. ----------
  2018. prompt : str, optional
  2019. The prompt to show. If not specified, the previous prompt is used.
  2020. html : bool, optional (default False)
  2021. Only relevant when a prompt is specified. If set, the prompt will
  2022. be inserted as formatted HTML. Otherwise, the prompt will be treated
  2023. as plain text, though ANSI color codes will be handled.
  2024. newline : bool, optional (default True)
  2025. If set, a new line will be written before showing the prompt if
  2026. there is not already a newline at the end of the buffer.
  2027. """
  2028. self._flush_pending_stream()
  2029. cursor = self._get_end_cursor()
  2030. # Save the current position to support _append*(before_prompt=True).
  2031. # We can't leave the cursor at the end of the document though, because
  2032. # that would cause any further additions to move the cursor. Therefore,
  2033. # we move it back one place and move it forward again at the end of
  2034. # this method. However, we only do this if the cursor isn't already
  2035. # at the start of the text.
  2036. if cursor.position() == 0:
  2037. move_forward = False
  2038. else:
  2039. move_forward = True
  2040. self._append_before_prompt_cursor.setPosition(cursor.position() - 1)
  2041. # Insert a preliminary newline, if necessary.
  2042. if newline and cursor.position() > 0:
  2043. cursor.movePosition(QtGui.QTextCursor.Left,
  2044. QtGui.QTextCursor.KeepAnchor)
  2045. if cursor.selection().toPlainText() != '\n':
  2046. self._append_block()
  2047. # Write the prompt.
  2048. self._append_plain_text(self._prompt_sep)
  2049. if prompt is None:
  2050. if self._prompt_html is None:
  2051. self._append_plain_text(self._prompt)
  2052. else:
  2053. self._append_html(self._prompt_html)
  2054. else:
  2055. if html:
  2056. self._prompt = self._append_html_fetching_plain_text(prompt)
  2057. self._prompt_html = prompt
  2058. else:
  2059. self._append_plain_text(prompt)
  2060. self._prompt = prompt
  2061. self._prompt_html = None
  2062. self._flush_pending_stream()
  2063. self._prompt_cursor.setPosition(self._get_end_pos() - 1)
  2064. if move_forward:
  2065. self._append_before_prompt_cursor.setPosition(
  2066. self._append_before_prompt_cursor.position() + 1)
  2067. self._prompt_started()
  2068. #------ Signal handlers ----------------------------------------------------
  2069. def _adjust_scrollbars(self):
  2070. """ Expands the vertical scrollbar beyond the range set by Qt.
  2071. """
  2072. # This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp
  2073. # and qtextedit.cpp.
  2074. document = self._control.document()
  2075. scrollbar = self._control.verticalScrollBar()
  2076. viewport_height = self._control.viewport().height()
  2077. if isinstance(self._control, QtWidgets.QPlainTextEdit):
  2078. maximum = max(0, document.lineCount() - 1)
  2079. step = viewport_height / self._control.fontMetrics().lineSpacing()
  2080. else:
  2081. # QTextEdit does not do line-based layout and blocks will not in
  2082. # general have the same height. Therefore it does not make sense to
  2083. # attempt to scroll in line height increments.
  2084. maximum = document.size().height()
  2085. step = viewport_height
  2086. diff = maximum - scrollbar.maximum()
  2087. scrollbar.setRange(0, round(maximum))
  2088. scrollbar.setPageStep(round(step))
  2089. # Compensate for undesirable scrolling that occurs automatically due to
  2090. # maximumBlockCount() text truncation.
  2091. if diff < 0 and document.blockCount() == document.maximumBlockCount():
  2092. scrollbar.setValue(round(scrollbar.value() + diff))
  2093. def _custom_context_menu_requested(self, pos):
  2094. """ Shows a context menu at the given QPoint (in widget coordinates).
  2095. """
  2096. menu = self._context_menu_make(pos)
  2097. menu.exec_(self._control.mapToGlobal(pos))