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

/src/plugins/fakevim/fakevimhandler.cpp

https://bitbucket.org/kpozn/qtcreator
C++ | 5170 lines | 4487 code | 352 blank | 331 comment | 1237 complexity | 037e0e1e9718f5e62091d284438a0b25 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-3.0
  1. /**************************************************************************
  2. **
  3. ** This file is part of Qt Creator
  4. **
  5. ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
  6. **
  7. ** Contact: Nokia Corporation (info@qt.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 info@qt.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 <QtCore/QDebug>
  64. #include <QtCore/QFile>
  65. #include <QtCore/QObject>
  66. #include <QtCore/QPointer>
  67. #include <QtCore/QProcess>
  68. #include <QtCore/QRegExp>
  69. #include <QtCore/QTextStream>
  70. #include <QtCore/QTimer>
  71. #include <QtCore/QtAlgorithms>
  72. #include <QtCore/QStack>
  73. #include <QtGui/QApplication>
  74. #include <QtGui/QInputMethodEvent>
  75. #include <QtGui/QKeyEvent>
  76. #include <QtGui/QLineEdit>
  77. #include <QtGui/QPlainTextEdit>
  78. #include <QtGui/QScrollBar>
  79. #include <QtGui/QTextBlock>
  80. #include <QtGui/QTextCursor>
  81. #include <QtGui/QTextDocumentFragment>
  82. #include <QtGui/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_WS_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. QDebug operator<<(QDebug ts, const ExCommand &cmd)
  283. {
  284. return ts << cmd.cmd << ' ' << cmd.args << ' ' << cmd.range;
  285. }
  286. QDebug operator<<(QDebug ts, const QList<QTextEdit::ExtraSelection> &sels)
  287. {
  288. foreach (const QTextEdit::ExtraSelection &sel, sels)
  289. ts << "SEL: " << sel.cursor.anchor() << sel.cursor.position();
  290. return ts;
  291. }
  292. QString quoteUnprintable(const QString &ba)
  293. {
  294. QString res;
  295. for (int i = 0, n = ba.size(); i != n; ++i) {
  296. const QChar c = ba.at(i);
  297. const int cc = c.unicode();
  298. if (c.isPrint())
  299. res += c;
  300. else if (cc == '\n')
  301. res += _("<CR>");
  302. else
  303. res += QString("\\x%1").arg(c.unicode(), 2, 16, QLatin1Char('0'));
  304. }
  305. return res;
  306. }
  307. static bool startsWithWhitespace(const QString &str, int col)
  308. {
  309. QTC_ASSERT(str.size() >= col, return false);
  310. for (int i = 0; i < col; ++i) {
  311. uint u = str.at(i).unicode();
  312. if (u != ' ' && u != '\t')
  313. return false;
  314. }
  315. return true;
  316. }
  317. inline QString msgMarkNotSet(const QString &text)
  318. {
  319. return FakeVimHandler::tr("Mark '%1' not set").arg(text);
  320. }
  321. class Input
  322. {
  323. public:
  324. // Remove some extra "information" on Mac.
  325. static int cleanModifier(int m) { return m & ~Qt::KeypadModifier; }
  326. Input()
  327. : m_key(0), m_xkey(0), m_modifiers(0) {}
  328. explicit Input(QChar x)
  329. : m_key(x.unicode()), m_xkey(x.unicode()), m_modifiers(0), m_text(x) {}
  330. Input(int k, int m, const QString &t)
  331. : m_key(k), m_modifiers(cleanModifier(m)), m_text(t)
  332. {
  333. // On Mac, QKeyEvent::text() returns non-empty strings for
  334. // cursor keys. This breaks some of the logic later on
  335. // relying on text() being empty for "special" keys.
  336. // FIXME: Check the real conditions.
  337. if (m_text.size() == 1 && m_text.at(0).unicode() < ' ')
  338. m_text.clear();
  339. // m_xkey is only a cache.
  340. m_xkey = (m_text.size() == 1 ? m_text.at(0).unicode() : m_key);
  341. }
  342. bool isDigit() const
  343. {
  344. return m_xkey >= '0' && m_xkey <= '9';
  345. }
  346. bool isKey(int c) const
  347. {
  348. return !m_modifiers && m_key == c;
  349. }
  350. bool isBackspace() const
  351. {
  352. return m_key == Key_Backspace || isControl('h');
  353. }
  354. bool isReturn() const
  355. {
  356. return m_key == Key_Return;
  357. }
  358. bool isEscape() const
  359. {
  360. return isKey(Key_Escape) || isKey(27) || isControl('c')
  361. || isControl(Key_BracketLeft);
  362. }
  363. bool is(int c) const
  364. {
  365. return m_xkey == c && m_modifiers != RealControlModifier;
  366. }
  367. bool isControl(int c) const
  368. {
  369. return m_modifiers == RealControlModifier
  370. && (m_xkey == c || m_xkey + 32 == c || m_xkey + 64 == c || m_xkey + 96 == c);
  371. }
  372. bool isShift(int c) const
  373. {
  374. return m_modifiers == Qt::ShiftModifier && m_xkey == c;
  375. }
  376. bool operator==(const Input &a) const
  377. {
  378. return a.m_key == m_key && a.m_modifiers == m_modifiers
  379. && m_text == a.m_text;
  380. }
  381. bool operator!=(const Input &a) const { return !operator==(a); }
  382. QString text() const { return m_text; }
  383. QChar asChar() const
  384. {
  385. return (m_text.size() == 1 ? m_text.at(0) : QChar());
  386. }
  387. int key() const { return m_key; }
  388. QChar raw() const
  389. {
  390. if (m_key == Key_Tab)
  391. return '\t';
  392. if (m_key == Key_Return)
  393. return '\n';
  394. return m_key;
  395. }
  396. QDebug dump(QDebug ts) const
  397. {
  398. return ts << m_key << '-' << m_modifiers << '-'
  399. << quoteUnprintable(m_text);
  400. }
  401. private:
  402. int m_key;
  403. int m_xkey;
  404. int m_modifiers;
  405. QString m_text;
  406. };
  407. QDebug operator<<(QDebug ts, const Input &input) { return input.dump(ts); }
  408. class Inputs : public QVector<Input>
  409. {
  410. public:
  411. Inputs() {}
  412. explicit Inputs(const QString &str) { parseFrom(str); }
  413. void parseFrom(const QString &str);
  414. };
  415. void Inputs::parseFrom(const QString &str)
  416. {
  417. const int n = str.size();
  418. for (int i = 0; i < n; ++i) {
  419. uint c0 = str.at(i).unicode(), c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0;
  420. if (i + 1 < n)
  421. c1 = str.at(i + 1).unicode();
  422. if (i + 2 < n)
  423. c2 = str.at(i + 2).unicode();
  424. if (i + 3 < n)
  425. c3 = str.at(i + 3).unicode();
  426. if (i + 4 < n)
  427. c4 = str.at(i + 4).unicode();
  428. if (i + 5 < n)
  429. c5 = str.at(i + 5).unicode();
  430. if (c0 == '<') {
  431. if ((c1 == 'C' || c1 == 'c') && c2 == '-' && c4 == '>') {
  432. uint c = (c3 < 90 ? c3 : c3 - 32);
  433. append(Input(c, RealControlModifier, QString(QChar(c - 64))));
  434. i += 4;
  435. } else if (c1 == 'C' && c2 == 'R' && c3 == '>') {
  436. append(Input(Key_Return, Qt::NoModifier, QString(QChar(13))));
  437. i += 3;
  438. } else if (c1 == 'E' && c2 == 's' && c3 == 'c' && c4 == '>') {
  439. append(Input(Key_Escape, Qt::NoModifier, QString(QChar(27))));
  440. i += 4;
  441. } else {
  442. append(Input(QLatin1Char(c0)));
  443. }
  444. } else {
  445. append(Input(QLatin1Char(c0)));
  446. }
  447. }
  448. }
  449. // This wraps a string and a "cursor position".
  450. class CommandBuffer
  451. {
  452. public:
  453. CommandBuffer() : m_pos(0) {}
  454. void clear() { m_buffer.clear(); m_pos = 0; }
  455. void setContents(const QString &s) { m_buffer = s; m_pos = s.size(); }
  456. QString contents() const { return m_buffer; }
  457. bool isEmpty() const { return m_buffer.isEmpty(); }
  458. int cursorPos() const { return m_pos; }
  459. void insertChar(QChar c) { m_buffer.insert(m_pos++, c); }
  460. void insertText(const QString &s) { m_buffer.insert(m_pos, s); m_pos += s.size(); }
  461. void deleteChar() { if (m_pos) m_buffer.remove(--m_pos, 1); }
  462. void moveLeft() { if (m_pos) --m_pos; }
  463. void moveRight() { if (m_pos < m_buffer.size()) ++m_pos; }
  464. void moveStart() { m_pos = 0; }
  465. void moveEnd() { m_pos = m_buffer.size(); }
  466. QString display() const
  467. {
  468. QString msg;
  469. for (int i = 0; i != m_buffer.size(); ++i) {
  470. const QChar c = m_buffer.at(i);
  471. if (c.unicode() < 32) {
  472. msg += '^';
  473. msg += QChar(c.unicode() + 64);
  474. } else {
  475. msg += c;
  476. }
  477. }
  478. return msg;
  479. }
  480. bool handleInput(const Input &input)
  481. {
  482. if (input.isKey(Key_Left)) {
  483. moveLeft();
  484. } else if (input.isKey(Key_Right)) {
  485. moveRight();
  486. } else if (input.isKey(Key_Home)) {
  487. moveStart();
  488. } else if (input.isKey(Key_End)) {
  489. moveEnd();
  490. } else if (input.isKey(Key_Delete)) {
  491. if (m_pos < m_buffer.size())
  492. m_buffer.remove(m_pos, 1);
  493. } else if (!input.text().isEmpty()) {
  494. insertText(input.text());
  495. } else {
  496. return false;
  497. }
  498. return true;
  499. }
  500. private:
  501. QString m_buffer;
  502. int m_pos;
  503. };
  504. class History
  505. {
  506. public:
  507. History() : m_index(0) {}
  508. void append(const QString &item);
  509. void down() { m_index = qMin(m_index + 1, m_items.size()); }
  510. void up() { m_index = qMax(m_index - 1, 0); }
  511. void restart() { m_index = m_items.size(); }
  512. QString current() const { return m_items.value(m_index, QString()); }
  513. QStringList items() const { return m_items; }
  514. private:
  515. QStringList m_items;
  516. int m_index;
  517. };
  518. void History::append(const QString &item)
  519. {
  520. if (item.isEmpty())
  521. return;
  522. m_items.removeAll(item);
  523. m_items.append(item); m_index = m_items.size() - 1;
  524. }
  525. // Mappings for a specific mode.
  526. class ModeMapping : public QList<QPair<Inputs, Inputs> >
  527. {
  528. public:
  529. ModeMapping() { test(); }
  530. void test()
  531. {
  532. //insert(Inputs() << Input('A') << Input('A'),
  533. // Inputs() << Input('x') << Input('x'));
  534. }
  535. void insert(const Inputs &from, const Inputs &to)
  536. {
  537. for (int i = 0; i != size(); ++i)
  538. if (at(i).first == from) {
  539. (*this)[i].second = to;
  540. return;
  541. }
  542. append(QPair<Inputs, Inputs>(from, to));
  543. }
  544. void remove(const Inputs &from)
  545. {
  546. for (int i = 0; i != size(); ++i)
  547. if (at(i).first == from) {
  548. removeAt(i);
  549. return;
  550. }
  551. }
  552. // Returns 'false' if more input is needed to decide whether a mapping
  553. // needs to be applied. If a decision can be made, return 'true',
  554. // and replace *input with the mapped data.
  555. bool mappingDone(Inputs *inputs) const
  556. {
  557. // FIXME: inefficient.
  558. for (int i = 0; i != size(); ++i) {
  559. const Inputs &haystack = at(i).first;
  560. // A mapping
  561. if (startsWith(haystack, *inputs)) {
  562. if (haystack.size() != inputs->size())
  563. return false; // This can be extended.
  564. // Actual mapping.
  565. *inputs = at(i).second;
  566. return true;
  567. }
  568. }
  569. // No extensible mapping found. Use inputs as-is.
  570. return true;
  571. }
  572. private:
  573. static bool startsWith(const Inputs &haystack, const Inputs &needle)
  574. {
  575. // Input is already too long.
  576. if (needle.size() > haystack.size())
  577. return false;
  578. for (int i = 0; i != needle.size(); ++i) {
  579. if (needle.at(i) != haystack.at(i))
  580. return false;
  581. }
  582. return true;
  583. }
  584. };
  585. class FakeVimHandler::Private : public QObject
  586. {
  587. Q_OBJECT
  588. public:
  589. Private(FakeVimHandler *parent, QWidget *widget);
  590. EventResult handleEvent(QKeyEvent *ev);
  591. bool wantsOverride(QKeyEvent *ev);
  592. void handleCommand(const QString &cmd); // Sets m_tc + handleExCommand
  593. void handleExCommand(const QString &cmd);
  594. void installEventFilter();
  595. void passShortcuts(bool enable);
  596. void setupWidget();
  597. void restoreWidget(int tabSize);
  598. friend class FakeVimHandler;
  599. void init();
  600. EventResult handleKey(const Input &);
  601. Q_SLOT EventResult handleKey2();
  602. EventResult handleInsertMode(const Input &);
  603. EventResult handleReplaceMode(const Input &);
  604. EventResult handleCommandMode(const Input &);
  605. EventResult handleCommandMode1(const Input &);
  606. EventResult handleCommandMode2(const Input &);
  607. EventResult handleRegisterMode(const Input &);
  608. EventResult handleExMode(const Input &);
  609. EventResult handleOpenSquareSubMode(const Input &);
  610. EventResult handleCloseSquareSubMode(const Input &);
  611. EventResult handleSearchSubSubMode(const Input &);
  612. EventResult handleCommandSubSubMode(const Input &);
  613. void finishMovement(const QString &dotCommand = QString());
  614. void finishMovement(const QString &dotCommand, int count);
  615. void resetCommandMode();
  616. void search(const SearchData &sd);
  617. void searchBalanced(bool forward, QChar needle, QChar other);
  618. void highlightMatches(const QString &needle);
  619. void stopIncrementalFind();
  620. int mvCount() const { return m_mvcount.isEmpty() ? 1 : m_mvcount.toInt(); }
  621. int opCount() const { return m_opcount.isEmpty() ? 1 : m_opcount.toInt(); }
  622. int count() const { return mvCount() * opCount(); }
  623. QTextBlock block() const { return cursor().block(); }
  624. int leftDist() const { return position() - block().position(); }
  625. int rightDist() const { return block().length() - leftDist() - 1; }
  626. bool atBlockEnd() const { return cursor().atBlockEnd(); }
  627. bool atEndOfLine() const { return atBlockEnd() && block().length() > 1; }
  628. int lastPositionInDocument() const; // Returns last valid position in doc.
  629. int firstPositionInLine(int line) const; // 1 based line, 0 based pos
  630. int lastPositionInLine(int line) const; // 1 based line, 0 based pos
  631. int lineForPosition(int pos) const; // 1 based line, 0 based pos
  632. QString lineContents(int line) const; // 1 based line
  633. void setLineContents(int line, const QString &contents); // 1 based line
  634. int linesOnScreen() const;
  635. int columnsOnScreen() const;
  636. int linesInDocument() const;
  637. // The following use all zero-based counting.
  638. int cursorLineOnScreen() const;
  639. int cursorLine() const;
  640. int physicalCursorColumn() const; // as stored in the data
  641. int logicalCursorColumn() const; // as visible on screen
  642. int physicalToLogicalColumn(int physical, const QString &text) const;
  643. int logicalToPhysicalColumn(int logical, const QString &text) const;
  644. Column cursorColumn() const; // as visible on screen
  645. int firstVisibleLine() const;
  646. void scrollToLine(int line);
  647. void scrollUp(int count);
  648. void scrollDown(int count) { scrollUp(-count); }
  649. CursorPosition cursorPosition() const
  650. { return CursorPosition(position(), firstVisibleLine()); }
  651. void setCursorPosition(const CursorPosition &p)
  652. { setPosition(p.position); scrollToLine(p.scrollLine); }
  653. // Helper functions for indenting/
  654. bool isElectricCharacter(QChar c) const;
  655. void indentSelectedText(QChar lastTyped = QChar());
  656. void indentText(const Range &range, QChar lastTyped = QChar());
  657. void shiftRegionLeft(int repeat = 1);
  658. void shiftRegionRight(int repeat = 1);
  659. void moveToFirstNonBlankOnLine();
  660. void moveToTargetColumn();
  661. void setTargetColumn() {
  662. m_targetColumn = logicalCursorColumn();
  663. m_visualTargetColumn = m_targetColumn;
  664. //qDebug() << "TARGET: " << m_targetColumn;
  665. }
  666. void moveToNextWord(bool simple, bool deleteWord = false);
  667. void moveToMatchingParanthesis();
  668. void moveToWordBoundary(bool simple, bool forward, bool changeWord = false);
  669. // Convenience wrappers to reduce line noise.
  670. void moveToStartOfLine();
  671. void moveToEndOfLine();
  672. void moveBehindEndOfLine();
  673. void moveUp(int n = 1) { moveDown(-n); }
  674. void moveDown(int n = 1);
  675. void dump(const char *msg) const {
  676. qDebug() << msg << "POS: " << anchor() << position()
  677. << "EXT: " << m_oldExternalAnchor << m_oldExternalPosition
  678. << "INT: " << m_oldInternalAnchor << m_oldInternalPosition
  679. << "VISUAL: " << m_visualMode;
  680. }
  681. void moveRight(int n = 1) {
  682. //dump("RIGHT 1");
  683. QTextCursor tc = cursor();
  684. tc.movePosition(Right, KeepAnchor, n);
  685. setCursor(tc);
  686. //dump("RIGHT 2");
  687. }
  688. void moveLeft(int n = 1) {
  689. QTextCursor tc = cursor();
  690. tc.movePosition(Left, KeepAnchor, n);
  691. setCursor(tc);
  692. }
  693. void setAnchor() {
  694. QTextCursor tc = cursor();
  695. tc.setPosition(tc.position(), MoveAnchor);
  696. setCursor(tc);
  697. }
  698. void setAnchor(int position) {
  699. QTextCursor tc = cursor();
  700. tc.setPosition(tc.anchor(), MoveAnchor);
  701. tc.setPosition(position, KeepAnchor);
  702. setCursor(tc);
  703. }
  704. void setPosition(int position) {
  705. QTextCursor tc = cursor();
  706. tc.setPosition(position, KeepAnchor);
  707. setCursor(tc);
  708. }
  709. void setAnchorAndPosition(int anchor, int position) {
  710. QTextCursor tc = cursor();
  711. tc.setPosition(anchor, MoveAnchor);
  712. tc.setPosition(position, KeepAnchor);
  713. setCursor(tc);
  714. }
  715. QTextCursor cursor() const { return EDITOR(textCursor()); }
  716. void setCursor(const QTextCursor &tc) { EDITOR(setTextCursor(tc)); }
  717. bool handleFfTt(QString key);
  718. // Helper function for handleExCommand returning 1 based line index.
  719. int readLineCode(QString &cmd);
  720. void enterInsertMode();
  721. void enterReplaceMode();
  722. void enterCommandMode();
  723. void enterExMode();
  724. void showRedMessage(const QString &msg);
  725. void showBlackMessage(const QString &msg);
  726. void notImplementedYet();
  727. void updateMiniBuffer();
  728. void updateSelection();
  729. void updateCursorShape();
  730. QWidget *editor() const;
  731. QTextDocument *document() const { return EDITOR(document()); }
  732. QChar characterAtCursor() const
  733. { return document()->characterAt(position()); }
  734. void beginEditBlock()
  735. { UNDO_DEBUG("BEGIN EDIT BLOCK"); cursor().beginEditBlock(); }
  736. void beginEditBlock(int pos)
  737. { setUndoPosition(pos); cursor().beginEditBlock(); }
  738. void endEditBlock()
  739. { UNDO_DEBUG("END EDIT BLOCK"); cursor().endEditBlock(); }
  740. void joinPreviousEditBlock()
  741. { UNDO_DEBUG("JOIN"); cursor().joinPreviousEditBlock(); }
  742. void breakEditBlock() {
  743. QTextCursor tc = cursor();
  744. tc.clearSelection();
  745. tc.beginEditBlock();
  746. tc.insertText("x");
  747. tc.deletePreviousChar();
  748. tc.endEditBlock();
  749. setCursor(tc);
  750. }
  751. bool isVisualMode() const { return m_visualMode != NoVisualMode; }
  752. bool isNoVisualMode() const { return m_visualMode == NoVisualMode; }
  753. bool isVisualCharMode() const { return m_visualMode == VisualCharMode; }
  754. bool isVisualLineMode() const { return m_visualMode == VisualLineMode; }
  755. bool isVisualBlockMode() const { return m_visualMode == VisualBlockMode; }
  756. void updateEditor();
  757. void selectWordTextObject(bool inner);
  758. void selectWORDTextObject(bool inner);
  759. void selectSentenceTextObject(bool inner);
  760. void selectParagraphTextObject(bool inner);
  761. void selectBlockTextObject(bool inner, char left, char right);
  762. void selectQuotedStringTextObject(bool inner, int type);
  763. Q_SLOT void importSelection();
  764. void exportSelection();
  765. void insertInInsertMode(const QString &text);
  766. public:
  767. QTextEdit *m_textedit;
  768. QPlainTextEdit *m_plaintextedit;
  769. bool m_wasReadOnly; // saves read-only state of document
  770. FakeVimHandler *q;
  771. Mode m_mode;
  772. bool m_passing; // let the core see the next event
  773. SubMode m_submode;
  774. SubSubMode m_subsubmode;
  775. Input m_subsubdata;
  776. int m_oldExternalPosition; // copy from last event to check for external changes
  777. int m_oldExternalAnchor;
  778. int m_oldInternalPosition; // copy from last event to check for external changes
  779. int m_oldInternalAnchor;
  780. int m_oldPosition; // FIXME: Merge with above.
  781. int m_register;
  782. QString m_mvcount;
  783. QString m_opcount;
  784. MoveType m_movetype;
  785. RangeMode m_rangemode;
  786. int m_visualInsertCount;
  787. bool m_fakeEnd;
  788. bool m_anchorPastEnd;
  789. bool m_positionPastEnd; // '$' & 'l' in visual mode can move past eol
  790. int m_gflag; // whether current command started with 'g'
  791. QString m_commandPrefix;
  792. CommandBuffer m_commandBuffer;
  793. QString m_currentFileName;
  794. QString m_currentMessage;
  795. bool m_lastSearchForward;
  796. bool m_findPending;
  797. int m_findStartPosition;
  798. QString m_lastInsertion;
  799. QString m_lastDeletion;
  800. int anchor() const { return cursor().anchor(); }
  801. int position() const { return cursor().position(); }
  802. struct TransformationData
  803. {
  804. TransformationData(const QString &s, const QVariant &d)
  805. : from(s), extraData(d) {}
  806. QString from;
  807. QString to;
  808. QVariant extraData;
  809. };
  810. typedef void (Private::*Transformation)(TransformationData *td);
  811. void transformText(const Range &range, Transformation transformation,
  812. const QVariant &extraData = QVariant());
  813. void insertText(const Register &reg);
  814. void removeText(const Range &range);
  815. void removeTransform(TransformationData *td);
  816. void invertCase(const Range &range);
  817. void invertCaseTransform(TransformationData *td);
  818. void upCase(const Range &range);
  819. void upCaseTransform(TransformationData *td);
  820. void downCase(const Range &range);
  821. void downCaseTransform(TransformationData *td);
  822. void replaceText(const Range &range, const QString &str);
  823. void replaceByStringTransform(TransformationData *td);
  824. void replaceByCharTransform(TransformationData *td);
  825. QString selectText(const Range &range) const;
  826. void setCurrentRange(const Range &range);
  827. Range currentRange() const { return Range(position(), anchor(), m_rangemode); }
  828. Range rangeFromCurrentLine() const;
  829. void yankText(const Range &range, int toregister = '"');
  830. void pasteText(bool afterCursor);
  831. // undo handling
  832. void undo();
  833. void redo();
  834. void setUndoPosition(int pos);
  835. QMap<int, int> m_undoCursorPosition; // revision -> position
  836. // extra data for '.'
  837. void replay(const QString &text, int count);
  838. void setDotCommand(const QString &cmd) { g.dotCommand = cmd; }
  839. void setDotCommand(const QString &cmd, int n) { g.dotCommand = cmd.arg(n); }
  840. // extra data for ';'
  841. QString m_semicolonCount;
  842. Input m_semicolonType; // 'f', 'F', 't', 'T'
  843. QString m_semicolonKey;
  844. // visual modes
  845. void toggleVisualMode(VisualMode visualMode);
  846. void leaveVisualMode();
  847. VisualMode m_visualMode;
  848. VisualMode m_oldVisualMode;
  849. // marks as lines
  850. int mark(int code) const;
  851. void setMark(int code, int position);
  852. typedef QHash<int, QTextCursor> Marks;
  853. typedef QHashIterator<int, QTextCursor> MarksIterator;
  854. Marks m_marks;
  855. // vi style configuration
  856. QVariant config(int code) const { return theFakeVimSetting(code)->value(); }
  857. bool hasConfig(int code) const { return config(code).toBool(); }
  858. bool hasConfig(int code, const char *value) const // FIXME
  859. { return config(code).toString().contains(value); }
  860. int m_targetColumn; // -1 if past end of line
  861. int m_visualTargetColumn; // 'l' can move past eol in visual mode only
  862. // auto-indent
  863. QString tabExpand(int len) const;
  864. Column indentation(const QString &line) const;
  865. void insertAutomaticIndentation(bool goingDown);
  866. bool removeAutomaticIndentation(); // true if something removed
  867. // number of autoindented characters
  868. int m_justAutoIndented;
  869. void handleStartOfLine();
  870. void recordJump();
  871. QVector<CursorPosition> m_jumpListUndo;
  872. QVector<CursorPosition> m_jumpListRedo;
  873. QList<QTextEdit::ExtraSelection> m_searchSelections;
  874. QTextCursor m_searchCursor;
  875. QString m_oldNeedle;
  876. bool handleExCommandHelper(const ExCommand &cmd); // Returns success.
  877. bool handleExPluginCommand(const ExCommand &cmd); // Handled by plugin?
  878. bool handleExBangCommand(const ExCommand &cmd);
  879. bool handleExDeleteCommand(const ExCommand &cmd);
  880. bool handleExGotoCommand(const ExCommand &cmd);
  881. bool handleExHistoryCommand(const ExCommand &cmd);
  882. bool handleExRegisterCommand(const ExCommand &cmd);
  883. bool handleExMapCommand(const ExCommand &cmd);
  884. bool handleExNohlsearchCommand(const ExCommand &cmd);
  885. bool handleExNormalCommand(const ExCommand &cmd);
  886. bool handleExReadCommand(const ExCommand &cmd);
  887. bool handleExRedoCommand(const ExCommand &cmd);
  888. bool handleExSetCommand(const ExCommand &cmd);
  889. bool handleExShiftCommand(const ExCommand &cmd);
  890. bool handleExSourceCommand(const ExCommand &cmd);
  891. bool handleExSubstituteCommand(const ExCommand &cmd);
  892. bool handleExWriteCommand(const ExCommand &cmd);
  893. bool handleExEchoCommand(const ExCommand &cmd);
  894. void timerEvent(QTimerEvent *ev);
  895. void setupCharClass();
  896. int charClass(QChar c, bool simple) const;
  897. signed char m_charClass[256];
  898. bool m_ctrlVActive;
  899. static struct GlobalData
  900. {
  901. GlobalData()
  902. {
  903. inputTimer = -1;
  904. }
  905. // Input.
  906. Inputs pendingInput;
  907. int inputTimer;
  908. // Repetition.
  909. QString dotCommand;
  910. // History for searches.
  911. History searchHistory;
  912. // History for :ex commands.
  913. History commandHistory;
  914. QHash<int, Register> registers;
  915. // All mappings.
  916. typedef QHash<char, ModeMapping> Mappings;
  917. Mappings mappings;
  918. } g;
  919. };
  920. FakeVimHandler::Private::GlobalData FakeVimHandler::Private::g;
  921. FakeVimHandler::Private::Private(FakeVimHandler *parent, QWidget *widget)
  922. {
  923. //static PythonHighlighterRules pythonRules;
  924. q = parent;
  925. m_textedit = qobject_cast<QTextEdit *>(widget);
  926. m_plaintextedit = qobject_cast<QPlainTextEdit *>(widget);
  927. //new Highlighter(document(), &pythonRules);
  928. init();
  929. }
  930. void FakeVimHandler::Private::init()
  931. {
  932. m_mode = CommandMode;
  933. m_submode = NoSubMode;
  934. m_subsubmode = NoSubSubMode;
  935. m_passing = false;
  936. m_findPending = false;
  937. m_findStartPosition = -1;
  938. m_fakeEnd = false;
  939. m_positionPastEnd = false;
  940. m_anchorPastEnd = false;
  941. m_lastSearchForward = true;
  942. m_register = '"';
  943. m_gflag = false;
  944. m_visualMode = NoVisualMode;
  945. m_oldVisualMode = NoVisualMode;
  946. m_targetColumn = 0;
  947. m_visualTargetColumn = 0;
  948. m_movetype = MoveInclusive;
  949. m_justAutoIndented = 0;
  950. m_rangemode = RangeCharMode;
  951. m_ctrlVActive = false;
  952. m_oldInternalAnchor = -1;
  953. m_oldInternalPosition = -1;
  954. m_oldExternalAnchor = -1;
  955. m_oldExternalPosition = -1;
  956. m_oldPosition = -1;
  957. setupCharClass();
  958. }
  959. bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
  960. {
  961. const int key = ev->key();
  962. const int mods = ev->modifiers();
  963. KEY_DEBUG("SHORTCUT OVERRIDE" << key << " PASSING: " << m_passing);
  964. if (key == Key_Escape) {
  965. if (m_subsubmode == SearchSubSubMode)
  966. return true;
  967. // Not sure this feels good. People often hit Esc several times.
  968. if (isNoVisualMode()
  969. && m_mode == CommandMode
  970. && m_submode == NoSubMode
  971. && m_opcount.isEmpty()
  972. && m_mvcount.isEmpty())
  973. return false;
  974. return true;
  975. }
  976. // We are interested in overriding most Ctrl key combinations.
  977. if (mods == RealControlModifier
  978. && !config(ConfigPassControlKey).toBool()
  979. && ((key >= Key_A && key <= Key_Z && key != Key_K)
  980. || key == Key_BracketLeft || key == Key_BracketRight)) {
  981. // Ctrl-K is special as it is the Core's default notion of Locator
  982. if (m_passing) {
  983. KEY_DEBUG(" PASSING CTRL KEY");
  984. // We get called twice on the same key
  985. //m_passing = false;
  986. return false;
  987. }
  988. KEY_DEBUG(" NOT PASSING CTRL KEY");
  989. //updateMiniBuffer();
  990. return true;
  991. }
  992. // Let other shortcuts trigger.
  993. return false;
  994. }
  995. EventResult FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
  996. {
  997. const int key = ev->key();
  998. const int mods = ev->modifiers();
  999. if (key == Key_Shift || key == Key_Alt || key == Key_Control
  1000. || key == Key_Alt || key == Key_AltGr || key == Key_Meta)
  1001. {
  1002. KEY_DEBUG("PLAIN MODIFIER");
  1003. return EventUnhandled;
  1004. }
  1005. if (m_passing) {
  1006. passShortcuts(false);
  1007. KEY_DEBUG("PASSING PLAIN KEY..." << ev->key() << ev->text());
  1008. //if (input.is(',')) { // use ',,' to leave, too.
  1009. // qDebug() << "FINISHED...";
  1010. // return EventHandled;
  1011. //}
  1012. m_passing = false;
  1013. updateMiniBuffer();
  1014. KEY_DEBUG(" PASS TO CORE");
  1015. return EventPassedToCore;
  1016. }
  1017. bool inSnippetMode = false;
  1018. QMetaObject::invokeMethod(editor(),
  1019. "inSnippetMode", Q_ARG(bool *, &inSnippetMode));
  1020. if (inSnippetMode)
  1021. return EventPassedToCore;
  1022. // Fake "End of line"
  1023. //m_tc = cursor();
  1024. //bool hasBlock = false;
  1025. //emit q->requestHasBlockSelection(&hasBlock);
  1026. //qDebug() << "IMPORT BLOCK 2:" << hasBlock;
  1027. //if (0 && hasBlock) {
  1028. // (pos > anc) ? --pos : --anc;
  1029. importSelection();
  1030. // Position changed externally, e.g. by code completion.
  1031. if (position() != m_oldPosition) {
  1032. setTargetColumn();
  1033. //qDebug() << "POSITION CHANGED EXTERNALLY";
  1034. if (m_mode == InsertMode) {
  1035. int dist = position() - m_oldPosition;
  1036. // Try to compensate for code completion
  1037. if (dist > 0 && dist <= physicalCursorColumn()) {
  1038. Range range(m_oldPosition, position());
  1039. m_lastInsertion.append(selectText(range));
  1040. }
  1041. } else if (!isVisualMode()) {
  1042. if (atEndOfLine())
  1043. moveLeft();
  1044. }
  1045. }
  1046. QTextCursor tc = cursor();
  1047. tc.setVisualNavigation(true);
  1048. setCursor(tc);
  1049. if (m_fakeEnd)
  1050. moveRight();
  1051. //if ((mods & RealControlModifier) != 0) {
  1052. // if (key >= Key_A && key <= Key_Z)
  1053. // key = shift(key); // make it lower case
  1054. // key = control(key);
  1055. //} else if (key >= Key_A && key <= Key_Z && (mods & Qt::ShiftModifier) == 0) {
  1056. // key = shift(key);
  1057. //}
  1058. //QTC_ASSERT(m_mode == InsertMode || m_mode == ReplaceMode
  1059. // || !atBlockEnd() || block().length() <= 1,
  1060. // qDebug() << "Cursor at EOL before key handler");
  1061. EventResult result = handleKey(Input(key, mods, ev->text()));
  1062. // The command might have destroyed the editor.
  1063. if (m_textedit || m_plaintextedit) {
  1064. // We fake vi-style end-of-line behaviour
  1065. m_fakeEnd = atEndOfLine() && m_mode == CommandMode && !isVisualBlockMode();
  1066. //QTC_ASSERT(m_mode == InsertMode || m_mode == ReplaceMode
  1067. // || !atBlockEnd() || block().length() <= 1,
  1068. // qDebug() << "Cursor at EOL after key handler");
  1069. if (m_fakeEnd)
  1070. moveLeft();
  1071. m_oldPosition = position();
  1072. if (hasConfig(ConfigShowMarks))
  1073. updateSelection();
  1074. exportSelection();
  1075. updateCursorShape();
  1076. }
  1077. return result;
  1078. }
  1079. void FakeVimHandler::Private::installEventFilter()
  1080. {
  1081. EDITOR(viewport()->installEventFilter(q));
  1082. EDITOR(installEventFilter(q));
  1083. }
  1084. void FakeVimHandler::Private::setupWidget()
  1085. {
  1086. enterCommandMode();
  1087. if (m_textedit) {
  1088. m_textedit->setLineWrapMode(QTextEdit::NoWrap);
  1089. } else if (m_plaintextedit) {
  1090. m_plaintextedit->setLineWrapMode(QPlainTextEdit::NoWrap);
  1091. }
  1092. m_wasReadOnly = EDITOR(isReadOnly());
  1093. updateEditor();
  1094. importSelection();
  1095. updateMiniBuffer();
  1096. updateCursorShape();
  1097. }
  1098. void FakeVimHandler::Private::exportSelection()
  1099. {
  1100. int pos = position();
  1101. int anc = anchor();
  1102. m_oldInternalPosition = pos;
  1103. m_oldInternalAnchor = anc;
  1104. if (isVisualMode()) {
  1105. if (pos >= anc)
  1106. setAnchorAndPosition(anc, pos + 1);
  1107. else
  1108. setAnchorAndPosition(anc + 1, pos);
  1109. if (m_visualMode == VisualBlockMode) {
  1110. emit q->requestSetBlockSelection(false);
  1111. emit q->requestSetBlockSelection(true);
  1112. } else if (m_visualMode == VisualLineMode) {
  1113. const int posLine = lineForPosition(pos);
  1114. const int ancLine = lineForPosition(anc);
  1115. if (anc < pos) {
  1116. pos = lastPositionInLine(posLine);
  1117. anc = firstPositionInLine(ancLine);
  1118. } else {
  1119. pos = firstPositionInLine(posLine);
  1120. anc = lastPositionInLine(ancLine);
  1121. }
  1122. setAnchorAndPosition(anc, pos);
  1123. } else if (m_visualMode == VisualCharMode) {
  1124. /* Nothing */
  1125. } else {
  1126. QTC_CHECK(false);
  1127. }
  1128. } else {
  1129. setAnchorAndPosition(pos, pos);
  1130. }
  1131. m_oldExternalPosition = position();
  1132. m_oldExternalAnchor = anchor();
  1133. m_oldVisualMode = m_visualMode;
  1134. }
  1135. void FakeVimHandler::Private::importSelection()
  1136. {
  1137. bool hasBlock = false;
  1138. emit q->requestHasBlockSelection(&hasBlock);
  1139. if (position() == m_oldExternalPosition
  1140. && anchor() == m_oldExternalAnchor) {
  1141. // Undo drawing correction.
  1142. m_visualMode = m_oldVisualMode;
  1143. setAnchorAndPosition(m_oldInternalAnchor, m_oldInternalPosition);
  1144. //setMark('<', m_oldInternalAnchor);
  1145. //setMark('>', m_oldInternalPosition);
  1146. } else {
  1147. // Import new selection.
  1148. Qt::KeyboardModifiers mods = QApplication::keyboardModifiers();
  1149. if (cursor().hasSelection()) {
  1150. if (mods & RealControlModifier)
  1151. m_visualMode = VisualBlockMode;
  1152. else if (mods & Qt::AltModifier)
  1153. m_visualMode = VisualBlockMode;
  1154. else if (mods & Qt::ShiftModifier)
  1155. m_visualMode = VisualLineMode;
  1156. else
  1157. m_visualMode = VisualCharMode;
  1158. } else {
  1159. m_visualMode = NoVisualMode;
  1160. }
  1161. //dump("IS @");
  1162. //setMark('<', tc.anchor());
  1163. //setMark('>', tc.position());
  1164. }
  1165. }
  1166. void FakeVimHandler::Private::updateEditor()
  1167. {
  1168. const int charWidth = QFontMetrics(EDITOR(font())).width(QChar(' '));
  1169. EDITOR(setTabStopWidth(charWidth * config(ConfigTabStop).toInt()));
  1170. setupCharClass();
  1171. }
  1172. void FakeVimHandler::Private::restoreWidget(int tabSize)
  1173. {
  1174. //showBlackMessage(QString());
  1175. //updateMiniBuffer();
  1176. //EDITOR(removeEventFilter(q));
  1177. //EDITOR(setReadOnly(m_wasReadOnly));
  1178. const int charWidth = QFontMetrics(EDITOR(font())).width(QChar(' '));
  1179. EDITOR(setTabStopWidth(charWidth * tabSize));
  1180. m_visualMode = NoVisualMode;
  1181. // Force "ordinary" cursor.
  1182. m_mode = InsertMode;
  1183. m_submode = NoSubMode;
  1184. m_subsubmode = NoSubSubMode;
  1185. updateCursorShape();
  1186. updateSelection();
  1187. }
  1188. EventResult FakeVimHandler::Private::handleKey(const Input &input)
  1189. {
  1190. KEY_DEBUG("HANDLE INPUT: " << input << " MODE: " << mode);
  1191. if (m_mode == ExMode)
  1192. return handleExMode(input);
  1193. if (m_subsubmode == SearchSubSubMode)
  1194. return handleSearchSubSubMode(input);
  1195. if (m_mode == InsertMode || m_mode == ReplaceMode || m_mode == CommandMode) {
  1196. g.pendingInput.append(input);
  1197. const char code = m_mode == InsertMode ? 'i' : 'n';
  1198. if (g.mappings[code].mappingDone(&g.pendingInput))
  1199. return handleKey2();
  1200. if (g.inputTimer != -1)
  1201. killTimer(g.inputTimer);
  1202. g.inputTimer = startTimer(1000);
  1203. return EventHandled;
  1204. }
  1205. return EventUnhandled;
  1206. }
  1207. EventResult FakeVimHandler::Private::handleKey2()
  1208. {
  1209. setUndoPosition(position());
  1210. if (m_mode == InsertMode) {
  1211. EventResult result = EventUnhandled;
  1212. foreach (const Input &in, g.pendingInput) {
  1213. EventResult r = handleInsertMode(in);
  1214. if (r == EventHandled)
  1215. result = EventHandled;
  1216. }
  1217. g.pendingInput.clear();
  1218. return result;
  1219. }
  1220. if (m_mode == ReplaceMode) {
  1221. EventResult result = EventUnhandled;
  1222. foreach (const Input &in, g.pendingInput) {
  1223. EventResult r = handleReplaceMode(in);
  1224. if (r == EventHandled)
  1225. result = EventHandled;
  1226. }
  1227. g.pendingInput.clear();
  1228. return result;
  1229. }
  1230. if (m_mode == CommandMode) {
  1231. EventResult result = EventUnhandled;
  1232. foreach (const Input &in, g.pendingInput) {
  1233. EventResult r = handleCommandMode(in);
  1234. if (r == EventHandled)
  1235. result = EventHandled;
  1236. }
  1237. g.pendingInput.clear();
  1238. return result;
  1239. }
  1240. return EventUnhandled;
  1241. }
  1242. void FakeVimHandler::Private::timerEvent(QTimerEvent *ev)
  1243. {
  1244. Q_UNUSED(ev);
  1245. handleKey2();
  1246. }
  1247. void FakeVimHandler::Private::stopIncrementalFind()
  1248. {
  1249. if (m_findPending) {
  1250. m_findPending = false;
  1251. QTextCursor tc = cursor();
  1252. setAnchorAndPosition(m_findStartPosition, tc.selectionStart());
  1253. finishMovement();
  1254. setAnchor();
  1255. }
  1256. }
  1257. void FakeVimHandler::Private::setUndoPosition(int pos)
  1258. {
  1259. //qDebug() << " CURSOR POS: " << m_undoCursorPosition;
  1260. m_undoCursorPosition[document()->availableUndoSteps()] = pos;
  1261. }
  1262. void FakeVimHandler::Private::moveDown(int n)
  1263. {
  1264. #if 0
  1265. // does not work for "hidden" documents like in the autotests
  1266. tc.movePosition(Down, MoveAnchor, n);
  1267. #else
  1268. const int col = position() - block().position();
  1269. const int lastLine = document()->lastBlock().blockNumber();
  1270. const int targetLine = qMax(0, qMin(lastLine, block().blockNumber() + n));
  1271. const QTextBlock &block = document()->findBlockByNumber(targetLine);
  1272. const int pos = block.position();
  1273. setPosition(pos + qMax(0, qMin(block.length() - 2, col)));
  1274. moveToTargetColumn();
  1275. #endif
  1276. }
  1277. void FakeVimHandler::Private::moveToEndOfLine()
  1278. {
  1279. #if 0
  1280. // does not work for "hidden" documents like in the autotests
  1281. tc.movePosition(EndOfLine, MoveAnchor);
  1282. #else
  1283. const int pos = block().position() + block().length() - 2;
  1284. setPosition(qMax(block().position(), pos));
  1285. #endif
  1286. }
  1287. void FakeVimHandler::Private::moveBehindEndOfLine()
  1288. {
  1289. int pos = qMin(block().position() + block().length() - 1,
  1290. lastPositionInDocument());
  1291. setPosition(pos);
  1292. }
  1293. void FakeVimHandler::Private::moveToStartOfLine()
  1294. {
  1295. #if 0
  1296. // does not work for "hidden" documents like in the autotests
  1297. tc.movePosition(StartOfLine, MoveAnchor);
  1298. #else
  1299. setPosition(block().position());
  1300. #endif
  1301. }
  1302. void FakeVimHandler::Private::finishMovement(const QString &dotCommand, int count)
  1303. {
  1304. finishMovement(dotCommand.arg(count));
  1305. }
  1306. void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
  1307. {
  1308. //dump("FINISH MOVEMENT");
  1309. if (m_submode == FilterSubMode) {
  1310. int beginLine = lineForPosition(anchor());
  1311. int endLine = lineForPosition(position());
  1312. setPosition(qMin(anchor(), position()));
  1313. enterExMode();
  1314. m_currentMessage.clear();
  1315. m_commandBuffer.setContents(QString(".,+%1!").arg(qAbs(endLine - beginLine)));
  1316. //g.commandHistory.append(QString());
  1317. updateMiniBuffer();
  1318. return;
  1319. }
  1320. //if (isVisualMode())
  1321. // setMark('>', position());
  1322. if (m_submode == ChangeSubMode
  1323. || m_submode == DeleteSubMode
  1324. || m_submode == YankSubMode
  1325. || m_submode == TransformSubMode) {
  1326. if (m_submode != YankSubMode)
  1327. beginEditBlock();
  1328. if (m_movetype == MoveLineWise)
  1329. m_rangemode = (m_submode == ChangeSubMode)
  1330. ? RangeLineModeExclusive
  1331. : RangeLineMode;
  1332. if (m_movetype == MoveInclusive) {
  1333. if (anchor() <= position()) {
  1334. if (!cursor().atBlockEnd())
  1335. setPosition(position() + 1); // correction
  1336. } else {
  1337. setAnchorAndPosition(anchor() + 1, position());
  1338. }
  1339. }
  1340. if (m_positionPastEnd) {
  1341. const int anc = anchor();
  1342. moveBehindEndOfLine();
  1343. moveRight();
  1344. setAnchorAndPosition(anc, position());
  1345. }
  1346. if (m_anchorPastEnd) {
  1347. setAnchorAndPosition(anchor() + 1, position());
  1348. }
  1349. if (m_submode != TransformSubMode) {
  1350. yankText(currentRange(), m_register);
  1351. if (m_movetype == MoveLineWise)
  1352. g.registers[m_register].rangemode = RangeLineMode;
  1353. }
  1354. m_positionPastEnd = m_anchorPastEnd = false;
  1355. }
  1356. if (m_submode == ChangeSubMode) {
  1357. if (m_rangemode == RangeLineMode)
  1358. m_rangemode = RangeLineModeExclusive;
  1359. removeText(currentRange());
  1360. if (!dotCommand.isEmpty())
  1361. setDotCommand(QLatin1Char('c') + dotCommand);
  1362. if (m_movetype == MoveLineWise)
  1363. insertAutomaticIndentation(true);
  1364. endEditBlock();
  1365. setUndoPosition(position());
  1366. enterInsertMode();
  1367. m_submode = NoSubMode;
  1368. } else if (m_submode == DeleteSubMode) {
  1369. removeText(currentRange());
  1370. if (!dotCommand.isEmpty())
  1371. setDotCommand(QLatin1Char('d') + dotCommand);
  1372. if (m_movetype == MoveLineWise)
  1373. handleStartOfLine();
  1374. m_submode = NoSubMode;
  1375. if (atEndOfLine())
  1376. moveLeft();
  1377. else
  1378. setTargetColumn();
  1379. endEditBlock();
  1380. } else if (m_submode == YankSubMode) {
  1381. m_submode = NoSubMode;
  1382. const int la = lineForPosition(anchor());
  1383. const int lp = lineForPosition(position());
  1384. if (m_register != '"') {
  1385. setPosition(mark(m_register));
  1386. moveToStartOfLine();
  1387. } else {
  1388. if (anchor() <= position())
  1389. setPosition(anchor());
  1390. }
  1391. if (la != lp)
  1392. showBlackMessage(QString("%1 lines yanked").arg(qAbs(la - lp) + 1));
  1393. } else if (m_submode == TransformSubMode) {
  1394. if (m_subsubmode == InvertCaseSubSubMode) {
  1395. invertCase(currentRange());
  1396. if (!dotCommand.isEmpty())
  1397. setDotCommand(QLatin1Char('~') + dotCommand);
  1398. } else if (m_subsubmode == UpCaseSubSubMode) {
  1399. upCase(currentRange());
  1400. if (!dotCommand.isEmpty())
  1401. setDotCommand("gU" + dotCommand);
  1402. } else if (m_subsubmode == DownCaseSubSubMode) {
  1403. downCase(currentRange());
  1404. if (!dotCommand.isEmpty())
  1405. setDotCommand("gu" + dotCommand);
  1406. }
  1407. m_submode = NoSubMode;
  1408. m_subsubmode = NoSubSubMode;
  1409. setPosition(qMin(anchor(), position()));
  1410. if (m_movetype == MoveLineWise)
  1411. handleStartOfLine();
  1412. endEditBlock();
  1413. } else if (m_submode == IndentSubMode) {
  1414. recordJump();
  1415. beginEditBlock();
  1416. indentSelectedText();
  1417. endEditBlock();
  1418. m_submode = NoSubMode;
  1419. } else if (m_submode == ShiftRightSubMode) {
  1420. recordJump();
  1421. shiftRegionRight(1);
  1422. m_submode = NoSubMode;
  1423. } else if (m_submode == ShiftLeftSubMode) {
  1424. recordJump();
  1425. shiftRegionLeft(1);
  1426. m_submode = NoSubMode;
  1427. }
  1428. resetCommandMode();
  1429. updateSelection();
  1430. updateMiniBuffer();
  1431. }
  1432. void FakeVimHandler::Private::resetCommandMode()
  1433. {
  1434. m_movetype = MoveInclusive;
  1435. m_mvcount.clear();
  1436. m_opcount.clear();
  1437. m_gflag = false;
  1438. m_register = '"';
  1439. //m_tc.clearSelection();
  1440. m_rangemode = RangeCharMode;
  1441. }
  1442. void FakeVimHandler::Private::updateSelection()
  1443. {
  1444. QList<QTextEdit::ExtraSelection> selections = m_searchSelections;
  1445. if (!m_searchCursor.isNull()) {
  1446. QTextEdit::ExtraSelection sel;
  1447. sel.cursor = m_searchCursor;
  1448. sel.format = m_searchCursor.blockCharFormat();
  1449. sel.format.setForeground(Qt::white);
  1450. sel.format.setBackground(Qt::black);
  1451. selections.append(sel);
  1452. }
  1453. if (hasConfig(ConfigShowMarks)) {
  1454. for (MarksIterator it(m_marks); it.hasNext(); ) {
  1455. it.next();
  1456. QTextEdit::ExtraSelection sel;
  1457. const int pos = it.value().position();
  1458. sel.cursor = cursor();
  1459. sel.cursor.setPosition(pos, MoveAnchor);
  1460. sel.cursor.setPosition(pos + 1, KeepAnchor);
  1461. sel.format = cursor().blockCharFormat();
  1462. sel.format.setForeground(Qt::blue);
  1463. sel.format.setBackground(Qt::green);
  1464. selections.append(sel);
  1465. }
  1466. }
  1467. //qDebug() << "SELECTION: " << selections;
  1468. emit q->selectionChanged(selections);
  1469. }
  1470. void FakeVimHandler::Private::updateMiniBuffer()
  1471. {
  1472. if (!m_textedit && !m_plaintextedit)
  1473. return;
  1474. QString msg;
  1475. int cursorPos = -1;
  1476. if (m_passing) {
  1477. msg = "-- PASSING -- ";
  1478. } else if (!m_currentMessage.isEmpty()) {
  1479. msg = m_currentMessage;
  1480. } else if (m_mode == CommandMode && isVisualMode()) {
  1481. if (isVisualCharMode()) {
  1482. msg = "-- VISUAL --";
  1483. } else if (isVisualLineMode()) {
  1484. msg = "-- VISUAL LINE --";
  1485. } else if (isVisualBlockMode()) {
  1486. msg = "-- VISUAL BLOCK --";
  1487. }
  1488. } else if (m_mode == InsertMode) {
  1489. msg = "-- INSERT --";
  1490. } else if (m_mode == ReplaceMode) {
  1491. msg = "-- REPLACE --";
  1492. } else if (!m_commandPrefix.isEmpty()) {
  1493. //QTC_ASSERT(m_mode == ExMode || m_subsubmode == SearchSubSubMode,
  1494. // qDebug() << "MODE: " << m_mode << m_subsubmode);
  1495. msg = m_commandPrefix + m_commandBuffer.display();
  1496. if (m_mode != CommandMode)
  1497. cursorPos = m_commandPrefix.size() + m_commandBuffer.cursorPos();
  1498. } else {
  1499. QTC_CHECK(m_mode == CommandMode && m_subsubmode != SearchSubSubMode);
  1500. msg = "-- COMMAND --";
  1501. }
  1502. emit q->commandBufferChanged(msg, cursorPos);
  1503. int linesInDoc = linesInDocument();
  1504. int l = cursorLine();
  1505. QString status;
  1506. const QString pos = QString::fromLatin1("%1,%2")
  1507. .arg(l + 1).arg(physicalCursorColumn() + 1);
  1508. // FIXME: physical "-" logical
  1509. if (linesInDoc != 0) {
  1510. status = FakeVimHandler::tr("%1%2%").arg(pos, -10).arg(l * 100 / linesInDoc, 4);
  1511. } else {
  1512. status = FakeVimHandler::tr("%1All").arg(pos, -10);
  1513. }
  1514. emit q->statusDataChanged(status);
  1515. }
  1516. void FakeVimHandler::Private::showRedMessage(const QString &msg)
  1517. {
  1518. //qDebug() << "MSG: " << msg;
  1519. m_currentMessage = msg;
  1520. updateMiniBuffer();
  1521. }
  1522. void FakeVimHandler::Private::showBlackMessage(const QString &msg)
  1523. {
  1524. //qDebug() << "MSG: " << msg;
  1525. m_commandBuffer.setContents(msg);
  1526. updateMiniBuffer();
  1527. }
  1528. void FakeVimHandler::Private::notImplementedYet()
  1529. {
  1530. qDebug() << "Not implemented in FakeVim";
  1531. showRedMessage(FakeVimHandler::tr("Not implemented in FakeVim"));
  1532. updateMiniBuffer();
  1533. }
  1534. void FakeVimHandler::Private::passShortcuts(bool enable)
  1535. {
  1536. m_passing = enable;
  1537. updateMiniBuffer();
  1538. if (enable)
  1539. QCoreApplication::instance()->installEventFilter(q);
  1540. else
  1541. QCoreApplication::instance()->removeEventFilter(q);
  1542. }
  1543. static bool subModeCanUseTextObjects(int submode)
  1544. {
  1545. return submode == DeleteSubMode
  1546. || submode == YankSubMode
  1547. || submode == ChangeSubMode
  1548. || submode == IndentSubMode
  1549. || submode == ShiftLeftSubMode
  1550. || submode == ShiftRightSubMode;
  1551. }
  1552. EventResult FakeVimHandler::Private::handleCommandSubSubMode(const Input &input)
  1553. {
  1554. //const int key = input.key;
  1555. EventResult handled = EventHandled;
  1556. if (m_subsubmode == FtSubSubMode) {
  1557. m_semicolonType = m_subsubdata;
  1558. m_semicolonKey = input.text();
  1559. bool valid = handleFfTt(m_semicolonKey);
  1560. m_subsubmode = NoSubSubMode;
  1561. if (!valid) {
  1562. m_submode = NoSubMode;
  1563. finishMovement();
  1564. } else {
  1565. finishMovement(QString("%1%2%3")
  1566. .arg(count())
  1567. .arg(m_semicolonType.text())
  1568. .arg(m_semicolonKey));
  1569. }
  1570. } else if (m_subsubmode == TextObjectSubSubMode) {
  1571. if (input.is('w'))
  1572. selectWordTextObject(m_subsubdata.is('i'));
  1573. else if (input.is('W'))
  1574. selectWORDTextObject(m_subsubdata.is('i'));
  1575. else if (input.is('s'))
  1576. selectSentenceTextObject(m_subsubdata.is('i'));
  1577. else if (input.is('p'))
  1578. selectParagraphTextObject(m_subsubdata.is('i'));
  1579. else if (input.is('[') || input.is(']'))
  1580. selectBlockTextObject(m_subsubdata.is('i'), '[', ']');
  1581. else if (input.is('(') || input.is(')') || input.is('b'))
  1582. selectBlockTextObject(m_subsubdata.is('i'), '(', ')');
  1583. else if (input.is('<') || input.is('>'))
  1584. selectBlockTextObject(m_subsubdata.is('i'), '<', '>');
  1585. else if (input.is('{') || input.is('}') || input.is('B'))
  1586. selectBlockTextObject(m_subsubdata.is('i'), '{', '}');
  1587. else if (input.is('"') || input.is('\'') || input.is('`'))
  1588. selectQuotedStringTextObject(m_subsubdata.is('i'), input.key());
  1589. m_subsubmode = NoSubSubMode;
  1590. finishMovement();
  1591. } else if (m_subsubmode == MarkSubSubMode) {
  1592. setMark(input.asChar().unicode(), position());
  1593. m_subsubmode = NoSubSubMode;
  1594. } else if (m_subsubmode == BackTickSubSubMode
  1595. || m_subsubmode == TickSubSubMode) {
  1596. int m = mark(input.asChar().unicode());
  1597. if (m != -1) {
  1598. setPosition(m);
  1599. if (m_subsubmode == TickSubSubMode)
  1600. moveToFirstNonBlankOnLine();
  1601. finishMovement();
  1602. } else {
  1603. showRedMessage(msgMarkNotSet(input.text()));
  1604. }
  1605. m_subsubmode = NoSubSubMode;
  1606. } else {
  1607. handled = EventUnhandled;
  1608. }
  1609. return handled;
  1610. }
  1611. EventResult FakeVimHandler::Private::handleOpenSquareSubMode(const Input &input)
  1612. {
  1613. EventResult handled = EventHandled;
  1614. m_submode = NoSubMode;
  1615. if (input.is('{')) {
  1616. searchBalanced(false, '{', '}');
  1617. } else if (input.is('(')) {
  1618. searchBalanced(false, '(', ')');
  1619. } else {
  1620. handled = EventUnhandled;
  1621. }
  1622. return handled;
  1623. }
  1624. EventResult FakeVimHandler::Private::handleCloseSquareSubMode(const Input &input)
  1625. {
  1626. EventResult handled = EventHandled;
  1627. m_submode = NoSubMode;
  1628. if (input.is('}')) {
  1629. searchBalanced(true, '}', '{');
  1630. } else if (input.is(')')) {
  1631. searchBalanced(true, ')', '(');
  1632. } else {
  1633. handled = EventUnhandled;
  1634. }
  1635. return handled;
  1636. }
  1637. EventResult FakeVimHandler::Private::handleCommandMode(const Input &input)
  1638. {
  1639. EventResult handled = EventHandled;
  1640. if (input.isEscape()) {
  1641. if (isVisualMode()) {
  1642. leaveVisualMode();
  1643. } else if (m_submode != NoSubMode) {
  1644. m_submode = NoSubMode;
  1645. m_subsubmode = NoSubSubMode;
  1646. finishMovement();
  1647. } else {
  1648. resetCommandMode();
  1649. updateSelection();
  1650. updateMiniBuffer();
  1651. }
  1652. } else if (m_subsubmode != NoSubSubMode) {
  1653. handleCommandSubSubMode(input);
  1654. } else if (m_submode == OpenSquareSubMode) {
  1655. handled = handleOpenSquareSubMode(input);
  1656. } else if (m_submode == CloseSquareSubMode) {
  1657. handled = handleCloseSquareSubMode(input);
  1658. } else if (m_submode == WindowSubMode) {
  1659. emit q->windowCommandRequested(input.key());
  1660. m_submode = NoSubMode;
  1661. } else if (m_submode == RegisterSubMode) {
  1662. m_register = input.asChar().unicode();
  1663. m_submode = NoSubMode;
  1664. m_rangemode = RangeLineMode;
  1665. } else if (m_submode == ReplaceSubMode) {
  1666. if (isVisualMode()) {
  1667. if (isVisualLineMode())
  1668. m_rangemode = RangeLineMode;
  1669. else if (isVisualBlockMode())
  1670. m_rangemode = RangeBlockMode;
  1671. else
  1672. m_rangemode = RangeCharMode;
  1673. leaveVisualMode();
  1674. Range range = currentRange();
  1675. Transformation tr =
  1676. &FakeVimHandler::Private::replaceByCharTransform;
  1677. transformText(range, tr, input.asChar());
  1678. setPosition(range.beginPos);
  1679. } else if (count() <= rightDist()) {
  1680. setAnchor();
  1681. moveRight(count());
  1682. if (input.isReturn()) {
  1683. beginEditBlock();
  1684. replaceText(currentRange(), QString());
  1685. insertText(QString("\n"));
  1686. endEditBlock();
  1687. } else {
  1688. replaceText(currentRange(), QString(count(), input.asChar()));
  1689. moveLeft();
  1690. }
  1691. setTargetColumn();
  1692. setDotCommand("%1r" + input.text(), count());
  1693. }
  1694. m_submode = NoSubMode;
  1695. finishMovement();
  1696. } else if (m_submode == ChangeSubMode && input.is('c')) { // tested
  1697. moveToStartOfLine();
  1698. setAnchor();
  1699. moveDown(count() - 1);
  1700. moveToEndOfLine();
  1701. m_movetype = MoveLineWise;
  1702. m_lastInsertion.clear();
  1703. setDotCommand("%1cc", count());
  1704. finishMovement();
  1705. } else if (m_submode == DeleteSubMode && input.is('d')) { // tested
  1706. m_movetype = MoveLineWise;
  1707. int endPos = firstPositionInLine(lineForPosition(position()) + count() - 1);
  1708. Range range(position(), endPos, RangeLineMode);
  1709. yankText(range);
  1710. removeText(range);
  1711. setDotCommand("%1dd", count());
  1712. m_submode = NoSubMode;
  1713. handleStartOfLine();
  1714. setTargetColumn();
  1715. finishMovement();
  1716. } else if ((subModeCanUseTextObjects(m_submode) || isVisualMode())
  1717. && (input.is('a') || input.is('i'))) {
  1718. m_subsubmode = TextObjectSubSubMode;
  1719. m_subsubdata = input;
  1720. } else if (m_submode == ShiftLeftSubMode && input.is('<')) {
  1721. setAnchor();
  1722. moveDown(count() - 1);
  1723. m_movetype = MoveLineWise;
  1724. setDotCommand("%1<<", count());
  1725. finishMovement();
  1726. } else if (m_submode == ShiftRightSubMode && input.is('>')) {
  1727. setAnchor();
  1728. moveDown(count() - 1);
  1729. m_movetype = MoveLineWise;
  1730. setDotCommand("%1>>", count());
  1731. finishMovement();
  1732. } else if (m_submode == IndentSubMode && input.is('=')) {
  1733. setAnchor();
  1734. moveDown(count() - 1);
  1735. m_movetype = MoveLineWise;
  1736. setDotCommand("%1==", count());
  1737. finishMovement();
  1738. } else if (m_submode == ZSubMode) {
  1739. //qDebug() << "Z_MODE " << cursorLine() << linesOnScreen();
  1740. if (input.isReturn() || input.is('t')) {
  1741. // Cursor line to top of window.
  1742. if (!m_mvcount.isEmpty())
  1743. setPosition(firstPositionInLine(count()));
  1744. scrollUp(- cursorLineOnScreen());
  1745. if (input.isReturn())
  1746. moveToFirstNonBlankOnLine();
  1747. finishMovement();
  1748. } else if (input.is('.') || input.is('z')) {
  1749. // Cursor line to center of window.
  1750. if (!m_mvcount.isEmpty())
  1751. setPosition(firstPositionInLine(count()));
  1752. scrollUp(linesOnScreen() / 2 - cursorLineOnScreen());
  1753. if (input.is('.'))
  1754. moveToFirstNonBlankOnLine();
  1755. finishMovement();
  1756. } else if (input.is('-') || input.is('b')) {
  1757. // Cursor line to bottom of window.
  1758. if (!m_mvcount.isEmpty())
  1759. setPosition(firstPositionInLine(count()));
  1760. scrollUp(linesOnScreen() - cursorLineOnScreen());
  1761. if (input.is('-'))
  1762. moveToFirstNonBlankOnLine();
  1763. finishMovement();
  1764. } else {
  1765. qDebug() << "IGNORED Z_MODE " << input.key() << input.text();
  1766. }
  1767. m_submode = NoSubMode;
  1768. } else if (m_submode == CapitalZSubMode) {
  1769. // Recognize ZZ and ZQ as aliases for ":x" and ":q!".
  1770. m_submode = NoSubMode;
  1771. if (input.is('Z'))
  1772. handleExCommand(QString(QLatin1Char('x')));
  1773. else if (input.is('Q'))
  1774. handleExCommand("q!");
  1775. } else if (input.isDigit()) {
  1776. if (input.is('0') && m_mvcount.isEmpty()) {
  1777. m_movetype = MoveExclusive;
  1778. moveToStartOfLine();
  1779. setTargetColumn();
  1780. finishMovement(QString(QLatin1Char('0')));
  1781. } else {
  1782. m_mvcount.append(input.text());
  1783. }
  1784. } else {
  1785. handled = handleCommandMode1(input);
  1786. }
  1787. return handled;
  1788. }
  1789. EventResult FakeVimHandler::Private::handleCommandMode1(const Input &input)
  1790. {
  1791. EventResult handled = EventHandled;
  1792. if (input.is('^') || input.is('_')) {
  1793. moveToFirstNonBlankOnLine();
  1794. setTargetColumn();
  1795. m_movetype = MoveExclusive;
  1796. finishMovement(input.text());
  1797. } else if (0 && input.is(',')) {
  1798. // FIXME: fakevim uses ',' by itself, so it is incompatible
  1799. m_subsubmode = FtSubSubMode;
  1800. // HACK: toggle 'f' <-> 'F', 't' <-> 'T'
  1801. //m_subsubdata = m_semicolonType ^ 32;
  1802. handleFfTt(m_semicolonKey);
  1803. m_subsubmode = NoSubSubMode;
  1804. finishMovement();
  1805. } else if (input.is(';')) {
  1806. m_subsubmode = FtSubSubMode;
  1807. m_subsubdata = m_semicolonType;
  1808. handleFfTt(m_semicolonKey);
  1809. m_subsubmode = NoSubSubMode;
  1810. finishMovement();
  1811. } else if (input.is(':')) {
  1812. enterExMode();
  1813. g.commandHistory.restart();
  1814. m_currentMessage.clear();
  1815. m_commandBuffer.clear();
  1816. if (isVisualMode())
  1817. m_commandBuffer.setContents("'<,'>");
  1818. updateMiniBuffer();
  1819. } else if (input.is('/') || input.is('?')) {
  1820. m_lastSearchForward = input.is('/');
  1821. g.searchHistory.restart();
  1822. if (hasConfig(ConfigUseCoreSearch)) {
  1823. // re-use the core dialog.
  1824. m_findPending = true;
  1825. m_findStartPosition = position();
  1826. m_movetype = MoveExclusive;
  1827. setAnchor(); // clear selection: otherwise, search is restricted to selection
  1828. emit q->findRequested(!m_lastSearchForward);
  1829. } else {
  1830. // FIXME: make core find dialog sufficiently flexible to
  1831. // produce the "default vi" behaviour too. For now, roll our own.
  1832. m_currentMessage.clear();
  1833. m_movetype = MoveExclusive;
  1834. m_subsubmode = SearchSubSubMode;
  1835. m_commandPrefix = QLatin1Char(m_lastSearchForward ? '/' : '?');
  1836. m_commandBuffer.clear();
  1837. updateMiniBuffer();
  1838. }
  1839. } else if (input.is('`')) {
  1840. m_subsubmode = BackTickSubSubMode;
  1841. if (m_submode != NoSubMode)
  1842. m_movetype = MoveLineWise;
  1843. } else if (input.is('#') || input.is('*')) {
  1844. // FIXME: That's not proper vim behaviour
  1845. QString needle;
  1846. QTextCursor tc = cursor();
  1847. tc.select(QTextCursor::WordUnderCursor);
  1848. needle = "\\<" + tc.selection().toPlainText() + "\\>";
  1849. setAnchorAndPosition(tc.position(), tc.anchor());
  1850. g.searchHistory.append(needle);
  1851. m_lastSearchForward = input.is('*');
  1852. m_currentMessage.clear();
  1853. m_commandPrefix = QLatin1Char(m_lastSearchForward ? '/' : '?');
  1854. m_commandBuffer.setContents(needle);
  1855. SearchData sd;
  1856. sd.needle = needle;
  1857. sd.forward = m_lastSearchForward;
  1858. sd.highlightCursor = false;
  1859. sd.highlightMatches = true;
  1860. search(sd);
  1861. //m_searchCursor = QTextCursor();
  1862. //updateSelection();
  1863. //updateMiniBuffer();
  1864. } else if (input.is('\'')) {
  1865. m_subsubmode = TickSubSubMode;
  1866. if (m_submode != NoSubMode)
  1867. m_movetype = MoveLineWise;
  1868. } else if (input.is('|')) {
  1869. moveToStartOfLine();
  1870. moveRight(qMin(count(), rightDist()) - 1);
  1871. setTargetColumn();
  1872. finishMovement();
  1873. } else if (input.is('!') && isNoVisualMode()) {
  1874. m_submode = FilterSubMode;
  1875. } else if (input.is('!') && isVisualMode()) {
  1876. enterExMode();
  1877. m_currentMessage.clear();
  1878. m_commandBuffer.setContents("'<,'>!");
  1879. //g.commandHistory.append(QString());
  1880. updateMiniBuffer();
  1881. } else if (input.is('"')) {
  1882. m_submode = RegisterSubMode;
  1883. } else if (input.isReturn()) {
  1884. moveToStartOfLine();
  1885. moveDown();
  1886. moveToFirstNonBlankOnLine();
  1887. m_movetype = MoveLineWise;
  1888. finishMovement("%1j", count());
  1889. } else if (input.is('-')) {
  1890. moveToStartOfLine();
  1891. moveUp(count());
  1892. moveToFirstNonBlankOnLine();
  1893. m_movetype = MoveLineWise;
  1894. finishMovement("%1-", count());
  1895. } else if (input.is('+')) {
  1896. moveToStartOfLine();
  1897. moveDown(count());
  1898. moveToFirstNonBlankOnLine();
  1899. m_movetype = MoveLineWise;
  1900. finishMovement("%1+", count());
  1901. } else if (input.isKey(Key_Home)) {
  1902. moveToStartOfLine();
  1903. setTargetColumn();
  1904. finishMovement();
  1905. } else if (input.is('$') || input.isKey(Key_End)) {
  1906. if (count() > 1)
  1907. moveDown(count() - 1);
  1908. moveToEndOfLine();
  1909. m_movetype = MoveInclusive;
  1910. setTargetColumn();
  1911. if (m_submode == NoSubMode)
  1912. m_targetColumn = -1;
  1913. if (isVisualMode())
  1914. m_visualTargetColumn = -1;
  1915. finishMovement("%1$", count());
  1916. } else if (input.is(',')) {
  1917. passShortcuts(true);
  1918. } else if (input.is('.')) {
  1919. //qDebug() << "REPEATING" << quoteUnprintable(g.dotCommand) << count()
  1920. // << input;
  1921. QString savedCommand = g.dotCommand;
  1922. g.dotCommand.clear();
  1923. replay(savedCommand, count());
  1924. enterCommandMode();
  1925. g.dotCommand = savedCommand;
  1926. } else if (input.is('<') && isNoVisualMode()) {
  1927. m_submode = ShiftLeftSubMode;
  1928. } else if (input.is('<') && isVisualMode()) {
  1929. shiftRegionLeft(1);
  1930. leaveVisualMode();
  1931. } else if (input.is('>') && isNoVisualMode()) {
  1932. m_submode = ShiftRightSubMode;
  1933. } else if (input.is('>') && isVisualMode()) {
  1934. shiftRegionRight(1);
  1935. leaveVisualMode();
  1936. } else if (input.is('=') && isNoVisualMode()) {
  1937. m_submode = IndentSubMode;
  1938. } else if (input.is('=') && isVisualMode()) {
  1939. beginEditBlock();
  1940. indentSelectedText();
  1941. endEditBlock();
  1942. leaveVisualMode();
  1943. } else if (input.is('%')) {
  1944. moveToMatchingParanthesis();
  1945. finishMovement();
  1946. } else if ((!isVisualMode() && input.is('a')) || (isVisualMode() && input.is('A'))) {
  1947. leaveVisualMode();
  1948. setUndoPosition(position());
  1949. breakEditBlock();
  1950. enterInsertMode();
  1951. m_lastInsertion.clear();
  1952. if (!atEndOfLine())
  1953. moveRight();
  1954. updateMiniBuffer();
  1955. } else if (input.is('A')) {
  1956. setUndoPosition(position());
  1957. breakEditBlock();
  1958. moveBehindEndOfLine();
  1959. setAnchor();
  1960. enterInsertMode();
  1961. setDotCommand(QString(QLatin1Char('A')));
  1962. m_lastInsertion.clear();
  1963. updateMiniBuffer();
  1964. } else if (input.isControl('a')) {
  1965. // FIXME: eat it to prevent the global "select all" shortcut to trigger
  1966. } else if (input.is('b') || input.isShift(Key_Left)) {
  1967. m_movetype = MoveExclusive;
  1968. moveToWordBoundary(false, false);
  1969. setTargetColumn();
  1970. finishMovement();
  1971. } else if (input.is('B')) {
  1972. m_movetype = MoveExclusive;
  1973. moveToWordBoundary(true, false);
  1974. setTargetColumn();
  1975. finishMovement();
  1976. } else if (input.is('c') && isNoVisualMode()) {
  1977. if (atEndOfLine())
  1978. moveLeft();
  1979. setAnchor();
  1980. m_submode = ChangeSubMode;
  1981. } else if ((input.is('c') || input.is('C') || input.is('s') || input.is('R'))
  1982. && (isVisualCharMode() || isVisualLineMode())) {
  1983. if ((input.is('c')|| input.is('s')) && isVisualCharMode()) {
  1984. leaveVisualMode();
  1985. m_rangemode = RangeCharMode;
  1986. } else {
  1987. leaveVisualMode();
  1988. m_rangemode = RangeLineMode;
  1989. // leaveVisualMode() has set this to MoveInclusive for visual character mode
  1990. m_movetype = MoveLineWise;
  1991. }
  1992. m_submode = ChangeSubMode;
  1993. finishMovement();
  1994. } else if (input.is('C')) {
  1995. setAnchor();
  1996. moveToEndOfLine();
  1997. m_submode = ChangeSubMode;
  1998. setDotCommand(QString(QLatin1Char('C')));
  1999. finishMovement();
  2000. } else if (input.isControl('c')) {
  2001. if (isNoVisualMode())
  2002. showBlackMessage("Type Alt-v,Alt-v to quit FakeVim mode");
  2003. else
  2004. leaveVisualMode();
  2005. } else if (input.is('d') && isNoVisualMode()) {
  2006. if (m_rangemode == RangeLineMode) {
  2007. int pos = position();
  2008. moveToEndOfLine();
  2009. setAnchor();
  2010. setPosition(pos);
  2011. } else {
  2012. setAnchor();
  2013. }
  2014. m_opcount = m_mvcount;
  2015. m_mvcount.clear();
  2016. m_submode = DeleteSubMode;
  2017. } else if ((input.is('d') || input.is('x') || input.isKey(Key_Delete))
  2018. && isVisualMode()) {
  2019. if (isVisualCharMode()) {
  2020. leaveVisualMode();
  2021. m_submode = DeleteSubMode;
  2022. finishMovement();
  2023. } else if (isVisualLineMode()) {
  2024. leaveVisualMode();
  2025. m_rangemode = RangeLineMode;
  2026. yankText(currentRange(), m_register);
  2027. removeText(currentRange());
  2028. handleStartOfLine();
  2029. } else if (isVisualBlockMode()) {
  2030. leaveVisualMode();
  2031. m_rangemode = RangeBlockMode;
  2032. yankText(currentRange(), m_register);
  2033. removeText(currentRange());
  2034. setPosition(qMin(position(), anchor()));
  2035. }
  2036. } else if (input.is('D') && isNoVisualMode()) {
  2037. if (atEndOfLine())
  2038. moveLeft();
  2039. m_submode = DeleteSubMode;
  2040. setAnchor();
  2041. moveDown(qMax(count() - 1, 0));
  2042. m_movetype = MoveInclusive;
  2043. moveToEndOfLine();
  2044. setDotCommand(QString(QLatin1Char('D')));
  2045. finishMovement();
  2046. } else if ((input.is('D') || input.is('X')) &&
  2047. (isVisualCharMode() || isVisualLineMode())) {
  2048. leaveVisualMode();
  2049. m_rangemode = RangeLineMode;
  2050. m_submode = NoSubMode;
  2051. yankText(currentRange(), m_register);
  2052. removeText(currentRange());
  2053. moveToFirstNonBlankOnLine();
  2054. } else if ((input.is('D') || input.is('X')) && isVisualBlockMode()) {
  2055. leaveVisualMode();
  2056. m_rangemode = RangeBlockAndTailMode;
  2057. yankText(currentRange(), m_register);
  2058. removeText(currentRange());
  2059. setPosition(qMin(position(), anchor()));
  2060. } else if (input.isControl('d')) {
  2061. int sline = cursorLineOnScreen();
  2062. // FIXME: this should use the "scroll" option, and "count"
  2063. moveDown(linesOnScreen() / 2);
  2064. handleStartOfLine();
  2065. scrollToLine(cursorLine() - sline);
  2066. finishMovement();
  2067. } else if (input.is('e') || input.isShift(Key_Right)) {
  2068. m_movetype = MoveInclusive;
  2069. moveToWordBoundary(false, true);
  2070. setTargetColumn();
  2071. finishMovement("%1e", count());
  2072. } else if (input.is('E')) {
  2073. m_movetype = MoveInclusive;
  2074. moveToWordBoundary(true, true);
  2075. setTargetColumn();
  2076. finishMovement("%1E", count());
  2077. } else if (input.isControl('e')) {
  2078. // FIXME: this should use the "scroll" option, and "count"
  2079. if (cursorLineOnScreen() == 0)
  2080. moveDown(1);
  2081. scrollDown(1);
  2082. finishMovement();
  2083. } else if (input.is('f')) {
  2084. m_subsubmode = FtSubSubMode;
  2085. m_movetype = MoveInclusive;
  2086. m_subsubdata = input;
  2087. } else if (input.is('F')) {
  2088. m_subsubmode = FtSubSubMode;
  2089. m_movetype = MoveExclusive;
  2090. m_subsubdata = input;
  2091. } else if (input.is('g') && !m_gflag) {
  2092. m_gflag = true;
  2093. } else if (input.is('g') || input.is('G')) {
  2094. QString dotCommand = QString("%1G").arg(count());
  2095. if (input.is('G') && m_mvcount.isEmpty())
  2096. dotCommand = QString(QLatin1Char('G'));
  2097. if (input.is('g'))
  2098. m_gflag = false;
  2099. int n = (input.is('g')) ? 1 : linesInDocument();
  2100. n = m_mvcount.isEmpty() ? n : count();
  2101. if (m_submode == NoSubMode || m_submode == ZSubMode
  2102. || m_submode == CapitalZSubMode || m_submode == RegisterSubMode) {
  2103. setPosition(firstPositionInLine(n));
  2104. handleStartOfLine();
  2105. } else {
  2106. m_movetype = MoveLineWise;
  2107. m_rangemode = RangeLineMode;
  2108. setAnchor();
  2109. setPosition(firstPositionInLine(n));
  2110. }
  2111. finishMovement(dotCommand);
  2112. } else if (input.is('h') || input.isKey(Key_Left) || input.isBackspace()) {
  2113. m_movetype = MoveExclusive;
  2114. int n = qMin(count(), leftDist());
  2115. if (m_fakeEnd && block().length() > 1)
  2116. ++n;
  2117. moveLeft(n);
  2118. setTargetColumn();
  2119. finishMovement("%1h", count());
  2120. } else if (input.is('H')) {
  2121. setCursor(EDITOR(cursorForPosition(QPoint(0, 0))));
  2122. moveDown(qMax(count() - 1, 0));
  2123. handleStartOfLine();
  2124. finishMovement();
  2125. } else if (!isVisualMode() && (input.is('i') || input.isKey(Key_Insert))) {
  2126. setDotCommand(QString(QLatin1Char('i'))); // setDotCommand("%1i", count());
  2127. setUndoPosition(position());
  2128. breakEditBlock();
  2129. enterInsertMode();
  2130. updateMiniBuffer();
  2131. if (atEndOfLine())
  2132. moveLeft();
  2133. } else {
  2134. handled = handleCommandMode2(input);
  2135. }
  2136. return handled;
  2137. }
  2138. EventResult FakeVimHandler::Private::handleCommandMode2(const Input &input)
  2139. {
  2140. EventResult handled = EventHandled;
  2141. if (input.is('I')) {
  2142. setDotCommand(QString(QLatin1Char('I'))); // setDotCommand("%1I", count());
  2143. if (isVisualMode()) {
  2144. int beginLine = lineForPosition(anchor());
  2145. int endLine = lineForPosition(position());
  2146. m_visualInsertCount = qAbs(endLine - beginLine);
  2147. setPosition(qMin(position(), anchor()));
  2148. } else {
  2149. if (m_gflag)
  2150. moveToStartOfLine();
  2151. else
  2152. moveToFirstNonBlankOnLine();
  2153. m_gflag = false;
  2154. //m_tc.clearSelection();
  2155. }
  2156. setUndoPosition(position());
  2157. breakEditBlock();
  2158. enterInsertMode();
  2159. } else if (input.isControl('i')) {
  2160. if (!m_jumpListRedo.isEmpty()) {
  2161. m_jumpListUndo.append(cursorPosition());
  2162. setCursorPosition(m_jumpListRedo.last());
  2163. m_jumpListRedo.pop_back();
  2164. }
  2165. } else if (input.is('j') || input.isKey(Key_Down)
  2166. || input.isControl('j') || input.isControl('n')) {
  2167. m_movetype = MoveLineWise;
  2168. moveDown(count());
  2169. finishMovement("%1j", count());
  2170. } else if (input.is('J')) {
  2171. setDotCommand("%1J", count());
  2172. beginEditBlock();
  2173. if (m_submode == NoSubMode) {
  2174. for (int i = qMax(count(), 2) - 1; --i >= 0; ) {
  2175. moveBehindEndOfLine();
  2176. setAnchor();
  2177. moveRight();
  2178. if (m_gflag) {
  2179. removeText(currentRange());
  2180. } else {
  2181. while (characterAtCursor() == ' '
  2182. || characterAtCursor() == '\t')
  2183. moveRight();
  2184. removeText(currentRange());
  2185. cursor().insertText(QString(QLatin1Char(' ')));
  2186. }
  2187. }
  2188. if (!m_gflag)
  2189. moveLeft();
  2190. }
  2191. endEditBlock();
  2192. finishMovement();
  2193. } else if (input.is('k') || input.isKey(Key_Up) || input.isControl('p')) {
  2194. m_movetype = MoveLineWise;
  2195. moveUp(count());
  2196. finishMovement("%1k", count());
  2197. } else if (input.is('l') || input.isKey(Key_Right) || input.is(' ')) {
  2198. m_movetype = MoveExclusive;
  2199. bool pastEnd = count() >= rightDist() - 1;
  2200. moveRight(qMax(0, qMin(count(), rightDist() - (m_submode == NoSubMode))));
  2201. setTargetColumn();
  2202. if (pastEnd && isVisualMode())
  2203. m_visualTargetColumn = -1;
  2204. finishMovement("%1l", count());
  2205. } else if (input.is('L')) {
  2206. QTextCursor tc = EDITOR(cursorForPosition(QPoint(0, EDITOR(height()))));
  2207. setCursor(tc);
  2208. moveUp(qMax(count(), 1));
  2209. handleStartOfLine();
  2210. finishMovement();
  2211. } else if (input.isControl('l')) {
  2212. // screen redraw. should not be needed
  2213. } else if (input.is('m')) {
  2214. m_subsubmode = MarkSubSubMode;
  2215. } else if (input.is('M')) {
  2216. QTextCursor tc = EDITOR(cursorForPosition(QPoint(0, EDITOR(height()) / 2)));
  2217. setCursor(tc);
  2218. handleStartOfLine();
  2219. finishMovement();
  2220. } else if (input.is('n') || input.is('N')) {
  2221. if (hasConfig(ConfigUseCoreSearch)) {
  2222. bool forward = (input.is('n')) ? m_lastSearchForward : !m_lastSearchForward;
  2223. int pos = position();
  2224. emit q->findNextRequested(!forward);
  2225. if (forward && pos == cursor().selectionStart()) {
  2226. // if cursor is already positioned at the start of a find result, this is returned
  2227. emit q->findNextRequested(false);
  2228. }
  2229. setPosition(cursor().selectionStart());
  2230. } else {
  2231. SearchData sd;
  2232. sd.needle = g.searchHistory.current();
  2233. sd.forward = input.is('n') ? m_lastSearchForward : !m_lastSearchForward;
  2234. sd.highlightCursor = false;
  2235. sd.highlightMatches = true;
  2236. search(sd);
  2237. }
  2238. } else if (isVisualMode() && (input.is('o') || input.is('O'))) {
  2239. int pos = position();
  2240. setAnchorAndPosition(pos, anchor());
  2241. std::swap(m_marks['<'], m_marks['>']);
  2242. std::swap(m_positionPastEnd, m_anchorPastEnd);
  2243. setTargetColumn();
  2244. if (m_positionPastEnd)
  2245. m_visualTargetColumn = -1;
  2246. updateSelection();
  2247. } else if (input.is('o')) {
  2248. setDotCommand("%1o", count());
  2249. setUndoPosition(position());
  2250. breakEditBlock();
  2251. enterInsertMode();
  2252. beginEditBlock(position());
  2253. moveToFirstNonBlankOnLine();
  2254. moveBehindEndOfLine();
  2255. insertText(Register("\n"));
  2256. insertAutomaticIndentation(true);
  2257. endEditBlock();
  2258. } else if (input.is('O')) {
  2259. setDotCommand("%1O", count());
  2260. setUndoPosition(position());
  2261. breakEditBlock();
  2262. enterInsertMode();
  2263. beginEditBlock(position());
  2264. moveToFirstNonBlankOnLine();
  2265. moveToStartOfLine();
  2266. insertText(Register("\n"));
  2267. moveUp();
  2268. insertAutomaticIndentation(false);
  2269. endEditBlock();
  2270. } else if (input.isControl('o')) {
  2271. if (!m_jumpListUndo.isEmpty()) {
  2272. m_jumpListRedo.append(cursorPosition());
  2273. setCursorPosition(m_jumpListUndo.last());
  2274. m_jumpListUndo.pop_back();
  2275. }
  2276. } else if (input.is('p') || input.is('P')) {
  2277. pasteText(input.is('p'));
  2278. setTargetColumn();
  2279. setDotCommand("%1p", count());
  2280. finishMovement();
  2281. } else if (input.is('r')) {
  2282. m_submode = ReplaceSubMode;
  2283. } else if (!isVisualMode() && input.is('R')) {
  2284. setUndoPosition(position());
  2285. breakEditBlock();
  2286. enterReplaceMode();
  2287. updateMiniBuffer();
  2288. } else if (input.isControl('r')) {
  2289. redo();
  2290. } else if (input.is('s') && isVisualBlockMode()) {
  2291. Range range(position(), anchor(), RangeBlockMode);
  2292. int beginLine = lineForPosition(anchor());
  2293. int endLine = lineForPosition(position());
  2294. m_visualInsertCount = qAbs(endLine - beginLine);
  2295. setPosition(qMin(position(), anchor()));
  2296. yankText(range, m_register);
  2297. removeText(range);
  2298. setDotCommand("%1s", count());
  2299. setUndoPosition(position());
  2300. breakEditBlock();
  2301. enterInsertMode();
  2302. } else if (input.is('s')) {
  2303. leaveVisualMode();
  2304. if (atEndOfLine())
  2305. moveLeft();
  2306. setAnchor();
  2307. moveRight(qMin(count(), rightDist()));
  2308. yankText(currentRange(), m_register);
  2309. removeText(currentRange());
  2310. setDotCommand("%1s", count());
  2311. m_opcount.clear();
  2312. m_mvcount.clear();
  2313. setUndoPosition(position());
  2314. breakEditBlock();
  2315. enterInsertMode();
  2316. } else if (input.is('S')) {
  2317. beginEditBlock();
  2318. if (!isVisualMode()) {
  2319. const int line = cursorLine() + 1;
  2320. const int anc = firstPositionInLine(line);
  2321. const int pos = lastPositionInLine(line + count() - 1);
  2322. setAnchorAndPosition(anc, pos);
  2323. }
  2324. setDotCommand("%1S", count());
  2325. setUndoPosition(position());
  2326. breakEditBlock();
  2327. enterInsertMode();
  2328. m_submode = ChangeSubMode;
  2329. m_movetype = MoveLineWise;
  2330. endEditBlock();
  2331. finishMovement();
  2332. } else if (m_gflag && input.is('t')) {
  2333. m_gflag = false;
  2334. handleExCommand("tabnext");
  2335. } else if (input.is('t')) {
  2336. m_movetype = MoveInclusive;
  2337. m_subsubmode = FtSubSubMode;
  2338. m_subsubdata = input;
  2339. } else if (m_gflag && input.is('T')) {
  2340. m_gflag = false;
  2341. handleExCommand("tabprev");
  2342. } else if (input.is('T')) {
  2343. m_movetype = MoveExclusive;
  2344. m_subsubmode = FtSubSubMode;
  2345. m_subsubdata = input;
  2346. } else if (input.isControl('t')) {
  2347. handleExCommand("pop");
  2348. } else if (!m_gflag && input.is('u')) {
  2349. undo();
  2350. } else if (input.isControl('u')) {
  2351. int sline = cursorLineOnScreen();
  2352. // FIXME: this should use the "scroll" option, and "count"
  2353. moveUp(linesOnScreen() / 2);
  2354. handleStartOfLine();
  2355. scrollToLine(cursorLine() - sline);
  2356. finishMovement();
  2357. } else if (input.is('v')) {
  2358. toggleVisualMode(VisualCharMode);
  2359. } else if (input.is('V')) {
  2360. toggleVisualMode(VisualLineMode);
  2361. } else if (input.isControl('v')) {
  2362. toggleVisualMode(VisualBlockMode);
  2363. } else if (input.is('w')) { // tested
  2364. // Special case: "cw" and "cW" work the same as "ce" and "cE" if the
  2365. // cursor is on a non-blank - except if the cursor is on the last
  2366. // character of a word: only the current word will be changed
  2367. if (m_submode == ChangeSubMode) {
  2368. moveToWordBoundary(false, true, true);
  2369. setTargetColumn();
  2370. m_movetype = MoveInclusive;
  2371. } else {
  2372. moveToNextWord(false, m_submode == DeleteSubMode);
  2373. m_movetype = MoveExclusive;
  2374. }
  2375. finishMovement("%1w", count());
  2376. } else if (input.is('W')) {
  2377. if (m_submode == ChangeSubMode) {
  2378. moveToWordBoundary(true, true, true);
  2379. setTargetColumn();
  2380. m_movetype = MoveInclusive;
  2381. } else {
  2382. moveToNextWord(true, m_submode == DeleteSubMode);
  2383. m_movetype = MoveExclusive;
  2384. }
  2385. finishMovement("%1W", count());
  2386. } else if (input.isControl('w')) {
  2387. m_submode = WindowSubMode;
  2388. } else if (input.is('x') && isNoVisualMode()) { // = "dl"
  2389. m_movetype = MoveExclusive;
  2390. m_submode = DeleteSubMode;
  2391. const int n = qMin(count(), rightDist());
  2392. setAnchorAndPosition(position(), position() + n);
  2393. setDotCommand("%1x", count());
  2394. finishMovement();
  2395. } else if (input.is('X')) {
  2396. if (leftDist() > 0) {
  2397. setAnchor();
  2398. moveLeft(qMin(count(), leftDist()));
  2399. yankText(currentRange(), m_register);
  2400. removeText(currentRange());
  2401. }
  2402. finishMovement();
  2403. } else if ((m_submode == YankSubMode && input.is('y'))
  2404. || (input.is('Y') && isNoVisualMode())) {
  2405. setAnchor();
  2406. if (count() > 1)
  2407. moveDown(count()-1);
  2408. m_rangemode = RangeLineMode;
  2409. m_movetype = MoveLineWise;
  2410. m_submode = YankSubMode;
  2411. finishMovement();
  2412. } else if (input.isControl('y')) {
  2413. // FIXME: this should use the "scroll" option, and "count"
  2414. if (cursorLineOnScreen() == linesOnScreen() - 1)
  2415. moveUp(1);
  2416. scrollUp(1);
  2417. finishMovement();
  2418. } else if (input.is('y') && isNoVisualMode()) {
  2419. setAnchor();
  2420. m_submode = YankSubMode;
  2421. } else if (input.is('y') && isVisualCharMode()) {
  2422. Range range(position(), anchor(), RangeCharMode);
  2423. range.endPos++; // MoveInclusive
  2424. yankText(range, m_register);
  2425. setPosition(qMin(position(), anchor()));
  2426. leaveVisualMode();
  2427. finishMovement();
  2428. } else if ((input.is('y') && isVisualLineMode())
  2429. || (input.is('Y') && isVisualLineMode())
  2430. || (input.is('Y') && isVisualCharMode())) {
  2431. m_rangemode = RangeLineMode;
  2432. yankText(currentRange(), m_register);
  2433. setPosition(qMin(position(), anchor()));
  2434. moveToStartOfLine();
  2435. leaveVisualMode();
  2436. finishMovement();
  2437. } else if ((input.is('y') || input.is('Y')) && isVisualBlockMode()) {
  2438. m_rangemode = RangeBlockMode;
  2439. yankText(currentRange(), m_register);
  2440. setPosition(qMin(position(), anchor()));
  2441. leaveVisualMode();
  2442. finishMovement();
  2443. } else if (input.is('z')) {
  2444. m_submode = ZSubMode;
  2445. } else if (input.is('Z')) {
  2446. m_submode = CapitalZSubMode;
  2447. } else if (!m_gflag && input.is('~') && !isVisualMode()) {
  2448. m_movetype = MoveExclusive;
  2449. if (!atEndOfLine()) {
  2450. beginEditBlock();
  2451. setAnchor();
  2452. moveRight(qMin(count(), rightDist()));
  2453. if (input.is('~')) {
  2454. invertCase(currentRange());
  2455. setDotCommand("%1~", count());
  2456. } else if (input.is('u')) {
  2457. downCase(currentRange());
  2458. setDotCommand("%1gu", count());
  2459. } else if (input.is('U')) {
  2460. upCase(currentRange());
  2461. setDotCommand("%1gU", count());
  2462. }
  2463. endEditBlock();
  2464. }
  2465. finishMovement();
  2466. } else if ((m_gflag && input.is('~') && !isVisualMode())
  2467. || (m_gflag && input.is('u') && !isVisualMode())
  2468. || (m_gflag && input.is('U') && !isVisualMode())) {
  2469. m_gflag = false;
  2470. m_movetype = MoveExclusive;
  2471. if (atEndOfLine())
  2472. moveLeft();
  2473. setAnchor();
  2474. m_submode = TransformSubMode;
  2475. if (input.is('~'))
  2476. m_subsubmode = InvertCaseSubSubMode;
  2477. if (input.is('u'))
  2478. m_subsubmode = DownCaseSubSubMode;
  2479. else if (input.is('U'))
  2480. m_subsubmode = UpCaseSubSubMode;
  2481. } else if ((input.is('~') && isVisualMode())
  2482. || (m_gflag && input.is('u') && isVisualMode())
  2483. || (m_gflag && input.is('U') && isVisualMode())) {
  2484. m_gflag = false;
  2485. m_movetype = MoveExclusive;
  2486. if (isVisualLineMode())
  2487. m_rangemode = RangeLineMode;
  2488. else if (isVisualBlockMode())
  2489. m_rangemode = RangeBlockMode;
  2490. leaveVisualMode();
  2491. m_submode = TransformSubMode;
  2492. if (input.is('~'))
  2493. m_subsubmode = InvertCaseSubSubMode;
  2494. else if (input.is('u'))
  2495. m_subsubmode = DownCaseSubSubMode;
  2496. else if (input.is('U'))
  2497. m_subsubmode = UpCaseSubSubMode;
  2498. finishMovement();
  2499. } else if (input.is('[')) {
  2500. m_submode = OpenSquareSubMode;
  2501. } else if (input.is(']')) {
  2502. m_submode = CloseSquareSubMode;
  2503. } else if (input.isKey(Key_PageDown) || input.isControl('f')) {
  2504. moveDown(count() * (linesOnScreen() - 2) - cursorLineOnScreen());
  2505. scrollToLine(cursorLine());
  2506. handleStartOfLine();
  2507. finishMovement();
  2508. } else if (input.isKey(Key_PageUp) || input.isControl('b')) {
  2509. moveUp(count() * (linesOnScreen() - 2) + cursorLineOnScreen());
  2510. scrollToLine(cursorLine() + linesOnScreen() - 2);
  2511. handleStartOfLine();
  2512. finishMovement();
  2513. } else if (input.isKey(Key_Delete)) {
  2514. setAnchor();
  2515. moveRight(qMin(1, rightDist()));
  2516. removeText(currentRange());
  2517. if (atEndOfLine())
  2518. moveLeft();
  2519. } else if (input.isKey(Key_BracketLeft) || input.isKey(Key_BracketRight)) {
  2520. } else if (input.isControl(Key_BracketRight)) {
  2521. handleExCommand("tag");
  2522. } else {
  2523. //qDebug() << "IGNORED IN COMMAND MODE: " << key << text
  2524. // << " VISUAL: " << m_visualMode;
  2525. // if a key which produces text was pressed, don't mark it as unhandled
  2526. // - otherwise the text would be inserted while being in command mode
  2527. if (input.text().isEmpty()) {
  2528. handled = EventUnhandled;
  2529. }
  2530. }
  2531. m_positionPastEnd = (m_visualTargetColumn == -1) && isVisualMode();
  2532. return handled;
  2533. }
  2534. EventResult FakeVimHandler::Private::handleReplaceMode(const Input &input)
  2535. {
  2536. if (input.isEscape()) {
  2537. moveLeft(qMin(1, leftDist()));
  2538. setTargetColumn();
  2539. m_submode = NoSubMode;
  2540. m_mode = CommandMode;
  2541. finishMovement();
  2542. } else if (input.isKey(Key_Left)) {
  2543. breakEditBlock();
  2544. moveLeft(1);
  2545. setTargetColumn();
  2546. } else if (input.isKey(Key_Right)) {
  2547. breakEditBlock();
  2548. moveRight(1);
  2549. setTargetColumn();
  2550. } else if (input.isKey(Key_Up)) {
  2551. breakEditBlock();
  2552. moveUp(1);
  2553. setTargetColumn();
  2554. } else if (input.isKey(Key_Down)) {
  2555. breakEditBlock();
  2556. moveDown(1);
  2557. } else {
  2558. joinPreviousEditBlock();
  2559. if (!atEndOfLine()) {
  2560. setAnchor();
  2561. moveRight();
  2562. m_lastDeletion += selectText(Range(position(), anchor()));
  2563. removeText(currentRange());
  2564. }
  2565. const QString text = input.text();
  2566. m_lastInsertion += text;
  2567. setAnchor();
  2568. insertText(text);
  2569. endEditBlock();
  2570. }
  2571. return EventHandled;
  2572. }
  2573. EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
  2574. {
  2575. //const int key = input.key;
  2576. //const QString &text = input.text;
  2577. if (input.isEscape()) {
  2578. if (isVisualBlockMode() && !m_lastInsertion.contains('\n')) {
  2579. leaveVisualMode();
  2580. joinPreviousEditBlock();
  2581. moveLeft(m_lastInsertion.size());
  2582. setAnchor();
  2583. int pos = position();
  2584. setTargetColumn();
  2585. for (int i = 0; i < m_visualInsertCount; ++i) {
  2586. moveDown();
  2587. insertText(m_lastInsertion);
  2588. }
  2589. moveLeft(1);
  2590. Range range(pos, position(), RangeBlockMode);
  2591. yankText(range);
  2592. setPosition(pos);
  2593. setDotCommand("p");
  2594. endEditBlock();
  2595. } else {
  2596. // Normal insertion. Start with '1', as one instance was
  2597. // already physically inserted while typing.
  2598. QString data;
  2599. for (int i = 1; i < count(); ++i)
  2600. data += m_lastInsertion;
  2601. insertText(data);
  2602. moveLeft(qMin(1, leftDist()));
  2603. setTargetColumn();
  2604. leaveVisualMode();
  2605. }
  2606. g.dotCommand += m_lastInsertion;
  2607. g.dotCommand += QChar(27);
  2608. enterCommandMode();
  2609. m_submode = NoSubMode;
  2610. m_ctrlVActive = false;
  2611. m_opcount.clear();
  2612. m_mvcount.clear();
  2613. } else if (m_ctrlVActive) {
  2614. insertInInsertMode(input.raw());
  2615. } else if (input.isControl('v')) {
  2616. m_ctrlVActive = true;
  2617. } else if (input.isControl('w')) {
  2618. int endPos = position();
  2619. moveToWordBoundary(false, false, false);
  2620. setTargetColumn();
  2621. int beginPos = position();
  2622. Range range(beginPos, endPos, RangeCharMode);
  2623. removeText(range);
  2624. } else if (input.isKey(Key_Insert)) {
  2625. if (m_mode == ReplaceMode)
  2626. m_mode = InsertMode;
  2627. else
  2628. m_mode = ReplaceMode;
  2629. } else if (input.isKey(Key_Left)) {
  2630. moveLeft(count());
  2631. setTargetColumn();
  2632. m_lastInsertion.clear();
  2633. } else if (input.isControl(Key_Left)) {
  2634. moveToWordBoundary(false, false);
  2635. setTargetColumn();
  2636. m_lastInsertion.clear();
  2637. } else if (input.isKey(Key_Down)) {
  2638. //removeAutomaticIndentation();
  2639. m_submode = NoSubMode;
  2640. moveDown(count());
  2641. m_lastInsertion.clear();
  2642. } else if (input.isKey(Key_Up)) {
  2643. //removeAutomaticIndentation();
  2644. m_submode = NoSubMode;
  2645. moveUp(count());
  2646. m_lastInsertion.clear();
  2647. } else if (input.isKey(Key_Right)) {
  2648. moveRight(count());
  2649. setTargetColumn();
  2650. m_lastInsertion.clear();
  2651. } else if (input.isControl(Key_Right)) {
  2652. moveToWordBoundary(false, true);
  2653. moveRight(); // we need one more move since we are in insert mode
  2654. setTargetColumn();
  2655. m_lastInsertion.clear();
  2656. } else if (input.isKey(Key_Home)) {
  2657. moveToStartOfLine();
  2658. setTargetColumn();
  2659. m_lastInsertion.clear();
  2660. } else if (input.isKey(Key_End)) {
  2661. if (count() > 1)
  2662. moveDown(count() - 1);
  2663. moveBehindEndOfLine();
  2664. setTargetColumn();
  2665. m_lastInsertion.clear();
  2666. } else if (input.isReturn()) {
  2667. m_submode = NoSubMode;
  2668. insertText(Register("\n"));
  2669. m_lastInsertion += '\n';
  2670. insertAutomaticIndentation(true);
  2671. setTargetColumn();
  2672. } else if (input.isBackspace()) {
  2673. joinPreviousEditBlock();
  2674. m_justAutoIndented = 0;
  2675. if (!m_lastInsertion.isEmpty() || hasConfig(ConfigBackspace, "start")) {
  2676. const int line = cursorLine() + 1;
  2677. const Column col = cursorColumn();
  2678. QString data = lineContents(line);
  2679. const Column ind = indentation(data);
  2680. if (col.logical <= ind.logical && col.logical
  2681. && startsWithWhitespace(data, col.physical)) {
  2682. const int ts = config(ConfigTabStop).toInt();
  2683. const int newl = col.logical - 1 - (col.logical - 1) % ts;
  2684. const QString prefix = tabExpand(newl);
  2685. setLineContents(line, prefix + data.mid(col.physical));
  2686. moveToStartOfLine();
  2687. moveRight(prefix.size());
  2688. m_lastInsertion.clear(); // FIXME
  2689. } else {
  2690. setAnchor();
  2691. cursor().deletePreviousChar();
  2692. m_lastInsertion.chop(1);
  2693. }
  2694. setTargetColumn();
  2695. }
  2696. endEditBlock();
  2697. } else if (input.isKey(Key_Delete)) {
  2698. setAnchor();
  2699. cursor().deleteChar();
  2700. m_lastInsertion.clear();
  2701. } else if (input.isKey(Key_PageDown) || input.isControl('f')) {
  2702. removeAutomaticIndentation();
  2703. moveDown(count() * (linesOnScreen() - 2));
  2704. m_lastInsertion.clear();
  2705. } else if (input.isKey(Key_PageUp) || input.isControl('b')) {
  2706. removeAutomaticIndentation();
  2707. moveUp(count() * (linesOnScreen() - 2));
  2708. m_lastInsertion.clear();
  2709. } else if (input.isKey(Key_Tab)) {
  2710. m_justAutoIndented = 0;
  2711. if (hasConfig(ConfigExpandTab)) {
  2712. const int ts = config(ConfigTabStop).toInt();
  2713. const int col = logicalCursorColumn();
  2714. QString str = QString(ts - col % ts, ' ');
  2715. m_lastInsertion.append(str);
  2716. insertText(str);
  2717. setTargetColumn();
  2718. } else {
  2719. insertInInsertMode(input.raw());
  2720. }
  2721. } else if (input.isControl('d')) {
  2722. // remove one level of indentation from the current line
  2723. int shift = config(ConfigShiftWidth).toInt();
  2724. int tab = config(ConfigTabStop).toInt();
  2725. int line = cursorLine() + 1;
  2726. int pos = firstPositionInLine(line);
  2727. QString text = lineContents(line);
  2728. int amount = 0;
  2729. int i = 0;
  2730. for (; i < text.size() && amount < shift; ++i) {
  2731. if (text.at(i) == ' ')
  2732. ++amount;
  2733. else if (text.at(i) == '\t')
  2734. amount += tab; // FIXME: take position into consideration
  2735. else
  2736. break;
  2737. }
  2738. removeText(Range(pos, pos+i));
  2739. //} else if (key >= control('a') && key <= control('z')) {
  2740. // // ignore these
  2741. } else if (input.isControl('p') || input.isControl('n')) {
  2742. QTextCursor tc = EDITOR(textCursor());
  2743. moveToWordBoundary(false, false);
  2744. QString str = selectText(Range(position(), tc.position()));
  2745. EDITOR(setTextCursor(tc));
  2746. emit q->simpleCompletionRequested(str, input.isControl('n'));
  2747. } else if (!input.text().isEmpty()) {
  2748. insertInInsertMode(input.text());
  2749. } else {
  2750. // We don't want fancy stuff in insert mode.
  2751. return EventHandled;
  2752. }
  2753. updateMiniBuffer();
  2754. return EventHandled;
  2755. }
  2756. void FakeVimHandler::Private::insertInInsertMode(const QString &text)
  2757. {
  2758. joinPreviousEditBlock();
  2759. m_justAutoIndented = 0;
  2760. m_lastInsertion.append(text);
  2761. insertText(text);
  2762. if (hasConfig(ConfigSmartIndent) && isElectricCharacter(text.at(0))) {
  2763. const QString leftText = block().text()
  2764. .left(position() - 1 - block().position());
  2765. if (leftText.simplified().isEmpty()) {
  2766. Range range(position(), position(), m_rangemode);
  2767. indentText(range, text.at(0));
  2768. }
  2769. }
  2770. setTargetColumn();
  2771. endEditBlock();
  2772. m_ctrlVActive = false;
  2773. }
  2774. EventResult FakeVimHandler::Private::handleExMode(const Input &input)
  2775. {
  2776. if (input.isEscape()) {
  2777. m_commandBuffer.clear();
  2778. enterCommandMode();
  2779. updateMiniBuffer();
  2780. m_ctrlVActive = false;
  2781. } else if (m_ctrlVActive) {
  2782. m_commandBuffer.insertChar(input.raw());
  2783. m_ctrlVActive = false;
  2784. } else if (input.isControl('v')) {
  2785. m_ctrlVActive = true;
  2786. } else if (input.isBackspace()) {
  2787. if (m_commandBuffer.isEmpty()) {
  2788. m_commandPrefix.clear();
  2789. enterCommandMode();
  2790. } else {
  2791. m_commandBuffer.deleteChar();
  2792. }
  2793. updateMiniBuffer();
  2794. } else if (input.isKey(Key_Tab)) {
  2795. QStringList completions;
  2796. foreach (const QString &entry, g.commandHistory.items()) {
  2797. if (entry.startsWith(m_commandBuffer.contents()))
  2798. completions.append(entry);
  2799. }
  2800. qDebug() << completions;
  2801. } else if (input.isKey(Key_Left)) {
  2802. m_commandBuffer.moveLeft();
  2803. updateMiniBuffer();
  2804. } else if (input.isReturn()) {
  2805. if (!m_commandBuffer.isEmpty()) {
  2806. //g.commandHistory.takeLast();
  2807. g.commandHistory.append(m_commandBuffer.contents());
  2808. handleExCommand(m_commandBuffer.contents());
  2809. if (m_textedit || m_plaintextedit)
  2810. leaveVisualMode();
  2811. }
  2812. updateMiniBuffer();
  2813. } else if (input.isKey(Key_Up) || input.isKey(Key_PageUp)) {
  2814. g.commandHistory.up();
  2815. m_commandBuffer.setContents(g.commandHistory.current());
  2816. updateMiniBuffer();
  2817. } else if (input.isKey(Key_Down) || input.isKey(Key_PageDown)) {
  2818. g.commandHistory.down();
  2819. m_commandBuffer.setContents(g.commandHistory.current());
  2820. updateMiniBuffer();
  2821. } else if (m_commandBuffer.handleInput(input)) {
  2822. updateMiniBuffer();
  2823. } else {
  2824. qDebug() << "IGNORED IN EX-MODE: " << input.key() << input.text();
  2825. return EventUnhandled;
  2826. }
  2827. return EventHandled;
  2828. }
  2829. EventResult FakeVimHandler::Private::handleSearchSubSubMode(const Input &input)
  2830. {
  2831. if (input.isEscape()) {
  2832. m_commandBuffer.clear();
  2833. g.searchHistory.append(m_searchCursor.selectedText());
  2834. m_searchCursor = QTextCursor();
  2835. updateSelection();
  2836. enterCommandMode();
  2837. updateMiniBuffer();
  2838. } else if (input.isBackspace()) {
  2839. if (m_commandBuffer.isEmpty()) {
  2840. m_commandPrefix.clear();
  2841. m_searchCursor = QTextCursor();
  2842. enterCommandMode();
  2843. } else {
  2844. m_commandBuffer.deleteChar();
  2845. }
  2846. updateMiniBuffer();
  2847. } else if (input.isKey(Key_Left)) {
  2848. m_commandBuffer.moveLeft();
  2849. updateMiniBuffer();
  2850. } else if (input.isKey(Key_Right)) {
  2851. m_commandBuffer.moveRight();
  2852. updateMiniBuffer();
  2853. } else if (input.isReturn()) {
  2854. m_searchCursor = QTextCursor();
  2855. QString needle = m_commandBuffer.contents();
  2856. if (!needle.isEmpty()) {
  2857. g.searchHistory.append(needle);
  2858. if (!hasConfig(ConfigIncSearch)) {
  2859. SearchData sd;
  2860. sd.needle = needle;
  2861. sd.forward = m_lastSearchForward;
  2862. sd.highlightCursor = false;
  2863. sd.highlightMatches = true;
  2864. search(sd);
  2865. }
  2866. finishMovement(m_commandPrefix + needle + '\n');
  2867. }
  2868. enterCommandMode();
  2869. highlightMatches(needle);
  2870. updateMiniBuffer();
  2871. } else if (input.isKey(Key_Up) || input.isKey(Key_PageUp)) {
  2872. // FIXME: This and the three cases below are wrong as vim
  2873. // takes only matching entries in the history into account.
  2874. g.searchHistory.up();
  2875. showBlackMessage(g.searchHistory.current());
  2876. } else if (input.isKey(Key_Down) || input.isKey(Key_PageDown)) {
  2877. g.searchHistory.down();
  2878. showBlackMessage(g.searchHistory.current());
  2879. } else if (input.isKey(Key_Tab)) {
  2880. m_commandBuffer.insertChar(QChar(9));
  2881. updateMiniBuffer();
  2882. } else if (m_commandBuffer.handleInput(input)) {
  2883. updateMiniBuffer();
  2884. }
  2885. if (hasConfig(ConfigIncSearch) && !input.isReturn() && !input.isEscape()) {
  2886. SearchData sd;
  2887. sd.needle = m_commandBuffer.contents();
  2888. sd.forward = m_lastSearchForward;
  2889. sd.mustMove = false;
  2890. sd.highlightCursor = true;
  2891. sd.highlightMatches = false;
  2892. search(sd);
  2893. }
  2894. //else {
  2895. // qDebug() << "IGNORED IN SEARCH MODE: " << input.key() << input.text();
  2896. // return EventUnhandled;
  2897. //}
  2898. return EventHandled;
  2899. }
  2900. // This uses 1 based line counting.
  2901. int FakeVimHandler::Private::readLineCode(QString &cmd)
  2902. {
  2903. //qDebug() << "CMD: " << cmd;
  2904. if (cmd.isEmpty())
  2905. return -1;
  2906. QChar c = cmd.at(0);
  2907. cmd = cmd.mid(1);
  2908. if (c == '.') {
  2909. if (cmd.isEmpty())
  2910. return cursorLine() + 1;
  2911. QChar c1 = cmd.at(0);
  2912. if (c1 == '+' || c1 == '-') {
  2913. // Repeat for things like .+4
  2914. cmd = cmd.mid(1);
  2915. return cursorLine() + readLineCode(cmd);
  2916. }
  2917. return cursorLine() + 1;
  2918. }
  2919. if (c == '$')
  2920. return linesInDocument();
  2921. if (c == '\'' && !cmd.isEmpty()) {
  2922. if (cmd.isEmpty()) {
  2923. showRedMessage(msgMarkNotSet(QString()));
  2924. return -1;
  2925. }
  2926. int m = mark(cmd.at(0).unicode());
  2927. if (m == -1) {
  2928. showRedMessage(msgMarkNotSet(cmd.at(0)));
  2929. cmd = cmd.mid(1);
  2930. return -1;
  2931. }
  2932. cmd = cmd.mid(1);
  2933. return lineForPosition(m);
  2934. }
  2935. if (c == '-') {
  2936. int n = readLineCode(cmd);
  2937. return cursorLine() + 1 - (n == -1 ? 1 : n);
  2938. }
  2939. if (c == '+') {
  2940. int n = readLineCode(cmd);
  2941. return cursorLine() + 1 + (n == -1 ? 1 : n);
  2942. }
  2943. if (c == '\'' && !cmd.isEmpty()) {
  2944. int pos = mark(cmd.at(0).unicode());
  2945. if (pos == -1) {
  2946. showRedMessage(msgMarkNotSet(cmd.at(0)));
  2947. cmd = cmd.mid(1);
  2948. return -1;
  2949. }
  2950. cmd = cmd.mid(1);
  2951. return lineForPosition(pos);
  2952. }
  2953. if (c.isDigit()) {
  2954. int n = c.unicode() - '0';
  2955. while (!cmd.isEmpty()) {
  2956. c = cmd.at(0);
  2957. if (!c.isDigit())
  2958. break;
  2959. cmd = cmd.mid(1);
  2960. n = n * 10 + (c.unicode() - '0');
  2961. }
  2962. //qDebug() << "N: " << n;
  2963. return n;
  2964. }
  2965. // Parsing failed.
  2966. cmd = c + cmd;
  2967. return -1;
  2968. }
  2969. void FakeVimHandler::Private::setCurrentRange(const Range &range)
  2970. {
  2971. setAnchorAndPosition(range.beginPos, range.endPos);
  2972. m_rangemode = range.rangemode;
  2973. }
  2974. Range FakeVimHandler::Private::rangeFromCurrentLine() const
  2975. {
  2976. Range range;
  2977. int line = cursorLine() + 1;
  2978. range.beginPos = firstPositionInLine(line);
  2979. range.endPos = lastPositionInLine(line) + 1;
  2980. return range;
  2981. }
  2982. // use handleExCommand for invoking commands that might move the cursor
  2983. void FakeVimHandler::Private::handleCommand(const QString &cmd)
  2984. {
  2985. handleExCommand(cmd);
  2986. }
  2987. bool FakeVimHandler::Private::handleExSubstituteCommand(const ExCommand &cmd)
  2988. // :substitute
  2989. {
  2990. QString line = cmd.cmd + ' ' + cmd.args;
  2991. line = line.trimmed();
  2992. if (line.startsWith(_("substitute")))
  2993. line = line.mid(10);
  2994. else if (line.startsWith('s') && line.size() > 1
  2995. && !isalpha(line.at(1).unicode()))
  2996. line = line.mid(1);
  2997. else
  2998. return false;
  2999. // we have /{pattern}/{string}/[flags] now
  3000. if (line.isEmpty())
  3001. return false;
  3002. const QChar separator = line.at(0);
  3003. int pos1 = -1;
  3004. int pos2 = -1;
  3005. int i;
  3006. for (i = 1; i < line.size(); ++i) {
  3007. if (line.at(i) == separator && line.at(i - 1) != '\\') {
  3008. pos1 = i;
  3009. break;
  3010. }
  3011. }
  3012. if (pos1 == -1)
  3013. return false;
  3014. for (++i; i < line.size(); ++i) {
  3015. if (line.at(i) == separator && line.at(i - 1) != '\\') {
  3016. pos2 = i;
  3017. break;
  3018. }
  3019. }
  3020. if (pos2 == -1)
  3021. pos2 = line.size();
  3022. QString needle = line.mid(1, pos1 - 1);
  3023. const QString replacement = line.mid(pos1 + 1, pos2 - pos1 - 1);
  3024. QString flags = line.mid(pos2 + 1);
  3025. needle.replace('$', '\n');
  3026. needle.replace("\\\n", "\\$");
  3027. QRegExp pattern(needle);
  3028. if (flags.contains('i'))
  3029. pattern.setCaseSensitivity(Qt::CaseInsensitive);
  3030. const bool global = flags.contains('g');
  3031. const Range range = cmd.range.endPos == 0 ? rangeFromCurrentLine() : cmd.range;
  3032. const int beginLine = lineForPosition(range.beginPos);
  3033. const int endLine = lineForPosition(range.endPos);
  3034. beginEditBlock();
  3035. for (int line = endLine; line >= beginLine; --line) {
  3036. QString origText = lineContents(line);
  3037. QString text = origText;
  3038. int pos = 0;
  3039. while (true) {
  3040. pos = pattern.indexIn(text, pos, QRegExp::CaretAtZero);
  3041. if (pos == -1)
  3042. break;
  3043. if (pattern.cap(0).isEmpty())
  3044. break;
  3045. QStringList caps = pattern.capturedTexts();
  3046. QString matched = text.mid(pos, caps.at(0).size());
  3047. QString repl = replacement;
  3048. for (int i = 1; i < caps.size(); ++i)
  3049. repl.replace("\\" + QString::number(i), caps.at(i));
  3050. for (int i = 0; i < repl.size(); ++i) {
  3051. if (repl.at(i) == '&' && (i == 0 || repl.at(i - 1) != '\\')) {
  3052. repl.replace(i, 1, caps.at(0));
  3053. i += caps.at(0).size();
  3054. }
  3055. }
  3056. text = text.left(pos) + repl + text.mid(pos + matched.size());
  3057. pos += repl.size();
  3058. if (!global)
  3059. break;
  3060. }
  3061. if (text != origText)
  3062. setLineContents(line, text);
  3063. }
  3064. endEditBlock();
  3065. return true;
  3066. }
  3067. bool FakeVimHandler::Private::handleExMapCommand(const ExCommand &cmd0) // :map
  3068. {
  3069. QByteArray modes;
  3070. enum Type { Map, Noremap, Unmap } type;
  3071. QByteArray cmd = cmd0.cmd.toLatin1();
  3072. // Strange formatting. But everything else is even uglier.
  3073. if (cmd == "map") { modes = "nvo"; type = Map; } else
  3074. if (cmd == "nm" || cmd == "nmap") { modes = "n"; type = Map; } else
  3075. if (cmd == "vm" || cmd == "vmap") { modes = "v"; type = Map; } else
  3076. if (cmd == "xm" || cmd == "xmap") { modes = "x"; type = Map; } else
  3077. if (cmd == "smap") { modes = "s"; type = Map; } else
  3078. if (cmd == "map!") { modes = "ic"; type = Map; } else
  3079. if (cmd == "im" || cmd == "imap") { modes = "i"; type = Map; } else
  3080. if (cmd == "lm" || cmd == "lmap") { modes = "l"; type = Map; } else
  3081. if (cmd == "cm" || cmd == "cmap") { modes = "c"; type = Map; } else
  3082. if (cmd == "no" || cmd == "noremap") { modes = "nvo"; type = Noremap; } else
  3083. if (cmd == "nn" || cmd == "nnoremap") { modes = "n"; type = Noremap; } else
  3084. if (cmd == "vn" || cmd == "vnoremap") { modes = "v"; type = Noremap; } else
  3085. if (cmd == "xn" || cmd == "xnoremap") { modes = "x"; type = Noremap; } else
  3086. if (cmd == "snor" || cmd == "snoremap") { modes = "s"; type = Noremap; } else
  3087. if (cmd == "ono" || cmd == "onoremap") { modes = "o"; type = Noremap; } else
  3088. if (cmd == "no!" || cmd == "noremap!") { modes = "ic"; type = Noremap; } else
  3089. if (cmd == "ino" || cmd == "inoremap") { modes = "i"; type = Noremap; } else
  3090. if (cmd == "ln" || cmd == "lnoremap") { modes = "l"; type = Noremap; } else
  3091. if (cmd == "cno" || cmd == "cnoremap") { modes = "c"; type = Noremap; } else
  3092. if (cmd == "unm" || cmd == "unmap") { modes = "nvo"; type = Unmap; } else
  3093. if (cmd == "nun" || cmd == "nunmap") { modes = "n"; type = Unmap; } else
  3094. if (cmd == "vu" || cmd == "vunmap") { modes = "v"; type = Unmap; } else
  3095. if (cmd == "xu" || cmd == "xunmap") { modes = "x"; type = Unmap; } else
  3096. if (cmd == "sunm" || cmd == "sunmap") { modes = "s"; type = Unmap; } else
  3097. if (cmd == "ou" || cmd == "ounmap") { modes = "o"; type = Unmap; } else
  3098. if (cmd == "unm!" || cmd == "unmap!") { modes = "ic"; type = Unmap; } else
  3099. if (cmd == "iu" || cmd == "iunmap") { modes = "i"; type = Unmap; } else
  3100. if (cmd == "lu" || cmd == "lunmap") { modes = "l"; type = Unmap; } else
  3101. if (cmd == "cu" || cmd == "cunmap") { modes = "c"; type = Unmap; }
  3102. else
  3103. return false;
  3104. const int pos = cmd0.args.indexOf(QLatin1Char(' '));
  3105. if (pos == -1) {
  3106. // FIXME: Dump mappings here.
  3107. //qDebug() << g.mappings;
  3108. return true;
  3109. }
  3110. QString lhs = cmd0.args.left(pos);
  3111. QString rhs = cmd0.args.mid(pos + 1);
  3112. Inputs key;
  3113. key.parseFrom(lhs);
  3114. //qDebug() << "MAPPING: " << modes << lhs << rhs;
  3115. switch (type) {
  3116. case Unmap:
  3117. foreach (char c, modes)
  3118. if (g.mappings.contains(c))
  3119. g.mappings[c].remove(key);
  3120. break;
  3121. case Map:
  3122. rhs = rhs; // FIXME: expand rhs.
  3123. // Fall through.
  3124. case Noremap: {
  3125. Inputs inputs(rhs);
  3126. foreach (char c, modes)
  3127. g.mappings[c].insert(key, inputs);
  3128. break;
  3129. }
  3130. }
  3131. return true;
  3132. }
  3133. bool FakeVimHandler::Private::handleExHistoryCommand(const ExCommand &cmd)
  3134. {
  3135. // :his[tory]
  3136. if (!cmd.matches("his", "history"))
  3137. return false;
  3138. if (cmd.args.isEmpty()) {
  3139. QString info;
  3140. info += "# command history\n";
  3141. int i = 0;
  3142. foreach (const QString &item, g.commandHistory.items()) {
  3143. ++i;
  3144. info += QString("%1 %2\n").arg(i, -8).arg(item);
  3145. }
  3146. emit q->extraInformationChanged(info);
  3147. } else {
  3148. notImplementedYet();
  3149. }
  3150. updateMiniBuffer();
  3151. return true;
  3152. }
  3153. bool FakeVimHandler::Private::handleExRegisterCommand(const ExCommand &cmd)
  3154. {
  3155. // :reg[isters] and :di[splay]
  3156. if (!cmd.matches("reg", "registers") && !cmd.matches("di", "display"))
  3157. return false;
  3158. QByteArray regs = cmd.args.toLatin1();
  3159. if (regs.isEmpty()) {
  3160. regs = "\"0123456789";
  3161. QHashIterator<int, Register> it(g.registers);
  3162. while (it.hasNext()) {
  3163. it.next();
  3164. if (it.key() > '9')
  3165. regs += char(it.key());
  3166. }
  3167. }
  3168. QString info;
  3169. info += "--- Registers ---\n";
  3170. foreach (char reg, regs) {
  3171. QString value = quoteUnprintable(g.registers[reg].contents);
  3172. info += QString("\"%1 %2\n").arg(reg).arg(value);
  3173. }
  3174. emit q->extraInformationChanged(info);
  3175. updateMiniBuffer();
  3176. return true;
  3177. }
  3178. bool FakeVimHandler::Private::handleExSetCommand(const ExCommand &cmd)
  3179. {
  3180. // :se[t]
  3181. if (!cmd.matches("se", "set"))
  3182. return false;
  3183. showBlackMessage(QString());
  3184. SavedAction *act = theFakeVimSettings()->item(cmd.args);
  3185. QTC_CHECK(!cmd.args.isEmpty()); // Handled by plugin.
  3186. if (act && act->value().type() == QVariant::Bool) {
  3187. // Boolean config to be switched on.
  3188. bool oldValue = act->value().toBool();
  3189. if (oldValue == false)
  3190. act->setValue(true);
  3191. else if (oldValue == true)
  3192. {} // nothing to do
  3193. } else if (act) {
  3194. // Non-boolean to show.
  3195. showBlackMessage(cmd.args + '=' + act->value().toString());
  3196. } else if (cmd.args.startsWith(_("no"))
  3197. && (act = theFakeVimSettings()->item(cmd.args.mid(2)))) {
  3198. // Boolean config to be switched off.
  3199. bool oldValue = act->value().toBool();
  3200. if (oldValue == true)
  3201. act->setValue(false);
  3202. else if (oldValue == false)
  3203. {} // nothing to do
  3204. } else if (cmd.args.contains('=')) {
  3205. // Non-boolean config to set.
  3206. int p = cmd.args.indexOf('=');
  3207. act = theFakeVimSettings()->item(cmd.args.left(p));
  3208. if (act)
  3209. act->setValue(cmd.args.mid(p + 1));
  3210. } else {
  3211. showRedMessage(FakeVimHandler::tr("Unknown option: ") + cmd.args);
  3212. }
  3213. updateMiniBuffer();
  3214. updateEditor();
  3215. return true;
  3216. }
  3217. bool FakeVimHandler::Private::handleExNormalCommand(const ExCommand &cmd)
  3218. {
  3219. // :norm[al]
  3220. if (!cmd.matches("norm", "normal"))
  3221. return false;
  3222. //qDebug() << "REPLAY NORMAL: " << quoteUnprintable(reNormal.cap(3));
  3223. replay(cmd.args, 1);
  3224. return true;
  3225. }
  3226. bool FakeVimHandler::Private::handleExDeleteCommand(const ExCommand &cmd)
  3227. {
  3228. // :d[elete]
  3229. if (!cmd.matches("d", "delete"))
  3230. return false;
  3231. Range range = cmd.range.endPos == 0 ? rangeFromCurrentLine() : cmd.range;
  3232. setCurrentRange(range);
  3233. QString reg = cmd.args;
  3234. QString text = selectText(range);
  3235. removeText(currentRange());
  3236. if (!reg.isEmpty()) {
  3237. Register &r = g.registers[reg.at(0).unicode()];
  3238. r.contents = text;
  3239. r.rangemode = RangeLineMode;
  3240. }
  3241. return true;
  3242. }
  3243. bool FakeVimHandler::Private::handleExWriteCommand(const ExCommand &cmd)
  3244. {
  3245. // :w, :x, :wq, ...
  3246. //static QRegExp reWrite("^[wx]q?a?!?( (.*))?$");
  3247. if (cmd.cmd != "w" && cmd.cmd != "x" && cmd.cmd != "wq")
  3248. return false;
  3249. int beginLine = lineForPosition(cmd.range.beginPos);
  3250. int endLine = lineForPosition(cmd.range.endPos);
  3251. const bool noArgs = (beginLine == -1);
  3252. if (beginLine == -1)
  3253. beginLine = 0;
  3254. if (endLine == -1)
  3255. endLine = linesInDocument();
  3256. //qDebug() << "LINES: " << beginLine << endLine;
  3257. QString prefix = cmd.args;
  3258. const bool forced = cmd.hasBang;
  3259. //const bool quit = prefix.contains(QChar('q')) || prefix.contains(QChar('x'));
  3260. //const bool quitAll = quit && prefix.contains(QChar('a'));
  3261. QString fileName = cmd.args;
  3262. if (fileName.isEmpty())
  3263. fileName = m_currentFileName;
  3264. QFile file1(fileName);
  3265. const bool exists = file1.exists();
  3266. if (exists && !forced && !noArgs) {
  3267. showRedMessage(FakeVimHandler::tr
  3268. ("File \"%1\" exists (add ! to override)").arg(fileName));
  3269. } else if (file1.open(QIODevice::ReadWrite)) {
  3270. // Nobody cared, so act ourselves.
  3271. file1.close();
  3272. Range range(firstPositionInLine(beginLine),
  3273. firstPositionInLine(endLine), RangeLineMode);
  3274. QString contents = selectText(range);
  3275. QFile::remove(fileName);
  3276. QFile file2(fileName);
  3277. if (file2.open(QIODevice::ReadWrite)) {
  3278. QTextStream ts(&file2);
  3279. ts << contents;
  3280. } else {
  3281. showRedMessage(FakeVimHandler::tr
  3282. ("Cannot open file \"%1\" for writing").arg(fileName));
  3283. }
  3284. // Check result by reading back.
  3285. QFile file3(fileName);
  3286. file3.open(QIODevice::ReadOnly);
  3287. QByteArray ba = file3.readAll();
  3288. showBlackMessage(FakeVimHandler::tr("\"%1\" %2 %3L, %4C written")
  3289. .arg(fileName).arg(exists ? " " : tr(" [New] "))
  3290. .arg(ba.count('\n')).arg(ba.size()));
  3291. //if (quitAll)
  3292. // passUnknownExCommand(forced ? "qa!" : "qa");
  3293. //else if (quit)
  3294. // passUnknownExCommand(forced ? "q!" : "q");
  3295. } else {
  3296. showRedMessage(FakeVimHandler::tr
  3297. ("Cannot open file \"%1\" for reading").arg(fileName));
  3298. }
  3299. return true;
  3300. }
  3301. bool FakeVimHandler::Private::handleExReadCommand(const ExCommand &cmd)
  3302. {
  3303. // :r[ead]
  3304. if (!cmd.matches("r", "read"))
  3305. return false;
  3306. beginEditBlock();
  3307. moveToStartOfLine();
  3308. setTargetColumn();
  3309. moveDown();
  3310. m_currentFileName = cmd.args;
  3311. QFile file(m_currentFileName);
  3312. file.open(QIODevice::ReadOnly);
  3313. QTextStream ts(&file);
  3314. QString data = ts.readAll();
  3315. insertText(data);
  3316. endEditBlock();
  3317. showBlackMessage(FakeVimHandler::tr("\"%1\" %2L, %3C")
  3318. .arg(m_currentFileName).arg(data.count('\n')).arg(data.size()));
  3319. return true;
  3320. }
  3321. bool FakeVimHandler::Private::handleExBangCommand(const ExCommand &cmd) // :!
  3322. {
  3323. if (!cmd.cmd.startsWith(QLatin1Char('!')))
  3324. return false;
  3325. setCurrentRange(cmd.range);
  3326. int targetPosition = firstPositionInLine(lineForPosition(cmd.range.beginPos));
  3327. QString command = QString(cmd.cmd.mid(1) + ' ' + cmd.args).trimmed();
  3328. QString text = selectText(cmd.range);
  3329. QProcess proc;
  3330. proc.start(command);
  3331. proc.waitForStarted();
  3332. #ifdef Q_OS_WIN
  3333. text.replace(_("\n"), _("\r\n"));
  3334. #endif
  3335. proc.write(text.toUtf8());
  3336. proc.closeWriteChannel();
  3337. proc.waitForFinished();
  3338. QString result = QString::fromUtf8(proc.readAllStandardOutput());
  3339. beginEditBlock(targetPosition);
  3340. removeText(currentRange());
  3341. insertText(result);
  3342. setPosition(targetPosition);
  3343. endEditBlock();
  3344. leaveVisualMode();
  3345. //qDebug() << "FILTER: " << command;
  3346. showBlackMessage(FakeVimHandler::tr("%n lines filtered", 0,
  3347. text.count('\n')));
  3348. return true;
  3349. }
  3350. bool FakeVimHandler::Private::handleExShiftCommand(const ExCommand &cmd)
  3351. {
  3352. if (cmd.cmd != "<" && cmd.cmd != ">")
  3353. return false;
  3354. Range range = cmd.range;
  3355. if (cmd.range.endPos == 0) {
  3356. range = rangeFromCurrentLine();
  3357. --range.endPos;
  3358. }
  3359. setCurrentRange(range);
  3360. int count = qMax(1, cmd.args.toInt());
  3361. if (cmd.cmd == "<")
  3362. shiftRegionLeft(count);
  3363. else
  3364. shiftRegionRight(count);
  3365. leaveVisualMode();
  3366. const int beginLine = lineForPosition(range.beginPos);
  3367. const int endLine = lineForPosition(range.endPos);
  3368. showBlackMessage(FakeVimHandler::tr("%n lines %1ed %2 time", 0,
  3369. (endLine - beginLine + 1)).arg(cmd.cmd).arg(count));
  3370. return true;
  3371. }
  3372. bool FakeVimHandler::Private::handleExNohlsearchCommand(const ExCommand &cmd)
  3373. {
  3374. // :nohlsearch
  3375. if (!cmd.cmd.startsWith("noh"))
  3376. return false;
  3377. m_searchSelections.clear();
  3378. updateSelection();
  3379. return true;
  3380. }
  3381. bool FakeVimHandler::Private::handleExRedoCommand(const ExCommand &cmd)
  3382. {
  3383. // :redo
  3384. if (cmd.cmd != "red" && cmd.cmd != "redo")
  3385. return false;
  3386. redo();
  3387. updateMiniBuffer();
  3388. return true;
  3389. }
  3390. bool FakeVimHandler::Private::handleExGotoCommand(const ExCommand &cmd)
  3391. {
  3392. // :<nr>
  3393. if (!cmd.cmd.isEmpty())
  3394. return false;
  3395. const int beginLine = lineForPosition(cmd.range.beginPos);
  3396. setPosition(firstPositionInLine(beginLine));
  3397. showBlackMessage(QString());
  3398. return true;
  3399. }
  3400. bool FakeVimHandler::Private::handleExSourceCommand(const ExCommand &cmd)
  3401. {
  3402. // :source
  3403. if (cmd.cmd != "so" && cmd.cmd != "source")
  3404. return false;
  3405. QString fileName = cmd.args;
  3406. QFile file(fileName);
  3407. if (!file.open(QIODevice::ReadOnly)) {
  3408. showRedMessage(FakeVimHandler::tr("Cannot open file %1").arg(fileName));
  3409. return true;
  3410. }
  3411. bool inFunction = false;
  3412. while (!file.atEnd()) {
  3413. QByteArray line = file.readLine();
  3414. line = line.trimmed();
  3415. if (line.startsWith("function")) {
  3416. //qDebug() << "IGNORING FUNCTION" << line;
  3417. inFunction = true;
  3418. } else if (inFunction && line.startsWith("endfunction")) {
  3419. inFunction = false;
  3420. } else if (line.startsWith("function")) {
  3421. //qDebug() << "IGNORING FUNCTION" << line;
  3422. inFunction = true;
  3423. } else if (line.startsWith('"')) {
  3424. // A comment.
  3425. } else if (!line.isEmpty() && !inFunction) {
  3426. //qDebug() << "EXECUTING: " << line;
  3427. handleExCommandHelper(QString::fromUtf8(line));
  3428. }
  3429. }
  3430. file.close();
  3431. return true;
  3432. }
  3433. bool FakeVimHandler::Private::handleExEchoCommand(const ExCommand &cmd)
  3434. {
  3435. // :echo
  3436. if (cmd.cmd != "echo")
  3437. return false;
  3438. m_currentMessage = cmd.args;
  3439. return true;
  3440. }
  3441. void FakeVimHandler::Private::handleExCommand(const QString &line0)
  3442. {
  3443. QString line = line0; // Make sure we have a copy to prevent aliasing.
  3444. // FIXME: that seems to be different for %w and %s
  3445. if (line.startsWith(QLatin1Char('%')))
  3446. line = "1,$" + line.mid(1);
  3447. const int beginLine = readLineCode(line);
  3448. int endLine = -1;
  3449. if (line.startsWith(',')) {
  3450. line = line.mid(1);
  3451. endLine = readLineCode(line);
  3452. }
  3453. if (beginLine != -1 && endLine == -1)
  3454. endLine = beginLine;
  3455. const int beginPos = firstPositionInLine(beginLine);
  3456. const int endPos = lastPositionInLine(endLine);
  3457. ExCommand cmd;
  3458. const QString arg0 = line.section(' ', 0, 0);
  3459. cmd.cmd = arg0;
  3460. cmd.args = line.mid(arg0.size() + 1).trimmed();
  3461. cmd.range = Range(beginPos, endPos, RangeLineMode);
  3462. cmd.hasBang = arg0.endsWith('!');
  3463. if (cmd.hasBang)
  3464. cmd.cmd.chop(1);
  3465. if (beginLine != -1)
  3466. cmd.count = beginLine;
  3467. //qDebug() << "CMD: " << cmd;
  3468. enterCommandMode();
  3469. showBlackMessage(QString());
  3470. if (!handleExCommandHelper(cmd))
  3471. showRedMessage(tr("Not an editor command: %1").arg(cmd.cmd));
  3472. }
  3473. bool FakeVimHandler::Private::handleExCommandHelper(const ExCommand &cmd)
  3474. {
  3475. return handleExPluginCommand(cmd)
  3476. || handleExGotoCommand(cmd)
  3477. || handleExBangCommand(cmd)
  3478. || handleExHistoryCommand(cmd)
  3479. || handleExRegisterCommand(cmd)
  3480. || handleExDeleteCommand(cmd)
  3481. || handleExMapCommand(cmd)
  3482. || handleExNohlsearchCommand(cmd)
  3483. || handleExNormalCommand(cmd)
  3484. || handleExReadCommand(cmd)
  3485. || handleExRedoCommand(cmd)
  3486. || handleExSetCommand(cmd)
  3487. || handleExShiftCommand(cmd)
  3488. || handleExSourceCommand(cmd)
  3489. || handleExSubstituteCommand(cmd)
  3490. || handleExWriteCommand(cmd)
  3491. || handleExEchoCommand(cmd);
  3492. }
  3493. bool FakeVimHandler::Private::handleExPluginCommand(const ExCommand &cmd)
  3494. {
  3495. bool handled = false;
  3496. emit q->handleExCommandRequested(&handled, cmd);
  3497. //qDebug() << "HANDLER REQUEST: " << cmd.cmd << handled;
  3498. return handled;
  3499. }
  3500. static QRegExp vimPatternToQtPattern(QString needle, QTextDocument::FindFlags *flags)
  3501. {
  3502. // FIXME: Rough mapping of a common case.
  3503. if (needle.startsWith(_("\\<")) && needle.endsWith(_("\\>")))
  3504. (*flags) |= QTextDocument::FindWholeWords;
  3505. // Half-hearted attempt at removing pitfalls.
  3506. if (needle.startsWith(_(".*")))
  3507. needle = needle.mid(2);
  3508. if (needle.endsWith(_(".*")))
  3509. needle = needle.left(needle.size() - 2);
  3510. needle.remove(_("\\<")); // start of word
  3511. needle.remove(_("\\>")); // end of word
  3512. // QRegExp's | and \| have the opposite meaning of vim's.
  3513. QString dummy(QLatin1Char(1));
  3514. needle.replace(_("\\|"), dummy);
  3515. needle.replace(_("|"), _("\\|"));
  3516. needle.replace(dummy, _("|"));
  3517. //qDebug() << "NEEDLE " << needle << needle;
  3518. return QRegExp(needle);
  3519. }
  3520. void FakeVimHandler::Private::searchBalanced(bool forward, QChar needle, QChar other)
  3521. {
  3522. int level = 1;
  3523. int pos = position();
  3524. const int npos = forward ? lastPositionInDocument() : 0;
  3525. while (true) {
  3526. if (forward)
  3527. ++pos;
  3528. else
  3529. --pos;
  3530. if (pos == npos)
  3531. return;
  3532. QChar c = document()->characterAt(pos);
  3533. if (c == other)
  3534. ++level;
  3535. else if (c == needle)
  3536. --level;
  3537. if (level == 0) {
  3538. const int oldLine = cursorLine() - cursorLineOnScreen();
  3539. // Making this unconditional feels better, but is not "vim like".
  3540. if (oldLine != cursorLine() - cursorLineOnScreen())
  3541. scrollToLine(cursorLine() - linesOnScreen() / 2);
  3542. setTargetColumn();
  3543. updateSelection();
  3544. recordJump();
  3545. return;
  3546. }
  3547. }
  3548. }
  3549. void FakeVimHandler::Private::search(const SearchData &sd)
  3550. {
  3551. if (sd.needle.isEmpty())
  3552. return;
  3553. const bool incSearch = hasConfig(ConfigIncSearch);
  3554. QTextDocument::FindFlags flags = QTextDocument::FindCaseSensitively;
  3555. if (!sd.forward)
  3556. flags |= QTextDocument::FindBackward;
  3557. QRegExp needleExp = vimPatternToQtPattern(sd.needle, &flags);
  3558. const int oldLine = cursorLine() - cursorLineOnScreen();
  3559. int startPos = position();
  3560. if (sd.mustMove)
  3561. sd.forward ? ++startPos : --startPos;
  3562. m_searchCursor = QTextCursor();
  3563. QTextCursor tc = document()->find(needleExp, startPos, flags);
  3564. if (tc.isNull()) {
  3565. int startPos = sd.forward ? 0 : lastPositionInDocument();
  3566. tc = document()->find(needleExp, startPos, flags);
  3567. if (tc.isNull()) {
  3568. if (!incSearch) {
  3569. highlightMatches(QString());
  3570. showRedMessage(FakeVimHandler::tr("Pattern not found: %1")
  3571. .arg(needleExp.pattern()));
  3572. }
  3573. updateSelection();
  3574. return;
  3575. }
  3576. if (!incSearch) {
  3577. QString msg = sd.forward
  3578. ? FakeVimHandler::tr("search hit BOTTOM, continuing at TOP")
  3579. : FakeVimHandler::tr("search hit TOP, continuing at BOTTOM");
  3580. showRedMessage(msg);
  3581. }
  3582. }
  3583. // Set Cursor. In contrast to the main editor we have the cursor
  3584. // position before the anchor position.
  3585. setAnchorAndPosition(tc.position(), tc.anchor());
  3586. // Making this unconditional feels better, but is not "vim like".
  3587. if (oldLine != cursorLine() - cursorLineOnScreen())
  3588. scrollToLine(cursorLine() - linesOnScreen() / 2);
  3589. if (incSearch && sd.highlightCursor)
  3590. m_searchCursor = cursor();
  3591. setTargetColumn();
  3592. if (sd.highlightMatches)
  3593. highlightMatches(sd.needle);
  3594. updateSelection();
  3595. recordJump();
  3596. }
  3597. void FakeVimHandler::Private::highlightMatches(const QString &needle)
  3598. {
  3599. if (!hasConfig(ConfigHlSearch))
  3600. return;
  3601. if (needle == m_oldNeedle)
  3602. return;
  3603. m_oldNeedle = needle;
  3604. m_searchSelections.clear();
  3605. if (!needle.isEmpty()) {
  3606. QTextCursor tc = cursor();
  3607. tc.movePosition(StartOfDocument, MoveAnchor);
  3608. QTextDocument::FindFlags flags = QTextDocument::FindCaseSensitively;
  3609. QRegExp needleExp = vimPatternToQtPattern(needle, &flags);
  3610. while (!tc.atEnd()) {
  3611. tc = tc.document()->find(needleExp, tc.position(), flags);
  3612. if (tc.isNull())
  3613. break;
  3614. QTextEdit::ExtraSelection sel;
  3615. sel.cursor = tc;
  3616. sel.format = tc.blockCharFormat();
  3617. sel.format.setBackground(QColor(177, 177, 0));
  3618. m_searchSelections.append(sel);
  3619. if (document()->characterAt(tc.position()) == ParagraphSeparator)
  3620. tc.movePosition(Right, MoveAnchor);
  3621. }
  3622. }
  3623. updateSelection();
  3624. }
  3625. void FakeVimHandler::Private::moveToFirstNonBlankOnLine()
  3626. {
  3627. QTextDocument *doc = document();
  3628. int firstPos = block().position();
  3629. for (int i = firstPos, n = firstPos + block().length(); i < n; ++i) {
  3630. if (!doc->characterAt(i).isSpace() || i == n - 1) {
  3631. setPosition(i);
  3632. return;
  3633. }
  3634. }
  3635. setPosition(block().position());
  3636. }
  3637. void FakeVimHandler::Private::indentSelectedText(QChar typedChar)
  3638. {
  3639. setTargetColumn();
  3640. int beginLine = qMin(lineForPosition(position()), lineForPosition(anchor()));
  3641. int endLine = qMax(lineForPosition(position()), lineForPosition(anchor()));
  3642. Range range(anchor(), position(), m_rangemode);
  3643. indentText(range, typedChar);
  3644. setPosition(firstPositionInLine(beginLine));
  3645. handleStartOfLine();
  3646. setTargetColumn();
  3647. setDotCommand("%1==", endLine - beginLine + 1);
  3648. }
  3649. void FakeVimHandler::Private::indentText(const Range &range, QChar typedChar)
  3650. {
  3651. int beginLine = lineForPosition(range.beginPos);
  3652. int endLine = lineForPosition(range.endPos);
  3653. if (beginLine > endLine)
  3654. qSwap(beginLine, endLine);
  3655. // LineForPosition has returned 1-based line numbers.
  3656. emit q->indentRegion(beginLine - 1, endLine - 1, typedChar);
  3657. if (beginLine != endLine)
  3658. showBlackMessage("MARKS ARE OFF NOW");
  3659. }
  3660. bool FakeVimHandler::Private::isElectricCharacter(QChar c) const
  3661. {
  3662. bool result = false;
  3663. emit q->checkForElectricCharacter(&result, c);
  3664. return result;
  3665. }
  3666. void FakeVimHandler::Private::shiftRegionRight(int repeat)
  3667. {
  3668. int beginLine = lineForPosition(anchor());
  3669. int endLine = lineForPosition(position());
  3670. int targetPos = anchor();
  3671. if (beginLine > endLine) {
  3672. qSwap(beginLine, endLine);
  3673. targetPos = position();
  3674. }
  3675. if (hasConfig(ConfigStartOfLine))
  3676. targetPos = firstPositionInLine(beginLine);
  3677. const int sw = config(ConfigShiftWidth).toInt();
  3678. beginEditBlock(targetPos);
  3679. for (int line = beginLine; line <= endLine; ++line) {
  3680. QString data = lineContents(line);
  3681. const Column col = indentation(data);
  3682. data = tabExpand(col.logical + sw * repeat) + data.mid(col.physical);
  3683. setLineContents(line, data);
  3684. }
  3685. endEditBlock();
  3686. setPosition(targetPos);
  3687. handleStartOfLine();
  3688. setTargetColumn();
  3689. setDotCommand("%1>>", endLine - beginLine + 1);
  3690. }
  3691. void FakeVimHandler::Private::shiftRegionLeft(int repeat)
  3692. {
  3693. int beginLine = lineForPosition(anchor());
  3694. int endLine = lineForPosition(position());
  3695. int targetPos = anchor();
  3696. if (beginLine > endLine) {
  3697. qSwap(beginLine, endLine);
  3698. targetPos = position();
  3699. }
  3700. const int shift = config(ConfigShiftWidth).toInt() * repeat;
  3701. const int tab = config(ConfigTabStop).toInt();
  3702. if (hasConfig(ConfigStartOfLine))
  3703. targetPos = firstPositionInLine(beginLine);
  3704. beginEditBlock(targetPos);
  3705. for (int line = endLine; line >= beginLine; --line) {
  3706. int pos = firstPositionInLine(line);
  3707. const QString text = lineContents(line);
  3708. int amount = 0;
  3709. int i = 0;
  3710. for (; i < text.size() && amount < shift; ++i) {
  3711. if (text.at(i) == ' ')
  3712. amount++;
  3713. else if (text.at(i) == '\t')
  3714. amount += tab; // FIXME: take position into consideration
  3715. else
  3716. break;
  3717. }
  3718. removeText(Range(pos, pos + i));
  3719. setPosition(pos);
  3720. }
  3721. endEditBlock();
  3722. setPosition(targetPos);
  3723. handleStartOfLine();
  3724. setTargetColumn();
  3725. setDotCommand("%1<<", endLine - beginLine + 1);
  3726. }
  3727. void FakeVimHandler::Private::moveToTargetColumn()
  3728. {
  3729. const QTextBlock &bl = block();
  3730. //Column column = cursorColumn();
  3731. //int logical = logical
  3732. const int maxcol = bl.length() - 2;
  3733. if (m_targetColumn == -1) {
  3734. setPosition(bl.position() + qMax(0, maxcol));
  3735. return;
  3736. }
  3737. const int physical = logicalToPhysicalColumn(m_targetColumn, bl.text());
  3738. //qDebug() << "CORRECTING COLUMN FROM: " << logical << "TO" << m_targetColumn;
  3739. if (physical >= maxcol)
  3740. setPosition(bl.position() + qMax(0, maxcol));
  3741. else
  3742. setPosition(bl.position() + physical);
  3743. }
  3744. /* if simple is given:
  3745. * class 0: spaces
  3746. * class 1: non-spaces
  3747. * else
  3748. * class 0: spaces
  3749. * class 1: non-space-or-letter-or-number
  3750. * class 2: letter-or-number
  3751. */
  3752. int FakeVimHandler::Private::charClass(QChar c, bool simple) const
  3753. {
  3754. if (simple)
  3755. return c.isSpace() ? 0 : 1;
  3756. // FIXME: This means that only characters < 256 in the
  3757. // ConfigIsKeyword setting are handled properly.
  3758. if (c.unicode() < 256) {
  3759. //int old = (c.isLetterOrNumber() || c.unicode() == '_') ? 2
  3760. // : c.isSpace() ? 0 : 1;
  3761. //qDebug() << c.unicode() << old << m_charClass[c.unicode()];
  3762. return m_charClass[c.unicode()];
  3763. }
  3764. if (c.isLetterOrNumber() || c.unicode() == '_')
  3765. return 2;
  3766. return c.isSpace() ? 0 : 1;
  3767. }
  3768. // Helper to parse a-z,A-Z,48-57,_
  3769. static int someInt(const QString &str)
  3770. {
  3771. if (str.toInt())
  3772. return str.toInt();
  3773. if (str.size())
  3774. return str.at(0).unicode();
  3775. return 0;
  3776. }
  3777. void FakeVimHandler::Private::setupCharClass()
  3778. {
  3779. for (int i = 0; i < 256; ++i) {
  3780. const QChar c = QChar(QLatin1Char(i));
  3781. m_charClass[i] = c.isSpace() ? 0 : 1;
  3782. }
  3783. const QString conf = config(ConfigIsKeyword).toString();
  3784. foreach (const QString &part, conf.split(QLatin1Char(','))) {
  3785. if (part.contains(QLatin1Char('-'))) {
  3786. const int from = someInt(part.section(QLatin1Char('-'), 0, 0));
  3787. const int to = someInt(part.section(QLatin1Char('-'), 1, 1));
  3788. for (int i = qMax(0, from); i <= qMin(255, to); ++i)
  3789. m_charClass[i] = 2;
  3790. } else {
  3791. m_charClass[qMin(255, someInt(part))] = 2;
  3792. }
  3793. }
  3794. }
  3795. void FakeVimHandler::Private::moveToWordBoundary(bool simple, bool forward, bool changeWord)
  3796. {
  3797. int repeat = count();
  3798. QTextDocument *doc = document();
  3799. int n = forward ? lastPositionInDocument() : 0;
  3800. int lastClass = -1;
  3801. if (changeWord) {
  3802. lastClass = charClass(characterAtCursor(), simple);
  3803. --repeat;
  3804. if (changeWord && block().length() == 1) // empty line
  3805. --repeat;
  3806. }
  3807. while (repeat >= 0) {
  3808. QChar c = doc->characterAt(position() + (forward ? 1 : -1));
  3809. int thisClass = charClass(c, simple);
  3810. if (thisClass != lastClass && (lastClass != 0 || changeWord))
  3811. --repeat;
  3812. if (repeat == -1)
  3813. break;
  3814. lastClass = thisClass;
  3815. if (position() == n)
  3816. break;
  3817. forward ? moveRight() : moveLeft();
  3818. if (changeWord && block().length() == 1) // empty line
  3819. --repeat;
  3820. if (repeat == -1)
  3821. break;
  3822. }
  3823. }
  3824. bool FakeVimHandler::Private::handleFfTt(QString key)
  3825. {
  3826. int key0 = key.size() == 1 ? key.at(0).unicode() : 0;
  3827. int oldPos = position();
  3828. // m_subsubmode \in { 'f', 'F', 't', 'T' }
  3829. bool forward = m_subsubdata.is('f') || m_subsubdata.is('t');
  3830. int repeat = count();
  3831. QTextDocument *doc = document();
  3832. int n = block().position();
  3833. if (forward)
  3834. n += block().length();
  3835. int pos = position();
  3836. while (pos != n) {
  3837. pos += forward ? 1 : -1;
  3838. if (pos == n)
  3839. break;
  3840. int uc = doc->characterAt(pos).unicode();
  3841. if (uc == ParagraphSeparator)
  3842. break;
  3843. if (uc == key0)
  3844. --repeat;
  3845. if (repeat == 0) {
  3846. if (m_subsubdata.is('t'))
  3847. --pos;
  3848. else if (m_subsubdata.is('T'))
  3849. ++pos;
  3850. if (forward)
  3851. moveRight(pos - position());
  3852. else
  3853. moveLeft(position() - pos);
  3854. break;
  3855. }
  3856. }
  3857. if (repeat == 0) {
  3858. setTargetColumn();
  3859. return true;
  3860. }
  3861. setPosition(oldPos);
  3862. return false;
  3863. }
  3864. void FakeVimHandler::Private::moveToNextWord(bool simple, bool deleteWord)
  3865. {
  3866. int repeat = count();
  3867. int n = lastPositionInDocument();
  3868. int lastClass = charClass(characterAtCursor(), simple);
  3869. while (true) {
  3870. QChar c = characterAtCursor();
  3871. int thisClass = charClass(c, simple);
  3872. if (thisClass != lastClass && thisClass != 0)
  3873. --repeat;
  3874. if (repeat == 0)
  3875. break;
  3876. lastClass = thisClass;
  3877. moveRight();
  3878. if (deleteWord) {
  3879. if (atBlockEnd())
  3880. --repeat;
  3881. } else {
  3882. if (block().length() == 1) // empty line
  3883. --repeat;
  3884. }
  3885. if (repeat == 0)
  3886. break;
  3887. if (position() == n)
  3888. break;
  3889. }
  3890. setTargetColumn();
  3891. }
  3892. void FakeVimHandler::Private::moveToMatchingParanthesis()
  3893. {
  3894. bool moved = false;
  3895. bool forward = false;
  3896. const int anc = anchor();
  3897. QTextCursor tc = cursor();
  3898. emit q->moveToMatchingParenthesis(&moved, &forward, &tc);
  3899. if (moved && forward)
  3900. tc.movePosition(Left, KeepAnchor, 1);
  3901. setAnchorAndPosition(anc, tc.position());
  3902. setTargetColumn();
  3903. }
  3904. int FakeVimHandler::Private::cursorLineOnScreen() const
  3905. {
  3906. if (!editor())
  3907. return 0;
  3908. QRect rect = EDITOR(cursorRect());
  3909. return rect.y() / rect.height();
  3910. }
  3911. int FakeVimHandler::Private::linesOnScreen() const
  3912. {
  3913. if (!editor())
  3914. return 1;
  3915. QRect rect = EDITOR(cursorRect());
  3916. return EDITOR(height()) / rect.height();
  3917. }
  3918. int FakeVimHandler::Private::columnsOnScreen() const
  3919. {
  3920. if (!editor())
  3921. return 1;
  3922. QRect rect = EDITOR(cursorRect());
  3923. // qDebug() << "WID: " << EDITOR(width()) << "RECT: " << rect;
  3924. return EDITOR(width()) / rect.width();
  3925. }
  3926. int FakeVimHandler::Private::cursorLine() const
  3927. {
  3928. return block().blockNumber();
  3929. }
  3930. int FakeVimHandler::Private::physicalCursorColumn() const
  3931. {
  3932. return position() - block().position();
  3933. }
  3934. int FakeVimHandler::Private::physicalToLogicalColumn
  3935. (const int physical, const QString &line) const
  3936. {
  3937. const int ts = config(ConfigTabStop).toInt();
  3938. int p = 0;
  3939. int logical = 0;
  3940. while (p < physical) {
  3941. QChar c = line.at(p);
  3942. //if (c == QLatin1Char(' '))
  3943. // ++logical;
  3944. //else
  3945. if (c == QLatin1Char('\t'))
  3946. logical += ts - logical % ts;
  3947. else
  3948. ++logical;
  3949. //break;
  3950. ++p;
  3951. }
  3952. return logical;
  3953. }
  3954. int FakeVimHandler::Private::logicalToPhysicalColumn
  3955. (const int logical, const QString &line) const
  3956. {
  3957. const int ts = config(ConfigTabStop).toInt();
  3958. int physical = 0;
  3959. for (int l = 0; l < logical && physical < line.size(); ++physical) {
  3960. QChar c = line.at(physical);
  3961. if (c == QLatin1Char('\t'))
  3962. l += ts - l % ts;
  3963. else
  3964. ++l;
  3965. }
  3966. return physical;
  3967. }
  3968. int FakeVimHandler::Private::logicalCursorColumn() const
  3969. {
  3970. const int physical = physicalCursorColumn();
  3971. const QString line = block().text();
  3972. return physicalToLogicalColumn(physical, line);
  3973. }
  3974. Column FakeVimHandler::Private::cursorColumn() const
  3975. {
  3976. return Column(physicalCursorColumn(), logicalCursorColumn());
  3977. }
  3978. int FakeVimHandler::Private::linesInDocument() const
  3979. {
  3980. if (cursor().isNull())
  3981. return 0;
  3982. const int count = document()->blockCount();
  3983. // Qt inserts an empty line if the last character is a '\n',
  3984. // but that's not how vi does it.
  3985. return document()->lastBlock().length() <= 1 ? count - 1 : count;
  3986. }
  3987. void FakeVimHandler::Private::scrollToLine(int line)
  3988. {
  3989. // FIXME: works only for QPlainTextEdit
  3990. QScrollBar *scrollBar = EDITOR(verticalScrollBar());
  3991. //qDebug() << "SCROLL: " << scrollBar->value() << line;
  3992. scrollBar->setValue(line);
  3993. //QTC_CHECK(firstVisibleLine() == line);
  3994. }
  3995. int FakeVimHandler::Private::firstVisibleLine() const
  3996. {
  3997. QScrollBar *scrollBar = EDITOR(verticalScrollBar());
  3998. if (0 && scrollBar->value() != cursorLine() - cursorLineOnScreen()) {
  3999. qDebug() << "SCROLLBAR: " << scrollBar->value()
  4000. << "CURSORLINE IN DOC" << cursorLine()
  4001. << "CURSORLINE ON SCREEN" << cursorLineOnScreen();
  4002. }
  4003. //return scrollBar->value();
  4004. return cursorLine() - cursorLineOnScreen();
  4005. }
  4006. void FakeVimHandler::Private::scrollUp(int count)
  4007. {
  4008. scrollToLine(cursorLine() - cursorLineOnScreen() - count);
  4009. }
  4010. int FakeVimHandler::Private::lastPositionInDocument() const
  4011. {
  4012. QTextBlock block = document()->lastBlock();
  4013. return block.position() + block.length() - 1;
  4014. }
  4015. QString FakeVimHandler::Private::selectText(const Range &range) const
  4016. {
  4017. if (range.rangemode == RangeCharMode) {
  4018. QTextCursor tc = cursor();
  4019. tc.setPosition(range.beginPos, MoveAnchor);
  4020. tc.setPosition(range.endPos, KeepAnchor);
  4021. return tc.selection().toPlainText();
  4022. }
  4023. if (range.rangemode == RangeLineMode) {
  4024. QTextCursor tc = cursor();
  4025. int firstPos = firstPositionInLine(lineForPosition(range.beginPos));
  4026. int lastLine = lineForPosition(range.endPos);
  4027. bool endOfDoc = lastLine == document()->lastBlock().blockNumber() + 1;
  4028. int lastPos = endOfDoc ? lastPositionInDocument() : firstPositionInLine(lastLine + 1);
  4029. tc.setPosition(firstPos, MoveAnchor);
  4030. tc.setPosition(lastPos, KeepAnchor);
  4031. return tc.selection().toPlainText() + QString((endOfDoc? "\n" : ""));
  4032. }
  4033. // FIXME: Performance?
  4034. int beginLine = lineForPosition(range.beginPos);
  4035. int endLine = lineForPosition(range.endPos);
  4036. int beginColumn = 0;
  4037. int endColumn = INT_MAX;
  4038. if (range.rangemode == RangeBlockMode) {
  4039. int column1 = range.beginPos - firstPositionInLine(beginLine);
  4040. int column2 = range.endPos - firstPositionInLine(endLine);
  4041. beginColumn = qMin(column1, column2);
  4042. endColumn = qMax(column1, column2);
  4043. }
  4044. int len = endColumn - beginColumn + 1;
  4045. QString contents;
  4046. QTextBlock block = document()->findBlockByNumber(beginLine - 1);
  4047. for (int i = beginLine; i <= endLine && block.isValid(); ++i) {
  4048. QString line = block.text();
  4049. if (range.rangemode == RangeBlockMode) {
  4050. line = line.mid(beginColumn, len);
  4051. if (line.size() < len)
  4052. line += QString(len - line.size(), QChar(' '));
  4053. }
  4054. contents += line;
  4055. if (!contents.endsWith('\n'))
  4056. contents += '\n';
  4057. block = block.next();
  4058. }
  4059. //qDebug() << "SELECTED: " << contents;
  4060. return contents;
  4061. }
  4062. void FakeVimHandler::Private::yankText(const Range &range, int toregister)
  4063. {
  4064. Register &reg = g.registers[toregister];
  4065. reg.contents = selectText(range);
  4066. reg.rangemode = range.rangemode;
  4067. }
  4068. void FakeVimHandler::Private::transformText(const Range &range,
  4069. Transformation transformFunc, const QVariant &extra)
  4070. {
  4071. QTextCursor tc = cursor();
  4072. switch (range.rangemode) {
  4073. case RangeCharMode: {
  4074. // This can span multiple lines.
  4075. beginEditBlock();
  4076. tc.setPosition(range.beginPos, MoveAnchor);
  4077. tc.setPosition(range.endPos, KeepAnchor);
  4078. TransformationData td(tc.selectedText(), extra);
  4079. (this->*transformFunc)(&td);
  4080. tc.removeSelectedText();
  4081. tc.insertText(td.to);
  4082. endEditBlock();
  4083. return;
  4084. }
  4085. case RangeLineMode:
  4086. case RangeLineModeExclusive: {
  4087. beginEditBlock(range.beginPos);
  4088. tc.setPosition(range.beginPos, MoveAnchor);
  4089. tc.movePosition(StartOfLine, MoveAnchor);
  4090. tc.setPosition(range.endPos, KeepAnchor);
  4091. tc.movePosition(EndOfLine, KeepAnchor);
  4092. if (range.rangemode != RangeLineModeExclusive) {
  4093. // make sure that complete lines are removed
  4094. // - also at the beginning and at the end of the document
  4095. if (tc.atEnd()) {
  4096. tc.setPosition(range.beginPos, MoveAnchor);
  4097. tc.movePosition(StartOfLine, MoveAnchor);
  4098. if (!tc.atStart()) {
  4099. // also remove first line if it is the only one
  4100. tc.movePosition(Left, MoveAnchor, 1);
  4101. tc.movePosition(EndOfLine, MoveAnchor, 1);
  4102. }
  4103. tc.setPosition(range.endPos, KeepAnchor);
  4104. tc.movePosition(EndOfLine, KeepAnchor);
  4105. } else {
  4106. tc.movePosition(Right, KeepAnchor, 1);
  4107. }
  4108. }
  4109. TransformationData td(tc.selectedText(), extra);
  4110. (this->*transformFunc)(&td);
  4111. tc.removeSelectedText();
  4112. tc.insertText(td.to);
  4113. endEditBlock();
  4114. return;
  4115. }
  4116. case RangeBlockAndTailMode:
  4117. case RangeBlockMode: {
  4118. int beginLine = lineForPosition(range.beginPos);
  4119. int endLine = lineForPosition(range.endPos);
  4120. int column1 = range.beginPos - firstPositionInLine(beginLine);
  4121. int column2 = range.endPos - firstPositionInLine(endLine);
  4122. int beginColumn = qMin(column1, column2);
  4123. int endColumn = qMax(column1, column2);
  4124. if (range.rangemode == RangeBlockAndTailMode)
  4125. endColumn = INT_MAX - 1;
  4126. QTextBlock block = document()->findBlockByNumber(endLine - 1);
  4127. beginEditBlock(range.beginPos);
  4128. for (int i = beginLine; i <= endLine && block.isValid(); ++i) {
  4129. int bCol = qMin(beginColumn, block.length() - 1);
  4130. int eCol = qMin(endColumn + 1, block.length() - 1);
  4131. tc.setPosition(block.position() + bCol, MoveAnchor);
  4132. tc.setPosition(block.position() + eCol, KeepAnchor);
  4133. TransformationData td(tc.selectedText(), extra);
  4134. (this->*transformFunc)(&td);
  4135. tc.removeSelectedText();
  4136. tc.insertText(td.to);
  4137. block = block.previous();
  4138. }
  4139. endEditBlock();
  4140. }
  4141. }
  4142. }
  4143. void FakeVimHandler::Private::insertText(const Register &reg)
  4144. {
  4145. QTC_ASSERT(reg.rangemode == RangeCharMode,
  4146. qDebug() << "WRONG INSERT MODE: " << reg.rangemode; return);
  4147. setAnchor();
  4148. cursor().insertText(reg.contents);
  4149. //dump("AFTER INSERT");
  4150. }
  4151. void FakeVimHandler::Private::removeText(const Range &range)
  4152. {
  4153. //qDebug() << "REMOVE: " << range;
  4154. transformText(range, &FakeVimHandler::Private::removeTransform);
  4155. }
  4156. void FakeVimHandler::Private::removeTransform(TransformationData *td)
  4157. {
  4158. Q_UNUSED(td);
  4159. }
  4160. void FakeVimHandler::Private::downCase(const Range &range)
  4161. {
  4162. transformText(range, &FakeVimHandler::Private::downCaseTransform);
  4163. }
  4164. void FakeVimHandler::Private::downCaseTransform(TransformationData *td)
  4165. {
  4166. td->to = td->from.toLower();
  4167. }
  4168. void FakeVimHandler::Private::upCase(const Range &range)
  4169. {
  4170. transformText(range, &FakeVimHandler::Private::upCaseTransform);
  4171. }
  4172. void FakeVimHandler::Private::upCaseTransform(TransformationData *td)
  4173. {
  4174. td->to = td->from.toUpper();
  4175. }
  4176. void FakeVimHandler::Private::invertCase(const Range &range)
  4177. {
  4178. transformText(range, &FakeVimHandler::Private::invertCaseTransform);
  4179. }
  4180. void FakeVimHandler::Private::invertCaseTransform(TransformationData *td)
  4181. {
  4182. foreach (QChar c, td->from)
  4183. td->to += c.isUpper() ? c.toLower() : c.toUpper();
  4184. }
  4185. void FakeVimHandler::Private::replaceText(const Range &range, const QString &str)
  4186. {
  4187. Transformation tr = &FakeVimHandler::Private::replaceByStringTransform;
  4188. transformText(range, tr, str);
  4189. }
  4190. void FakeVimHandler::Private::replaceByStringTransform(TransformationData *td)
  4191. {
  4192. td->to = td->extraData.toString();
  4193. }
  4194. void FakeVimHandler::Private::replaceByCharTransform(TransformationData *td)
  4195. {
  4196. td->to = QString(td->from.size(), td->extraData.toChar());
  4197. }
  4198. void FakeVimHandler::Private::pasteText(bool afterCursor)
  4199. {
  4200. const QString text = g.registers[m_register].contents;
  4201. const QStringList lines = text.split(QChar('\n'));
  4202. beginEditBlock();
  4203. if (isVisualCharMode()) {
  4204. leaveVisualMode();
  4205. m_submode = DeleteSubMode;
  4206. finishMovement();
  4207. } else if (isVisualLineMode()) {
  4208. leaveVisualMode();
  4209. m_rangemode = RangeLineMode;
  4210. yankText(currentRange(), m_register);
  4211. removeText(currentRange());
  4212. handleStartOfLine();
  4213. } else if (isVisualBlockMode()) {
  4214. leaveVisualMode();
  4215. m_rangemode = RangeBlockMode;
  4216. yankText(currentRange(), m_register);
  4217. removeText(currentRange());
  4218. setPosition(qMin(position(), anchor()));
  4219. }
  4220. switch (g.registers[m_register].rangemode) {
  4221. case RangeCharMode: {
  4222. m_targetColumn = 0;
  4223. for (int i = count(); --i >= 0; ) {
  4224. if (afterCursor && rightDist() > 0)
  4225. moveRight();
  4226. setAnchor();
  4227. insertText(text);
  4228. if (!afterCursor && atEndOfLine())
  4229. moveLeft();
  4230. moveLeft();
  4231. }
  4232. break;
  4233. }
  4234. case RangeLineMode:
  4235. case RangeLineModeExclusive: {
  4236. moveToStartOfLine();
  4237. m_targetColumn = 0;
  4238. QTextCursor tc = cursor();
  4239. for (int i = count(); --i >= 0; ) {
  4240. bool lastLine = document()->lastBlock() == this->block();
  4241. if (afterCursor) {
  4242. if (lastLine) {
  4243. tc.movePosition(EndOfLine, MoveAnchor);
  4244. tc.insertBlock();
  4245. }
  4246. moveDown();
  4247. }
  4248. setAnchor();
  4249. insertText(text);
  4250. if (afterCursor && lastLine) {
  4251. tc.movePosition(Left, KeepAnchor);
  4252. tc.removeSelectedText();
  4253. setAnchor();
  4254. moveUp(lines.size() - 2);
  4255. } else {
  4256. moveUp(lines.size() - 1);
  4257. }
  4258. }
  4259. moveToFirstNonBlankOnLine();
  4260. break;
  4261. }
  4262. case RangeBlockAndTailMode:
  4263. case RangeBlockMode: {
  4264. QTextBlock block = this->block();
  4265. if (afterCursor)
  4266. moveRight();
  4267. QTextCursor tc = cursor();
  4268. const int col = tc.position() - block.position();
  4269. //for (int i = lines.size(); --i >= 0; ) {
  4270. for (int i = 0; i < lines.size(); ++i) {
  4271. const QString line = lines.at(i);
  4272. tc.movePosition(StartOfLine, MoveAnchor);
  4273. if (col >= block.length()) {
  4274. tc.movePosition(EndOfLine, MoveAnchor);
  4275. tc.insertText(QString(col - line.size() + 1, QChar(' ')));
  4276. } else {
  4277. tc.movePosition(Right, MoveAnchor, col - 1 + afterCursor);
  4278. }
  4279. //qDebug() << "INSERT " << line << " AT " << tc.position()
  4280. // << "COL: " << col;
  4281. tc.insertText(line);
  4282. tc.movePosition(StartOfLine, MoveAnchor);
  4283. tc.movePosition(Down, MoveAnchor, 1);
  4284. if (tc.position() >= lastPositionInDocument() - 1) {
  4285. tc.insertText(QString(QChar('\n')));
  4286. tc.movePosition(Up, MoveAnchor, 1);
  4287. }
  4288. block = block.next();
  4289. }
  4290. moveLeft();
  4291. break;
  4292. }
  4293. }
  4294. endEditBlock();
  4295. }
  4296. QString FakeVimHandler::Private::lineContents(int line) const
  4297. {
  4298. return document()->findBlockByNumber(line - 1).text();
  4299. }
  4300. void FakeVimHandler::Private::setLineContents(int line, const QString &contents)
  4301. {
  4302. QTextBlock block = document()->findBlockByNumber(line - 1);
  4303. QTextCursor tc = cursor();
  4304. const int begin = block.position();
  4305. const int len = block.length();
  4306. tc.setPosition(begin);
  4307. tc.setPosition(begin + len - 1, KeepAnchor);
  4308. tc.removeSelectedText();
  4309. tc.insertText(contents);
  4310. }
  4311. int FakeVimHandler::Private::firstPositionInLine(int line) const
  4312. {
  4313. return document()->findBlockByNumber(line - 1).position();
  4314. }
  4315. int FakeVimHandler::Private::lastPositionInLine(int line) const
  4316. {
  4317. QTextBlock block = document()->findBlockByNumber(line - 1);
  4318. return block.position() + block.length() - 1;
  4319. }
  4320. int FakeVimHandler::Private::lineForPosition(int pos) const
  4321. {
  4322. QTextCursor tc = cursor();
  4323. tc.setPosition(pos);
  4324. return tc.block().blockNumber() + 1;
  4325. }
  4326. void FakeVimHandler::Private::toggleVisualMode(VisualMode visualMode)
  4327. {
  4328. if (isVisualMode()) {
  4329. leaveVisualMode();
  4330. } else {
  4331. m_positionPastEnd = false;
  4332. m_anchorPastEnd = false;
  4333. m_visualMode = visualMode;
  4334. const int pos = position();
  4335. //setMark('<', pos);
  4336. //setMark('>', pos + 1);
  4337. setAnchorAndPosition(pos, pos);
  4338. updateMiniBuffer();
  4339. updateSelection();
  4340. }
  4341. }
  4342. void FakeVimHandler::Private::leaveVisualMode()
  4343. {
  4344. if (isVisualLineMode())
  4345. m_movetype = MoveLineWise;
  4346. else if (isVisualCharMode())
  4347. m_movetype = MoveInclusive;
  4348. m_visualMode = NoVisualMode;
  4349. updateMiniBuffer();
  4350. updateSelection();
  4351. }
  4352. QWidget *FakeVimHandler::Private::editor() const
  4353. {
  4354. return m_textedit
  4355. ? static_cast<QWidget *>(m_textedit)
  4356. : static_cast<QWidget *>(m_plaintextedit);
  4357. }
  4358. void FakeVimHandler::Private::undo()
  4359. {
  4360. //qDebug() << " CURSOR POS: " << m_undoCursorPosition;
  4361. // FIXME: That's only an approximaxtion. The real solution might
  4362. // be to store marks and old userData with QTextBlock setUserData
  4363. // and retrieve them afterward.
  4364. const int current = document()->availableUndoSteps();
  4365. EDITOR(undo());
  4366. const int rev = document()->availableUndoSteps();
  4367. if (current == rev)
  4368. showBlackMessage(FakeVimHandler::tr("Already at oldest change"));
  4369. else
  4370. showBlackMessage(QString());
  4371. if (m_undoCursorPosition.contains(rev))
  4372. setPosition(m_undoCursorPosition[rev]);
  4373. setTargetColumn();
  4374. if (atEndOfLine())
  4375. moveLeft();
  4376. }
  4377. void FakeVimHandler::Private::redo()
  4378. {
  4379. const int current = document()->availableUndoSteps();
  4380. EDITOR(redo());
  4381. const int rev = document()->availableUndoSteps();
  4382. if (rev == current)
  4383. showBlackMessage(FakeVimHandler::tr("Already at newest change"));
  4384. else
  4385. showBlackMessage(QString());
  4386. if (m_undoCursorPosition.contains(rev))
  4387. setPosition(m_undoCursorPosition[rev]);
  4388. setTargetColumn();
  4389. }
  4390. void FakeVimHandler::Private::updateCursorShape()
  4391. {
  4392. bool thinCursor = m_mode == ExMode
  4393. || m_subsubmode == SearchSubSubMode
  4394. || m_mode == InsertMode
  4395. || isVisualMode()
  4396. || cursor().hasSelection();
  4397. EDITOR(setOverwriteMode(!thinCursor));
  4398. }
  4399. void FakeVimHandler::Private::enterReplaceMode()
  4400. {
  4401. m_mode = ReplaceMode;
  4402. m_submode = NoSubMode;
  4403. m_subsubmode = NoSubSubMode;
  4404. m_commandPrefix.clear();
  4405. m_lastInsertion.clear();
  4406. m_lastDeletion.clear();
  4407. }
  4408. void FakeVimHandler::Private::enterInsertMode()
  4409. {
  4410. m_mode = InsertMode;
  4411. m_submode = NoSubMode;
  4412. m_subsubmode = NoSubSubMode;
  4413. m_commandPrefix.clear();
  4414. m_lastInsertion.clear();
  4415. m_lastDeletion.clear();
  4416. }
  4417. void FakeVimHandler::Private::enterCommandMode()
  4418. {
  4419. if (atEndOfLine())
  4420. moveLeft();
  4421. m_mode = CommandMode;
  4422. m_submode = NoSubMode;
  4423. m_subsubmode = NoSubSubMode;
  4424. m_commandPrefix.clear();
  4425. }
  4426. void FakeVimHandler::Private::enterExMode()
  4427. {
  4428. m_mode = ExMode;
  4429. m_submode = NoSubMode;
  4430. m_subsubmode = NoSubSubMode;
  4431. m_commandPrefix = ':';
  4432. }
  4433. void FakeVimHandler::Private::recordJump()
  4434. {
  4435. m_jumpListUndo.append(cursorPosition());
  4436. m_jumpListRedo.clear();
  4437. UNDO_DEBUG("jumps: " << m_jumpListUndo);
  4438. }
  4439. Column FakeVimHandler::Private::indentation(const QString &line) const
  4440. {
  4441. int ts = config(ConfigTabStop).toInt();
  4442. int physical = 0;
  4443. int logical = 0;
  4444. int n = line.size();
  4445. while (physical < n) {
  4446. QChar c = line.at(physical);
  4447. if (c == QLatin1Char(' '))
  4448. ++logical;
  4449. else if (c == QLatin1Char('\t'))
  4450. logical += ts - logical % ts;
  4451. else
  4452. break;
  4453. ++physical;
  4454. }
  4455. return Column(physical, logical);
  4456. }
  4457. QString FakeVimHandler::Private::tabExpand(int n) const
  4458. {
  4459. int ts = config(ConfigTabStop).toInt();
  4460. if (hasConfig(ConfigExpandTab) || ts < 1)
  4461. return QString(n, QLatin1Char(' '));
  4462. return QString(n / ts, QLatin1Char('\t'))
  4463. + QString(n % ts, QLatin1Char(' '));
  4464. }
  4465. void FakeVimHandler::Private::insertAutomaticIndentation(bool goingDown)
  4466. {
  4467. if (!hasConfig(ConfigAutoIndent) && !hasConfig(ConfigSmartIndent))
  4468. return;
  4469. if (hasConfig(ConfigSmartIndent)) {
  4470. QTextBlock bl = block();
  4471. Range range(bl.position(), bl.position());
  4472. const int oldSize = bl.text().size();
  4473. indentText(range, QLatin1Char('\n'));
  4474. m_justAutoIndented = bl.text().size() - oldSize;
  4475. } else {
  4476. QTextBlock bl = goingDown ? block().previous() : block().next();
  4477. QString text = bl.text();
  4478. int pos = 0;
  4479. int n = text.size();
  4480. while (pos < n && text.at(pos).isSpace())
  4481. ++pos;
  4482. text.truncate(pos);
  4483. // FIXME: handle 'smartindent' and 'cindent'
  4484. insertText(text);
  4485. m_justAutoIndented = text.size();
  4486. }
  4487. }
  4488. bool FakeVimHandler::Private::removeAutomaticIndentation()
  4489. {
  4490. if (!hasConfig(ConfigAutoIndent) || m_justAutoIndented == 0)
  4491. return false;
  4492. /*
  4493. m_tc.movePosition(StartOfLine, KeepAnchor);
  4494. m_tc.removeSelectedText();
  4495. m_lastInsertion.chop(m_justAutoIndented);
  4496. */
  4497. m_justAutoIndented = 0;
  4498. return true;
  4499. }
  4500. void FakeVimHandler::Private::handleStartOfLine()
  4501. {
  4502. if (hasConfig(ConfigStartOfLine))
  4503. moveToFirstNonBlankOnLine();
  4504. }
  4505. void FakeVimHandler::Private::replay(const QString &command, int n)
  4506. {
  4507. //qDebug() << "REPLAY: " << quoteUnprintable(command);
  4508. for (int i = n; --i >= 0; ) {
  4509. foreach (QChar c, command) {
  4510. //qDebug() << " REPLAY: " << c.unicode();
  4511. handleKey(Input(c));
  4512. }
  4513. }
  4514. }
  4515. void FakeVimHandler::Private::selectWordTextObject(bool inner)
  4516. {
  4517. Q_UNUSED(inner); // FIXME
  4518. m_movetype = MoveExclusive;
  4519. moveToWordBoundary(false, false, true);
  4520. setAnchor();
  4521. // FIXME: Rework the 'anchor' concept.
  4522. //if (isVisualMode())
  4523. // setMark('<', cursor().position());
  4524. moveToWordBoundary(false, true, true);
  4525. setTargetColumn();
  4526. m_movetype = MoveInclusive;
  4527. }
  4528. void FakeVimHandler::Private::selectWORDTextObject(bool inner)
  4529. {
  4530. Q_UNUSED(inner); // FIXME
  4531. m_movetype = MoveExclusive;
  4532. moveToWordBoundary(true, false, true);
  4533. setAnchor();
  4534. // FIXME: Rework the 'anchor' concept.
  4535. //if (isVisualMode())
  4536. // setMark('<', cursor().position());
  4537. moveToWordBoundary(true, true, true);
  4538. setTargetColumn();
  4539. m_movetype = MoveInclusive;
  4540. }
  4541. void FakeVimHandler::Private::selectSentenceTextObject(bool inner)
  4542. {
  4543. Q_UNUSED(inner);
  4544. }
  4545. void FakeVimHandler::Private::selectParagraphTextObject(bool inner)
  4546. {
  4547. Q_UNUSED(inner);
  4548. }
  4549. void FakeVimHandler::Private::selectBlockTextObject(bool inner, char left, char right)
  4550. {
  4551. QString sleft = QString(QLatin1Char(left));
  4552. QString sright = QString(QLatin1Char(right));
  4553. QTextCursor tc2 = document()->find(sright, cursor());
  4554. if (tc2.isNull())
  4555. return;
  4556. QTextCursor tc1 = document()->find(sleft, cursor(), QTextDocument::FindBackward);
  4557. if (tc1.isNull())
  4558. return;
  4559. int p1 = tc1.position() + inner - sleft.size();
  4560. if (inner && document()->characterAt(p1) == ParagraphSeparator)
  4561. ++p1;
  4562. const int p2 = tc2.position() - inner - sright.size();
  4563. //setMark('>', p1);
  4564. //setMark('<', p2);
  4565. setAnchorAndPosition(p2, p1);
  4566. m_movetype = MoveInclusive;
  4567. }
  4568. void FakeVimHandler::Private::selectQuotedStringTextObject(bool inner, int type)
  4569. {
  4570. Q_UNUSED(inner);
  4571. Q_UNUSED(type);
  4572. }
  4573. int FakeVimHandler::Private::mark(int code) const
  4574. {
  4575. // FIXME: distinguish local and global marks.
  4576. //qDebug() << "MARK: " << code << m_marks.value(code, -1) << m_marks;
  4577. if (isVisualMode()) {
  4578. if (code == '<')
  4579. return position();
  4580. if (code == '>')
  4581. return anchor();
  4582. }
  4583. QTextCursor tc = m_marks.value(code);
  4584. return tc.isNull() ? -1 : tc.position();
  4585. }
  4586. void FakeVimHandler::Private::setMark(int code, int position)
  4587. {
  4588. // FIXME: distinguish local and global marks.
  4589. QTextCursor tc = cursor();
  4590. tc.setPosition(position, MoveAnchor);
  4591. m_marks[code] = tc;
  4592. }
  4593. ///////////////////////////////////////////////////////////////////////
  4594. //
  4595. // FakeVimHandler
  4596. //
  4597. ///////////////////////////////////////////////////////////////////////
  4598. FakeVimHandler::FakeVimHandler(QWidget *widget, QObject *parent)
  4599. : QObject(parent), d(new Private(this, widget))
  4600. {}
  4601. FakeVimHandler::~FakeVimHandler()
  4602. {
  4603. delete d;
  4604. }
  4605. // gracefully handle that the parent editor is deleted
  4606. void FakeVimHandler::disconnectFromEditor()
  4607. {
  4608. d->m_textedit = 0;
  4609. d->m_plaintextedit = 0;
  4610. }
  4611. bool FakeVimHandler::eventFilter(QObject *ob, QEvent *ev)
  4612. {
  4613. bool active = theFakeVimSetting(ConfigUseFakeVim)->value().toBool();
  4614. // Catch mouse events on the viewport.
  4615. QWidget *viewport = 0;
  4616. if (d->m_plaintextedit)
  4617. viewport = d->m_plaintextedit->viewport();
  4618. else if (d->m_textedit)
  4619. viewport = d->m_textedit->viewport();
  4620. if (ob == viewport) {
  4621. if (active && ev->type() == QEvent::MouseButtonRelease) {
  4622. QMouseEvent *mev = static_cast<QMouseEvent *>(ev);
  4623. if (mev->button() == Qt::LeftButton) {
  4624. d->importSelection();
  4625. //return true;
  4626. }
  4627. }
  4628. if (active && ev->type() == QEvent::MouseButtonPress) {
  4629. QMouseEvent *mev = static_cast<QMouseEvent *>(ev);
  4630. if (mev->button() == Qt::LeftButton) {
  4631. d->m_visualMode = NoVisualMode;
  4632. d->updateSelection();
  4633. }
  4634. }
  4635. return QObject::eventFilter(ob, ev);
  4636. }
  4637. if (active && ev->type() == QEvent::Shortcut) {
  4638. d->passShortcuts(false);
  4639. return false;
  4640. }
  4641. if (active && ev->type() == QEvent::InputMethod && ob == d->editor()) {
  4642. // This handles simple dead keys. The sequence of events is
  4643. // KeyRelease-InputMethod-KeyRelease for dead keys instead of
  4644. // KeyPress-KeyRelease as for simple keys. As vi acts on key presses,
  4645. // we have to act on the InputMethod event.
  4646. // FIXME: A first approximation working for e.g. ^ on a German keyboard
  4647. QInputMethodEvent *imev = static_cast<QInputMethodEvent *>(ev);
  4648. KEY_DEBUG("INPUTMETHOD" << imev->commitString() << imev->preeditString());
  4649. QString commitString = imev->commitString();
  4650. int key = commitString.size() == 1 ? commitString.at(0).unicode() : 0;
  4651. QKeyEvent kev(QEvent::KeyPress, key, Qt::KeyboardModifiers(), commitString);
  4652. EventResult res = d->handleEvent(&kev);
  4653. return res == EventHandled;
  4654. }
  4655. if (active && ev->type() == QEvent::KeyPress && ob == d->editor()) {
  4656. QKeyEvent *kev = static_cast<QKeyEvent *>(ev);
  4657. KEY_DEBUG("KEYPRESS" << kev->key() << kev->text() << QChar(kev->key()));
  4658. EventResult res = d->handleEvent(kev);
  4659. //if (d->m_mode == InsertMode)
  4660. // emit completionRequested();
  4661. // returning false core the app see it
  4662. //KEY_DEBUG("HANDLED CODE:" << res);
  4663. //return res != EventPassedToCore;
  4664. //return true;
  4665. return res == EventHandled;
  4666. }
  4667. if (active && ev->type() == QEvent::ShortcutOverride && ob == d->editor()) {
  4668. QKeyEvent *kev = static_cast<QKeyEvent *>(ev);
  4669. if (d->wantsOverride(kev)) {
  4670. KEY_DEBUG("OVERRIDING SHORTCUT" << kev->key());
  4671. ev->accept(); // accepting means "don't run the shortcuts"
  4672. return true;
  4673. }
  4674. KEY_DEBUG("NO SHORTCUT OVERRIDE" << kev->key());
  4675. return true;
  4676. }
  4677. if (active && ev->type() == QEvent::FocusIn && ob == d->editor()) {
  4678. d->stopIncrementalFind();
  4679. }
  4680. return QObject::eventFilter(ob, ev);
  4681. }
  4682. void FakeVimHandler::installEventFilter()
  4683. {
  4684. d->installEventFilter();
  4685. }
  4686. void FakeVimHandler::setupWidget()
  4687. {
  4688. d->setupWidget();
  4689. }
  4690. void FakeVimHandler::restoreWidget(int tabSize)
  4691. {
  4692. d->restoreWidget(tabSize);
  4693. }
  4694. void FakeVimHandler::handleCommand(const QString &cmd)
  4695. {
  4696. d->handleCommand(cmd);
  4697. }
  4698. void FakeVimHandler::handleReplay(const QString &keys)
  4699. {
  4700. d->replay(keys, 1);
  4701. }
  4702. void FakeVimHandler::handleInput(const QString &keys)
  4703. {
  4704. Mode oldMode = d->m_mode;
  4705. d->m_mode = CommandMode;
  4706. Inputs inputs;
  4707. inputs.parseFrom(keys);
  4708. foreach (const Input &input, inputs)
  4709. d->handleKey(input);
  4710. d->m_mode = oldMode;
  4711. }
  4712. void FakeVimHandler::setCurrentFileName(const QString &fileName)
  4713. {
  4714. d->m_currentFileName = fileName;
  4715. }
  4716. QString FakeVimHandler::currentFileName() const
  4717. {
  4718. return d->m_currentFileName;
  4719. }
  4720. void FakeVimHandler::showBlackMessage(const QString &msg)
  4721. {
  4722. d->showBlackMessage(msg);
  4723. }
  4724. void FakeVimHandler::showRedMessage(const QString &msg)
  4725. {
  4726. d->showRedMessage(msg);
  4727. }
  4728. QWidget *FakeVimHandler::widget()
  4729. {
  4730. return d->editor();
  4731. }
  4732. // Test only
  4733. int FakeVimHandler::physicalIndentation(const QString &line) const
  4734. {
  4735. Column ind = d->indentation(line);
  4736. return ind.physical;
  4737. }
  4738. int FakeVimHandler::logicalIndentation(const QString &line) const
  4739. {
  4740. Column ind = d->indentation(line);
  4741. return ind.logical;
  4742. }
  4743. QString FakeVimHandler::tabExpand(int n) const
  4744. {
  4745. return d->tabExpand(n);
  4746. }
  4747. } // namespace Internal
  4748. } // namespace FakeVim
  4749. #include "fakevimhandler.moc"