-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathemacskeyshandler.cpp
More file actions
2825 lines (2614 loc) · 91.3 KB
/
Copy pathemacskeyshandler.cpp
File metadata and controls
2825 lines (2614 loc) · 91.3 KB
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
/**************************************************************************
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/
#include "emacskeyshandler.h"
//
// ATTENTION:
//
// 1 Please do not add any direct dependencies to other Qt Creator code here.
// Instead emit signals and let the EmacsKeysPlugin channel the information to
// Qt Creator. The idea is to keep this keyfile here in a "clean" state that
// allows easy reuse with any QTextEdit or QPlainTextEdit derived class.
//
// 2 There are a few auto tests located in ../../../tests/auto/emacsKeys.
// Commands that are covered there are marked as "// tested" below.
//
// 3 Some conventions:
//
// Use 1 based line numbers and 0 based column numbers. Even though
// the 1 based line are not nice it matches vim's and QTextEdit's 'line'
// concepts.
//
// Do not pass QTextCursor etc around unless really needed. Convert
// early to line/column.
//
// There is always a "current" cursor (m_tc). A current "region of interest"
// spans between m_anchor (== anchor()) and m_tc.position() (== position())
// The value of m_tc.anchor() is not used.
//
#include <utils/qtcassert.h>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtCore/QObject>
#include <QtCore/QPointer>
#include <QtCore/QProcess>
#include <QtCore/QRegExp>
#include <QtCore/QTextStream>
#include <QtCore/QtAlgorithms>
#include <QtCore/QStack>
#include <QtGui/QApplication>
#include <QtGui/QKeyEvent>
#include <QtGui/QLineEdit>
#include <QtGui/QPlainTextEdit>
#include <QtGui/QScrollBar>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>
#include <QtGui/QTextDocumentFragment>
#include <QtGui/QTextEdit>
#include <QtGui/QClipboard>
#include "markring.h"
#include "killring.h"
#define DEBUG_KEY 1
#if DEBUG_KEY
# define KEY_DEBUG(s) qDebug() << s
#else
# define KEY_DEBUG(s)
#endif
//#define DEBUG_UNDO 1
#if DEBUG_UNDO
# define UNDO_DEBUG(s) qDebug() << << m_tc.document()->revision() << s
#else
# define UNDO_DEBUG(s)
#endif
using namespace Core::Utils;
namespace EmacsKeys {
namespace Internal {
///////////////////////////////////////////////////////////////////////
//
// EmacsKeysHandler
//
///////////////////////////////////////////////////////////////////////
#define StartOfLine QTextCursor::StartOfLine
#define EndOfLine QTextCursor::EndOfLine
#define MoveAnchor QTextCursor::MoveAnchor
#define KeepAnchor QTextCursor::KeepAnchor
#define Up QTextCursor::Up
#define Down QTextCursor::Down
#define Right QTextCursor::Right
#define Left QTextCursor::Left
#define EndOfDocument QTextCursor::End
#define StartOfDocument QTextCursor::Start
#define EDITOR(s) (m_textedit ? m_textedit->s : m_plaintextedit->s)
#define EDITOR_WIDGET m_textedit ? qobject_cast<QWidget*>(m_textedit) : qobject_cast<QWidget*>(m_plaintextedit)
const int ParagraphSeparator = 0x00002029;
using namespace Qt;
enum Mode
{
InsertMode,
CommandMode,
ExMode,
SearchForwardMode,
SearchBackwardMode,
};
enum SubMode
{
NoSubMode,
ChangeSubMode, // used for c
DeleteSubMode, // used for d
FilterSubMode, // used for !
IndentSubMode, // used for =
RegisterSubMode, // used for "
ReplaceSubMode, // used for R and r
ShiftLeftSubMode, // used for <
ShiftRightSubMode, // used for >
WindowSubMode, // used for Ctrl-w
YankSubMode, // used for y
ZSubMode, // used for z
CapitalZSubMode // used for Z
};
enum SubSubMode
{
// typically used for things that require one more data item
// and are 'nested' behind a mode
NoSubSubMode,
FtSubSubMode, // used for f, F, t, T
MarkSubSubMode, // used for m
BackTickSubSubMode, // used for `
TickSubSubMode, // used for '
};
enum VisualMode
{
NoVisualMode,
VisualCharMode,
VisualLineMode,
VisualBlockMode,
};
enum MoveType
{
MoveExclusive,
MoveInclusive,
MoveLineWise,
};
QDebug &operator<<(QDebug &ts, const QList<QTextEdit::ExtraSelection> &sels)
{
foreach (QTextEdit::ExtraSelection sel, sels)
ts << "SEL: " << sel.cursor.anchor() << sel.cursor.position();
return ts;
}
QString quoteUnprintable(const QString &ba)
{
QString res;
for (int i = 0, n = ba.size(); i != n; ++i) {
QChar c = ba.at(i);
if (c.isPrint())
res += c;
else
res += QString("\\x%1").arg(c.unicode(), 2, 16);
}
return res;
}
enum EventResult
{
EventHandled,
EventUnhandled,
EventPassedToCore
};
class EmacsKeysHandler::Private
{
public:
Private(EmacsKeysHandler *parent, QWidget *widget);
EventResult handleEvent(QKeyEvent *ev);
bool wantsOverride(QKeyEvent *ev);
void handleCommand(const QString &cmd); // sets m_tc + handleExCommand
void handleExCommand(const QString &cmd);
void installEventFilter();
void setupWidget();
void restoreWidget();
friend class EmacsKeysHandler;
static int shift(int key) { return key + 32; }
static int control(int key) { return key + 256; }
void init();
EventResult handleKey(int key, int unmodified, const QString &text);
EventResult handleInsertMode(int key, int unmodified, const QString &text);
EventResult handleCommandMode(int key, int unmodified, const QString &text);
EventResult handleRegisterMode(int key, int unmodified, const QString &text);
EventResult handleMiniBufferModes(int key, int unmodified, const QString &text);
bool exactMatch(int key, const QKeySequence& keySequence);
void finishMovement(const QString &text = QString());
void search(const QString &needle, bool forward);
void highlightMatches(const QString &needle);
void yankPop(QWidget* view);
void setMark();
void exchangeDotAndMark();
void popToMark();
void copy();
void cut();
void yank();
void killLine();
void killWord();
void backwardKillWord();
/*
void charactersInserted(int line, int column, const QString& text);
*/
int mvCount() const { return m_mvcount.isEmpty() ? 1 : m_mvcount.toInt(); }
int opCount() const { return m_opcount.isEmpty() ? 1 : m_opcount.toInt(); }
int count() const { return mvCount() * opCount(); }
int leftDist() const { return m_tc.position() - m_tc.block().position(); }
int rightDist() const { return m_tc.block().length() - leftDist() - 1; }
bool atEndOfLine() const
{ return m_tc.atBlockEnd() && m_tc.block().length() > 1; }
int lastPositionInDocument() const;
int firstPositionInLine(int line) const; // 1 based line, 0 based pos
int lastPositionInLine(int line) const; // 1 based line, 0 based pos
int lineForPosition(int pos) const; // 1 based line, 0 based pos
// all zero-based counting
int cursorLineOnScreen() const;
int linesOnScreen() const;
int columnsOnScreen() const;
int cursorLineInDocument() const;
int cursorColumnInDocument() const;
int linesInDocument() const;
void scrollToLineInDocument(int line);
void scrollUp(int count);
void scrollDown(int count) { scrollUp(-count); }
// helper functions for indenting
bool isElectricCharacter(QChar c) const
{ return c == '{' || c == '}' || c == '#'; }
void indentRegion(QChar lastTyped = QChar());
void shiftRegionLeft(int repeat = 1);
void shiftRegionRight(int repeat = 1);
void moveToFirstNonBlankOnLine();
void moveToTargetColumn();
void setTargetColumn() {
m_targetColumn = leftDist();
//qDebug() << "TARGET: " << m_targetColumn;
}
void moveToNextWord(bool simple);
void moveToMatchingParanthesis();
void moveToWordBoundary(bool simple, bool forward);
// to reduce line noise
void moveToEndOfDocument() { m_tc.movePosition(EndOfDocument, MoveAnchor); }
void moveToStartOfLine();
void moveToEndOfLine();
void moveUp(int n = 1) { moveDown(-n); }
void moveDown(int n = 1); // { m_tc.movePosition(Down, MoveAnchor, n); }
void moveRight(int n = 1) { m_tc.movePosition(Right, MoveAnchor, n); }
void moveLeft(int n = 1) { m_tc.movePosition(Left, MoveAnchor, n); }
void setAnchor() { m_anchor = m_tc.position(); }
void setAnchor(int position) { m_anchor = position; }
void setPosition(int position) { m_tc.setPosition(position, MoveAnchor); }
void handleFfTt(int key);
// helper function for handleExCommand. return 1 based line index.
int readLineCode(QString &cmd);
void selectRange(int beginLine, int endLine);
void enterInsertMode();
void enterCommandMode();
void enterExMode();
void showRedMessage(const QString &msg);
void showBlackMessage(const QString &msg);
void notImplementedYet();
void updateMiniBuffer();
void updateSelection();
QWidget *editor() const;
QChar characterAtCursor() const
{ return m_tc.document()->characterAt(m_tc.position()); }
void beginEditBlock() { UNDO_DEBUG("BEGIN EDIT BLOCK"); m_tc.beginEditBlock(); }
void endEditBlock() { UNDO_DEBUG("END EDIT BLOCK"); m_tc.endEditBlock(); }
void joinPreviousEditBlock() { UNDO_DEBUG("JOIN EDIT BLOCK"); m_tc.joinPreviousEditBlock(); }
public:
QTextEdit *m_textedit;
QPlainTextEdit *m_plaintextedit;
bool m_wasReadOnly; // saves read-only state of document
EmacsKeysHandler *q;
Mode m_mode;
bool m_passing; // let the core see the next event
SubMode m_submode;
SubSubMode m_subsubmode;
int m_subsubdata;
QString m_input;
QTextCursor m_tc;
QTextCursor m_oldTc; // copy from last event to check for external changes
int m_anchor;
QHash<int, QString> m_registers;
int m_register;
QString m_mvcount;
QString m_opcount;
MoveType m_moveType;
MarkRing markRing;
bool m_fakeEnd;
bool isSearchMode() const
{ return m_mode == SearchForwardMode || m_mode == SearchBackwardMode; }
int m_gflag; // whether current command started with 'g'
QString m_commandBuffer;
QString m_currentFileName;
QString m_currentMessage;
bool m_lastSearchForward;
QString m_lastInsertion;
QString removeSelectedText();
int anchor() const { return m_anchor; }
int position() const { return m_tc.position(); }
QString selectedText() const;
// undo handling
void undo();
void redo();
QMap<int, int> m_undoCursorPosition; // revision -> position
// extra data for '.'
void replay(const QString &text, int count);
void setDotCommand(const QString &cmd) { m_dotCommand = cmd; }
void setDotCommand(const QString &cmd, int n) { m_dotCommand = cmd.arg(n); }
QString m_dotCommand;
bool m_inReplay; // true if we are executing a '.'
// extra data for ';'
QString m_semicolonCount;
int m_semicolonType; // 'f', 'F', 't', 'T'
int m_semicolonKey;
// history for '/'
QString lastSearchString() const;
static QStringList m_searchHistory;
int m_searchHistoryIndex;
// history for ':'
static QStringList m_commandHistory;
int m_commandHistoryIndex;
// visual line mode
void enterVisualMode(VisualMode visualMode);
void leaveVisualMode();
VisualMode m_visualMode;
// marks as lines
QHash<int, int> m_marks;
QString m_oldNeedle;
// vi style configuration
QVariant config(int code) const { return theEmacsKeysSetting(code)->value(); }
bool hasConfig(int code) const { return config(code).toBool(); }
bool hasConfig(int code, const char *value) const // FIXME
{ return config(code).toString().contains(value); }
// for restoring cursor position
int m_savedYankPosition;
int m_targetColumn;
int m_cursorWidth;
// auto-indent
void insertAutomaticIndentation(bool goingDown);
bool removeAutomaticIndentation(); // true if something removed
// number of autoindented characters
int m_justAutoIndented;
void handleStartOfLine();
void recordJump();
void recordNewUndo();
QList<int> m_jumpListUndo;
QList<int> m_jumpListRedo;
QList<QTextEdit::ExtraSelection> m_searchSelections;
int yankEndPosition;
int yankStartPosition;
};
QStringList EmacsKeysHandler::Private::m_searchHistory;
QStringList EmacsKeysHandler::Private::m_commandHistory;
EmacsKeysHandler::Private::Private(EmacsKeysHandler *parent, QWidget *widget)
{
q = parent;
m_textedit = qobject_cast<QTextEdit *>(widget);
m_plaintextedit = qobject_cast<QPlainTextEdit *>(widget);
init();
}
void EmacsKeysHandler::Private::init()
{
m_mode = CommandMode;
m_submode = NoSubMode;
m_subsubmode = NoSubSubMode;
m_passing = false;
m_fakeEnd = false;
m_lastSearchForward = true;
m_register = '"';
m_gflag = false;
m_visualMode = NoVisualMode;
m_targetColumn = 0;
m_moveType = MoveInclusive;
m_anchor = 0;
m_savedYankPosition = 0;
m_cursorWidth = EDITOR(cursorWidth());
m_inReplay = false;
m_justAutoIndented = 0;
}
bool EmacsKeysHandler::Private::wantsOverride(QKeyEvent *ev)
{
const int key = ev->key();
const int mods = ev->modifiers();
KEY_DEBUG("SHORTCUT OVERRIDE" << key << " PASSING: " << m_passing);
if (key == Key_Escape) {
// Not sure this feels good. People often hit Esc several times
if (m_visualMode == NoVisualMode && m_mode == CommandMode)
return false;
return true;
}
// We are interested in overriding most Ctrl key combinations
if (mods == Qt::ControlModifier && key >= Key_A && key <= Key_Z && key != Key_X && key != Key_R && key != Key_S) {
// Ctrl-K is special as it is the Core's default notion of QuickOpen
KEY_DEBUG(" NOT PASSING CTRL KEY");
//updateMiniBuffer();
return true;
}
// Let other shortcuts trigger
return false;
}
bool EmacsKeysHandler::Private::exactMatch(int key, const QKeySequence& keySequence)
{
return QKeySequence(key).matches(keySequence) == QKeySequence::ExactMatch;
}
void EmacsKeysHandler::Private::yankPop(QWidget* view)
{
qDebug() << "yankPop called " << endl;
if (KillRing::instance()->currentYankView() != view) {
qDebug() << "the last previous yank was not in this view" << endl;
// generate beep and return
QApplication::beep();
return;
}
int position = m_tc.position();
if (position != yankEndPosition) {
qDebug() << "Cursor has been moved in the meantime" << endl;
qDebug() << "yank end position " << yankEndPosition << endl;
QApplication::beep();
return;
}
QString next(KillRing::instance()->next());
if (!next.isEmpty()) {
qDebug() << "yanking " << next << endl;
beginEditBlock();
m_tc.setPosition(yankStartPosition, QTextCursor::KeepAnchor);
m_tc.removeSelectedText();
m_tc.insertText(next);
yankEndPosition = m_tc.position();
endEditBlock();
}
else {
qDebug() << "killring empty" << endl;
QApplication::beep();
}
}
void EmacsKeysHandler::Private::setMark()
{
qDebug() << "set mark" << endl;
markRing.addMark(m_tc.position());
}
void EmacsKeysHandler::Private::exchangeDotAndMark()
{
int position = m_tc.position();
markRing.addMark(position);
popToMark();
}
void EmacsKeysHandler::Private::popToMark()
{
qDebug() << "pop mark" << endl;
Mark mark(markRing.getPreviousMark());
if (mark.valid) {
m_tc.setPosition(mark.position);
}
else {
QApplication::beep();
}
}
void EmacsKeysHandler::Private::copy()
{
qDebug() << "emacs copy" << endl;
Mark mark(markRing.getMostRecentMark());
if (mark.valid) {
beginEditBlock();
int position = m_tc.position();
m_tc.setPosition(mark.position, QTextCursor::KeepAnchor);
QApplication::clipboard()->setText(m_tc.selectedText());
m_tc.clearSelection();
m_tc.setPosition(position);
endEditBlock();
}
else {
QApplication::beep();
}
}
void EmacsKeysHandler::Private::cut()
{
qDebug() << "emacs cut" << endl;
Mark mark(markRing.getMostRecentMark());
if (mark.valid) {
beginEditBlock();
m_tc.setPosition(mark.position, QTextCursor::KeepAnchor);
QApplication::clipboard()->setText(m_tc.selectedText());
m_tc.removeSelectedText();
endEditBlock();
}
else {
QApplication::beep();
}
}
void EmacsKeysHandler::Private::yank()
{
qDebug() << "emacs yank" << endl;
int position = m_tc.position();
yankStartPosition = position;
EDITOR(paste());
yankEndPosition = m_tc.position();
if (position != yankEndPosition) {
KillRing::instance()->setCurrentYankView(EDITOR_WIDGET);
}
}
void EmacsKeysHandler::Private::killLine()
{
qDebug() << "kill line" << endl;
beginEditBlock();
int position = m_tc.position();
qDebug() << "current position " << position << endl;
m_tc.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
if (position == m_tc.position()) {
qDebug() << "at line end" << endl;
// at the end of the line, just delete new line character
m_tc.deleteChar();
} else {
qDebug() << "invoke cut" << endl;
QApplication::clipboard()->setText(m_tc.selectedText());
m_tc.removeSelectedText();
}
endEditBlock();
}
void EmacsKeysHandler::Private::killWord()
{
qDebug() << "kill word" << endl;
int position = m_tc.position();
qDebug() << "current position " << position << endl;
beginEditBlock();
m_tc.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor);
if (position != m_tc.position()) {
qDebug() << "invoke cut" << endl;
QApplication::clipboard()->setText(m_tc.selectedText());
m_tc.removeSelectedText();
} else {
QApplication::beep();
}
endEditBlock();
}
void EmacsKeysHandler::Private::backwardKillWord()
{
qDebug() << "backwards kill word" << endl;
int position = m_tc.position();
qDebug() << "current position " << position << endl;
beginEditBlock();
m_tc.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor);
if (position != m_tc.position()) {
qDebug() << "invoke cut" << endl;
QApplication::clipboard()->setText(m_tc.selectedText());
m_tc.removeSelectedText();
} else {
QApplication::beep();
}
endEditBlock();
}
/*
void EmacsKeysHandler::Private::charactersInserted(int l, int c, const QString& text)
{
qDebug() << "characters inserted " << text << " " << l << " " << c << endl;
KillRing::instance()->setCurrentYankView(view);
startLine = l;
startColumn = c;
KTextEditor::viewCursorInterface(view)->cursorPositionReal(&endLine,
&endColumn);
}
*/
EventResult EmacsKeysHandler::Private::handleEvent(QKeyEvent *ev)
{
int key = ev->key();
const int mods = ev->modifiers();
QKeySequence keySequence(ev->key() + ev->modifiers());
qDebug() << "sequence: " << keySequence << endl;
if (key == Key_Shift || key == Key_Alt || key == Key_Control
|| key == Key_Alt || key == Key_AltGr || key == Key_Meta)
{
KEY_DEBUG("PLAIN MODIFIER");
return EventUnhandled;
}
// Fake "End of line"
m_tc = EDITOR(textCursor());
if (m_tc.position() != m_oldTc.position())
setTargetColumn();
m_tc.setVisualNavigation(true);
if (m_fakeEnd)
moveRight();
if ((mods & Qt::ControlModifier) != 0) {
key += 256;
key += 32; // make it lower case
} else if (key >= Key_A && key <= Key_Z && (mods & Qt::ShiftModifier) == 0) {
key += 32;
}
m_undoCursorPosition[m_tc.document()->revision()] = m_tc.position();
EventResult result = EventHandled;
if (exactMatch(Qt::CTRL + Qt::Key_N, keySequence)) {
m_tc.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor);
} else if (exactMatch(Qt::CTRL + Qt::Key_P, keySequence)) {
m_tc.movePosition(QTextCursor::Up, QTextCursor::MoveAnchor);
} else if (exactMatch(Qt::CTRL + Qt::Key_A, keySequence)) {
moveToStartOfLine();
} else if (exactMatch(Qt::CTRL + Qt::Key_E, keySequence)) {
moveToEndOfLine();
} else if (exactMatch(Qt::CTRL + Qt::Key_B, keySequence)) {
moveLeft();
} else if (exactMatch(Qt::CTRL + Qt::Key_F, keySequence)) {
moveRight();
} else if (exactMatch(Qt::ALT + Qt::Key_B, keySequence)) {
moveToWordBoundary(false, false);
} else if (exactMatch(Qt::ALT + Qt::Key_F, keySequence)) {
moveToNextWord(false);
} else if (exactMatch(Qt::ALT + Qt::Key_D, keySequence)) {
killWord();
} else if (exactMatch(Qt::ALT + Qt::Key_Backspace, keySequence)) {
backwardKillWord();
} else if (exactMatch(Qt::CTRL + Qt::Key_D, keySequence)) {
m_tc.deleteChar();
} else if (exactMatch(Qt::ALT + Qt::SHIFT + Qt::Key_Less, keySequence)) {
m_tc.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
} else if (exactMatch(Qt::ALT + Qt::SHIFT + Qt::Key_Greater, keySequence)) {
m_tc.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
} else if (exactMatch(Qt::CTRL + Qt::Key_V, keySequence)) {
moveDown(count() * (linesOnScreen() - 2) - cursorLineOnScreen());
scrollToLineInDocument(cursorLineInDocument());
} else if (exactMatch(Qt::ALT + Qt::Key_V, keySequence)) {
moveUp(count() * (linesOnScreen() - 2) + cursorLineOnScreen());
scrollToLineInDocument(cursorLineInDocument() + linesOnScreen() - 2);
} else if (exactMatch(Qt::CTRL + Qt::Key_Space, keySequence)) {
setMark();
} else if (exactMatch(Qt::CTRL + Qt::Key_K, keySequence)) {
killLine();
} else if (exactMatch(Qt::CTRL + Qt::Key_Y, keySequence)) {
yank();
} else if (exactMatch(Qt::ALT + Qt::Key_Y, keySequence)) {
yankPop(EDITOR_WIDGET);
} else if (exactMatch(Qt::CTRL + Qt::Key_W, keySequence)) {
cut();
} else if (exactMatch(Qt::ALT + Qt::Key_W, keySequence)) {
copy();
} else if (QKeySequence(Qt::CTRL + Qt::Key_U, Qt::CTRL + Qt::Key_Space).matches(keySequence) == QKeySequence::ExactMatch) {
popToMark();
} else if (QKeySequence(Qt::CTRL + Qt::Key_X, Qt::Key_X).matches(keySequence) == QKeySequence::ExactMatch) {
exchangeDotAndMark();
} else {
result = EventUnhandled;
}
m_oldTc = m_tc;
EDITOR(setTextCursor(m_tc));
return result;
}
void EmacsKeysHandler::Private::installEventFilter()
{
EDITOR(installEventFilter(q));
}
void EmacsKeysHandler::Private::setupWidget()
{
enterCommandMode();
//EDITOR(setCursorWidth(QFontMetrics(ed->font()).width(QChar('x')));
if (m_textedit) {
m_textedit->setLineWrapMode(QTextEdit::NoWrap);
} else if (m_plaintextedit) {
m_plaintextedit->setLineWrapMode(QPlainTextEdit::NoWrap);
}
m_wasReadOnly = EDITOR(isReadOnly());
//EDITOR(setReadOnly(true));
QTextCursor tc = EDITOR(textCursor());
if (tc.hasSelection()) {
int pos = tc.position();
int anc = tc.anchor();
m_marks['<'] = anc;
m_marks['>'] = pos;
m_anchor = anc;
m_visualMode = VisualCharMode;
tc.clearSelection();
EDITOR(setTextCursor(tc));
m_tc = tc; // needed in updateSelection
updateSelection();
}
//showBlackMessage("vi emulation mode. Type :q to leave. Use , Ctrl-R to trigger run.");
updateMiniBuffer();
}
void EmacsKeysHandler::Private::restoreWidget()
{
//showBlackMessage(QString());
//updateMiniBuffer();
//EDITOR(removeEventFilter(q));
EDITOR(setReadOnly(m_wasReadOnly));
EDITOR(setCursorWidth(m_cursorWidth));
EDITOR(setOverwriteMode(false));
if (m_visualMode == VisualLineMode) {
m_tc = EDITOR(textCursor());
int beginLine = lineForPosition(m_marks['<']);
int endLine = lineForPosition(m_marks['>']);
m_tc.setPosition(firstPositionInLine(beginLine), MoveAnchor);
m_tc.setPosition(lastPositionInLine(endLine), KeepAnchor);
EDITOR(setTextCursor(m_tc));
} else if (m_visualMode == VisualCharMode) {
m_tc = EDITOR(textCursor());
m_tc.setPosition(m_marks['<'], MoveAnchor);
m_tc.setPosition(m_marks['>'], KeepAnchor);
EDITOR(setTextCursor(m_tc));
}
m_visualMode = NoVisualMode;
updateSelection();
}
EventResult EmacsKeysHandler::Private::handleKey(int key, int unmodified,
const QString &text)
{
qDebug() << "KEY: " << key << text << "POS: " << m_tc.position();
if (m_mode == InsertMode)
return handleInsertMode(key, unmodified, text);
if (m_mode == CommandMode)
return handleCommandMode(key, unmodified, text);
if (m_mode == ExMode || m_mode == SearchForwardMode
|| m_mode == SearchBackwardMode)
return handleMiniBufferModes(key, unmodified, text);
return EventUnhandled;
}
void EmacsKeysHandler::Private::moveDown(int n)
{
#if 0
// does not work for "hidden" documents like in the autotests
m_tc.movePosition(Down, MoveAnchor, n);
#else
const int col = m_tc.position() - m_tc.block().position();
const int lastLine = m_tc.document()->lastBlock().blockNumber();
const int targetLine = qMax(0, qMin(lastLine, m_tc.block().blockNumber() + n));
const QTextBlock &block = m_tc.document()->findBlockByNumber(targetLine);
const int pos = block.position();
setPosition(pos + qMin(block.length() - 1, col));
moveToTargetColumn();
#endif
}
void EmacsKeysHandler::Private::moveToEndOfLine()
{
#if 0
// does not work for "hidden" documents like in the autotests
m_tc.movePosition(EndOfLine, MoveAnchor);
#else
const QTextBlock &block = m_tc.block();
setPosition(block.position() + block.length() - 1);
#endif
}
void EmacsKeysHandler::Private::moveToStartOfLine()
{
#if 0
// does not work for "hidden" documents like in the autotests
m_tc.movePosition(StartOfLine, MoveAnchor);
#else
const QTextBlock &block = m_tc.block();
setPosition(block.position());
#endif
}
void EmacsKeysHandler::Private::finishMovement(const QString &dotCommand)
{
//qDebug() << "ANCHOR: " << position() << anchor();
if (m_submode == FilterSubMode) {
int beginLine = lineForPosition(anchor());
int endLine = lineForPosition(position());
setPosition(qMin(anchor(), position()));
enterExMode();
m_currentMessage.clear();
m_commandBuffer = QString(".,+%1!").arg(qAbs(endLine - beginLine));
m_commandHistory.append(QString());
m_commandHistoryIndex = m_commandHistory.size() - 1;
updateMiniBuffer();
return;
}
if (m_visualMode != NoVisualMode)
m_marks['>'] = m_tc.position();
if (m_submode == ChangeSubMode) {
if (m_moveType == MoveInclusive)
moveRight(); // correction
if (anchor() >= position())
m_anchor++;
if (!dotCommand.isEmpty())
setDotCommand("c" + dotCommand);
QString text = removeSelectedText();
//qDebug() << "CHANGING TO INSERT MODE" << text;
m_registers[m_register] = text;
enterInsertMode();
m_submode = NoSubMode;
} else if (m_submode == DeleteSubMode) {
if (m_moveType == MoveInclusive)
moveRight(); // correction
if (anchor() >= position())
m_anchor++;
if (!dotCommand.isEmpty())
setDotCommand("d" + dotCommand);
m_registers[m_register] = removeSelectedText();
m_submode = NoSubMode;
if (atEndOfLine())
moveLeft();
else
setTargetColumn();
} else if (m_submode == YankSubMode) {
m_registers[m_register] = selectedText();
setPosition(m_savedYankPosition);
m_submode = NoSubMode;
} else if (m_submode == ReplaceSubMode) {
m_submode = NoSubMode;
} else if (m_submode == IndentSubMode) {
recordJump();
indentRegion();
m_submode = NoSubMode;
updateMiniBuffer();
} else if (m_submode == ShiftRightSubMode) {
recordJump();
shiftRegionRight(1);
m_submode = NoSubMode;
updateMiniBuffer();
} else if (m_submode == ShiftLeftSubMode) {
recordJump();
shiftRegionLeft(1);
m_submode = NoSubMode;
updateMiniBuffer();
}
m_moveType = MoveInclusive;
m_mvcount.clear();
m_opcount.clear();
m_gflag = false;
m_register = '"';
m_tc.clearSelection();
updateSelection();
updateMiniBuffer();
}
void EmacsKeysHandler::Private::updateSelection()
{
QList<QTextEdit::ExtraSelection> selections = m_searchSelections;
if (m_visualMode != NoVisualMode) {
QTextEdit::ExtraSelection sel;
sel.cursor = m_tc;
sel.format = m_tc.blockCharFormat();
#if 0
sel.format.setFontWeight(QFont::Bold);
sel.format.setFontUnderline(true);
#else
sel.format.setForeground(Qt::white);
sel.format.setBackground(Qt::black);
#endif
int cursorPos = m_tc.position();
int anchorPos = m_marks['<'];
//qDebug() << "POS: " << cursorPos << " ANCHOR: " << anchorPos;
if (m_visualMode == VisualCharMode) {
sel.cursor.setPosition(anchorPos, KeepAnchor);
selections.append(sel);
} else if (m_visualMode == VisualLineMode) {
sel.cursor.setPosition(qMin(cursorPos, anchorPos), MoveAnchor);
sel.cursor.movePosition(StartOfLine, MoveAnchor);
sel.cursor.setPosition(qMax(cursorPos, anchorPos), KeepAnchor);
sel.cursor.movePosition(EndOfLine, KeepAnchor);
selections.append(sel);
} else if (m_visualMode == VisualBlockMode) {
QTextCursor tc = m_tc;
tc.setPosition(anchorPos);
tc.movePosition(StartOfLine, MoveAnchor);
QTextBlock anchorBlock = tc.block();
QTextBlock cursorBlock = m_tc.block();
int anchorColumn = anchorPos - anchorBlock.position();
int cursorColumn = cursorPos - cursorBlock.position();
int startColumn = qMin(anchorColumn, cursorColumn);
int endColumn = qMax(anchorColumn, cursorColumn);
int endPos = cursorBlock.position();
while (tc.position() <= endPos) {
if (startColumn < tc.block().length() - 1) {
int last = qMin(tc.block().length() - 1, endColumn);
int len = last - startColumn + 1;
sel.cursor = tc;
sel.cursor.movePosition(Right, MoveAnchor, startColumn);
sel.cursor.movePosition(Right, KeepAnchor, len);
selections.append(sel);
}
tc.movePosition(Down, MoveAnchor, 1);
}
}
}
//qDebug() << "SELECTION: " << selections;
emit q->selectionChanged(selections);
}
void EmacsKeysHandler::Private::updateMiniBuffer()
{
QString msg;
if (m_passing) {
msg = "-- PASSING -- ";
} else if (!m_currentMessage.isEmpty()) {
msg = m_currentMessage;
} else if (m_mode == CommandMode && m_visualMode != NoVisualMode) {
if (m_visualMode == VisualCharMode) {
msg = "-- VISUAL --";