forked from ipython/ipython
/
console_widget.py
2009 lines (1704 loc) · 79.5 KB
/
console_widget.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
""" An abstract base class for console-type widgets.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
import os.path
import re
import sys
from textwrap import dedent
from unicodedata import category
import webbrowser
# System library imports
from IPython.external.qt import QtCore, QtGui
# Local imports
from IPython.config.configurable import LoggingConfigurable
from IPython.core.inputsplitter import ESC_SEQUENCES
from IPython.frontend.qt.rich_text import HtmlExporter
from IPython.frontend.qt.util import MetaQObjectHasTraits, get_font
from IPython.utils.text import columnize
from IPython.utils.traitlets import Bool, Enum, Integer, Unicode
from ansi_code_processor import QtAnsiCodeProcessor
from completion_widget import CompletionWidget
from completion_html import CompletionHtml
from completion_plain import CompletionPlain
from kill_ring import QtKillRing
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
ESCAPE_CHARS = ''.join(ESC_SEQUENCES)
ESCAPE_RE = re.compile("^["+ESCAPE_CHARS+"]+")
def commonprefix(items):
"""Get common prefix for completions
Return the longest common prefix of a list of strings, but with special
treatment of escape characters that might precede commands in IPython,
such as %magic functions. Used in tab completion.
For a more general function, see os.path.commonprefix
"""
# the last item will always have the least leading % symbol
# min / max are first/last in alphabetical order
first_match = ESCAPE_RE.match(min(items))
last_match = ESCAPE_RE.match(max(items))
# common suffix is (common prefix of reversed items) reversed
if first_match and last_match:
prefix = os.path.commonprefix((first_match.group(0)[::-1], last_match.group(0)[::-1]))[::-1]
else:
prefix = ''
items = [s.lstrip(ESCAPE_CHARS) for s in items]
return prefix+os.path.commonprefix(items)
def is_letter_or_number(char):
""" Returns whether the specified unicode character is a letter or a number.
"""
cat = category(char)
return cat.startswith('L') or cat.startswith('N')
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ConsoleWidget(LoggingConfigurable, QtGui.QWidget):
""" An abstract base class for console-type widgets. This class has
functionality for:
* Maintaining a prompt and editing region
* Providing the traditional Unix-style console keyboard shortcuts
* Performing tab completion
* Paging text
* Handling ANSI escape codes
ConsoleWidget also provides a number of utility methods that will be
convenient to implementors of a console-style widget.
"""
__metaclass__ = MetaQObjectHasTraits
#------ Configuration ------------------------------------------------------
ansi_codes = Bool(True, config=True,
help="Whether to process ANSI escape codes."
)
buffer_size = Integer(500, config=True,
help="""
The maximum number of lines of text before truncation. Specifying a
non-positive number disables text truncation (not recommended).
"""
)
gui_completion = Enum(['plain', 'droplist', 'ncurses'], config=True,
default_value = 'ncurses',
help="""
The type of completer to use. Valid values are:
'plain' : Show the availlable completion as a text list
Below the editting area.
'droplist': Show the completion in a drop down list navigable
by the arrow keys, and from which you can select
completion by pressing Return.
'ncurses' : Show the completion as a text list which is navigable by
`tab` and arrow keys.
"""
)
# NOTE: this value can only be specified during initialization.
kind = Enum(['plain', 'rich'], default_value='plain', config=True,
help="""
The type of underlying text widget to use. Valid values are 'plain',
which specifies a QPlainTextEdit, and 'rich', which specifies a
QTextEdit.
"""
)
# NOTE: this value can only be specified during initialization.
paging = Enum(['inside', 'hsplit', 'vsplit', 'custom', 'none'],
default_value='inside', config=True,
help="""
The type of paging to use. Valid values are:
'inside' : The widget pages like a traditional terminal.
'hsplit' : When paging is requested, the widget is split
horizontally. The top pane contains the console, and the
bottom pane contains the paged text.
'vsplit' : Similar to 'hsplit', except that a vertical splitter
used.
'custom' : No action is taken by the widget beyond emitting a
'custom_page_requested(str)' signal.
'none' : The text is written directly to the console.
""")
font_family = Unicode(config=True,
help="""The font family to use for the console.
On OSX this defaults to Monaco, on Windows the default is
Consolas with fallback of Courier, and on other platforms
the default is Monospace.
""")
def _font_family_default(self):
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
return 'Consolas'
elif sys.platform == 'darwin':
# OSX always has Monaco, no need for a fallback
return 'Monaco'
else:
# Monospace should always exist, no need for a fallback
return 'Monospace'
font_size = Integer(config=True,
help="""The font size. If unconfigured, Qt will be entrusted
with the size of the font.
""")
width = Integer(81, config=True,
help="""The width of the console at start time in number
of characters (will double with `hsplit` paging)
""")
height = Integer(25, config=True,
help="""The height of the console at start time in number
of characters (will double with `vsplit` paging)
""")
# Whether to override ShortcutEvents for the keybindings defined by this
# widget (Ctrl+n, Ctrl+a, etc). Enable this if you want this widget to take
# priority (when it has focus) over, e.g., window-level menu shortcuts.
override_shortcuts = Bool(False)
# ------ Custom Qt Widgets -------------------------------------------------
# For other projects to easily override the Qt widgets used by the console
# (e.g. Spyder)
custom_control = None
custom_page_control = None
#------ Signals ------------------------------------------------------------
# Signals that indicate ConsoleWidget state.
copy_available = QtCore.Signal(bool)
redo_available = QtCore.Signal(bool)
undo_available = QtCore.Signal(bool)
# Signal emitted when paging is needed and the paging style has been
# specified as 'custom'.
custom_page_requested = QtCore.Signal(object)
# Signal emitted when the font is changed.
font_changed = QtCore.Signal(QtGui.QFont)
#------ Protected class variables ------------------------------------------
# control handles
_control = None
_page_control = None
_splitter = None
# When the control key is down, these keys are mapped.
_ctrl_down_remap = { QtCore.Qt.Key_B : QtCore.Qt.Key_Left,
QtCore.Qt.Key_F : QtCore.Qt.Key_Right,
QtCore.Qt.Key_A : QtCore.Qt.Key_Home,
QtCore.Qt.Key_P : QtCore.Qt.Key_Up,
QtCore.Qt.Key_N : QtCore.Qt.Key_Down,
QtCore.Qt.Key_H : QtCore.Qt.Key_Backspace, }
if not sys.platform == 'darwin':
# On OS X, Ctrl-E already does the right thing, whereas End moves the
# cursor to the bottom of the buffer.
_ctrl_down_remap[QtCore.Qt.Key_E] = QtCore.Qt.Key_End
# The shortcuts defined by this widget. We need to keep track of these to
# support 'override_shortcuts' above.
_shortcuts = set(_ctrl_down_remap.keys() +
[ QtCore.Qt.Key_C, QtCore.Qt.Key_G, QtCore.Qt.Key_O,
QtCore.Qt.Key_V ])
_temp_buffer_filled = False
#---------------------------------------------------------------------------
# 'QObject' interface
#---------------------------------------------------------------------------
def __init__(self, parent=None, **kw):
""" Create a ConsoleWidget.
Parameters:
-----------
parent : QWidget, optional [default None]
The parent for this widget.
"""
QtGui.QWidget.__init__(self, parent)
LoggingConfigurable.__init__(self, **kw)
# While scrolling the pager on Mac OS X, it tears badly. The
# NativeGesture is platform and perhaps build-specific hence
# we take adequate precautions here.
self._pager_scroll_events = [QtCore.QEvent.Wheel]
if hasattr(QtCore.QEvent, 'NativeGesture'):
self._pager_scroll_events.append(QtCore.QEvent.NativeGesture)
# Create the layout and underlying text widget.
layout = QtGui.QStackedLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._control = self._create_control()
if self.paging in ('hsplit', 'vsplit'):
self._splitter = QtGui.QSplitter()
if self.paging == 'hsplit':
self._splitter.setOrientation(QtCore.Qt.Horizontal)
else:
self._splitter.setOrientation(QtCore.Qt.Vertical)
self._splitter.addWidget(self._control)
layout.addWidget(self._splitter)
else:
layout.addWidget(self._control)
# Create the paging widget, if necessary.
if self.paging in ('inside', 'hsplit', 'vsplit'):
self._page_control = self._create_page_control()
if self._splitter:
self._page_control.hide()
self._splitter.addWidget(self._page_control)
else:
layout.addWidget(self._page_control)
# Initialize protected variables. Some variables contain useful state
# information for subclasses; they should be considered read-only.
self._append_before_prompt_pos = 0
self._ansi_processor = QtAnsiCodeProcessor()
if self.gui_completion == 'ncurses':
self._completion_widget = CompletionHtml(self)
elif self.gui_completion == 'droplist':
self._completion_widget = CompletionWidget(self)
elif self.gui_completion == 'plain':
self._completion_widget = CompletionPlain(self)
self._continuation_prompt = '> '
self._continuation_prompt_html = None
self._executing = False
self._filter_resize = False
self._html_exporter = HtmlExporter(self._control)
self._input_buffer_executing = ''
self._input_buffer_pending = ''
self._kill_ring = QtKillRing(self._control)
self._prompt = ''
self._prompt_html = None
self._prompt_pos = 0
self._prompt_sep = ''
self._reading = False
self._reading_callback = None
self._tab_width = 8
# Set a monospaced font.
self.reset_font()
# Configure actions.
action = QtGui.QAction('Print', None)
action.setEnabled(True)
printkey = QtGui.QKeySequence(QtGui.QKeySequence.Print)
if printkey.matches("Ctrl+P") and sys.platform != 'darwin':
# Only override the default if there is a collision.
# Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
printkey = "Ctrl+Shift+P"
action.setShortcut(printkey)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.print_)
self.addAction(action)
self.print_action = action
action = QtGui.QAction('Save as HTML/XML', None)
action.setShortcut(QtGui.QKeySequence.Save)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.export_html)
self.addAction(action)
self.export_action = action
action = QtGui.QAction('Select All', None)
action.setEnabled(True)
selectall = QtGui.QKeySequence(QtGui.QKeySequence.SelectAll)
if selectall.matches("Ctrl+A") and sys.platform != 'darwin':
# Only override the default if there is a collision.
# Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
selectall = "Ctrl+Shift+A"
action.setShortcut(selectall)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.select_all)
self.addAction(action)
self.select_all_action = action
self.increase_font_size = QtGui.QAction("Bigger Font",
self,
shortcut=QtGui.QKeySequence.ZoomIn,
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Increase the font size by one point",
triggered=self._increase_font_size)
self.addAction(self.increase_font_size)
self.decrease_font_size = QtGui.QAction("Smaller Font",
self,
shortcut=QtGui.QKeySequence.ZoomOut,
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Decrease the font size by one point",
triggered=self._decrease_font_size)
self.addAction(self.decrease_font_size)
self.reset_font_size = QtGui.QAction("Normal Font",
self,
shortcut="Ctrl+0",
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Restore the Normal font size",
triggered=self.reset_font)
self.addAction(self.reset_font_size)
# Accept drag and drop events here. Drops were already turned off
# in self._control when that widget was created.
self.setAcceptDrops(True)
#---------------------------------------------------------------------------
# Drag and drop support
#---------------------------------------------------------------------------
def dragEnterEvent(self, e):
if e.mimeData().hasUrls():
# The link action should indicate to that the drop will insert
# the file anme.
e.setDropAction(QtCore.Qt.LinkAction)
e.accept()
elif e.mimeData().hasText():
# By changing the action to copy we don't need to worry about
# the user accidentally moving text around in the widget.
e.setDropAction(QtCore.Qt.CopyAction)
e.accept()
def dragMoveEvent(self, e):
if e.mimeData().hasUrls():
pass
elif e.mimeData().hasText():
cursor = self._control.cursorForPosition(e.pos())
if self._in_buffer(cursor.position()):
e.setDropAction(QtCore.Qt.CopyAction)
self._control.setTextCursor(cursor)
else:
e.setDropAction(QtCore.Qt.IgnoreAction)
e.accept()
def dropEvent(self, e):
if e.mimeData().hasUrls():
self._keep_cursor_in_buffer()
cursor = self._control.textCursor()
filenames = [url.toLocalFile() for url in e.mimeData().urls()]
text = ', '.join("'" + f.replace("'", "'\"'\"'") + "'"
for f in filenames)
self._insert_plain_text_into_buffer(cursor, text)
elif e.mimeData().hasText():
cursor = self._control.cursorForPosition(e.pos())
if self._in_buffer(cursor.position()):
text = e.mimeData().text()
self._insert_plain_text_into_buffer(cursor, text)
def eventFilter(self, obj, event):
""" Reimplemented to ensure a console-like behavior in the underlying
text widgets.
"""
etype = event.type()
if etype == QtCore.QEvent.KeyPress:
# Re-map keys for all filtered widgets.
key = event.key()
if self._control_key_down(event.modifiers()) and \
key in self._ctrl_down_remap:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
self._ctrl_down_remap[key],
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(obj, new_event)
return True
elif obj == self._control:
return self._event_filter_console_keypress(event)
elif obj == self._page_control:
return self._event_filter_page_keypress(event)
# Make middle-click paste safe.
elif etype == QtCore.QEvent.MouseButtonRelease and \
event.button() == QtCore.Qt.MidButton and \
obj == self._control.viewport():
cursor = self._control.cursorForPosition(event.pos())
self._control.setTextCursor(cursor)
self.paste(QtGui.QClipboard.Selection)
return True
# Manually adjust the scrollbars *after* a resize event is dispatched.
elif etype == QtCore.QEvent.Resize and not self._filter_resize:
self._filter_resize = True
QtGui.qApp.sendEvent(obj, event)
self._adjust_scrollbars()
self._filter_resize = False
return True
# Override shortcuts for all filtered widgets.
elif etype == QtCore.QEvent.ShortcutOverride and \
self.override_shortcuts and \
self._control_key_down(event.modifiers()) and \
event.key() in self._shortcuts:
event.accept()
# Handle scrolling of the vsplit pager. This hack attempts to solve
# problems with tearing of the help text inside the pager window. This
# happens only on Mac OS X with both PySide and PyQt. This fix isn't
# perfect but makes the pager more usable.
elif etype in self._pager_scroll_events and \
obj == self._page_control:
self._page_control.repaint()
return True
elif etype == QtCore.QEvent.MouseMove:
anchor = self._control.anchorAt(event.pos())
QtGui.QToolTip.showText(event.globalPos(), anchor)
return super(ConsoleWidget, self).eventFilter(obj, event)
#---------------------------------------------------------------------------
# 'QWidget' interface
#---------------------------------------------------------------------------
def sizeHint(self):
""" Reimplemented to suggest a size that is 80 characters wide and
25 lines high.
"""
font_metrics = QtGui.QFontMetrics(self.font)
margin = (self._control.frameWidth() +
self._control.document().documentMargin()) * 2
style = self.style()
splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth)
# Note 1: Despite my best efforts to take the various margins into
# account, the width is still coming out a bit too small, so we include
# a fudge factor of one character here.
# Note 2: QFontMetrics.maxWidth is not used here or anywhere else due
# to a Qt bug on certain Mac OS systems where it returns 0.
width = font_metrics.width(' ') * self.width + margin
width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
if self.paging == 'hsplit':
width = width * 2 + splitwidth
height = font_metrics.height() * self.height + margin
if self.paging == 'vsplit':
height = height * 2 + splitwidth
return QtCore.QSize(width, height)
#---------------------------------------------------------------------------
# 'ConsoleWidget' public interface
#---------------------------------------------------------------------------
def can_copy(self):
""" Returns whether text can be copied to the clipboard.
"""
return self._control.textCursor().hasSelection()
def can_cut(self):
""" Returns whether text can be cut to the clipboard.
"""
cursor = self._control.textCursor()
return (cursor.hasSelection() and
self._in_buffer(cursor.anchor()) and
self._in_buffer(cursor.position()))
def can_paste(self):
""" Returns whether text can be pasted from the clipboard.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
return bool(QtGui.QApplication.clipboard().text())
return False
def clear(self, keep_input=True):
""" Clear the console.
Parameters:
-----------
keep_input : bool, optional (default True)
If set, restores the old input buffer if a new prompt is written.
"""
if self._executing:
self._control.clear()
else:
if keep_input:
input_buffer = self.input_buffer
self._control.clear()
self._show_prompt()
if keep_input:
self.input_buffer = input_buffer
def copy(self):
""" Copy the currently selected text to the clipboard.
"""
self.layout().currentWidget().copy()
def copy_anchor(self, anchor):
""" Copy anchor text to the clipboard
"""
QtGui.QApplication.clipboard().setText(anchor)
def cut(self):
""" Copy the currently selected text to the clipboard and delete it
if it's inside the input buffer.
"""
self.copy()
if self.can_cut():
self._control.textCursor().removeSelectedText()
def execute(self, source=None, hidden=False, interactive=False):
""" Executes source or the input buffer, possibly prompting for more
input.
Parameters:
-----------
source : str, optional
The source to execute. If not specified, the input buffer will be
used. If specified and 'hidden' is False, the input buffer will be
replaced with the source before execution.
hidden : bool, optional (default False)
If set, no output will be shown and the prompt will not be modified.
In other words, it will be completely invisible to the user that
an execution has occurred.
interactive : bool, optional (default False)
Whether the console is to treat the source as having been manually
entered by the user. The effect of this parameter depends on the
subclass implementation.
Raises:
-------
RuntimeError
If incomplete input is given and 'hidden' is True. In this case,
it is not possible to prompt for more input.
Returns:
--------
A boolean indicating whether the source was executed.
"""
# WARNING: The order in which things happen here is very particular, in
# large part because our syntax highlighting is fragile. If you change
# something, test carefully!
# Decide what to execute.
if source is None:
source = self.input_buffer
if not hidden:
# A newline is appended later, but it should be considered part
# of the input buffer.
source += '\n'
elif not hidden:
self.input_buffer = source
# Execute the source or show a continuation prompt if it is incomplete.
complete = self._is_complete(source, interactive)
if hidden:
if complete:
self._execute(source, hidden)
else:
error = 'Incomplete noninteractive input: "%s"'
raise RuntimeError(error % source)
else:
if complete:
self._append_plain_text('\n')
self._input_buffer_executing = self.input_buffer
self._executing = True
self._prompt_finished()
# The maximum block count is only in effect during execution.
# This ensures that _prompt_pos does not become invalid due to
# text truncation.
self._control.document().setMaximumBlockCount(self.buffer_size)
# Setting a positive maximum block count will automatically
# disable the undo/redo history, but just to be safe:
self._control.setUndoRedoEnabled(False)
# Perform actual execution.
self._execute(source, hidden)
else:
# Do this inside an edit block so continuation prompts are
# removed seamlessly via undo/redo.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.insertText('\n')
self._insert_continuation_prompt(cursor)
cursor.endEditBlock()
# Do not do this inside the edit block. It works as expected
# when using a QPlainTextEdit control, but does not have an
# effect when using a QTextEdit. I believe this is a Qt bug.
self._control.moveCursor(QtGui.QTextCursor.End)
return complete
def export_html(self):
""" Shows a dialog to export HTML/XML in various formats.
"""
self._html_exporter.export()
def _get_input_buffer(self, force=False):
""" The text that the user has entered entered at the current prompt.
If the console is currently executing, the text that is executing will
always be returned.
"""
# If we're executing, the input buffer may not even exist anymore due to
# the limit imposed by 'buffer_size'. Therefore, we store it.
if self._executing and not force:
return self._input_buffer_executing
cursor = self._get_end_cursor()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
input_buffer = cursor.selection().toPlainText()
# Strip out continuation prompts.
return input_buffer.replace('\n' + self._continuation_prompt, '\n')
def _set_input_buffer(self, string):
""" Sets the text in the input buffer.
If the console is currently executing, this call has no *immediate*
effect. When the execution is finished, the input buffer will be updated
appropriately.
"""
# If we're executing, store the text for later.
if self._executing:
self._input_buffer_pending = string
return
# Remove old text.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# Insert new text with continuation prompts.
self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string)
cursor.endEditBlock()
self._control.moveCursor(QtGui.QTextCursor.End)
input_buffer = property(_get_input_buffer, _set_input_buffer)
def _get_font(self):
""" The base font being used by the ConsoleWidget.
"""
return self._control.document().defaultFont()
def _set_font(self, font):
""" Sets the base font for the ConsoleWidget to the specified QFont.
"""
font_metrics = QtGui.QFontMetrics(font)
self._control.setTabStopWidth(self.tab_width * font_metrics.width(' '))
self._completion_widget.setFont(font)
self._control.document().setDefaultFont(font)
if self._page_control:
self._page_control.document().setDefaultFont(font)
self.font_changed.emit(font)
font = property(_get_font, _set_font)
def open_anchor(self, anchor):
""" Open selected anchor in the default webbrowser
"""
webbrowser.open( anchor )
def paste(self, mode=QtGui.QClipboard.Clipboard):
""" Paste the contents of the clipboard into the input region.
Parameters:
-----------
mode : QClipboard::Mode, optional [default QClipboard::Clipboard]
Controls which part of the system clipboard is used. This can be
used to access the selection clipboard in X11 and the Find buffer
in Mac OS. By default, the regular clipboard is used.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
# Make sure the paste is safe.
self._keep_cursor_in_buffer()
cursor = self._control.textCursor()
# Remove any trailing newline, which confuses the GUI and forces the
# user to backspace.
text = QtGui.QApplication.clipboard().text(mode).rstrip()
self._insert_plain_text_into_buffer(cursor, dedent(text))
def print_(self, printer = None):
""" Print the contents of the ConsoleWidget to the specified QPrinter.
"""
if (not printer):
printer = QtGui.QPrinter()
if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted):
return
self._control.print_(printer)
def prompt_to_top(self):
""" Moves the prompt to the top of the viewport.
"""
if not self._executing:
prompt_cursor = self._get_prompt_cursor()
if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():
self._set_cursor(prompt_cursor)
self._set_top_cursor(prompt_cursor)
def redo(self):
""" Redo the last operation. If there is no operation to redo, nothing
happens.
"""
self._control.redo()
def reset_font(self):
""" Sets the font to the default fixed-width font for this platform.
"""
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
fallback = 'Courier'
elif sys.platform == 'darwin':
# OSX always has Monaco
fallback = 'Monaco'
else:
# Monospace should always exist
fallback = 'Monospace'
font = get_font(self.font_family, fallback)
if self.font_size:
font.setPointSize(self.font_size)
else:
font.setPointSize(QtGui.qApp.font().pointSize())
font.setStyleHint(QtGui.QFont.TypeWriter)
self._set_font(font)
def change_font_size(self, delta):
"""Change the font size by the specified amount (in points).
"""
font = self.font
size = max(font.pointSize() + delta, 1) # minimum 1 point
font.setPointSize(size)
self._set_font(font)
def _increase_font_size(self):
self.change_font_size(1)
def _decrease_font_size(self):
self.change_font_size(-1)
def select_all(self):
""" Selects all the text in the buffer.
"""
self._control.selectAll()
def _get_tab_width(self):
""" The width (in terms of space characters) for tab characters.
"""
return self._tab_width
def _set_tab_width(self, tab_width):
""" Sets the width (in terms of space characters) for tab characters.
"""
font_metrics = QtGui.QFontMetrics(self.font)
self._control.setTabStopWidth(tab_width * font_metrics.width(' '))
self._tab_width = tab_width
tab_width = property(_get_tab_width, _set_tab_width)
def undo(self):
""" Undo the last operation. If there is no operation to undo, nothing
happens.
"""
self._control.undo()
#---------------------------------------------------------------------------
# 'ConsoleWidget' abstract interface
#---------------------------------------------------------------------------
def _is_complete(self, source, interactive):
""" Returns whether 'source' can be executed. When triggered by an
Enter/Return key press, 'interactive' is True; otherwise, it is
False.
"""
raise NotImplementedError
def _execute(self, source, hidden):
""" Execute 'source'. If 'hidden', do not show any output.
"""
raise NotImplementedError
def _prompt_started_hook(self):
""" Called immediately after a new prompt is displayed.
"""
pass
def _prompt_finished_hook(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
pass
def _up_pressed(self, shift_modifier):
""" Called when the up key is pressed. Returns whether to continue
processing the event.
"""
return True
def _down_pressed(self, shift_modifier):
""" Called when the down key is pressed. Returns whether to continue
processing the event.
"""
return True
def _tab_pressed(self):
""" Called when the tab key is pressed. Returns whether to continue
processing the event.
"""
return False
#--------------------------------------------------------------------------
# 'ConsoleWidget' protected interface
#--------------------------------------------------------------------------
def _append_custom(self, insert, input, before_prompt=False):
""" A low-level method for appending content to the end of the buffer.
If 'before_prompt' is enabled, the content will be inserted before the
current prompt, if there is one.
"""
# Determine where to insert the content.
cursor = self._control.textCursor()
if before_prompt and (self._reading or not self._executing):
cursor.setPosition(self._append_before_prompt_pos)
else:
cursor.movePosition(QtGui.QTextCursor.End)
start_pos = cursor.position()
# Perform the insertion.
result = insert(cursor, input)
# Adjust the prompt position if we have inserted before it. This is safe
# because buffer truncation is disabled when not executing.
if before_prompt and not self._executing:
diff = cursor.position() - start_pos
self._append_before_prompt_pos += diff
self._prompt_pos += diff
return result
def _append_block(self, block_format=None, before_prompt=False):
""" Appends an new QTextBlock to the end of the console buffer.
"""
self._append_custom(self._insert_block, block_format, before_prompt)
def _append_html(self, html, before_prompt=False):
""" Appends HTML at the end of the console buffer.
"""
self._append_custom(self._insert_html, html, before_prompt)
def _append_html_fetching_plain_text(self, html, before_prompt=False):
""" Appends HTML, then returns the plain text version of it.
"""
return self._append_custom(self._insert_html_fetching_plain_text,
html, before_prompt)
def _append_plain_text(self, text, before_prompt=False):
""" Appends plain text, processing ANSI codes if enabled.
"""
self._append_custom(self._insert_plain_text, text, before_prompt)
def _cancel_completion(self):
""" If text completion is progress, cancel it.
"""
self._completion_widget.cancel_completion()
def _clear_temporary_buffer(self):
""" Clears the "temporary text" buffer, i.e. all the text following
the prompt region.
"""
# Select and remove all text below the input buffer.
cursor = self._get_prompt_cursor()
prompt = self._continuation_prompt.lstrip()
if(self._temp_buffer_filled):
self._temp_buffer_filled = False
while cursor.movePosition(QtGui.QTextCursor.NextBlock):
temp_cursor = QtGui.QTextCursor(cursor)
temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor)
text = temp_cursor.selection().toPlainText().lstrip()
if not text.startswith(prompt):
break
else:
# We've reached the end of the input buffer and no text follows.
return
cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline.
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# After doing this, we have no choice but to clear the undo/redo
# history. Otherwise, the text is not "temporary" at all, because it
# can be recalled with undo/redo. Unfortunately, Qt does not expose
# fine-grained control to the undo/redo system.
if self._control.isUndoRedoEnabled():
self._control.setUndoRedoEnabled(False)
self._control.setUndoRedoEnabled(True)
def _complete_with_items(self, cursor, items):
""" Performs completion with 'items' at the specified cursor location.
"""
self._cancel_completion()
if len(items) == 1:
cursor.setPosition(self._control.textCursor().position(),
QtGui.QTextCursor.KeepAnchor)
cursor.insertText(items[0])
elif len(items) > 1:
current_pos = self._control.textCursor().position()
prefix = commonprefix(items)
if prefix:
cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor)
cursor.insertText(prefix)
current_pos = cursor.position()
cursor.movePosition(QtGui.QTextCursor.Left, n=len(prefix))
self._completion_widget.show_items(cursor, items)
def _fill_temporary_buffer(self, cursor, text, html=False):
"""fill the area below the active editting zone with text"""
current_pos = self._control.textCursor().position()
cursor.beginEditBlock()
self._append_plain_text('\n')
self._page(text, html=html)
cursor.endEditBlock()
cursor.setPosition(current_pos)
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
self._temp_buffer_filled = True
def _context_menu_make(self, pos):
""" Creates a context menu for the given QPoint (in widget coordinates).
"""
menu = QtGui.QMenu(self)
self.cut_action = menu.addAction('Cut', self.cut)
self.cut_action.setEnabled(self.can_cut())
self.cut_action.setShortcut(QtGui.QKeySequence.Cut)