PageRenderTime 66ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/src/plugins/fakevim/fakevimhandler.cpp

https://bitbucket.org/kpozn/qt-creator-py-reborn
C++ | 5366 lines | 4912 code | 223 blank | 231 comment | 605 complexity | 78dac7466090e757c1cacbc672aaa7e1 MD5 | raw file
Possible License(s): LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. /**************************************************************************
  2. **
  3. ** This file is part of Qt Creator
  4. **
  5. ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
  6. **
  7. ** Contact: Nokia Corporation (qt-info@nokia.com)
  8. **
  9. **
  10. ** GNU Lesser General Public License Usage
  11. **
  12. ** This file may be used under the terms of the GNU Lesser General Public
  13. ** License version 2.1 as published by the Free Software Foundation and
  14. ** appearing in the file LICENSE.LGPL included in the packaging of this file.
  15. ** Please review the following information to ensure the GNU Lesser General
  16. ** Public License version 2.1 requirements will be met:
  17. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  18. **
  19. ** In addition, as a special exception, Nokia gives you certain additional
  20. ** rights. These rights are described in the Nokia Qt LGPL Exception
  21. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  22. **
  23. ** Other Usage
  24. **
  25. ** Alternatively, this file may be used in accordance with the terms and
  26. ** conditions contained in a signed written agreement between you and Nokia.
  27. **
  28. ** If you have questions regarding the use of this file, please contact
  29. ** Nokia at qt-info@nokia.com.
  30. **
  31. **************************************************************************/
  32. //
  33. // ATTENTION:
  34. //
  35. // 1 Please do not add any direct dependencies to other Qt Creator code here.
  36. // Instead emit signals and let the FakeVimPlugin channel the information to
  37. // Qt Creator. The idea is to keep this file here in a "clean" state that
  38. // allows easy reuse with any QTextEdit or QPlainTextEdit derived class.
  39. //
  40. // 2 There are a few auto tests located in ../../../tests/auto/fakevim.
  41. // Commands that are covered there are marked as "// tested" below.
  42. //
  43. // 3 Some conventions:
  44. //
  45. // Use 1 based line numbers and 0 based column numbers. Even though
  46. // the 1 based line are not nice it matches vim's and QTextEdit's 'line'
  47. // concepts.
  48. //
  49. // Do not pass QTextCursor etc around unless really needed. Convert
  50. // early to line/column.
  51. //
  52. // A QTextCursor is always between characters, whereas vi's cursor is always
  53. // over a character. FakeVim interprets the QTextCursor to be over the character
  54. // to the right of the QTextCursor's position().
  55. //
  56. // A current "region of interest"
  57. // spans between anchor(), (i.e. the character below anchor()), and
  58. // position(). The character below position() is not included
  59. // if the last movement command was exclusive (MoveExclusive).
  60. //
  61. #include "fakevimhandler.h"
  62. #include <utils/qtcassert.h>
  63. #include <QDebug>
  64. #include <QFile>
  65. #include <QObject>
  66. #include <QPointer>
  67. #include <QProcess>
  68. #include <QRegExp>
  69. #include <QTextStream>
  70. #include <QTimer>
  71. #include <QtAlgorithms>
  72. #include <QStack>
  73. #include <QApplication>
  74. #include <QInputMethodEvent>
  75. #include <QKeyEvent>
  76. #include <QLineEdit>
  77. #include <QPlainTextEdit>
  78. #include <QScrollBar>
  79. #include <QTextBlock>
  80. #include <QTextCursor>
  81. #include <QTextDocumentFragment>
  82. #include <QTextEdit>
  83. #include <algorithm>
  84. #include <climits>
  85. #include <ctype.h>
  86. //#define DEBUG_KEY 1
  87. #if DEBUG_KEY
  88. # define KEY_DEBUG(s) qDebug() << s
  89. #else
  90. # define KEY_DEBUG(s)
  91. #endif
  92. //#define DEBUG_UNDO 1
  93. #if DEBUG_UNDO
  94. # define UNDO_DEBUG(s) qDebug() << << document()->availableUndoSteps() << s
  95. #else
  96. # define UNDO_DEBUG(s)
  97. #endif
  98. using namespace Utils;
  99. namespace FakeVim {
  100. namespace Internal {
  101. ///////////////////////////////////////////////////////////////////////
  102. //
  103. // FakeVimHandler
  104. //
  105. ///////////////////////////////////////////////////////////////////////
  106. #define StartOfLine QTextCursor::StartOfLine
  107. #define EndOfLine QTextCursor::EndOfLine
  108. #define MoveAnchor QTextCursor::MoveAnchor
  109. #define KeepAnchor QTextCursor::KeepAnchor
  110. #define Up QTextCursor::Up
  111. #define Down QTextCursor::Down
  112. #define Right QTextCursor::Right
  113. #define Left QTextCursor::Left
  114. #define EndOfDocument QTextCursor::End
  115. #define StartOfDocument QTextCursor::Start
  116. #define EDITOR(s) (m_textedit ? m_textedit->s : m_plaintextedit->s)
  117. enum {
  118. #ifdef Q_OS_MAC
  119. RealControlModifier = Qt::MetaModifier
  120. #else
  121. RealControlModifier = Qt::ControlModifier
  122. #endif
  123. };
  124. // Enforce use of RealControlModifier by breaking the compilation.
  125. #define MetaModifier // Use RealControlModifier instead
  126. #define ControlModifier // Use RealControlModifier instead
  127. const int ParagraphSeparator = 0x00002029;
  128. typedef QLatin1String _;
  129. using namespace Qt;
  130. /*! A \e Mode represents one of the basic modes of operation of FakeVim.
  131. */
  132. enum Mode
  133. {
  134. InsertMode,
  135. ReplaceMode,
  136. CommandMode,
  137. ExMode
  138. };
  139. /*! A \e SubMode is used for things that require one more data item
  140. and are 'nested' behind a \l Mode.
  141. */
  142. enum SubMode
  143. {
  144. NoSubMode,
  145. ChangeSubMode, // Used for c
  146. DeleteSubMode, // Used for d
  147. FilterSubMode, // Used for !
  148. IndentSubMode, // Used for =
  149. RegisterSubMode, // Used for "
  150. ShiftLeftSubMode, // Used for <
  151. ShiftRightSubMode, // Used for >
  152. TransformSubMode, // Used for ~/gu/gU
  153. WindowSubMode, // Used for Ctrl-w
  154. YankSubMode, // Used for y
  155. ZSubMode, // Used for z
  156. CapitalZSubMode, // Used for Z
  157. ReplaceSubMode, // Used for r
  158. OpenSquareSubMode, // Used for [
  159. CloseSquareSubMode // Used for ]
  160. };
  161. /*! A \e SubSubMode is used for things that require one more data item
  162. and are 'nested' behind a \l SubMode.
  163. */
  164. enum SubSubMode
  165. {
  166. NoSubSubMode,
  167. FtSubSubMode, // Used for f, F, t, T.
  168. MarkSubSubMode, // Used for m.
  169. BackTickSubSubMode, // Used for `.
  170. TickSubSubMode, // Used for '.
  171. InvertCaseSubSubMode, // Used for ~.
  172. DownCaseSubSubMode, // Used for gu.
  173. UpCaseSubSubMode, // Used for gU.
  174. TextObjectSubSubMode, // Used for thing like iw, aW, as etc.
  175. SearchSubSubMode
  176. };
  177. enum VisualMode
  178. {
  179. NoVisualMode,
  180. VisualCharMode,
  181. VisualLineMode,
  182. VisualBlockMode
  183. };
  184. enum MoveType
  185. {
  186. MoveExclusive,
  187. MoveInclusive,
  188. MoveLineWise
  189. };
  190. /*!
  191. \enum RangeMode
  192. The \e RangeMode serves as a means to define how the "Range" between
  193. the \l cursor and the \l anchor position is to be interpreted.
  194. \value RangeCharMode Entered by pressing \key v. The range includes
  195. all characters between cursor and anchor.
  196. \value RangeLineMode Entered by pressing \key V. The range includes
  197. all lines between the line of the cursor and
  198. the line of the anchor.
  199. \value RangeLineModeExclusice Like \l RangeLineMode, but keeps one
  200. newline when deleting.
  201. \value RangeBlockMode Entered by pressing \key Ctrl-v. The range includes
  202. all characters with line and column coordinates
  203. between line and columns coordinates of cursor and
  204. anchor.
  205. \value RangeBlockAndTailMode Like \l RangeBlockMode, but also includes
  206. all characters in the affected lines up to the end
  207. of these lines.
  208. */
  209. enum EventResult
  210. {
  211. EventHandled,
  212. EventUnhandled,
  213. EventPassedToCore
  214. };
  215. struct Column
  216. {
  217. Column(int p, int l) : physical(p), logical(l) {}
  218. int physical; // Number of characters in the data.
  219. int logical; // Column on screen.
  220. };
  221. QDebug operator<<(QDebug ts, const Column &col)
  222. {
  223. return ts << "(p: " << col.physical << ", l: " << col.logical << ")";
  224. }
  225. struct CursorPosition
  226. {
  227. // for jump history
  228. CursorPosition() : position(-1), scrollLine(-1) {}
  229. CursorPosition(int pos, int line) : position(pos), scrollLine(line) {}
  230. int position; // Position in document
  231. int scrollLine; // First visible line
  232. };
  233. struct Register
  234. {
  235. Register() : rangemode(RangeCharMode) {}
  236. Register(const QString &c) : contents(c), rangemode(RangeCharMode) {}
  237. Register(const QString &c, RangeMode m) : contents(c), rangemode(m) {}
  238. QString contents;
  239. RangeMode rangemode;
  240. };
  241. QDebug operator<<(QDebug ts, const Register &reg)
  242. {
  243. return ts << reg.contents;
  244. }
  245. struct SearchData
  246. {
  247. SearchData()
  248. {
  249. forward = true;
  250. mustMove = true;
  251. highlightMatches = true;
  252. highlightCursor = true;
  253. }
  254. QString needle;
  255. bool forward;
  256. bool mustMove;
  257. bool highlightMatches;
  258. bool highlightCursor;
  259. };
  260. Range::Range()
  261. : beginPos(-1), endPos(-1), rangemode(RangeCharMode)
  262. {}
  263. Range::Range(int b, int e, RangeMode m)
  264. : beginPos(qMin(b, e)), endPos(qMax(b, e)), rangemode(m)
  265. {}
  266. QString Range::toString() const
  267. {
  268. return QString("%1-%2 (mode: %3)").arg(beginPos).arg(endPos)
  269. .arg(rangemode);
  270. }
  271. QDebug operator<<(QDebug ts, const Range &range)
  272. {
  273. return ts << '[' << range.beginPos << ',' << range.endPos << ']';
  274. }
  275. ExCommand::ExCommand(const QString &c, const QString &a, const Range &r)
  276. : cmd(c), hasBang(false), args(a), range(r), count(1)
  277. {}
  278. bool ExCommand::matches(const QString &min, const QString &full) const
  279. {
  280. return cmd.startsWith(min) && full.startsWith(cmd);
  281. }
  282. void ExCommand::setContentsFromLine(const QString &line)
  283. {
  284. cmd = line.section(' ', 0, 0);
  285. args = line.mid(cmd.size() + 1).trimmed();
  286. while (cmd.startsWith(QLatin1Char(':')))
  287. cmd.remove(0, 1);
  288. hasBang = cmd.endsWith('!');
  289. if (hasBang)
  290. cmd.chop(1);
  291. }
  292. QDebug operator<<(QDebug ts, const ExCommand &cmd)
  293. {
  294. return ts << cmd.cmd << ' ' << cmd.args << ' ' << cmd.range;
  295. }
  296. QDebug operator<<(QDebug ts, const QList<QTextEdit::ExtraSelection> &sels)
  297. {
  298. foreach (const QTextEdit::ExtraSelection &sel, sels)
  299. ts << "SEL: " << sel.cursor.anchor() << sel.cursor.position();
  300. return ts;
  301. }
  302. QString quoteUnprintable(const QString &ba)
  303. {
  304. QString res;
  305. for (int i = 0, n = ba.size(); i != n; ++i) {
  306. const QChar c = ba.at(i);
  307. const int cc = c.unicode();
  308. if (c.isPrint())
  309. res += c;
  310. else if (cc == '\n')
  311. res += _("<CR>");
  312. else
  313. res += QString("\\x%1").arg(c.unicode(), 2, 16, QLatin1Char('0'));
  314. }
  315. return res;
  316. }
  317. static bool startsWithWhitespace(const QString &str, int col)
  318. {
  319. QTC_ASSERT(str.size() >= col, return false);
  320. for (int i = 0; i < col; ++i) {
  321. uint u = str.at(i).unicode();
  322. if (u != ' ' && u != '\t')
  323. return false;
  324. }
  325. return true;
  326. }
  327. inline QString msgMarkNotSet(const QString &text)
  328. {
  329. return FakeVimHandler::tr("Mark '%1' not set").arg(text);
  330. }
  331. class Input
  332. {
  333. public:
  334. // Remove some extra "information" on Mac.
  335. static int cleanModifier(int m) { return m & ~Qt::KeypadModifier; }
  336. Input()
  337. : m_key(0), m_xkey(0), m_modifiers(0) {}
  338. explicit Input(QChar x)
  339. : m_key(x.unicode()), m_xkey(x.unicode()), m_modifiers(0), m_text(x) {}
  340. Input(int k, int m, const QString &t)
  341. : m_key(k), m_modifiers(cleanModifier(m)), m_text(t)
  342. {
  343. // On Mac, QKeyEvent::text() returns non-empty strings for
  344. // cursor keys. This breaks some of the logic later on
  345. // relying on text() being empty for "special" keys.
  346. // FIXME: Check the real conditions.
  347. if (m_text.size() == 1 && m_text.at(0).unicode() < ' ')
  348. m_text.clear();
  349. // m_xkey is only a cache.
  350. m_xkey = (m_text.size() == 1 ? m_text.at(0).unicode() : m_key);
  351. }
  352. bool isDigit() const
  353. {
  354. return m_xkey >= '0' && m_xkey <= '9';
  355. }
  356. bool isKey(int c) const
  357. {
  358. return !m_modifiers && m_key == c;
  359. }
  360. bool isBackspace() const
  361. {
  362. return m_key == Key_Backspace || isControl('h');
  363. }
  364. bool isReturn() const
  365. {
  366. return m_key == Key_Return || m_key == Key_Enter;
  367. }
  368. bool isEscape() const
  369. {
  370. return isKey(Key_Escape) || isKey(27) || isControl('c')
  371. || isControl(Key_BracketLeft);
  372. }
  373. bool is(int c) const
  374. {
  375. return m_xkey == c && m_modifiers != RealControlModifier;
  376. }
  377. bool isControl(int c) const
  378. {
  379. return m_modifiers == RealControlModifier
  380. && (m_xkey == c || m_xkey + 32 == c || m_xkey + 64 == c || m_xkey + 96 == c);
  381. }
  382. bool isShift(int c) const
  383. {
  384. return m_modifiers == Qt::ShiftModifier && m_xkey == c;
  385. }
  386. bool operator==(const Input &a) const
  387. {
  388. return a.m_key == m_key && a.m_modifiers == m_modifiers
  389. && m_text == a.m_text;
  390. }
  391. // Ignore e.g. ShiftModifier, which is not available in sourced data.
  392. bool matchesForMap(const Input &a) const
  393. {
  394. return (a.m_key == m_key || a.m_xkey == m_xkey) && m_text == a.m_text;
  395. }
  396. bool operator!=(const Input &a) const { return !operator==(a); }
  397. QString text() const { return m_text; }
  398. QChar asChar() const
  399. {
  400. return (m_text.size() == 1 ? m_text.at(0) : QChar());
  401. }
  402. int key() const { return m_key; }
  403. QChar raw() const
  404. {
  405. if (m_key == Key_Tab)
  406. return '\t';
  407. if (m_key == Key_Return)
  408. return '\n';
  409. return m_key;
  410. }
  411. QDebug dump(QDebug ts) const
  412. {
  413. return ts << m_key << '-' << m_modifiers << '-'
  414. << quoteUnprintable(m_text);
  415. }
  416. private:
  417. int m_key;
  418. int m_xkey;
  419. int m_modifiers;
  420. QString m_text;
  421. };
  422. QDebug operator<<(QDebug ts, const Input &input) { return input.dump(ts); }
  423. class Inputs : public QVector<Input>
  424. {
  425. public:
  426. Inputs() {}
  427. explicit Inputs(const QString &str) { parseFrom(str); }
  428. void parseFrom(const QString &str);
  429. };
  430. static bool iss(char a, char b)
  431. {
  432. if (a >= 'a')
  433. a -= 'a' - 'A';
  434. if (b >= 'a')
  435. b -= 'a' - 'A';
  436. return a == b;
  437. }
  438. void Inputs::parseFrom(const QString &str)
  439. {
  440. const int n = str.size();
  441. for (int i = 0; i < n; ++i) {
  442. uint c0 = str.at(i).unicode(), c1 = 0, c2 = 0, c3 = 0, c4 = 0;
  443. if (i + 1 < n)
  444. c1 = str.at(i + 1).unicode();
  445. if (i + 2 < n)
  446. c2 = str.at(i + 2).unicode();
  447. if (i + 3 < n)
  448. c3 = str.at(i + 3).unicode();
  449. if (i + 4 < n)
  450. c4 = str.at(i + 4).unicode();
  451. if (c0 == '<') {
  452. if (iss(c1, 'C') && c2 == '-' && c4 == '>') {
  453. uint c = (c3 < 90 ? c3 : c3 - 32);
  454. append(Input(c, RealControlModifier, QString(QChar(c - 64))));
  455. i += 4;
  456. } else if (iss(c1, 'C') && iss(c2, 'R') && c3 == '>') {
  457. append(Input(Key_Return, Qt::NoModifier, QString(QChar(13))));
  458. i += 3;
  459. } else if (iss(c1, 'E') && iss(c2, 'S') && iss(c3, 'C') && c4 == '>') {
  460. append(Input(Key_Escape, Qt::NoModifier, QString(QChar(27))));
  461. i += 4;
  462. } else {
  463. append(Input(QLatin1Char(c0)));
  464. }
  465. } else {
  466. append(Input(QLatin1Char(c0)));
  467. }
  468. }
  469. }
  470. // This wraps a string and a "cursor position".
  471. class CommandBuffer
  472. {
  473. public:
  474. CommandBuffer() : m_pos(0) {}
  475. void clear() { m_buffer.clear(); m_pos = 0; }
  476. void setContents(const QString &s) { m_buffer = s; m_pos = s.size(); }
  477. QString contents() const { return m_buffer; }
  478. bool isEmpty() const { return m_buffer.isEmpty(); }
  479. int cursorPos() const { return m_pos; }
  480. void insertChar(QChar c) { m_buffer.insert(m_pos++, c); }
  481. void insertText(const QString &s) { m_buffer.insert(m_pos, s); m_pos += s.size(); }
  482. void deleteChar() { if (m_pos) m_buffer.remove(--m_pos, 1); }
  483. void moveLeft() { if (m_pos) --m_pos; }
  484. void moveRight() { if (m_pos < m_buffer.size()) ++m_pos; }
  485. void moveStart() { m_pos = 0; }
  486. void moveEnd() { m_pos = m_buffer.size(); }
  487. QString display() const
  488. {
  489. QString msg;
  490. for (int i = 0; i != m_buffer.size(); ++i) {
  491. const QChar c = m_buffer.at(i);
  492. if (c.unicode() < 32) {
  493. msg += '^';
  494. msg += QChar(c.unicode() + 64);
  495. } else {
  496. msg += c;
  497. }
  498. }
  499. return msg;
  500. }
  501. bool handleInput(const Input &input)
  502. {
  503. if (input.isKey(Key_Left)) {
  504. moveLeft();
  505. } else if (input.isKey(Key_Right)) {
  506. moveRight();
  507. } else if (input.isKey(Key_Home)) {
  508. moveStart();
  509. } else if (input.isKey(Key_End)) {
  510. moveEnd();
  511. } else if (input.isKey(Key_Delete)) {
  512. if (m_pos < m_buffer.size())
  513. m_buffer.remove(m_pos, 1);
  514. } else if (!input.text().isEmpty()) {
  515. insertText(input.text());
  516. } else {
  517. return false;
  518. }
  519. return true;
  520. }
  521. private:
  522. QString m_buffer;
  523. int m_pos;
  524. };
  525. class History
  526. {
  527. public:
  528. History() : m_index(0) {}
  529. void append(const QString &item);
  530. void down() { m_index = qMin(m_index + 1, m_items.size()); }
  531. void up() { m_index = qMax(m_index - 1, 0); }
  532. void restart() { m_index = m_items.size(); }
  533. QString current() const { return m_items.value(m_index, QString()); }
  534. QStringList items() const { return m_items; }
  535. private:
  536. QStringList m_items;
  537. int m_index;
  538. };
  539. void History::append(const QString &item)
  540. {
  541. if (item.isEmpty())
  542. return;
  543. m_items.removeAll(item);
  544. m_items.append(item); m_index = m_items.size() - 1;
  545. }
  546. // Mappings for a specific mode.
  547. class ModeMapping : public QList<QPair<Inputs, Inputs> >
  548. {
  549. public:
  550. ModeMapping() { test(); }
  551. void test()
  552. {
  553. //insert(Inputs() << Input('A') << Input('A'),
  554. // Inputs() << Input('x') << Input('x'));
  555. }
  556. void insert(const Inputs &from, const Inputs &to)
  557. {
  558. for (int i = 0; i != size(); ++i)
  559. if (at(i).first == from) {
  560. (*this)[i].second = to;
  561. return;
  562. }
  563. append(QPair<Inputs, Inputs>(from, to));
  564. }
  565. void remove(const Inputs &from)
  566. {
  567. for (int i = 0; i != size(); ++i)
  568. if (at(i).first == from) {
  569. removeAt(i);
  570. return;
  571. }
  572. }
  573. // Returns 'false' if more input is needed to decide whether a mapping
  574. // needs to be applied. If a decision can be made, return 'true',
  575. // and replace *input with the mapped data.
  576. bool mappingDone(Inputs *inputs) const
  577. {
  578. // FIXME: inefficient.
  579. for (int i = 0; i != size(); ++i) {
  580. const Inputs &haystack = at(i).first;
  581. // A mapping
  582. if (couldTriggerMap(haystack, *inputs)) {
  583. if (haystack.size() != inputs->size())
  584. return false; // This can be extended.
  585. // Actual mapping.
  586. *inputs = at(i).second;
  587. return true;
  588. }
  589. }
  590. // No extensible mapping found. Use inputs as-is.
  591. return true;
  592. }
  593. private:
  594. static bool couldTriggerMap(const Inputs &haystack, const Inputs &needle)
  595. {
  596. // Input is already too long.
  597. if (needle.size() > haystack.size())
  598. return false;
  599. for (int i = 0; i != needle.size(); ++i) {
  600. if (!needle.at(i).matchesForMap(haystack.at(i)))
  601. return false;
  602. }
  603. return true;
  604. }
  605. };
  606. class FakeVimHandler::Private : public QObject
  607. {
  608. Q_OBJECT
  609. public:
  610. Private(FakeVimHandler *parent, QWidget *widget);
  611. EventResult handleEvent(QKeyEvent *ev);
  612. bool wantsOverride(QKeyEvent *ev);
  613. void handleCommand(const QString &cmd); // Sets m_tc + handleExCommand
  614. void handleExCommand(const QString &cmd);
  615. void installEventFilter();
  616. void passShortcuts(bool enable);
  617. void setupWidget();
  618. void restoreWidget(int tabSize);
  619. friend class FakeVimHandler;
  620. void init();
  621. EventResult handleKey(const Input &);
  622. Q_SLOT EventResult handleKey2();
  623. EventResult handleInsertMode(const Input &);
  624. EventResult handleReplaceMode(const Input &);
  625. EventResult handleCommandMode(const Input &);
  626. EventResult handleCommandMode1(const Input &);
  627. EventResult handleCommandMode2(const Input &);
  628. EventResult handleRegisterMode(const Input &);
  629. EventResult handleExMode(const Input &);
  630. EventResult handleOpenSquareSubMode(const Input &);
  631. EventResult handleCloseSquareSubMode(const Input &);
  632. EventResult handleSearchSubSubMode(const Input &);
  633. EventResult handleCommandSubSubMode(const Input &);
  634. void finishMovement(const QString &dotCommand = QString());
  635. void finishMovement(const QString &dotCommand, int count);
  636. void resetCommandMode();
  637. void search(const SearchData &sd);
  638. void searchBalanced(bool forward, QChar needle, QChar other);
  639. void highlightMatches(const QString &needle);
  640. void stopIncrementalFind();
  641. int mvCount() const { return m_mvcount.isEmpty() ? 1 : m_mvcount.toInt(); }
  642. int opCount() const { return m_opcount.isEmpty() ? 1 : m_opcount.toInt(); }
  643. int count() const { return mvCount() * opCount(); }
  644. QTextBlock block() const { return cursor().block(); }
  645. int leftDist() const { return position() - block().position(); }
  646. int rightDist() const { return block().length() - leftDist() - 1; }
  647. bool atBlockEnd() const { return cursor().atBlockEnd(); }
  648. bool atEndOfLine() const { return atBlockEnd() && block().length() > 1; }
  649. int lastPositionInDocument() const; // Returns last valid position in doc.
  650. int firstPositionInLine(int line) const; // 1 based line, 0 based pos
  651. int lastPositionInLine(int line) const; // 1 based line, 0 based pos
  652. int lineForPosition(int pos) const; // 1 based line, 0 based pos
  653. QString lineContents(int line) const; // 1 based line
  654. void setLineContents(int line, const QString &contents); // 1 based line
  655. int linesOnScreen() const;
  656. int columnsOnScreen() const;
  657. int linesInDocument() const;
  658. // The following use all zero-based counting.
  659. int cursorLineOnScreen() const;
  660. int cursorLine() const;
  661. int physicalCursorColumn() const; // as stored in the data
  662. int logicalCursorColumn() const; // as visible on screen
  663. int physicalToLogicalColumn(int physical, const QString &text) const;
  664. int logicalToPhysicalColumn(int logical, const QString &text) const;
  665. Column cursorColumn() const; // as visible on screen
  666. int firstVisibleLine() const;
  667. void scrollToLine(int line);
  668. void scrollUp(int count);
  669. void scrollDown(int count) { scrollUp(-count); }
  670. CursorPosition cursorPosition() const
  671. { return CursorPosition(position(), firstVisibleLine()); }
  672. void setCursorPosition(const CursorPosition &p)
  673. { setPosition(p.position); scrollToLine(p.scrollLine); }
  674. // Helper functions for indenting/
  675. bool isElectricCharacter(QChar c) const;
  676. void indentSelectedText(QChar lastTyped = QChar());
  677. void indentText(const Range &range, QChar lastTyped = QChar());
  678. void shiftRegionLeft(int repeat = 1);
  679. void shiftRegionRight(int repeat = 1);
  680. void moveToFirstNonBlankOnLine();
  681. void moveToTargetColumn();
  682. void setTargetColumn() {
  683. m_targetColumn = logicalCursorColumn();
  684. m_visualTargetColumn = m_targetColumn;
  685. //qDebug() << "TARGET: " << m_targetColumn;
  686. }
  687. void moveToNextWord(bool simple, bool deleteWord = false);
  688. void moveToMatchingParanthesis();
  689. void moveToWordBoundary(bool simple, bool forward, bool changeWord = false);
  690. // Convenience wrappers to reduce line noise.
  691. void moveToStartOfLine();
  692. void moveToEndOfLine();
  693. void moveBehindEndOfLine();
  694. void moveUp(int n = 1) { moveDown(-n); }
  695. void moveDown(int n = 1);
  696. void dump(const char *msg) const {
  697. qDebug() << msg << "POS: " << anchor() << position()
  698. << "EXT: " << m_oldExternalAnchor << m_oldExternalPosition
  699. << "INT: " << m_oldInternalAnchor << m_oldInternalPosition
  700. << "VISUAL: " << m_visualMode;
  701. }
  702. void moveRight(int n = 1) {
  703. //dump("RIGHT 1");
  704. QTextCursor tc = cursor();
  705. tc.movePosition(Right, KeepAnchor, n);
  706. setCursor(tc);
  707. //dump("RIGHT 2");
  708. }
  709. void moveLeft(int n = 1) {
  710. QTextCursor tc = cursor();
  711. tc.movePosition(Left, KeepAnchor, n);
  712. setCursor(tc);
  713. }
  714. void setAnchor() {
  715. QTextCursor tc = cursor();
  716. tc.setPosition(tc.position(), MoveAnchor);
  717. setCursor(tc);
  718. }
  719. void setAnchor(int position) {
  720. QTextCursor tc = cursor();
  721. tc.setPosition(tc.anchor(), MoveAnchor);
  722. tc.setPosition(position, KeepAnchor);
  723. setCursor(tc);
  724. }
  725. void setPosition(int position) {
  726. QTextCursor tc = cursor();
  727. tc.setPosition(position, KeepAnchor);
  728. setCursor(tc);
  729. }
  730. void setAnchorAndPosition(int anchor, int position) {
  731. QTextCursor tc = cursor();
  732. tc.setPosition(anchor, MoveAnchor);
  733. tc.setPosition(position, KeepAnchor);
  734. setCursor(tc);
  735. }
  736. QTextCursor cursor() const { return EDITOR(textCursor()); }
  737. void setCursor(const QTextCursor &tc) { EDITOR(setTextCursor(tc)); }
  738. bool handleFfTt(QString key);
  739. // Helper function for handleExCommand returning 1 based line index.
  740. int readLineCode(QString &cmd);
  741. void enterInsertMode();
  742. void enterReplaceMode();
  743. void enterCommandMode();
  744. void enterExMode();
  745. void showRedMessage(const QString &msg);
  746. void showBlackMessage(const QString &msg);
  747. void notImplementedYet();
  748. void updateMiniBuffer();
  749. void updateSelection();
  750. void updateCursorShape();
  751. QWidget *editor() const;
  752. QTextDocument *document() const { return EDITOR(document()); }
  753. QChar characterAtCursor() const
  754. { return document()->characterAt(position()); }
  755. void beginEditBlock()
  756. { UNDO_DEBUG("BEGIN EDIT BLOCK"); cursor().beginEditBlock(); }
  757. void endEditBlock()
  758. { UNDO_DEBUG("END EDIT BLOCK"); cursor().endEditBlock(); }
  759. void joinPreviousEditBlock()
  760. { UNDO_DEBUG("JOIN"); cursor().joinPreviousEditBlock(); }
  761. void breakEditBlock() {
  762. QTextCursor tc = cursor();
  763. tc.clearSelection();
  764. tc.beginEditBlock();
  765. tc.insertText("x");
  766. tc.deletePreviousChar();
  767. tc.endEditBlock();
  768. setCursor(tc);
  769. }
  770. bool isVisualMode() const { return m_visualMode != NoVisualMode; }
  771. bool isNoVisualMode() const { return m_visualMode == NoVisualMode; }
  772. bool isVisualCharMode() const { return m_visualMode == VisualCharMode; }
  773. bool isVisualLineMode() const { return m_visualMode == VisualLineMode; }
  774. bool isVisualBlockMode() const { return m_visualMode == VisualBlockMode; }
  775. void updateEditor();
  776. void selectWordTextObject(bool inner);
  777. void selectWORDTextObject(bool inner);
  778. void selectSentenceTextObject(bool inner);
  779. void selectParagraphTextObject(bool inner);
  780. void selectBlockTextObject(bool inner, char left, char right);
  781. void changeNumberTextObject(bool doIncrement);
  782. void selectQuotedStringTextObject(bool inner, int type);
  783. Q_SLOT void importSelection();
  784. void exportSelection();
  785. void insertInInsertMode(const QString &text);
  786. public:
  787. QTextEdit *m_textedit;
  788. QPlainTextEdit *m_plaintextedit;
  789. bool m_wasReadOnly; // saves read-only state of document
  790. FakeVimHandler *q;
  791. Mode m_mode;
  792. bool m_passing; // let the core see the next event
  793. bool m_firstKeyPending;
  794. SubMode m_submode;
  795. SubSubMode m_subsubmode;
  796. Input m_subsubdata;
  797. int m_oldExternalPosition; // copy from last event to check for external changes
  798. int m_oldExternalAnchor;
  799. int m_oldInternalPosition; // copy from last event to check for external changes
  800. int m_oldInternalAnchor;
  801. int m_oldPosition; // FIXME: Merge with above.
  802. int m_register;
  803. QString m_mvcount;
  804. QString m_opcount;
  805. MoveType m_movetype;
  806. RangeMode m_rangemode;
  807. int m_visualInsertCount;
  808. bool m_fakeEnd;
  809. bool m_anchorPastEnd;
  810. bool m_positionPastEnd; // '$' & 'l' in visual mode can move past eol
  811. int m_gflag; // whether current command started with 'g'
  812. QString m_commandPrefix;
  813. CommandBuffer m_commandBuffer;
  814. QString m_currentFileName;
  815. QString m_currentMessage;
  816. bool m_lastSearchForward;
  817. bool m_findPending;
  818. int m_findStartPosition;
  819. QString m_lastInsertion;
  820. QString m_lastDeletion;
  821. int anchor() const { return cursor().anchor(); }
  822. int position() const { return cursor().position(); }
  823. struct TransformationData
  824. {
  825. TransformationData(const QString &s, const QVariant &d)
  826. : from(s), extraData(d) {}
  827. QString from;
  828. QString to;
  829. QVariant extraData;
  830. };
  831. typedef void (Private::*Transformation)(TransformationData *td);
  832. void transformText(const Range &range, Transformation transformation,
  833. const QVariant &extraData = QVariant());
  834. void insertText(const Register &reg);
  835. void removeText(const Range &range);
  836. void removeTransform(TransformationData *td);
  837. void invertCase(const Range &range);
  838. void invertCaseTransform(TransformationData *td);
  839. void upCase(const Range &range);
  840. void upCaseTransform(TransformationData *td);
  841. void downCase(const Range &range);
  842. void downCaseTransform(TransformationData *td);
  843. void replaceText(const Range &range, const QString &str);
  844. void replaceByStringTransform(TransformationData *td);
  845. void replaceByCharTransform(TransformationData *td);
  846. QString selectText(const Range &range) const;
  847. void setCurrentRange(const Range &range);
  848. Range currentRange() const { return Range(position(), anchor(), m_rangemode); }
  849. Range rangeFromCurrentLine() const;
  850. void yankText(const Range &range, int toregister = '"');
  851. void pasteText(bool afterCursor);
  852. // undo handling
  853. void undo();
  854. void redo();
  855. void setUndoPosition();
  856. QMap<int, int> m_undoCursorPosition; // revision -> position
  857. // extra data for '.'
  858. void replay(const QString &text, int count);
  859. void setDotCommand(const QString &cmd) { g.dotCommand = cmd; }
  860. void setDotCommand(const QString &cmd, int n) { g.dotCommand = cmd.arg(n); }
  861. // extra data for ';'
  862. QString m_semicolonCount;
  863. Input m_semicolonType; // 'f', 'F', 't', 'T'
  864. QString m_semicolonKey;
  865. // visual modes
  866. void toggleVisualMode(VisualMode visualMode);
  867. void leaveVisualMode();
  868. VisualMode m_visualMode;
  869. VisualMode m_oldVisualMode;
  870. // marks as lines
  871. int mark(int code) const;
  872. void setMark(int code, int position);
  873. typedef QHash<int, QTextCursor> Marks;
  874. typedef QHashIterator<int, QTextCursor> MarksIterator;
  875. Marks m_marks;
  876. // vi style configuration
  877. QVariant config(int code) const { return theFakeVimSetting(code)->value(); }
  878. bool hasConfig(int code) const { return config(code).toBool(); }
  879. bool hasConfig(int code, const char *value) const // FIXME
  880. { return config(code).toString().contains(value); }
  881. int m_targetColumn; // -1 if past end of line
  882. int m_visualTargetColumn; // 'l' can move past eol in visual mode only
  883. // auto-indent
  884. QString tabExpand(int len) const;
  885. Column indentation(const QString &line) const;
  886. void insertAutomaticIndentation(bool goingDown);
  887. bool removeAutomaticIndentation(); // true if something removed
  888. // number of autoindented characters
  889. int m_justAutoIndented;
  890. void handleStartOfLine();
  891. // register handling
  892. QString registerContents(int reg) const;
  893. void setRegisterContents(int reg, const QString &contents);
  894. RangeMode registerRangeMode(int reg) const;
  895. void setRegisterRangeMode(int reg, RangeMode mode);
  896. void recordJump();
  897. QVector<CursorPosition> m_jumpListUndo;
  898. QVector<CursorPosition> m_jumpListRedo;
  899. int m_lastChangePosition;
  900. QList<QTextEdit::ExtraSelection> m_searchSelections;
  901. QTextCursor m_searchCursor;
  902. QString m_oldNeedle;
  903. QString m_lastSubstituteFlags;
  904. QRegExp m_lastSubstitutePattern;
  905. QString m_lastSubstituteReplacement;
  906. bool handleExCommandHelper(const ExCommand &cmd); // Returns success.
  907. bool handleExPluginCommand(const ExCommand &cmd); // Handled by plugin?
  908. bool handleExBangCommand(const ExCommand &cmd);
  909. bool handleExDeleteCommand(const ExCommand &cmd);
  910. bool handleExGotoCommand(const ExCommand &cmd);
  911. bool handleExHistoryCommand(const ExCommand &cmd);
  912. bool handleExRegisterCommand(const ExCommand &cmd);
  913. bool handleExMapCommand(const ExCommand &cmd);
  914. bool handleExNohlsearchCommand(const ExCommand &cmd);
  915. bool handleExNormalCommand(const ExCommand &cmd);
  916. bool handleExReadCommand(const ExCommand &cmd);
  917. bool handleExRedoCommand(const ExCommand &cmd);
  918. bool handleExSetCommand(const ExCommand &cmd);
  919. bool handleExShiftCommand(const ExCommand &cmd);
  920. bool handleExSourceCommand(const ExCommand &cmd);
  921. bool handleExSubstituteCommand(const ExCommand &cmd);
  922. bool handleExWriteCommand(const ExCommand &cmd);
  923. bool handleExEchoCommand(const ExCommand &cmd);
  924. void timerEvent(QTimerEvent *ev);
  925. void setupCharClass();
  926. int charClass(QChar c, bool simple) const;
  927. signed char m_charClass[256];
  928. bool m_ctrlVActive;
  929. static struct GlobalData
  930. {
  931. GlobalData()
  932. {
  933. inputTimer = -1;
  934. }
  935. // Input.
  936. Inputs pendingInput;
  937. int inputTimer;
  938. // Repetition.
  939. QString dotCommand;
  940. // History for searches.
  941. History searchHistory;
  942. // History for :ex commands.
  943. History commandHistory;
  944. QHash<int, Register> registers;
  945. // All mappings.
  946. typedef QHash<char, ModeMapping> Mappings;
  947. Mappings mappings;
  948. } g;
  949. };
  950. FakeVimHandler::Private::GlobalData FakeVimHandler::Private::g;
  951. FakeVimHandler::Private::Private(FakeVimHandler *parent, QWidget *widget)
  952. {
  953. //static PythonHighlighterRules pythonRules;
  954. q = parent;
  955. m_textedit = qobject_cast<QTextEdit *>(widget);
  956. m_plaintextedit = qobject_cast<QPlainTextEdit *>(widget);
  957. //new Highlighter(document(), &pythonRules);
  958. init();
  959. }
  960. void FakeVimHandler::Private::init()
  961. {
  962. m_mode = CommandMode;
  963. m_submode = NoSubMode;
  964. m_subsubmode = NoSubSubMode;
  965. m_passing = false;
  966. m_firstKeyPending = false;
  967. m_findPending = false;
  968. m_findStartPosition = -1;
  969. m_fakeEnd = false;
  970. m_positionPastEnd = false;
  971. m_anchorPastEnd = false;
  972. m_lastSearchForward = true;
  973. m_register = '"';
  974. m_gflag = false;
  975. m_visualMode = NoVisualMode;
  976. m_oldVisualMode = NoVisualMode;
  977. m_targetColumn = 0;
  978. m_visualTargetColumn = 0;
  979. m_movetype = MoveInclusive;
  980. m_justAutoIndented = 0;
  981. m_rangemode = RangeCharMode;
  982. m_ctrlVActive = false;
  983. m_oldInternalAnchor = -1;
  984. m_oldInternalPosition = -1;
  985. m_oldExternalAnchor = -1;
  986. m_oldExternalPosition = -1;
  987. m_oldPosition = -1;
  988. m_lastChangePosition = -1;
  989. setupCharClass();
  990. }
  991. bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
  992. {
  993. const int key = ev->key();
  994. const int mods = ev->modifiers();
  995. KEY_DEBUG("SHORTCUT OVERRIDE" << key << " PASSING: " << m_passing);
  996. if (key == Key_Escape) {
  997. if (m_subsubmode == SearchSubSubMode)
  998. return true;
  999. // Not sure this feels good. People often hit Esc several times.
  1000. if (isNoVisualMode()
  1001. && m_mode == CommandMode
  1002. && m_submode == NoSubMode
  1003. && m_opcount.isEmpty()
  1004. && m_mvcount.isEmpty())
  1005. return false;
  1006. return true;
  1007. }
  1008. // We are interested in overriding most Ctrl key combinations.
  1009. if (mods == RealControlModifier
  1010. && !config(ConfigPassControlKey).toBool()
  1011. && ((key >= Key_A && key <= Key_Z && key != Key_K)
  1012. || key == Key_BracketLeft || key == Key_BracketRight)) {
  1013. // Ctrl-K is special as it is the Core's default notion of Locator
  1014. if (m_passing) {
  1015. KEY_DEBUG(" PASSING CTRL KEY");
  1016. // We get called twice on the same key
  1017. //m_passing = false;
  1018. return false;
  1019. }
  1020. KEY_DEBUG(" NOT PASSING CTRL KEY");
  1021. //updateMiniBuffer();
  1022. return true;
  1023. }
  1024. // Let other shortcuts trigger.
  1025. return false;
  1026. }
  1027. EventResult FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
  1028. {
  1029. const int key = ev->key();
  1030. const int mods = ev->modifiers();
  1031. if (key == Key_Shift || key == Key_Alt || key == Key_Control
  1032. || key == Key_Alt || key == Key_AltGr || key == Key_Meta)
  1033. {
  1034. KEY_DEBUG("PLAIN MODIFIER");
  1035. return EventUnhandled;
  1036. }
  1037. if (m_passing) {
  1038. passShortcuts(false);
  1039. KEY_DEBUG("PASSING PLAIN KEY..." << ev->key() << ev->text());
  1040. //if (input.is(',')) { // use ',,' to leave, too.
  1041. // qDebug() << "FINISHED...";
  1042. // return EventHandled;
  1043. //}
  1044. m_passing = false;
  1045. updateMiniBuffer();
  1046. KEY_DEBUG(" PASS TO CORE");
  1047. return EventPassedToCore;
  1048. }
  1049. bool inSnippetMode = false;
  1050. QMetaObject::invokeMethod(editor(),
  1051. "inSnippetMode", Q_ARG(bool *, &inSnippetMode));
  1052. if (inSnippetMode)
  1053. return EventPassedToCore;
  1054. // Fake "End of line"
  1055. //m_tc = cursor();
  1056. //bool hasBlock = false;
  1057. //emit q->requestHasBlockSelection(&hasBlock);
  1058. //qDebug() << "IMPORT BLOCK 2:" << hasBlock;
  1059. //if (0 && hasBlock) {
  1060. // (pos > anc) ? --pos : --anc;
  1061. importSelection();
  1062. // Position changed externally, e.g. by code completion.
  1063. if (position() != m_oldPosition) {
  1064. setTargetColumn();
  1065. //qDebug() << "POSITION CHANGED EXTERNALLY";
  1066. if (m_mode == InsertMode) {
  1067. int dist = position() - m_oldPosition;
  1068. // Try to compensate for code completion
  1069. if (dist > 0 && dist <= physicalCursorColumn()) {
  1070. Range range(m_oldPosition, position());
  1071. m_lastInsertion.append(selectText(range));
  1072. }
  1073. } else if (!isVisualMode()) {
  1074. if (atEndOfLine())
  1075. moveLeft();
  1076. }
  1077. }
  1078. QTextCursor tc = cursor();
  1079. tc.setVisualNavigation(true);
  1080. setCursor(tc);
  1081. if (m_firstKeyPending) {
  1082. m_firstKeyPending = false;
  1083. recordJump();
  1084. }
  1085. if (m_fakeEnd)
  1086. moveRight();
  1087. //if ((mods & RealControlModifier) != 0) {
  1088. // if (key >= Key_A && key <= Key_Z)
  1089. // key = shift(key); // make it lower case
  1090. // key = control(key);
  1091. //} else if (key >= Key_A && key <= Key_Z && (mods & Qt::ShiftModifier) == 0) {
  1092. // key = shift(key);
  1093. //}
  1094. //QTC_ASSERT(m_mode == InsertMode || m_mode == ReplaceMode
  1095. // || !atBlockEnd() || block().length() <= 1,
  1096. // qDebug() << "Cursor at EOL before key handler");
  1097. EventResult result = handleKey(Input(key, mods, ev->text()));
  1098. // The command might have destroyed the editor.
  1099. if (m_textedit || m_plaintextedit) {
  1100. // We fake vi-style end-of-line behaviour
  1101. m_fakeEnd = atEndOfLine() && m_mode == CommandMode && !isVisualBlockMode();
  1102. //QTC_ASSERT(m_mode == InsertMode || m_mode == ReplaceMode
  1103. // || !atBlockEnd() || block().length() <= 1,
  1104. // qDebug() << "Cursor at EOL after key handler");
  1105. if (m_fakeEnd)
  1106. moveLeft();
  1107. m_oldPosition = position();
  1108. if (hasConfig(ConfigShowMarks))
  1109. updateSelection();
  1110. exportSelection();
  1111. updateCursorShape();
  1112. }
  1113. return result;
  1114. }
  1115. void FakeVimHandler::Private::installEventFilter()
  1116. {
  1117. EDITOR(viewport()->installEventFilter(q));
  1118. EDITOR(installEventFilter(q));
  1119. }
  1120. void FakeVimHandler::Private::setupWidget()
  1121. {
  1122. enterCommandMode();
  1123. if (m_textedit) {
  1124. m_textedit->setLineWrapMode(QTextEdit::NoWrap);
  1125. } else if (m_plaintextedit) {
  1126. m_plaintextedit->setLineWrapMode(QPlainTextEdit::NoWrap);
  1127. }
  1128. m_wasReadOnly = EDITOR(isReadOnly());
  1129. m_firstKeyPending = true;
  1130. updateEditor();
  1131. importSelection();
  1132. updateMiniBuffer();
  1133. updateCursorShape();
  1134. }
  1135. void FakeVimHandler::Private::exportSelection()
  1136. {
  1137. int pos = position();
  1138. int anc = anchor();
  1139. m_oldInternalPosition = pos;
  1140. m_oldInternalAnchor = anc;
  1141. if (isVisualMode()) {
  1142. if (pos >= anc)
  1143. setAnchorAndPosition(anc, pos + 1);
  1144. else
  1145. setAnchorAndPosition(anc + 1, pos);
  1146. if (m_visualMode == VisualBlockMode) {
  1147. emit q->requestSetBlockSelection(false);
  1148. emit q->requestSetBlockSelection(true);
  1149. } else if (m_visualMode == VisualLineMode) {
  1150. const int posLine = lineForPosition(pos);
  1151. const int ancLine = lineForPosition(anc);
  1152. if (anc < pos) {
  1153. pos = lastPositionInLine(posLine);
  1154. anc = firstPositionInLine(ancLine);
  1155. } else {
  1156. pos = firstPositionInLine(posLine);
  1157. anc = lastPositionInLine(ancLine);
  1158. }
  1159. setAnchorAndPosition(anc, pos);
  1160. } else if (m_visualMode == VisualCharMode) {
  1161. /* Nothing */
  1162. } else {
  1163. QTC_CHECK(false);
  1164. }
  1165. } else {
  1166. setAnchorAndPosition(pos, pos);
  1167. }
  1168. m_oldExternalPosition = position();
  1169. m_oldExternalAnchor = anchor();
  1170. m_oldVisualMode = m_visualMode;
  1171. }
  1172. void FakeVimHandler::Private::importSelection()
  1173. {
  1174. bool hasBlock = false;
  1175. emit q->requestHasBlockSelection(&hasBlock);
  1176. if (position() == m_oldExternalPosition
  1177. && anchor() == m_oldExternalAnchor) {
  1178. // Undo drawing correction.
  1179. m_visualMode = m_oldVisualMode;
  1180. setAnchorAndPosition(m_oldInternalAnchor, m_oldInternalPosition);
  1181. //setMark('<', m_oldInternalAnchor);
  1182. //setMark('>', m_oldInternalPosition);
  1183. } else {
  1184. // Import new selection.
  1185. Qt::KeyboardModifiers mods = QApplication::keyboardModifiers();
  1186. if (cursor().hasSelection()) {
  1187. if (mods & RealControlModifier)
  1188. m_visualMode = VisualBlockMode;
  1189. else if (mods & Qt::AltModifier)
  1190. m_visualMode = VisualBlockMode;
  1191. else if (mods & Qt::ShiftModifier)
  1192. m_visualMode = VisualLineMode;
  1193. else
  1194. m_visualMode = VisualCharMode;
  1195. } else {
  1196. m_visualMode = NoVisualMode;
  1197. }
  1198. //dump("IS @");
  1199. //setMark('<', tc.anchor());
  1200. //setMark('>', tc.position());
  1201. }
  1202. }
  1203. void FakeVimHandler::Private::updateEditor()
  1204. {
  1205. const int charWidth = QFontMetrics(EDITOR(font())).width(QChar(' '));
  1206. EDITOR(setTabStopWidth(charWidth * config(ConfigTabStop).toInt()));
  1207. setupCharClass();
  1208. }
  1209. void FakeVimHandler::Private::restoreWidget(int tabSize)
  1210. {
  1211. //showBlackMessage(QString());
  1212. //updateMiniBuffer();
  1213. //EDITOR(removeEventFilter(q));
  1214. //EDITOR(setReadOnly(m_wasReadOnly));
  1215. const int charWidth = QFontMetrics(EDITOR(font())).width(QChar(' '));
  1216. EDITOR(setTabStopWidth(charWidth * tabSize));
  1217. m_visualMode = NoVisualMode;
  1218. // Force "ordinary" cursor.
  1219. m_mode = InsertMode;
  1220. m_submode = NoSubMode;
  1221. m_subsubmode = NoSubSubMode;
  1222. updateCursorShape();
  1223. updateSelection();
  1224. }
  1225. EventResult FakeVimHandler::Private::handleKey(const Input &input)
  1226. {
  1227. KEY_DEBUG("HANDLE INPUT: " << input << " MODE: " << mode);
  1228. if (m_mode == ExMode)
  1229. return handleExMode(input);
  1230. if (m_subsubmode == SearchSubSubMode)
  1231. return handleSearchSubSubMode(input);
  1232. if (m_mode == InsertMode || m_mode == ReplaceMode || m_mode == CommandMode) {
  1233. g.pendingInput.append(input);
  1234. const char code = m_mode == InsertMode ? 'i' : 'n';
  1235. if (g.mappings.value(code).mappingDone(&g.pendingInput))
  1236. return handleKey2();
  1237. if (g.inputTimer != -1)
  1238. killTimer(g.inputTimer);
  1239. g.inputTimer = startTimer(1000);
  1240. return EventHandled;
  1241. }
  1242. return EventUnhandled;
  1243. }
  1244. EventResult FakeVimHandler::Private::handleKey2()
  1245. {
  1246. Inputs pendingInput = g.pendingInput;
  1247. g.pendingInput.clear();
  1248. if (m_mode == InsertMode) {
  1249. EventResult result = EventUnhandled;
  1250. foreach (const Input &in, pendingInput) {
  1251. EventResult r = handleInsertMode(in);
  1252. if (r == EventHandled)
  1253. result = EventHandled;
  1254. }
  1255. return result;
  1256. }
  1257. if (m_mode == ReplaceMode) {
  1258. EventResult result = EventUnhandled;
  1259. foreach (const Input &in, pendingInput) {
  1260. EventResult r = handleReplaceMode(in);
  1261. if (r == EventHandled)
  1262. result = EventHandled;
  1263. }
  1264. return result;
  1265. }
  1266. if (m_mode == CommandMode) {
  1267. EventResult result = EventUnhandled;
  1268. foreach (const Input &in, pendingInput) {
  1269. EventResult r = handleCommandMode(in);
  1270. if (r == EventHandled)
  1271. result = EventHandled;
  1272. }
  1273. return result;
  1274. }
  1275. return EventUnhandled;
  1276. }
  1277. void FakeVimHandler::Private::timerEvent(QTimerEvent *ev)
  1278. {
  1279. Q_UNUSED(ev);
  1280. handleKey2();
  1281. }
  1282. void FakeVimHandler::Private::stopIncrementalFind()
  1283. {
  1284. if (m_findPending) {
  1285. m_findPending = false;
  1286. QTextCursor tc = cursor();
  1287. setAnchorAndPosition(m_findStartPosition, tc.selectionStart());
  1288. finishMovement();
  1289. setAnchor();
  1290. }
  1291. }
  1292. void FakeVimHandler::Private::setUndoPosition()
  1293. {
  1294. int pos = qMin(position(), anchor());
  1295. if (m_visualMode == VisualLineMode)
  1296. pos = firstPositionInLine(lineForPosition(pos));
  1297. const int rev = document()->availableUndoSteps();
  1298. m_undoCursorPosition[rev] = pos;
  1299. }
  1300. void FakeVimHandler::Private::moveDown(int n)
  1301. {
  1302. #if 0
  1303. // does not work for "hidden" documents like in the autotests
  1304. tc.movePosition(Down, MoveAnchor, n);
  1305. #else
  1306. const int col = position() - block().position();
  1307. const int lastLine = document()->lastBlock().blockNumber();
  1308. const int targetLine = qMax(0, qMin(lastLine, block().blockNumber() + n));
  1309. const QTextBlock &block = document()->findBlockByNumber(targetLine);
  1310. const int pos = block.position();
  1311. setPosition(pos + qMax(0, qMin(block.length() - 2, col)));
  1312. moveToTargetColumn();
  1313. #endif
  1314. }
  1315. void FakeVimHandler::Private::moveToEndOfLine()
  1316. {
  1317. #if 0
  1318. // does not work for "hidden" documents like in the autotests
  1319. tc.movePosition(EndOfLine, MoveAnchor);
  1320. #else
  1321. const int pos = block().position() + block().length() - 2;
  1322. setPosition(qMax(block().position(), pos));
  1323. #endif
  1324. }
  1325. void FakeVimHandler::Private::moveBehindEndOfLine()
  1326. {
  1327. int pos = qMin(block().position() + block().length() - 1,
  1328. lastPositionInDocument());
  1329. setPosition(pos);
  1330. }
  1331. void FakeVimHandler::Private::moveToStartOfLine()
  1332. {
  1333. #if 0
  1334. // does not work for "hidden" documents like in the autotests
  1335. tc.movePosition(StartOfLine, MoveAnchor);
  1336. #else
  1337. setPosition(block().position());
  1338. #endif
  1339. }
  1340. void FakeVimHandler::Private::finishMovement(const QString &dotCommand, int count)
  1341. {
  1342. finishMovement(dotCommand.arg(count));
  1343. }
  1344. void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
  1345. {
  1346. //dump("FINISH MOVEMENT");
  1347. if (m_submode == FilterSubMode) {
  1348. int beginLine = lineForPosition(anchor());
  1349. int endLine = lineForPosition(position());
  1350. setPosition(qMin(anchor(), position()));
  1351. enterExMode();
  1352. m_currentMessage.clear();
  1353. m_commandBuffer.setContents(QString(".,+%1!").arg(qAbs(endLine - beginLine)));
  1354. //g.commandHistory.append(QString());
  1355. updateMiniBuffer();
  1356. return;
  1357. }
  1358. //if (isVisualMode())
  1359. // setMark('>', position());
  1360. if (m_submode == ChangeSubMode
  1361. || m_submode == DeleteSubMode
  1362. || m_submode == YankSubMode
  1363. || m_submode == TransformSubMode) {
  1364. if (m_submode != YankSubMode)
  1365. beginEditBlock();
  1366. if (m_movetype == MoveLineWise)
  1367. m_rangemode = (m_submode == ChangeSubMode)
  1368. ? RangeLineModeExclusive
  1369. : RangeLineMode;
  1370. if (m_movetype == MoveInclusive) {
  1371. if (anchor() <= position()) {
  1372. if (!cursor().atBlockEnd())
  1373. setPosition(position() + 1); // correction
  1374. } else {
  1375. setAnchorAndPosition(anchor() + 1, position());
  1376. }
  1377. }
  1378. if (m_positionPastEnd) {
  1379. const int anc = anchor();
  1380. moveBehindEndOfLine();
  1381. moveRight();
  1382. setAnchorAndPosition(anc, position());
  1383. }
  1384. if (m_anchorPastEnd) {
  1385. setAnchorAndPosition(anchor() + 1, position());
  1386. }
  1387. if (m_submode != TransformSubMode) {
  1388. yankText(currentRange(), m_register);
  1389. if (m_movetype == MoveLineWise)
  1390. setRegisterRangeMode(m_register, RangeLineMode);
  1391. }
  1392. m_positionPastEnd = m_anchorPastEnd = false;
  1393. }
  1394. if (m_submode == ChangeSubMode) {
  1395. if (m_rangemode == RangeLineMode)
  1396. m_rangemode = RangeLineModeExclusive;
  1397. removeText(currentRange());
  1398. if (!dotCommand.isEmpty())
  1399. setDotCommand(QLatin1Char('c') + dotCommand);
  1400. if (m_movetype == MoveLineWise)
  1401. insertAutomaticIndentation(true);
  1402. endEditBlock();
  1403. enterInsertMode();
  1404. m_submode = NoSubMode;
  1405. } else if (m_submode == DeleteSubMode) {
  1406. removeText(currentRange());
  1407. if (!dotCommand.isEmpty())
  1408. setDotCommand(QLatin1Char('d') + dotCommand);
  1409. if (m_movetype == MoveLineWise)
  1410. handleStartOfLine();
  1411. m_submode = NoSubMode;
  1412. if (atEndOfLine())
  1413. moveLeft();
  1414. else
  1415. setTargetColumn();
  1416. endEditBlock();
  1417. } else if (m_submode == YankSubMode) {
  1418. m_submode = NoSubMode;
  1419. const int la = lineForPosition(anchor());
  1420. const int lp = lineForPosition(position());
  1421. if (m_register != '"') {
  1422. set

Large files files are truncated, but you can click here to view the full file