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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
|
"""
Adapted from a code editor component created
for Enki editor as replacement for QScintilla.
Copyright (C) 2020 Andrei Kopats
Originally licensed under the terms of GNU Lesser General Public License
as published by the Free Software Foundation, version 2.1 of the license.
This is compatible with Orange3's GPL-3.0 license.
"""
import sys
from AnyQt.QtCore import Qt, pyqtSignal, QObject
from AnyQt.QtWidgets import QTextEdit
from AnyQt.QtGui import QColor, QTextCursor
from orangewidget.utils import enum_as_int
# pylint: disable=protected-access
# pylint: disable=unused-argument
# pylint: disable=too-many-lines
# pylint: disable=too-many-branches
# This magic code sets variables like _a and _A in the global scope
# pylint: disable=undefined-variable
thismodule = sys.modules[__name__]
for charCode in range(ord('a'), ord('z') + 1):
shortName = chr(charCode)
longName = 'Key_' + shortName.upper()
qtCode = enum_as_int(getattr(Qt, longName))
setattr(thismodule, '_' + shortName, qtCode)
setattr(thismodule, '_' + shortName.upper(), enum_as_int(Qt.ShiftModifier) | qtCode)
def key_code(comb):
try:
return comb.toCombined()
except AttributeError:
return enum_as_int(comb)
_0 = key_code(Qt.Key_0)
_Dollar = key_code(Qt.ShiftModifier | Qt.Key_Dollar)
_Percent = key_code(Qt.ShiftModifier | Qt.Key_Percent)
_Caret = key_code(Qt.ShiftModifier | Qt.Key_AsciiCircum)
_Esc = key_code(Qt.Key_Escape)
_Insert = key_code(Qt.Key_Insert)
_Down = key_code(Qt.Key_Down)
_Up = key_code(Qt.Key_Up)
_Left = key_code(Qt.Key_Left)
_Right = key_code(Qt.Key_Right)
_Space = key_code(Qt.Key_Space)
_BackSpace = key_code(Qt.Key_Backspace)
_Equal = key_code(Qt.Key_Equal)
_Less = key_code(Qt.ShiftModifier | Qt.Key_Less)
_Greater = key_code(Qt.ShiftModifier | Qt.Key_Greater)
_Home = key_code(Qt.Key_Home)
_End = key_code(Qt.Key_End)
_PageDown = key_code(Qt.Key_PageDown)
_PageUp = key_code(Qt.Key_PageUp)
_Period = key_code(Qt.Key_Period)
_Enter = key_code(Qt.Key_Enter)
_Return = key_code(Qt.Key_Return)
def code(ev):
modifiers = ev.modifiers()
modifiers &= ~Qt.KeypadModifier # ignore keypad modifier to handle both main and numpad numbers
return enum_as_int(modifiers) | ev.key()
def isChar(ev):
""" Check if an event may be a typed character
"""
text = ev.text()
if len(text) != 1:
return False
if ev.modifiers() not in (Qt.ShiftModifier, Qt.KeypadModifier, Qt.NoModifier):
return False
asciiCode = ord(text)
if asciiCode <= 31 or asciiCode == 0x7f: # control characters
return False
if text == ' ' and ev.modifiers() == Qt.ShiftModifier:
return False # Shift+Space is a shortcut, not a text
return True
NORMAL = 'normal'
INSERT = 'insert'
REPLACE_CHAR = 'replace character'
MODE_COLORS = {NORMAL: QColor('#33cc33'),
INSERT: QColor('#ff9900'),
REPLACE_CHAR: QColor('#ff3300')}
class _GlobalClipboard:
def __init__(self):
self.value = ''
_globalClipboard = _GlobalClipboard()
class Vim(QObject):
"""Vim mode implementation.
Listens events and does actions
"""
modeIndicationChanged = pyqtSignal(QColor, str)
def __init__(self, qpart):
QObject.__init__(self)
self._qpart = qpart
self._mode = Normal(self, qpart)
self._qpart.selectionChanged.connect(self._onSelectionChanged)
self._qpart.document().modificationChanged.connect(self._onModificationChanged)
self._processingKeyPress = False
self.updateIndication()
self.lastEditCmdFunc = None
def terminate(self):
self._qpart.selectionChanged.disconnect(self._onSelectionChanged)
try:
self._qpart.document().modificationChanged.disconnect(self._onModificationChanged)
except TypeError:
pass
def indication(self):
return self._mode.color, self._mode.text()
def updateIndication(self):
self.modeIndicationChanged.emit(*self.indication())
def keyPressEvent(self, ev):
"""Check the event. Return True if processed and False otherwise
"""
if ev.key() in (Qt.Key_Shift, Qt.Key_Control,
Qt.Key_Meta, Qt.Key_Alt,
Qt.Key_AltGr, Qt.Key_CapsLock,
Qt.Key_NumLock, Qt.Key_ScrollLock):
return False # ignore modifier pressing. Will process key pressing later
self._processingKeyPress = True
try:
ret = self._mode.keyPressEvent(ev)
finally:
self._processingKeyPress = False
return ret
def inInsertMode(self):
return isinstance(self._mode, Insert)
def mode(self):
return self._mode
def setMode(self, mode):
self._mode = mode
self._qpart._updateVimExtraSelections()
self.updateIndication()
def extraSelections(self):
""" In normal mode - QTextEdit.ExtraSelection which highlightes the cursor
"""
if not isinstance(self._mode, Normal):
return []
selection = QTextEdit.ExtraSelection()
selection.format.setBackground(QColor('#ffcc22'))
selection.format.setForeground(QColor('#000000'))
selection.cursor = self._qpart.textCursor()
selection.cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor)
return [selection]
def _onSelectionChanged(self):
if not self._processingKeyPress:
if self._qpart.selectedText:
if not isinstance(self._mode, (Visual, VisualLines)):
self.setMode(Visual(self, self._qpart))
else:
self.setMode(Normal(self, self._qpart))
def _onModificationChanged(self, modified):
if not modified and isinstance(self._mode, Insert):
self.setMode(Normal(self, self._qpart))
class Mode:
# pylint: disable=no-self-use
color = None
def __init__(self, vim, qpart):
self._vim = vim
self._qpart = qpart
def text(self):
return None
def keyPressEvent(self, ev):
pass
def switchMode(self, modeClass, *args):
mode = modeClass(self._vim, self._qpart, *args)
self._vim.setMode(mode)
def switchModeAndProcess(self, text, modeClass, *args):
mode = modeClass(self._vim, self._qpart, *args)
self._vim.setMode(mode)
return mode.keyPressEvent(text)
class Insert(Mode):
color = QColor('#ff9900')
def text(self):
return 'insert'
def keyPressEvent(self, ev):
if ev.key() == Qt.Key_Escape:
self.switchMode(Normal)
return True
return False
class ReplaceChar(Mode):
color = QColor('#ee7777')
def text(self):
return 'replace char'
def keyPressEvent(self, ev):
if isChar(ev): # a char
self._qpart.setOverwriteMode(False)
line, col = self._qpart.cursorPosition
if col > 0:
# return the cursor back after replacement
self._qpart.cursorPosition = (line, col - 1)
self.switchMode(Normal)
return True
else:
self._qpart.setOverwriteMode(False)
self.switchMode(Normal)
return False
class Replace(Mode):
color = QColor('#ee7777')
def text(self):
return 'replace'
def keyPressEvent(self, ev):
if ev.key() == _Insert:
self._qpart.setOverwriteMode(False)
self.switchMode(Insert)
return True
elif ev.key() == _Esc:
self._qpart.setOverwriteMode(False)
self.switchMode(Normal)
return True
else:
return False
class BaseCommandMode(Mode):
""" Base class for Normal and Visual modes
"""
def __init__(self, *args):
Mode.__init__(self, *args)
self._reset()
def keyPressEvent(self, ev):
self._typedText += ev.text()
try:
self._processCharCoroutine.send(ev)
except StopIteration as ex:
retVal = ex.value
self._reset()
else:
retVal = True
self._vim.updateIndication()
return retVal
def text(self):
return self._typedText or self.name
def _reset(self):
self._processCharCoroutine = self._processChar()
next(self._processCharCoroutine) # run until the first yield
self._typedText = ''
_MOTIONS = (_0, _Home,
_Dollar, _End,
_Percent, _Caret,
_b, _B,
_e, _E,
_G,
_j, _Down,
_l, _Right, _Space,
_k, _Up,
_h, _Left, _BackSpace,
_w, _W,
'gg',
_f, _F, _t, _T,
_PageDown, _PageUp,
_Enter, _Return,
)
@staticmethod
def moveToFirstNonSpace(cursor, moveMode):
text = cursor.block().text()
spaceLen = len(text) - len(text.lstrip())
cursor.setPosition(cursor.block().position() + spaceLen, moveMode)
def _moveCursor(self, motion, count, searchChar=None, select=False):
""" Move cursor.
Used by Normal and Visual mode
"""
cursor = self._qpart.textCursor()
effectiveCount = count or 1
moveMode = QTextCursor.KeepAnchor if select else QTextCursor.MoveAnchor
moveOperation = {_b: QTextCursor.WordLeft,
_j: QTextCursor.Down,
_Down: QTextCursor.Down,
_k: QTextCursor.Up,
_Up: QTextCursor.Up,
_h: QTextCursor.Left,
_Left: QTextCursor.Left,
_BackSpace: QTextCursor.Left,
_l: QTextCursor.Right,
_Right: QTextCursor.Right,
_Space: QTextCursor.Right,
_w: QTextCursor.WordRight,
_Dollar: QTextCursor.EndOfBlock,
_End: QTextCursor.EndOfBlock,
_0: QTextCursor.StartOfBlock,
_Home: QTextCursor.StartOfBlock,
'gg': QTextCursor.Start,
_G: QTextCursor.End
}
if motion == _G:
if count == 0: # default - go to the end
cursor.movePosition(QTextCursor.End, moveMode)
else: # if count is set - move to line
block = self._qpart.document().findBlockByNumber(count - 1)
if not block.isValid():
return
cursor.setPosition(block.position(), moveMode)
self.moveToFirstNonSpace(cursor, moveMode)
elif motion in moveOperation:
for _ in range(effectiveCount):
cursor.movePosition(moveOperation[motion], moveMode)
elif motion in (_e, _E):
for _ in range(effectiveCount):
# skip spaces
text = cursor.block().text()
pos = cursor.positionInBlock()
for char in text[pos:]:
if char.isspace():
cursor.movePosition(QTextCursor.NextCharacter, moveMode)
else:
break
if cursor.positionInBlock() == len(text): # at the end of line
# move to the next line
cursor.movePosition(QTextCursor.NextCharacter, moveMode)
# now move to the end of word
if motion == _e:
cursor.movePosition(QTextCursor.EndOfWord, moveMode)
else:
text = cursor.block().text()
pos = cursor.positionInBlock()
for char in text[pos:]:
if not char.isspace():
cursor.movePosition(QTextCursor.NextCharacter, moveMode)
else:
break
elif motion == _B:
cursor.movePosition(QTextCursor.WordLeft, moveMode)
while cursor.positionInBlock() != 0 and \
(not cursor.block().text()[cursor.positionInBlock() - 1].isspace()):
cursor.movePosition(QTextCursor.WordLeft, moveMode)
elif motion == _W:
cursor.movePosition(QTextCursor.WordRight, moveMode)
while cursor.positionInBlock() != 0 and \
(not cursor.block().text()[cursor.positionInBlock() - 1].isspace()):
cursor.movePosition(QTextCursor.WordRight, moveMode)
elif motion == _Percent:
# Percent move is done only once
if self._qpart._bracketHighlighter.currentMatchedBrackets is not None:
((startBlock, startCol), (endBlock, endCol)) = \
self._qpart._bracketHighlighter.currentMatchedBrackets
startPos = startBlock.position() + startCol
endPos = endBlock.position() + endCol
if select and \
(endPos > startPos):
endPos += 1 # to select the bracket, not only chars before it
cursor.setPosition(endPos, moveMode)
elif motion == _Caret:
# Caret move is done only once
self.moveToFirstNonSpace(cursor, moveMode)
elif motion in (_f, _F, _t, _T):
if motion in (_f, _t):
iterator = self._iterateDocumentCharsForward(cursor.block(), cursor.columnNumber())
stepForward = QTextCursor.Right
stepBack = QTextCursor.Left
else:
iterator = self._iterateDocumentCharsBackward(cursor.block(), cursor.columnNumber())
stepForward = QTextCursor.Left
stepBack = QTextCursor.Right
for block, columnIndex, char in iterator:
if char == searchChar:
cursor.setPosition(block.position() + columnIndex, moveMode)
if motion in (_t, _T):
cursor.movePosition(stepBack, moveMode)
if select:
cursor.movePosition(stepForward, moveMode)
break
elif motion in (_PageDown, _PageUp):
cursorHeight = self._qpart.cursorRect().height()
qpartHeight = self._qpart.height()
visibleLineCount = qpartHeight / cursorHeight
direction = QTextCursor.Down if motion == _PageDown else QTextCursor.Up
for _ in range(int(visibleLineCount)):
cursor.movePosition(direction, moveMode)
elif motion in (_Enter, _Return):
if cursor.block().next().isValid(): # not the last line
for _ in range(effectiveCount):
cursor.movePosition(QTextCursor.NextBlock, moveMode)
self.moveToFirstNonSpace(cursor, moveMode)
else:
assert 0, 'Not expected motion ' + str(motion)
self._qpart.setTextCursor(cursor)
@staticmethod
def _iterateDocumentCharsForward(block, startColumnIndex):
"""Traverse document forward. Yield (block, columnIndex, char)
Raise _TimeoutException if time is over
"""
# Chars in the start line
for columnIndex, char in list(enumerate(block.text()))[startColumnIndex:]:
yield block, columnIndex, char
block = block.next()
# Next lines
while block.isValid():
for columnIndex, char in enumerate(block.text()):
yield block, columnIndex, char
block = block.next()
@staticmethod
def _iterateDocumentCharsBackward(block, startColumnIndex):
"""Traverse document forward. Yield (block, columnIndex, char)
Raise _TimeoutException if time is over
"""
# Chars in the start line
for columnIndex, char in reversed(list(enumerate(block.text()[:startColumnIndex]))):
yield block, columnIndex, char
block = block.previous()
# Next lines
while block.isValid():
for columnIndex, char in reversed(list(enumerate(block.text()))):
yield block, columnIndex, char
block = block.previous()
def _resetSelection(self, moveToTop=False):
""" Reset selection.
If moveToTop is True - move cursor to the top position
"""
ancor, pos = self._qpart.selectedPosition
dst = min(ancor, pos) if moveToTop else pos
self._qpart.cursorPosition = dst
def _expandSelection(self):
cursor = self._qpart.textCursor()
anchor = cursor.anchor()
pos = cursor.position()
if pos >= anchor:
anchorSide = QTextCursor.StartOfBlock
cursorSide = QTextCursor.EndOfBlock
else:
anchorSide = QTextCursor.EndOfBlock
cursorSide = QTextCursor.StartOfBlock
cursor.setPosition(anchor)
cursor.movePosition(anchorSide)
cursor.setPosition(pos, QTextCursor.KeepAnchor)
cursor.movePosition(cursorSide, QTextCursor.KeepAnchor)
self._qpart.setTextCursor(cursor)
class BaseVisual(BaseCommandMode):
color = QColor('#6699ff')
_selectLines = NotImplementedError()
def _processChar(self):
ev = yield None
# Get count
typedCount = 0
if ev.key() != _0:
char = ev.text()
while char.isdigit():
digit = int(char)
typedCount = (typedCount * 10) + digit
ev = yield
char = ev.text()
count = typedCount if typedCount else 1
# Now get the action
action = code(ev)
if action in self._SIMPLE_COMMANDS:
cmdFunc = self._SIMPLE_COMMANDS[action]
for _ in range(count):
cmdFunc(self, action)
if action not in (_v, _V): # if not switched to another visual mode
self._resetSelection(moveToTop=True)
if self._vim.mode() is self: # if the command didn't switch the mode
self.switchMode(Normal)
return True
elif action == _Esc:
self._resetSelection()
self.switchMode(Normal)
return True
elif action == _g:
ev = yield
if code(ev) == _g:
self._moveCursor('gg', 1, select=True)
if self._selectLines:
self._expandSelection()
return True
elif action in (_f, _F, _t, _T):
ev = yield
if not isChar(ev):
return True
searchChar = ev.text()
self._moveCursor(action, typedCount, searchChar=searchChar, select=True)
return True
elif action == _z:
ev = yield
if code(ev) == _z:
self._qpart.centerCursor()
return True
elif action in self._MOTIONS:
if self._selectLines and action in (_k, _Up, _j, _Down):
# There is a bug in visual mode:
# If a line is wrapped, cursor moves up, but stays on same line.
# Then selection is expanded and cursor returns to previous position.
# So user can't move the cursor up. So, in Visual mode we move cursor up until it
# moved to previous line. The same bug when moving down
cursorLine = self._qpart.cursorPosition[0]
if (action in (_k, _Up) and cursorLine > 0) or \
(action in (_j, _Down) and (cursorLine + 1) < len(self._qpart.lines)):
while self._qpart.cursorPosition[0] == cursorLine:
self._moveCursor(action, typedCount, select=True)
else:
self._moveCursor(action, typedCount, select=True)
if self._selectLines:
self._expandSelection()
return True
elif action == _r:
ev = yield
newChar = ev.text()
if newChar:
newChars = [newChar if char != '\n' else '\n' \
for char in self._qpart.selectedText
]
newText = ''.join(newChars)
self._qpart.selectedText = newText
self.switchMode(Normal)
return True
elif isChar(ev):
return True # ignore unknown character
else:
return False # but do not ignore not-a-character keys
assert 0 # must StopIteration on if
def _selectedLinesRange(self):
""" Selected lines range for line manipulation methods
"""
(startLine, _), (endLine, _) = self._qpart.selectedPosition
start = min(startLine, endLine)
end = max(startLine, endLine)
return start, end
def _selectRangeForRepeat(self, repeatLineCount):
start = self._qpart.cursorPosition[0]
self._qpart.selectedPosition = ((start, 0),
(start + repeatLineCount - 1, 0))
cursor = self._qpart.textCursor()
# expand until the end of line
cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
self._qpart.setTextCursor(cursor)
def _saveLastEditLinesCmd(self, cmd, lineCount):
self._vim.lastEditCmdFunc = lambda: self._SIMPLE_COMMANDS[cmd](self, cmd, lineCount)
#
# Simple commands
#
def cmdDelete(self, cmd, repeatLineCount=None):
if repeatLineCount is not None:
self._selectRangeForRepeat(repeatLineCount)
cursor = self._qpart.textCursor()
if cursor.selectedText():
if self._selectLines:
start, end = self._selectedLinesRange()
self._saveLastEditLinesCmd(cmd, end - start + 1)
_globalClipboard.value = self._qpart.lines[start:end + 1]
del self._qpart.lines[start:end + 1]
else:
_globalClipboard.value = cursor.selectedText()
cursor.removeSelectedText()
def cmdDeleteLines(self, cmd, repeatLineCount=None):
if repeatLineCount is not None:
self._selectRangeForRepeat(repeatLineCount)
start, end = self._selectedLinesRange()
self._saveLastEditLinesCmd(cmd, end - start + 1)
_globalClipboard.value = self._qpart.lines[start:end + 1]
del self._qpart.lines[start:end + 1]
def cmdInsertMode(self, cmd):
self.switchMode(Insert)
def cmdJoinLines(self, cmd, repeatLineCount=None):
if repeatLineCount is not None:
self._selectRangeForRepeat(repeatLineCount)
start, end = self._selectedLinesRange()
count = end - start
if not count: # nothing to join
return
self._saveLastEditLinesCmd(cmd, end - start + 1)
cursor = QTextCursor(self._qpart.document().findBlockByNumber(start))
with self._qpart:
for _ in range(count):
cursor.movePosition(QTextCursor.EndOfBlock)
cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor)
self.moveToFirstNonSpace(cursor, QTextCursor.KeepAnchor)
nonEmptyBlock = cursor.block().length() > 1
cursor.removeSelectedText()
if nonEmptyBlock:
cursor.insertText(' ')
self._qpart.setTextCursor(cursor)
def cmdAppendAfterChar(self, cmd):
cursor = self._qpart.textCursor()
cursor.clearSelection()
cursor.movePosition(QTextCursor.Right)
self._qpart.setTextCursor(cursor)
self.switchMode(Insert)
def cmdReplaceSelectedLines(self, cmd):
start, end = self._selectedLinesRange()
_globalClipboard.value = self._qpart.lines[start:end + 1]
lastLineLen = len(self._qpart.lines[end])
self._qpart.selectedPosition = ((start, 0), (end, lastLineLen))
self._qpart.selectedText = ''
self.switchMode(Insert)
def cmdResetSelection(self, cmd):
self._qpart.cursorPosition = self._qpart.selectedPosition[0]
def cmdInternalPaste(self, cmd):
if not _globalClipboard.value:
return
with self._qpart:
cursor = self._qpart.textCursor()
if self._selectLines:
start, end = self._selectedLinesRange()
del self._qpart.lines[start:end + 1]
else:
cursor.removeSelectedText()
if isinstance(_globalClipboard.value, str):
self._qpart.textCursor().insertText(_globalClipboard.value)
elif isinstance(_globalClipboard.value, list):
currentLineIndex = self._qpart.cursorPosition[0]
text = '\n'.join(_globalClipboard.value)
index = currentLineIndex if self._selectLines else currentLineIndex + 1
self._qpart.lines.insert(index, text)
def cmdVisualMode(self, cmd):
if not self._selectLines:
self._resetSelection()
return # already in visual mode
self.switchMode(Visual)
def cmdVisualLinesMode(self, cmd):
if self._selectLines:
self._resetSelection()
return # already in visual lines mode
self.switchMode(VisualLines)
def cmdYank(self, cmd):
if self._selectLines:
start, end = self._selectedLinesRange()
_globalClipboard.value = self._qpart.lines[start:end + 1]
else:
_globalClipboard.value = self._qpart.selectedText
self._qpart.copy()
def cmdChange(self, cmd):
cursor = self._qpart.textCursor()
if cursor.selectedText():
if self._selectLines:
_globalClipboard.value = cursor.selectedText().splitlines()
else:
_globalClipboard.value = cursor.selectedText()
cursor.removeSelectedText()
self.switchMode(Insert)
def cmdUnIndent(self, cmd, repeatLineCount=None):
if repeatLineCount is not None:
self._selectRangeForRepeat(repeatLineCount)
else:
start, end = self._selectedLinesRange()
self._saveLastEditLinesCmd(cmd, end - start + 1)
self._qpart._indenter.onChangeSelectedBlocksIndent(increase=False, withSpace=False)
if repeatLineCount:
self._resetSelection(moveToTop=True)
def cmdIndent(self, cmd, repeatLineCount=None):
if repeatLineCount is not None:
self._selectRangeForRepeat(repeatLineCount)
else:
start, end = self._selectedLinesRange()
self._saveLastEditLinesCmd(cmd, end - start + 1)
self._qpart._indenter.onChangeSelectedBlocksIndent(increase=True, withSpace=False)
if repeatLineCount:
self._resetSelection(moveToTop=True)
def cmdAutoIndent(self, cmd, repeatLineCount=None):
if repeatLineCount is not None:
self._selectRangeForRepeat(repeatLineCount)
else:
start, end = self._selectedLinesRange()
self._saveLastEditLinesCmd(cmd, end - start + 1)
self._qpart._indenter.onAutoIndentTriggered()
if repeatLineCount:
self._resetSelection(moveToTop=True)
_SIMPLE_COMMANDS = {
_A: cmdAppendAfterChar,
_c: cmdChange,
_C: cmdReplaceSelectedLines,
_d: cmdDelete,
_D: cmdDeleteLines,
_i: cmdInsertMode,
_J: cmdJoinLines,
_R: cmdReplaceSelectedLines,
_p: cmdInternalPaste,
_u: cmdResetSelection,
_x: cmdDelete,
_s: cmdChange,
_S: cmdReplaceSelectedLines,
_v: cmdVisualMode,
_V: cmdVisualLinesMode,
_X: cmdDeleteLines,
_y: cmdYank,
_Less: cmdUnIndent,
_Greater: cmdIndent,
_Equal: cmdAutoIndent,
}
class Visual(BaseVisual):
name = 'visual'
_selectLines = False
class VisualLines(BaseVisual):
name = 'visual lines'
_selectLines = True
def __init__(self, *args):
BaseVisual.__init__(self, *args)
self._expandSelection()
class Normal(BaseCommandMode):
color = QColor('#33cc33')
name = 'normal'
def _processChar(self):
ev = yield None
# Get action count
typedCount = 0
if ev.key() != _0:
char = ev.text()
while char.isdigit():
digit = int(char)
typedCount = (typedCount * 10) + digit
ev = yield
char = ev.text()
effectiveCount = typedCount or 1
# Now get the action
action = code(ev)
if action in self._SIMPLE_COMMANDS:
cmdFunc = self._SIMPLE_COMMANDS[action]
cmdFunc(self, action, effectiveCount)
return True
elif action == _g:
ev = yield
if code(ev) == _g:
self._moveCursor('gg', 1)
return True
elif action in (_f, _F, _t, _T):
ev = yield
if not isChar(ev):
return True
searchChar = ev.text()
self._moveCursor(action, effectiveCount, searchChar=searchChar, select=False)
return True
elif action == _Period: # repeat command
if self._vim.lastEditCmdFunc is not None:
if typedCount:
self._vim.lastEditCmdFunc(typedCount)
else:
self._vim.lastEditCmdFunc()
return True
elif action in self._MOTIONS:
self._moveCursor(action, typedCount, select=False)
return True
elif action in self._COMPOSITE_COMMANDS:
moveCount = 0
ev = yield
if ev.key() != _0: # 0 is a command, not a count
char = ev.text()
while char.isdigit():
digit = int(char)
moveCount = (moveCount * 10) + digit
ev = yield
char = ev.text()
if moveCount == 0:
moveCount = 1
count = effectiveCount * moveCount
# Get motion for a composite command
motion = code(ev)
searchChar = None
if motion == _g:
ev = yield
if code(ev) == _g:
motion = 'gg'
else:
return True
elif motion in (_f, _F, _t, _T):
ev = yield
if not isChar(ev):
return True
searchChar = ev.text()
if (action != _z and motion in self._MOTIONS) or \
(action, motion) in ((_d, _d),
(_y, _y),
(_Less, _Less),
(_Greater, _Greater),
(_Equal, _Equal),
(_z, _z)):
cmdFunc = self._COMPOSITE_COMMANDS[action]
cmdFunc(self, action, motion, searchChar, count)
return True
elif isChar(ev):
return True # ignore unknown character
else:
return False # but do not ignore not-a-character keys
assert 0 # must StopIteration on if
def _repeat(self, count, func):
""" Repeat action 1 or more times.
If more than one - do it as 1 undoble action
"""
if count != 1:
with self._qpart:
for _ in range(count):
func()
else:
func()
def _saveLastEditSimpleCmd(self, cmd, count):
def doCmd(count=count):
self._SIMPLE_COMMANDS[cmd](self, cmd, count)
self._vim.lastEditCmdFunc = doCmd
def _saveLastEditCompositeCmd(self, cmd, motion, searchChar, count):
def doCmd(count=count):
self._COMPOSITE_COMMANDS[cmd](self, cmd, motion, searchChar, count)
self._vim.lastEditCmdFunc = doCmd
#
# Simple commands
#
def cmdInsertMode(self, cmd, count):
self.switchMode(Insert)
def cmdInsertAtLineStartMode(self, cmd, count):
cursor = self._qpart.textCursor()
text = cursor.block().text()
spaceLen = len(text) - len(text.lstrip())
cursor.setPosition(cursor.block().position() + spaceLen)
self._qpart.setTextCursor(cursor)
self.switchMode(Insert)
def cmdJoinLines(self, cmd, count):
cursor = self._qpart.textCursor()
if not cursor.block().next().isValid(): # last block
return
with self._qpart:
for _ in range(count):
cursor.movePosition(QTextCursor.EndOfBlock)
cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor)
self.moveToFirstNonSpace(cursor, QTextCursor.KeepAnchor)
nonEmptyBlock = cursor.block().length() > 1
cursor.removeSelectedText()
if nonEmptyBlock:
cursor.insertText(' ')
if not cursor.block().next().isValid(): # last block
break
self._qpart.setTextCursor(cursor)
def cmdReplaceMode(self, cmd, count):
self.switchMode(Replace)
self._qpart.setOverwriteMode(True)
def cmdReplaceCharMode(self, cmd, count):
self.switchMode(ReplaceChar)
self._qpart.setOverwriteMode(True)
def cmdAppendAfterLine(self, cmd, count):
cursor = self._qpart.textCursor()
cursor.movePosition(QTextCursor.EndOfBlock)
self._qpart.setTextCursor(cursor)
self.switchMode(Insert)
def cmdAppendAfterChar(self, cmd, count):
cursor = self._qpart.textCursor()
cursor.movePosition(QTextCursor.Right)
self._qpart.setTextCursor(cursor)
self.switchMode(Insert)
def cmdUndo(self, cmd, count):
for _ in range(count):
self._qpart.undo()
def cmdRedo(self, cmd, count):
for _ in range(count):
self._qpart.redo()
def cmdNewLineBelow(self, cmd, count):
cursor = self._qpart.textCursor()
cursor.movePosition(QTextCursor.EndOfBlock)
self._qpart.setTextCursor(cursor)
self._repeat(count, self._qpart._insertNewBlock)
self._saveLastEditSimpleCmd(cmd, count)
self.switchMode(Insert)
def cmdNewLineAbove(self, cmd, count):
cursor = self._qpart.textCursor()
def insert():
cursor.movePosition(QTextCursor.StartOfBlock)
self._qpart.setTextCursor(cursor)
self._qpart._insertNewBlock()
cursor.movePosition(QTextCursor.Up)
self._qpart._indenter.autoIndentBlock(cursor.block())
self._repeat(count, insert)
self._qpart.setTextCursor(cursor)
self._saveLastEditSimpleCmd(cmd, count)
self.switchMode(Insert)
def cmdInternalPaste(self, cmd, count):
if not _globalClipboard.value:
return
if isinstance(_globalClipboard.value, str):
cursor = self._qpart.textCursor()
if cmd == _p:
cursor.movePosition(QTextCursor.Right)
self._qpart.setTextCursor(cursor)
self._repeat(count,
lambda: cursor.insertText(_globalClipboard.value))
cursor.movePosition(QTextCursor.Left)
self._qpart.setTextCursor(cursor)
elif isinstance(_globalClipboard.value, list):
index = self._qpart.cursorPosition[0]
if cmd == _p:
index += 1
self._repeat(count,
lambda: self._qpart.lines.insert(index, '\n'.join(_globalClipboard.value)))
self._saveLastEditSimpleCmd(cmd, count)
def cmdSubstitute(self, cmd, count):
""" s
"""
cursor = self._qpart.textCursor()
for _ in range(count):
cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor)
if cursor.selectedText():
_globalClipboard.value = cursor.selectedText()
cursor.removeSelectedText()
self._saveLastEditSimpleCmd(cmd, count)
self.switchMode(Insert)
def cmdSubstituteLines(self, cmd, count):
""" S
"""
lineIndex = self._qpart.cursorPosition[0]
availableCount = len(self._qpart.lines) - lineIndex
effectiveCount = min(availableCount, count)
_globalClipboard.value = self._qpart.lines[lineIndex:lineIndex + effectiveCount]
with self._qpart:
del self._qpart.lines[lineIndex:lineIndex + effectiveCount]
self._qpart.lines.insert(lineIndex, '')
self._qpart.cursorPosition = (lineIndex, 0)
self._qpart._indenter.autoIndentBlock(self._qpart.textCursor().block())
self._saveLastEditSimpleCmd(cmd, count)
self.switchMode(Insert)
def cmdVisualMode(self, cmd, count):
cursor = self._qpart.textCursor()
cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor)
self._qpart.setTextCursor(cursor)
self.switchMode(Visual)
def cmdVisualLinesMode(self, cmd, count):
self.switchMode(VisualLines)
def cmdDelete(self, cmd, count):
""" x
"""
cursor = self._qpart.textCursor()
direction = QTextCursor.Left if cmd == _X else QTextCursor.Right
for _ in range(count):
cursor.movePosition(direction, QTextCursor.KeepAnchor)
if cursor.selectedText():
_globalClipboard.value = cursor.selectedText()
cursor.removeSelectedText()
self._saveLastEditSimpleCmd(cmd, count)
def cmdDeleteUntilEndOfBlock(self, cmd, count):
""" C and D
"""
cursor = self._qpart.textCursor()
for _ in range(count - 1):
cursor.movePosition(QTextCursor.Down, QTextCursor.KeepAnchor)
cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
_globalClipboard.value = cursor.selectedText()
cursor.removeSelectedText()
if cmd == _C:
self.switchMode(Insert)
self._saveLastEditSimpleCmd(cmd, count)
def cmdYankUntilEndOfLine(self, cmd, count):
oldCursor = self._qpart.textCursor()
cursor = self._qpart.textCursor()
cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
_globalClipboard.value = cursor.selectedText()
self._qpart.setTextCursor(cursor)
self._qpart.copy()
self._qpart.setTextCursor(oldCursor)
_SIMPLE_COMMANDS = {_A: cmdAppendAfterLine,
_a: cmdAppendAfterChar,
_C: cmdDeleteUntilEndOfBlock,
_D: cmdDeleteUntilEndOfBlock,
_i: cmdInsertMode,
_I: cmdInsertAtLineStartMode,
_J: cmdJoinLines,
_r: cmdReplaceCharMode,
_R: cmdReplaceMode,
_v: cmdVisualMode,
_V: cmdVisualLinesMode,
_o: cmdNewLineBelow,
_O: cmdNewLineAbove,
_p: cmdInternalPaste,
_P: cmdInternalPaste,
_s: cmdSubstitute,
_S: cmdSubstituteLines,
_u: cmdUndo,
_U: cmdRedo,
_x: cmdDelete,
_X: cmdDelete,
_Y: cmdYankUntilEndOfLine,
}
#
# Composite commands
#
def cmdCompositeDelete(self, cmd, motion, searchChar, count):
if motion in (_j, _Down):
lineIndex = self._qpart.cursorPosition[0]
availableCount = len(self._qpart.lines) - lineIndex
if availableCount < 2: # last line
return
effectiveCount = min(availableCount, count)
_globalClipboard.value = self._qpart.lines[lineIndex:lineIndex + effectiveCount + 1]
del self._qpart.lines[lineIndex:lineIndex + effectiveCount + 1]
elif motion in (_k, _Up):
lineIndex = self._qpart.cursorPosition[0]
if lineIndex == 0: # first line
return
effectiveCount = min(lineIndex, count)
_globalClipboard.value = self._qpart.lines[lineIndex - effectiveCount:lineIndex + 1]
del self._qpart.lines[lineIndex - effectiveCount:lineIndex + 1]
elif motion == _d: # delete whole line
lineIndex = self._qpart.cursorPosition[0]
availableCount = len(self._qpart.lines) - lineIndex
effectiveCount = min(availableCount, count)
_globalClipboard.value = self._qpart.lines[lineIndex:lineIndex + effectiveCount]
del self._qpart.lines[lineIndex:lineIndex + effectiveCount]
elif motion == _G:
currentLineIndex = self._qpart.cursorPosition[0]
_globalClipboard.value = self._qpart.lines[currentLineIndex:]
del self._qpart.lines[currentLineIndex:]
elif motion == 'gg':
currentLineIndex = self._qpart.cursorPosition[0]
_globalClipboard.value = self._qpart.lines[:currentLineIndex + 1]
del self._qpart.lines[:currentLineIndex + 1]
else:
self._moveCursor(motion, count, select=True, searchChar=searchChar)
selText = self._qpart.textCursor().selectedText()
if selText:
_globalClipboard.value = selText
self._qpart.textCursor().removeSelectedText()
self._saveLastEditCompositeCmd(cmd, motion, searchChar, count)
def cmdCompositeChange(self, cmd, motion, searchChar, count):
# TODO deletion and next insertion should be undo-ble as 1 action
self.cmdCompositeDelete(cmd, motion, searchChar, count)
self.switchMode(Insert)
def cmdCompositeYank(self, cmd, motion, searchChar, count):
oldCursor = self._qpart.textCursor()
if motion == _y:
cursor = self._qpart.textCursor()
cursor.movePosition(QTextCursor.StartOfBlock)
for _ in range(count - 1):
cursor.movePosition(QTextCursor.Down, QTextCursor.KeepAnchor)
cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
self._qpart.setTextCursor(cursor)
_globalClipboard.value = [self._qpart.selectedText]
else:
self._moveCursor(motion, count, select=True, searchChar=searchChar)
_globalClipboard.value = self._qpart.selectedText
self._qpart.copy()
self._qpart.setTextCursor(oldCursor)
def cmdCompositeUnIndent(self, cmd, motion, searchChar, count):
if motion == _Less:
pass # current line is already selected
else:
self._moveCursor(motion, count, select=True, searchChar=searchChar)
self._expandSelection()
self._qpart._indenter.onChangeSelectedBlocksIndent(increase=False, withSpace=False)
self._resetSelection(moveToTop=True)
self._saveLastEditCompositeCmd(cmd, motion, searchChar, count)
def cmdCompositeIndent(self, cmd, motion, searchChar, count):
if motion == _Greater:
pass # current line is already selected
else:
self._moveCursor(motion, count, select=True, searchChar=searchChar)
self._expandSelection()
self._qpart._indenter.onChangeSelectedBlocksIndent(increase=True, withSpace=False)
self._resetSelection(moveToTop=True)
self._saveLastEditCompositeCmd(cmd, motion, searchChar, count)
def cmdCompositeAutoIndent(self, cmd, motion, searchChar, count):
if motion == _Equal:
pass # current line is already selected
else:
self._moveCursor(motion, count, select=True, searchChar=searchChar)
self._expandSelection()
self._qpart._indenter.onAutoIndentTriggered()
self._resetSelection(moveToTop=True)
self._saveLastEditCompositeCmd(cmd, motion, searchChar, count)
def cmdCompositeScrollView(self, cmd, motion, searchChar, count):
if motion == _z:
self._qpart.centerCursor()
_COMPOSITE_COMMANDS = {_c: cmdCompositeChange,
_d: cmdCompositeDelete,
_y: cmdCompositeYank,
_Less: cmdCompositeUnIndent,
_Greater: cmdCompositeIndent,
_Equal: cmdCompositeAutoIndent,
_z: cmdCompositeScrollView,
}
|