veditor.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  1. #include "veditor.h"
  2. #include <QtWidgets>
  3. #include <QTextDocument>
  4. #include "vconfigmanager.h"
  5. #include "utils/vutils.h"
  6. #include "utils/veditutils.h"
  7. #include "veditoperations.h"
  8. #include "dialog/vinsertlinkdialog.h"
  9. #include "utils/vmetawordmanager.h"
  10. #include "utils/vvim.h"
  11. extern VConfigManager *g_config;
  12. extern VMetaWordManager *g_mwMgr;
  13. VEditor::VEditor(VFile *p_file,
  14. QWidget *p_editor,
  15. const QSharedPointer<VTextEditCompleter> &p_completer)
  16. : m_editor(p_editor),
  17. m_object(new VEditorObject(this, p_editor)),
  18. m_file(p_file),
  19. m_editOps(nullptr),
  20. m_document(nullptr),
  21. m_enableInputMethod(true),
  22. m_timeStamp(0),
  23. m_trailingSpaceSelectionTS(0),
  24. m_completer(p_completer),
  25. m_trailingSpaceHighlightEnabled(false),
  26. m_tabHighlightEnabled(false)
  27. {
  28. }
  29. VEditor::~VEditor()
  30. {
  31. if (m_completer->widget() == m_editor) {
  32. m_completer->setWidget(NULL);
  33. }
  34. cleanUp();
  35. }
  36. void VEditor::cleanUp()
  37. {
  38. for (auto const & file : m_tempFiles) {
  39. VUtils::deleteFile(file);
  40. }
  41. m_tempFiles.clear();
  42. }
  43. void VEditor::init()
  44. {
  45. const int labelTimerInterval = 500;
  46. const int extraSelectionHighlightTimer = 500;
  47. const int trailingSpaceUpdateTimer = 500;
  48. const int labelSize = 64;
  49. m_document = documentW();
  50. QObject::connect(m_document, &QTextDocument::contentsChanged,
  51. m_object, &VEditorObject::clearFindCache);
  52. m_selectedWordFg = QColor(g_config->getEditorSelectedWordFg());
  53. m_selectedWordBg = QColor(g_config->getEditorSelectedWordBg());
  54. m_searchedWordFg = QColor(g_config->getEditorSearchedWordFg());
  55. m_searchedWordBg = QColor(g_config->getEditorSearchedWordBg());
  56. m_searchedWordCursorFg = QColor(g_config->getEditorSearchedWordCursorFg());
  57. m_searchedWordCursorBg = QColor(g_config->getEditorSearchedWordCursorBg());
  58. m_incrementalSearchedWordFg = QColor(g_config->getEditorIncrementalSearchedWordFg());
  59. m_incrementalSearchedWordBg = QColor(g_config->getEditorIncrementalSearchedWordBg());
  60. m_trailingSpaceColor = QColor(g_config->getEditorTrailingSpaceBg());
  61. m_tabColor = g_config->getMdEditPalette().color(QPalette::Text);
  62. QPixmap wrapPixmap(":/resources/icons/search_wrap.svg");
  63. m_wrapLabel = new QLabel(m_editor);
  64. m_wrapLabel->setPixmap(wrapPixmap.scaled(labelSize, labelSize));
  65. m_wrapLabel->hide();
  66. m_labelTimer = new QTimer(m_editor);
  67. m_labelTimer->setSingleShot(true);
  68. m_labelTimer->setInterval(labelTimerInterval);
  69. QObject::connect(m_labelTimer, &QTimer::timeout,
  70. m_object, &VEditorObject::labelTimerTimeout);
  71. m_highlightTimer = new QTimer(m_editor);
  72. m_highlightTimer->setSingleShot(true);
  73. m_highlightTimer->setInterval(extraSelectionHighlightTimer);
  74. QObject::connect(m_highlightTimer, &QTimer::timeout,
  75. m_object, &VEditorObject::doHighlightExtraSelections);
  76. m_trailingSpaceTimer = new QTimer(m_editor);
  77. m_trailingSpaceTimer->setSingleShot(true);
  78. m_trailingSpaceTimer->setInterval(trailingSpaceUpdateTimer);
  79. QObject::connect(m_trailingSpaceTimer, &QTimer::timeout,
  80. m_object, &VEditorObject::doUpdateTrailingSpaceAndTabHighlights);
  81. m_extraSelections.resize((int)SelectionId::MaxSelection);
  82. updateFontAndPalette();
  83. m_config.init(QFontMetrics(m_editor->font()), false);
  84. updateEditConfig();
  85. }
  86. void VEditor::labelTimerTimeout()
  87. {
  88. m_wrapLabel->hide();
  89. }
  90. bool VEditor::needUpdateTrailingSpaceAndTabHighlights()
  91. {
  92. bool ret = false;
  93. bool space = g_config->getEnableTrailingSpaceHighlight();
  94. if (m_trailingSpaceHighlightEnabled != space) {
  95. m_trailingSpaceHighlightEnabled = space;
  96. ret = true;
  97. }
  98. bool tab = g_config->getEnableTabHighlight();
  99. if (m_tabHighlightEnabled != tab) {
  100. m_tabHighlightEnabled = tab;
  101. ret = true;
  102. }
  103. if (m_trailingSpaceSelectionTS != m_timeStamp) {
  104. ret = true;
  105. }
  106. return ret;
  107. }
  108. void VEditor::updateTrailingSpaceAndTabHighlights()
  109. {
  110. if (needUpdateTrailingSpaceAndTabHighlights()) {
  111. m_trailingSpaceTimer->start();
  112. } else {
  113. highlightExtraSelections(false);
  114. }
  115. }
  116. void VEditor::doHighlightExtraSelections()
  117. {
  118. int nrExtra = m_extraSelections.size();
  119. Q_ASSERT(nrExtra == (int)SelectionId::MaxSelection);
  120. QList<QTextEdit::ExtraSelection> extraSelects;
  121. for (int i = 0; i < nrExtra; ++i) {
  122. if (i == (int)SelectionId::TrailingSpace) {
  123. filterTrailingSpace(extraSelects, m_extraSelections[i]);
  124. } else {
  125. extraSelects.append(m_extraSelections[i]);
  126. }
  127. }
  128. setExtraSelectionsW(extraSelects);
  129. }
  130. void VEditor::doUpdateTrailingSpaceAndTabHighlights()
  131. {
  132. bool needHighlight = false;
  133. // Trailing space.
  134. if (!m_trailingSpaceHighlightEnabled) {
  135. QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::TrailingSpace];
  136. if (!selects.isEmpty()) {
  137. selects.clear();
  138. needHighlight = true;
  139. }
  140. } else {
  141. needHighlight = true;
  142. QTextCharFormat format;
  143. format.setBackground(m_trailingSpaceColor);
  144. QString text("\\s+$");
  145. highlightTextAll(text,
  146. FindOption::RegularExpression,
  147. SelectionId::TrailingSpace,
  148. format);
  149. }
  150. // Tab.
  151. if (!m_tabHighlightEnabled) {
  152. QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::Tab];
  153. if (!selects.isEmpty()) {
  154. selects.clear();
  155. needHighlight = true;
  156. }
  157. } else {
  158. needHighlight = true;
  159. QTextCharFormat format;
  160. format.setBackground(m_tabColor);
  161. QString text("\\t");
  162. highlightTextAll(text,
  163. FindOption::RegularExpression,
  164. SelectionId::Tab,
  165. format);
  166. }
  167. m_trailingSpaceSelectionTS = m_timeStamp;
  168. if (needHighlight) {
  169. highlightExtraSelections(true);
  170. }
  171. }
  172. void VEditor::updateEditConfig()
  173. {
  174. m_config.update(QFontMetrics(m_editor->font()));
  175. if (m_config.m_tabStopWidth > 0) {
  176. setTabStopWidthW(m_config.m_tabStopWidth);
  177. }
  178. emit m_object->configUpdated();
  179. }
  180. void VEditor::highlightOnCursorPositionChanged()
  181. {
  182. static QTextCursor lastCursor;
  183. QTextCursor cursor = textCursorW();
  184. if (lastCursor.isNull() || cursor.blockNumber() != lastCursor.blockNumber()) {
  185. updateTrailingSpaceAndTabHighlights();
  186. highlightCurrentLine();
  187. } else {
  188. // Judge whether we have trailing space at current line.
  189. QString text = cursor.block().text();
  190. if (!text.isEmpty()) {
  191. auto it = text.rbegin();
  192. bool needUpdate = it->isSpace();
  193. if (!needUpdate
  194. && cursor.atBlockEnd()
  195. && text.size() > 1) {
  196. ++it;
  197. needUpdate = it->isSpace();
  198. // Input two chars at once in Chinese.
  199. if (!needUpdate && text.size() > 2) {
  200. ++it;
  201. needUpdate = it->isSpace();
  202. }
  203. }
  204. if (needUpdate) {
  205. updateTrailingSpaceAndTabHighlights();
  206. }
  207. }
  208. // Handle word-wrap in one block.
  209. // Highlight current line if in different visual line.
  210. if ((lastCursor.positionInBlock() - lastCursor.columnNumber()) !=
  211. (cursor.positionInBlock() - cursor.columnNumber())) {
  212. highlightCurrentLine();
  213. }
  214. }
  215. lastCursor = cursor;
  216. }
  217. void VEditor::updateTimeStamp()
  218. {
  219. ++m_timeStamp;
  220. }
  221. void VEditor::highlightCurrentLine()
  222. {
  223. QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::CurrentLine];
  224. if (g_config->getHighlightCursorLine()) {
  225. // Need to highlight current line.
  226. selects.clear();
  227. // A long block maybe splited into multiple visual lines.
  228. QTextEdit::ExtraSelection select;
  229. select.format.setBackground(m_config.m_cursorLineBg);
  230. select.format.setProperty(QTextFormat::FullWidthSelection, true);
  231. QTextCursor cursor = textCursorW();
  232. if (m_config.m_highlightWholeBlock) {
  233. cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor, 1);
  234. QTextBlock block = cursor.block();
  235. int blockEnd = block.position() + block.length();
  236. int pos = -1;
  237. while (cursor.position() < blockEnd && pos != cursor.position()) {
  238. QTextEdit::ExtraSelection newSelect = select;
  239. newSelect.cursor = cursor;
  240. selects.append(newSelect);
  241. pos = cursor.position();
  242. cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, 1);
  243. }
  244. } else {
  245. cursor.clearSelection();
  246. select.cursor = cursor;
  247. selects.append(select);
  248. }
  249. } else {
  250. // Need to clear current line highlight.
  251. if (selects.isEmpty()) {
  252. return;
  253. }
  254. selects.clear();
  255. }
  256. highlightExtraSelections(true);
  257. }
  258. void VEditor::filterTrailingSpace(QList<QTextEdit::ExtraSelection> &p_selects,
  259. const QList<QTextEdit::ExtraSelection> &p_src)
  260. {
  261. QTextCursor cursor = textCursorW();
  262. bool blockEnd = cursor.atBlockEnd();
  263. int blockNum = cursor.blockNumber();
  264. for (auto it = p_src.begin(); it != p_src.end(); ++it) {
  265. if (it->cursor.blockNumber() == blockNum) {
  266. if (blockEnd) {
  267. // When cursor is at block end, we do not display any trailing space
  268. // at current line.
  269. continue;
  270. }
  271. QString text = cursor.block().text();
  272. if (text.isEmpty()) {
  273. continue;
  274. } else if (!text[text.size() - 1].isSpace()) {
  275. continue;
  276. }
  277. }
  278. p_selects.append(*it);
  279. }
  280. }
  281. void VEditor::highlightExtraSelections(bool p_now)
  282. {
  283. m_highlightTimer->stop();
  284. if (p_now) {
  285. doHighlightExtraSelections();
  286. } else {
  287. m_highlightTimer->start();
  288. }
  289. }
  290. void VEditor::highlightTextAll(const QString &p_text,
  291. uint p_options,
  292. SelectionId p_id,
  293. QTextCharFormat p_format,
  294. void (*p_filter)(VEditor *,
  295. QList<QTextEdit::ExtraSelection> &))
  296. {
  297. QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)p_id];
  298. if (!p_text.isEmpty()) {
  299. selects.clear();
  300. QList<QTextCursor> occurs = findTextAll(p_text, p_options);
  301. for (int i = 0; i < occurs.size(); ++i) {
  302. QTextEdit::ExtraSelection select;
  303. select.format = p_format;
  304. select.cursor = occurs[i];
  305. selects.append(select);
  306. }
  307. } else {
  308. if (selects.isEmpty()) {
  309. return;
  310. }
  311. selects.clear();
  312. }
  313. if (p_filter) {
  314. p_filter(this, selects);
  315. }
  316. highlightExtraSelections();
  317. }
  318. static QTextDocument::FindFlags findOptionsToFlags(uint p_options, bool p_forward)
  319. {
  320. QTextDocument::FindFlags findFlags;
  321. if (p_options & FindOption::CaseSensitive) {
  322. findFlags |= QTextDocument::FindCaseSensitively;
  323. }
  324. if (p_options & FindOption::WholeWordOnly) {
  325. findFlags |= QTextDocument::FindWholeWords;
  326. }
  327. if (!p_forward) {
  328. findFlags |= QTextDocument::FindBackward;
  329. }
  330. return findFlags;
  331. }
  332. QList<QTextCursor> VEditor::findTextAll(const QString &p_text,
  333. uint p_options,
  334. int p_start,
  335. int p_end)
  336. {
  337. QList<QTextCursor> results;
  338. if (p_text.isEmpty()) {
  339. return results;
  340. }
  341. // Options
  342. bool caseSensitive = p_options & FindOption::CaseSensitive;
  343. QTextDocument::FindFlags findFlags = findOptionsToFlags(p_options, true);
  344. if (p_options & FindOption::RegularExpression) {
  345. QRegExp exp(p_text,
  346. caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive);
  347. results = findTextAllInRange(m_document, exp, findFlags, p_start, p_end);
  348. } else {
  349. results = findTextAllInRange(m_document, p_text, findFlags, p_start, p_end);
  350. }
  351. return results;
  352. }
  353. static void mergeResult(QList<QTextCursor> &p_result, const QList<QTextCursor> &p_part)
  354. {
  355. if (p_result.isEmpty()) {
  356. p_result = p_part;
  357. return;
  358. }
  359. int idx = 0;
  360. for (auto const & cur : p_part) {
  361. // Find position to insert into @p_result.
  362. while (idx < p_result.size()) {
  363. const QTextCursor &toCur = p_result[idx];
  364. if (cur.selectionEnd() <= toCur.selectionStart()) {
  365. // Insert it before toCur.
  366. p_result.insert(idx, cur);
  367. ++idx;
  368. break;
  369. } else if (cur.selectionStart() < toCur.selectionEnd()) {
  370. // Interleave. Abandon it.
  371. break;
  372. } else {
  373. ++idx;
  374. }
  375. }
  376. // Insert to the end.
  377. if (idx >= p_result.size()) {
  378. p_result.append(cur);
  379. idx = p_result.size();
  380. }
  381. }
  382. }
  383. QList<QTextCursor> VEditor::findTextAll(const VSearchToken &p_token,
  384. int p_start,
  385. int p_end)
  386. {
  387. QList<QTextCursor> results;
  388. if (p_token.isEmpty()) {
  389. return results;
  390. }
  391. QTextDocument::FindFlags flags;
  392. if (p_token.m_caseSensitivity == Qt::CaseSensitive) {
  393. flags |= QTextDocument::FindCaseSensitively;
  394. }
  395. if (p_token.m_type == VSearchToken::RawString) {
  396. for (auto const & wd : p_token.m_keywords) {
  397. QList<QTextCursor> part = findTextAllInRange(m_document, wd, flags, p_start, p_end);
  398. mergeResult(results, part);
  399. }
  400. } else {
  401. // Regular expression.
  402. for (auto const & reg : p_token.m_regs) {
  403. QList<QTextCursor> part = findTextAllInRange(m_document, reg, flags, p_start, p_end);
  404. mergeResult(results, part);
  405. }
  406. }
  407. return results;
  408. }
  409. const QList<QTextCursor> &VEditor::findTextAllCached(const QString &p_text,
  410. uint p_options,
  411. int p_start,
  412. int p_end)
  413. {
  414. if (p_text.isEmpty()) {
  415. m_findInfo.clear();
  416. return m_findInfo.m_result;
  417. }
  418. if (m_findInfo.isCached(p_text, p_options, p_start, p_end)) {
  419. return m_findInfo.m_result;
  420. }
  421. QList<QTextCursor> result = findTextAll(p_text, p_options, p_start, p_end);
  422. m_findInfo.update(p_text, p_options, p_start, p_end, result);
  423. return m_findInfo.m_result;
  424. }
  425. const QList<QTextCursor> &VEditor::findTextAllCached(const VSearchToken &p_token,
  426. int p_start,
  427. int p_end)
  428. {
  429. if (p_token.isEmpty()) {
  430. m_findInfo.clear();
  431. return m_findInfo.m_result;
  432. }
  433. if (m_findInfo.isCached(p_token, p_start, p_end)) {
  434. return m_findInfo.m_result;
  435. }
  436. QList<QTextCursor> result = findTextAll(p_token, p_start, p_end);
  437. m_findInfo.update(p_token, p_start, p_end, result);
  438. return m_findInfo.m_result;
  439. }
  440. void VEditor::highlightSelectedWord()
  441. {
  442. QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SelectedWord];
  443. if (!g_config->getHighlightSelectedWord()) {
  444. if (!selects.isEmpty()) {
  445. selects.clear();
  446. highlightExtraSelections(true);
  447. }
  448. return;
  449. }
  450. QString text = textCursorW().selectedText().trimmed();
  451. if (text.isEmpty() || wordInSearchedSelection(text)) {
  452. selects.clear();
  453. highlightExtraSelections(true);
  454. return;
  455. }
  456. QTextCharFormat format;
  457. format.setForeground(m_selectedWordFg);
  458. format.setBackground(m_selectedWordBg);
  459. highlightTextAll(text,
  460. FindOption::CaseSensitive,
  461. SelectionId::SelectedWord,
  462. format);
  463. }
  464. bool VEditor::wordInSearchedSelection(const QString &p_text)
  465. {
  466. QString text = p_text.trimmed();
  467. QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeyword];
  468. for (int i = 0; i < selects.size(); ++i) {
  469. QString searchedWord = selects[i].cursor.selectedText();
  470. if (text == searchedWord.trimmed()) {
  471. return true;
  472. }
  473. }
  474. return false;
  475. }
  476. bool VEditor::isModified() const
  477. {
  478. return m_document->isModified();
  479. }
  480. void VEditor::setModified(bool p_modified)
  481. {
  482. m_document->setModified(p_modified);
  483. }
  484. void VEditor::insertImage()
  485. {
  486. if (m_editOps) {
  487. m_editOps->insertImage();
  488. }
  489. }
  490. void VEditor::insertLink()
  491. {
  492. if (!m_editOps) {
  493. return;
  494. }
  495. QString text;
  496. QString linkText, linkUrl;
  497. QTextCursor cursor = textCursorW();
  498. if (cursor.hasSelection()) {
  499. text = VEditUtils::selectedText(cursor).trimmed();
  500. // Only pure space is accepted.
  501. QRegExp reg("[\\S ]*");
  502. if (reg.exactMatch(text)) {
  503. QUrl url = QUrl::fromUserInput(text,
  504. m_file->fetchBasePath());
  505. QRegExp urlReg("[\\.\\\\/]");
  506. if (url.isValid()
  507. && text.contains(urlReg)) {
  508. // Url.
  509. linkUrl = text;
  510. } else {
  511. // Text.
  512. linkText = text;
  513. }
  514. }
  515. }
  516. VInsertLinkDialog dialog(QObject::tr("Insert Link"),
  517. "",
  518. "",
  519. linkText,
  520. linkUrl,
  521. false,
  522. m_editor);
  523. if (dialog.exec() == QDialog::Accepted) {
  524. linkText = dialog.getLinkText();
  525. linkUrl = dialog.getLinkUrl();
  526. Q_ASSERT(!linkText.isEmpty() && !linkUrl.isEmpty());
  527. m_editOps->insertLink(linkText, linkUrl);
  528. }
  529. }
  530. bool VEditor::peekText(const QString &p_text, uint p_options, bool p_forward)
  531. {
  532. if (p_text.isEmpty()) {
  533. makeBlockVisible(m_document->findBlock(textCursorW().selectionStart()));
  534. highlightIncrementalSearchedWord(QTextCursor());
  535. return false;
  536. }
  537. bool wrapped = false;
  538. QTextCursor retCursor;
  539. int start = textCursorW().position();
  540. int skipPosition = start;
  541. bool found = false;
  542. while (true) {
  543. found = findTextHelper(p_text, p_options, p_forward, start, wrapped, retCursor);
  544. if (found) {
  545. if (p_forward && retCursor.selectionStart() == skipPosition) {
  546. // Skip the first match.
  547. skipPosition = -1;
  548. start = retCursor.selectionEnd();
  549. continue;
  550. }
  551. makeBlockVisible(m_document->findBlock(retCursor.selectionStart()));
  552. highlightIncrementalSearchedWord(retCursor);
  553. }
  554. break;
  555. }
  556. return found;
  557. }
  558. // @p_cursors is in ascending order.
  559. // If @p_forward is true, find the smallest cursor whose selection start is greater
  560. // than @p_pos or the first cursor if wrapped.
  561. // Otherwise, find the largest cursor whose selection start is smaller than @p_pos
  562. // or the last cursor if wrapped.
  563. static int selectCursor(const QList<QTextCursor> &p_cursors,
  564. int p_pos,
  565. bool p_forward,
  566. bool &p_wrapped)
  567. {
  568. Q_ASSERT(!p_cursors.isEmpty());
  569. p_wrapped = false;
  570. int first = 0, last = p_cursors.size() - 1;
  571. int lastMatch = -1;
  572. while (first <= last) {
  573. int mid = (first + last) / 2;
  574. const QTextCursor &cur = p_cursors.at(mid);
  575. if (p_forward) {
  576. if (cur.selectionStart() < p_pos) {
  577. first = mid + 1;
  578. } else if (cur.selectionStart() == p_pos) {
  579. // Next one is the right one.
  580. if (mid < p_cursors.size() - 1) {
  581. lastMatch = mid + 1;
  582. } else {
  583. lastMatch = 0;
  584. p_wrapped = true;
  585. }
  586. break;
  587. } else {
  588. // It is a match.
  589. if (lastMatch == -1 || mid < lastMatch) {
  590. lastMatch = mid;
  591. }
  592. last = mid - 1;
  593. }
  594. } else {
  595. if (cur.selectionStart() > p_pos) {
  596. last = mid - 1;
  597. } else if (cur.selectionStart() == p_pos) {
  598. // Previous one is the right one.
  599. if (mid > 0) {
  600. lastMatch = mid - 1;
  601. } else {
  602. lastMatch = p_cursors.size() - 1;
  603. p_wrapped = true;
  604. }
  605. break;
  606. } else {
  607. // It is a match.
  608. if (lastMatch == -1 || mid > lastMatch) {
  609. lastMatch = mid;
  610. }
  611. first = mid + 1;
  612. }
  613. }
  614. }
  615. if (lastMatch == -1) {
  616. p_wrapped = true;
  617. lastMatch = p_forward ? 0 : (p_cursors.size() - 1);
  618. }
  619. return lastMatch;
  620. }
  621. bool VEditor::findText(const QString &p_text,
  622. uint p_options,
  623. bool p_forward,
  624. QTextCursor *p_cursor,
  625. QTextCursor::MoveMode p_moveMode,
  626. bool p_useLeftSideOfCursor)
  627. {
  628. return findTextInRange(p_text,
  629. p_options,
  630. p_forward,
  631. p_cursor,
  632. p_moveMode,
  633. p_useLeftSideOfCursor);
  634. }
  635. bool VEditor::findText(const VSearchToken &p_token, bool p_forward, bool p_fromStart)
  636. {
  637. clearIncrementalSearchedWordHighlight();
  638. if (p_token.isEmpty()) {
  639. m_findInfo.clear();
  640. clearSearchedWordHighlight();
  641. return false;
  642. }
  643. const QList<QTextCursor> &result = findTextAllCached(p_token);
  644. if (result.isEmpty()) {
  645. clearSearchedWordHighlight();
  646. emit m_object->statusMessage(QObject::tr("No match found"));
  647. } else {
  648. // Locate to the right match and update current cursor.
  649. QTextCursor cursor = textCursorW();
  650. int pos = p_fromStart ? (m_document->characterCount() + 1) : cursor.position();
  651. bool wrapped = false;
  652. int idx = selectCursor(result, pos, p_forward, wrapped);
  653. const QTextCursor &tcursor = result.at(idx);
  654. if (wrapped && !p_fromStart) {
  655. showWrapLabel();
  656. }
  657. cursor.setPosition(tcursor.selectionStart(), QTextCursor::MoveAnchor);
  658. setTextCursorW(cursor);
  659. highlightSearchedWord(result);
  660. highlightSearchedWordUnderCursor(tcursor);
  661. emit m_object->statusMessage(QObject::tr("Match found: %1 of %2")
  662. .arg(idx + 1)
  663. .arg(result.size()));
  664. }
  665. return !result.isEmpty();
  666. }
  667. bool VEditor::findTextInRange(const QString &p_text,
  668. uint p_options,
  669. bool p_forward,
  670. QTextCursor *p_cursor,
  671. QTextCursor::MoveMode p_moveMode,
  672. bool p_useLeftSideOfCursor,
  673. int p_start,
  674. int p_end)
  675. {
  676. clearIncrementalSearchedWordHighlight();
  677. if (p_text.isEmpty()) {
  678. m_findInfo.clear();
  679. clearSearchedWordHighlight();
  680. return false;
  681. }
  682. const QList<QTextCursor> &result = findTextAllCached(p_text, p_options, p_start, p_end);
  683. if (result.isEmpty()) {
  684. clearSearchedWordHighlight();
  685. emit m_object->statusMessage(QObject::tr("No match found"));
  686. } else {
  687. // Locate to the right match and update current cursor.
  688. QTextCursor cursor = textCursorW();
  689. int pos = p_cursor ? p_cursor->position() : cursor.position();
  690. if (p_useLeftSideOfCursor) {
  691. --pos;
  692. }
  693. bool wrapped = false;
  694. int idx = selectCursor(result, pos, p_forward, wrapped);
  695. const QTextCursor &tcursor = result.at(idx);
  696. if (wrapped) {
  697. showWrapLabel();
  698. }
  699. if (p_cursor) {
  700. p_cursor->setPosition(tcursor.selectionStart(), p_moveMode);
  701. } else {
  702. cursor.setPosition(tcursor.selectionStart(), p_moveMode);
  703. setTextCursorW(cursor);
  704. }
  705. highlightSearchedWord(result);
  706. highlightSearchedWordUnderCursor(tcursor);
  707. emit m_object->statusMessage(QObject::tr("Match found: %1 of %2")
  708. .arg(idx + 1)
  709. .arg(result.size()));
  710. }
  711. return !result.isEmpty();
  712. }
  713. bool VEditor::findTextOne(const QString &p_text, uint p_options, bool p_forward)
  714. {
  715. clearIncrementalSearchedWordHighlight();
  716. if (p_text.isEmpty()) {
  717. clearSearchedWordHighlight();
  718. return false;
  719. }
  720. QTextCursor cursor = textCursorW();
  721. bool wrapped = false;
  722. QTextCursor retCursor;
  723. int start = cursor.position();
  724. bool found = findTextHelper(p_text, p_options, p_forward, start, wrapped, retCursor);
  725. if (found) {
  726. Q_ASSERT(!retCursor.isNull());
  727. if (wrapped) {
  728. showWrapLabel();
  729. }
  730. cursor.setPosition(retCursor.selectionStart(), QTextCursor::MoveAnchor);
  731. setTextCursorW(cursor);
  732. highlightSearchedWordUnderCursor(retCursor);
  733. } else {
  734. clearSearchedWordHighlight();
  735. }
  736. return found;
  737. }
  738. bool VEditor::findTextInRange(const QString &p_text,
  739. uint p_options,
  740. bool p_forward,
  741. int p_start,
  742. int p_end)
  743. {
  744. return findTextInRange(p_text,
  745. p_options,
  746. p_forward,
  747. nullptr,
  748. QTextCursor::MoveAnchor,
  749. false,
  750. p_start,
  751. p_end);
  752. }
  753. void VEditor::highlightIncrementalSearchedWord(const QTextCursor &p_cursor)
  754. {
  755. QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::IncrementalSearchedKeyword];
  756. if (!g_config->getHighlightSearchedWord() || !p_cursor.hasSelection()) {
  757. if (!selects.isEmpty()) {
  758. selects.clear();
  759. highlightExtraSelections(true);
  760. }
  761. return;
  762. }
  763. selects.clear();
  764. QTextEdit::ExtraSelection select;
  765. select.format.setForeground(m_incrementalSearchedWordFg);
  766. select.format.setBackground(m_incrementalSearchedWordBg);
  767. select.cursor = p_cursor;
  768. selects.append(select);
  769. highlightExtraSelections(true);
  770. }
  771. static bool isRegularExpressionSupported(const QRegExp &p_reg)
  772. {
  773. if (!p_reg.isValid()) {
  774. return false;
  775. }
  776. // FIXME: hang bug in Qt's find().
  777. QRegExp test("[$^]+");
  778. if (test.exactMatch(p_reg.pattern())) {
  779. return false;
  780. }
  781. return true;
  782. }
  783. // Use QPlainTextEdit::find() instead of QTextDocument::find() because the later has
  784. // bugs in searching backward.
  785. bool VEditor::findTextHelper(const QString &p_text,
  786. uint p_options,
  787. bool p_forward,
  788. int p_start,
  789. bool &p_wrapped,
  790. QTextCursor &p_cursor)
  791. {
  792. p_wrapped = false;
  793. bool found = false;
  794. // Options
  795. bool caseSensitive = p_options & FindOption::CaseSensitive;
  796. QTextDocument::FindFlags findFlags = findOptionsToFlags(p_options, p_forward);
  797. // Use regular expression
  798. bool useRegExp = p_options & FindOption::RegularExpression;
  799. QRegExp exp;
  800. if (useRegExp) {
  801. useRegExp = true;
  802. exp = QRegExp(p_text,
  803. caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive);
  804. if (!isRegularExpressionSupported(exp)) {
  805. return false;
  806. }
  807. }
  808. // Store current state of the cursor.
  809. QTextCursor cursor = textCursorW();
  810. if (cursor.position() != p_start) {
  811. if (p_start < 0) {
  812. p_start = 0;
  813. } else if (p_start > m_document->characterCount()) {
  814. p_start = m_document->characterCount();
  815. }
  816. }
  817. QTextCursor startCursor = cursor;
  818. // Will clear the selection.
  819. startCursor.setPosition(p_start);
  820. setTextCursorW(startCursor);
  821. while (!found) {
  822. if (useRegExp) {
  823. found = findW(exp, findFlags);
  824. } else {
  825. found = findW(p_text, findFlags);
  826. }
  827. if (p_wrapped) {
  828. break;
  829. }
  830. if (!found) {
  831. // Wrap to the other end of the document to search again.
  832. p_wrapped = true;
  833. QTextCursor wrapCursor = textCursorW();
  834. if (p_forward) {
  835. wrapCursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
  836. } else {
  837. wrapCursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
  838. }
  839. setTextCursorW(wrapCursor);
  840. }
  841. }
  842. if (found) {
  843. p_cursor = textCursorW();
  844. }
  845. // Restore the original cursor.
  846. setTextCursorW(cursor);
  847. return found;
  848. }
  849. void VEditor::clearIncrementalSearchedWordHighlight(bool p_now)
  850. {
  851. QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::IncrementalSearchedKeyword];
  852. if (selects.isEmpty()) {
  853. return;
  854. }
  855. selects.clear();
  856. highlightExtraSelections(p_now);
  857. }
  858. void VEditor::clearSearchedWordHighlight()
  859. {
  860. clearIncrementalSearchedWordHighlight(false);
  861. clearSearchedWordUnderCursorHighlight(false);
  862. QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeyword];
  863. if (selects.isEmpty()) {
  864. return;
  865. }
  866. selects.clear();
  867. highlightExtraSelections(true);
  868. }
  869. void VEditor::clearSearchedWordUnderCursorHighlight(bool p_now)
  870. {
  871. QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeywordUnderCursor];
  872. if (selects.isEmpty()) {
  873. return;
  874. }
  875. selects.clear();
  876. highlightExtraSelections(p_now);
  877. }
  878. void VEditor::showWrapLabel()
  879. {
  880. int labelW = m_wrapLabel->width();
  881. int labelH = m_wrapLabel->height();
  882. int x = (m_editor->width() - labelW) / 2;
  883. int y = (m_editor->height() - labelH) / 2;
  884. if (x < 0) {
  885. x = 0;
  886. }
  887. if (y < 0) {
  888. y = 0;
  889. }
  890. m_wrapLabel->move(x, y);
  891. m_wrapLabel->show();
  892. m_labelTimer->stop();
  893. m_labelTimer->start();
  894. }
  895. void VEditor::highlightSearchedWord(const QList<QTextCursor> &p_matches)
  896. {
  897. QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeyword];
  898. if (!g_config->getHighlightSearchedWord() || p_matches.isEmpty()) {
  899. if (!selects.isEmpty()) {
  900. selects.clear();
  901. highlightExtraSelections(true);
  902. }
  903. return;
  904. }
  905. selects.clear();
  906. QTextCharFormat format;
  907. format.setForeground(m_searchedWordFg);
  908. format.setBackground(m_searchedWordBg);
  909. for (int i = 0; i < p_matches.size(); ++i) {
  910. QTextEdit::ExtraSelection select;
  911. select.format = format;
  912. select.cursor = p_matches[i];
  913. selects.append(select);
  914. }
  915. highlightExtraSelections();
  916. }
  917. void VEditor::highlightSearchedWordUnderCursor(const QTextCursor &p_cursor)
  918. {
  919. QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeywordUnderCursor];
  920. if (!p_cursor.hasSelection()) {
  921. if (!selects.isEmpty()) {
  922. selects.clear();
  923. highlightExtraSelections(true);
  924. }
  925. return;
  926. }
  927. selects.clear();
  928. QTextEdit::ExtraSelection select;
  929. select.format.setForeground(m_searchedWordCursorFg);
  930. select.format.setBackground(m_searchedWordCursorBg);
  931. select.cursor = p_cursor;
  932. selects.append(select);
  933. highlightExtraSelections(true);
  934. }
  935. static void fillReplaceTextWithBackReference(QString &p_replaceText,
  936. const QString &p_text,
  937. const QRegExp &p_exp)
  938. {
  939. int idx = p_exp.indexIn(p_text);
  940. if (idx != 0) {
  941. return;
  942. }
  943. QStringList caps = p_exp.capturedTexts();
  944. if (caps.size() < 2) {
  945. return;
  946. }
  947. QChar sla('\\');
  948. int pos = 0;
  949. while (pos < p_replaceText.size()) {
  950. int idx = p_replaceText.indexOf(sla, pos);
  951. if (idx == -1 || idx == p_replaceText.size() - 1) {
  952. break;
  953. }
  954. QChar ne(p_replaceText[idx + 1]);
  955. if (ne == sla) {
  956. // \\ to \.
  957. p_replaceText.remove(idx, 1);
  958. } else if (ne.isDigit()) {
  959. // TODO: for now, we only support 1 - 9.
  960. int num = ne.digitValue();
  961. if (num > 0 && num < caps.size()) {
  962. // Replace it.
  963. p_replaceText.replace(idx, 2, caps[num]);
  964. pos = idx + caps[num].size() - 2;
  965. continue;
  966. }
  967. }
  968. pos = idx + 1;
  969. }
  970. }
  971. void VEditor::replaceText(const QString &p_text,
  972. uint p_options,
  973. const QString &p_replaceText,
  974. bool p_findNext)
  975. {
  976. QTextCursor cursor = textCursorW();
  977. bool wrapped = false;
  978. QTextCursor retCursor;
  979. QString newText(p_replaceText);
  980. bool useRegExp = p_options & FindOption::RegularExpression;
  981. QRegExp exp;
  982. if (useRegExp) {
  983. exp = QRegExp(p_text,
  984. (p_options & FindOption::CaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive);
  985. }
  986. bool found = findTextHelper(p_text,
  987. p_options,
  988. true,
  989. cursor.position(),
  990. wrapped,
  991. retCursor);
  992. if (found) {
  993. if (retCursor.selectionStart() == cursor.position()) {
  994. // Matched.
  995. if (useRegExp) {
  996. // Handle \1, \2 in replace text.
  997. fillReplaceTextWithBackReference(newText,
  998. VEditUtils::selectedText(retCursor),
  999. exp);
  1000. }
  1001. retCursor.beginEditBlock();
  1002. retCursor.insertText(newText);
  1003. retCursor.endEditBlock();
  1004. setTextCursorW(retCursor);
  1005. }
  1006. if (p_findNext) {
  1007. findTextOne(p_text, p_options, true);
  1008. }
  1009. }
  1010. }
  1011. void VEditor::replaceTextAll(const QString &p_text,
  1012. uint p_options,
  1013. const QString &p_replaceText)
  1014. {
  1015. // Replace from the start to the end and restore the cursor.
  1016. QTextCursor cursor = textCursorW();
  1017. int nrReplaces = 0;
  1018. QTextCursor tmpCursor = cursor;
  1019. tmpCursor.setPosition(0);
  1020. setTextCursorW(tmpCursor);
  1021. int start = tmpCursor.position();
  1022. QString newText;
  1023. bool useRegExp = p_options & FindOption::RegularExpression;
  1024. QRegExp exp;
  1025. if (useRegExp) {
  1026. exp = QRegExp(p_text,
  1027. (p_options & FindOption::CaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive);
  1028. } else {
  1029. newText = p_replaceText;
  1030. }
  1031. while (true) {
  1032. bool wrapped = false;
  1033. QTextCursor retCursor;
  1034. bool found = findTextHelper(p_text,
  1035. p_options,
  1036. true,
  1037. start,
  1038. wrapped,
  1039. retCursor);
  1040. if (!found) {
  1041. break;
  1042. } else {
  1043. if (wrapped) {
  1044. // Wrap back.
  1045. break;
  1046. }
  1047. if (useRegExp) {
  1048. newText = p_replaceText;
  1049. fillReplaceTextWithBackReference(newText,
  1050. VEditUtils::selectedText(retCursor),
  1051. exp);
  1052. }
  1053. nrReplaces++;
  1054. retCursor.beginEditBlock();
  1055. retCursor.insertText(newText);
  1056. retCursor.endEditBlock();
  1057. setTextCursorW(retCursor);
  1058. start = retCursor.position();
  1059. }
  1060. }
  1061. // Restore cursor position.
  1062. cursor.clearSelection();
  1063. setTextCursorW(cursor);
  1064. qDebug() << "replace all" << nrReplaces << "occurences";
  1065. emit m_object->statusMessage(QObject::tr("Replace %1 %2").arg(nrReplaces)
  1066. .arg(nrReplaces > 1 ? QObject::tr("occurences")
  1067. : QObject::tr("occurence")));
  1068. }
  1069. void VEditor::evaluateMagicWords()
  1070. {
  1071. QString text;
  1072. QTextCursor cursor = textCursorW();
  1073. if (!cursor.hasSelection()) {
  1074. // Get the WORD in current cursor.
  1075. int start, end;
  1076. VEditUtils::findCurrentWORD(cursor, start, end);
  1077. if (start == end) {
  1078. return;
  1079. } else {
  1080. cursor.setPosition(start);
  1081. cursor.setPosition(end, QTextCursor::KeepAnchor);
  1082. }
  1083. }
  1084. text = VEditUtils::selectedText(cursor);
  1085. Q_ASSERT(!text.isEmpty());
  1086. QString evaText = g_mwMgr->evaluate(text);
  1087. if (text != evaText) {
  1088. qDebug() << "evaluateMagicWords" << text << evaText;
  1089. cursor.insertText(evaText);
  1090. if (m_editOps) {
  1091. m_editOps->setVimMode(VimMode::Insert);
  1092. }
  1093. setTextCursorW(cursor);
  1094. }
  1095. }
  1096. void VEditor::setReadOnlyAndHighlightCurrentLine(bool p_readonly)
  1097. {
  1098. setReadOnlyW(p_readonly);
  1099. highlightCurrentLine();
  1100. }
  1101. bool VEditor::handleMousePressEvent(QMouseEvent *p_event)
  1102. {
  1103. if (p_event->button() == Qt::LeftButton
  1104. && p_event->modifiers() == Qt::ControlModifier
  1105. && !textCursorW().hasSelection()) {
  1106. m_oriMouseX = p_event->x();
  1107. m_oriMouseY = p_event->y();
  1108. m_readyToScroll = true;
  1109. m_mouseMoveScrolled = false;
  1110. p_event->accept();
  1111. return true;
  1112. }
  1113. m_readyToScroll = false;
  1114. m_mouseMoveScrolled = false;
  1115. return false;
  1116. }
  1117. bool VEditor::handleMouseReleaseEvent(QMouseEvent *p_event)
  1118. {
  1119. if (m_mouseMoveScrolled || m_readyToScroll) {
  1120. viewportW()->setCursor(Qt::IBeamCursor);
  1121. m_readyToScroll = false;
  1122. m_mouseMoveScrolled = false;
  1123. p_event->accept();
  1124. return true;
  1125. }
  1126. m_readyToScroll = false;
  1127. m_mouseMoveScrolled = false;
  1128. return false;
  1129. }
  1130. bool VEditor::handleMouseMoveEvent(QMouseEvent *p_event)
  1131. {
  1132. const int threshold = 5;
  1133. if (m_readyToScroll) {
  1134. int deltaX = p_event->x() - m_oriMouseX;
  1135. int deltaY = p_event->y() - m_oriMouseY;
  1136. if (qAbs(deltaX) >= threshold || qAbs(deltaY) >= threshold) {
  1137. m_oriMouseX = p_event->x();
  1138. m_oriMouseY = p_event->y();
  1139. if (!m_mouseMoveScrolled) {
  1140. m_mouseMoveScrolled = true;
  1141. viewportW()->setCursor(Qt::SizeAllCursor);
  1142. }
  1143. QScrollBar *verBar = verticalScrollBarW();
  1144. QScrollBar *horBar = horizontalScrollBarW();
  1145. if (verBar->isVisible()) {
  1146. verBar->setValue(verBar->value() - deltaY);
  1147. }
  1148. if (horBar->isVisible()) {
  1149. horBar->setValue(horBar->value() - deltaX);
  1150. }
  1151. }
  1152. p_event->accept();
  1153. return true;
  1154. }
  1155. return false;
  1156. }
  1157. bool VEditor::handleWheelEvent(QWheelEvent *p_event)
  1158. {
  1159. Qt::KeyboardModifiers modifiers = p_event->modifiers();
  1160. if (modifiers == Qt::ShiftModifier) {
  1161. // Scroll horizontally.
  1162. QPoint numPixels = p_event->pixelDelta();
  1163. QPoint numDegrees = p_event->angleDelta() / 8;
  1164. QScrollBar *horBar = horizontalScrollBarW();
  1165. int steps = 0;
  1166. if (!numPixels.isNull()) {
  1167. steps = numPixels.y();
  1168. } else if (!numDegrees.isNull()) {
  1169. QPoint numSteps = numDegrees / 15;
  1170. steps = numSteps.y() * horBar->singleStep();
  1171. }
  1172. if (horBar->minimum() != horBar->maximum()) {
  1173. horBar->setValue(horBar->value() - steps);
  1174. }
  1175. p_event->accept();
  1176. return true;
  1177. } else if (modifiers == Qt::ControlModifier) {
  1178. // Zoom in/out.
  1179. QPoint angle = p_event->angleDelta();
  1180. if (!angle.isNull() && (angle.y() != 0)) {
  1181. if (angle.y() > 0) {
  1182. zoomInW();
  1183. } else {
  1184. zoomOutW();
  1185. }
  1186. }
  1187. p_event->accept();
  1188. return true;
  1189. }
  1190. return false;
  1191. }
  1192. void VEditor::requestUpdateVimStatus()
  1193. {
  1194. if (m_editOps) {
  1195. m_editOps->requestUpdateVimStatus();
  1196. } else {
  1197. emit m_object->vimStatusUpdated(NULL);
  1198. }
  1199. }
  1200. bool VEditor::handleInputMethodQuery(Qt::InputMethodQuery p_query,
  1201. QVariant &p_var) const
  1202. {
  1203. if (p_query == Qt::ImEnabled) {
  1204. p_var = m_enableInputMethod;
  1205. return true;
  1206. }
  1207. return false;
  1208. }
  1209. void VEditor::setInputMethodEnabled(bool p_enabled)
  1210. {
  1211. if (m_enableInputMethod != p_enabled) {
  1212. m_enableInputMethod = p_enabled;
  1213. QInputMethod *im = QGuiApplication::inputMethod();
  1214. im->reset();
  1215. // Ask input method to query current state, which will call inputMethodQuery().
  1216. im->update(Qt::ImEnabled);
  1217. }
  1218. }
  1219. void VEditor::decorateText(TextDecoration p_decoration, int p_level)
  1220. {
  1221. if (m_editOps) {
  1222. m_editOps->decorateText(p_decoration, p_level);
  1223. }
  1224. }
  1225. void VEditor::updateConfig()
  1226. {
  1227. updateEditConfig();
  1228. }
  1229. void VEditor::setVimMode(VimMode p_mode)
  1230. {
  1231. if (m_editOps) {
  1232. m_editOps->setVimMode(p_mode);
  1233. }
  1234. }
  1235. VVim *VEditor::getVim() const
  1236. {
  1237. if (m_editOps) {
  1238. return m_editOps->getVim();
  1239. }
  1240. return NULL;
  1241. }
  1242. bool VEditor::setCursorPosition(int p_blockNumber, int p_posInBlock)
  1243. {
  1244. QTextDocument *doc = documentW();
  1245. QTextBlock block = doc->findBlockByNumber(p_blockNumber);
  1246. if (!block.isValid() || block.length() <= p_posInBlock) {
  1247. return false;
  1248. }
  1249. QTextCursor cursor = textCursorW();
  1250. cursor.setPosition(block.position() + p_posInBlock);
  1251. setTextCursorW(cursor);
  1252. return true;
  1253. }
  1254. static Qt::CaseSensitivity completionCaseSensitivity(const QString &p_text)
  1255. {
  1256. bool upperCase = false;
  1257. for (int i = 0; i < p_text.size(); ++i) {
  1258. if (p_text[i].isUpper()) {
  1259. upperCase = true;
  1260. break;
  1261. }
  1262. }
  1263. return upperCase ? Qt::CaseSensitive : Qt::CaseInsensitive;
  1264. }
  1265. void VEditor::requestCompletion(bool p_reversed)
  1266. {
  1267. QTextCursor cursor = textCursorW();
  1268. cursor.clearSelection();
  1269. setTextCursorW(cursor);
  1270. QStringList words = generateCompletionCandidates(p_reversed);
  1271. QString prefix = fetchCompletionPrefix();
  1272. // Smart case.
  1273. Qt::CaseSensitivity cs = completionCaseSensitivity(prefix);
  1274. cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::MoveAnchor, prefix.size());
  1275. QRect popupRect = cursorRectW(cursor);
  1276. popupRect.setLeft(popupRect.left() + lineNumberAreaWidth());
  1277. m_completer->performCompletion(words, prefix, cs, p_reversed, popupRect, this);
  1278. }
  1279. bool VEditor::isCompletionActivated() const
  1280. {
  1281. if (m_completer->widget() == m_editor
  1282. && m_completer->isPopupVisible()) {
  1283. return true;
  1284. }
  1285. return false;
  1286. }
  1287. QStringList VEditor::generateCompletionCandidates(bool p_reversed) const
  1288. {
  1289. QString content = getContent();
  1290. QTextCursor cursor = textCursorW();
  1291. int start, end;
  1292. VEditUtils::findCurrentWord(cursor, start, end, true);
  1293. QRegExp reg("\\W+");
  1294. QStringList above = content.left(start).split(reg, QString::SkipEmptyParts);
  1295. QStringList below = content.mid(end).split(reg, QString::SkipEmptyParts);
  1296. if (p_reversed) {
  1297. QStringList rev;
  1298. rev.reserve(above.size() + below.size());
  1299. for (auto it = above.rbegin(); it != above.rend(); ++it) {
  1300. rev.append(*it);
  1301. }
  1302. for (auto it = below.rbegin(); it != below.rend(); ++it) {
  1303. rev.append(*it);
  1304. }
  1305. rev.removeDuplicates();
  1306. QStringList res;
  1307. res.reserve(rev.size());
  1308. for (auto it = rev.rbegin(); it != rev.rend(); ++it) {
  1309. res.append(*it);
  1310. }
  1311. return res;
  1312. } else {
  1313. // below + above.
  1314. below.append(above);
  1315. below.removeDuplicates();
  1316. return below;
  1317. }
  1318. }
  1319. QString VEditor::fetchCompletionPrefix() const
  1320. {
  1321. QTextCursor cursor = textCursorW();
  1322. if (cursor.atBlockStart()) {
  1323. return QString();
  1324. }
  1325. int pos = cursor.position() - 1;
  1326. int blockPos = cursor.block().position();
  1327. QString prefix;
  1328. while (pos >= blockPos) {
  1329. QChar ch = m_document->characterAt(pos);
  1330. if (VEditUtils::isSpaceOrWordSeparator(ch)) {
  1331. break;
  1332. }
  1333. prefix.prepend(ch);
  1334. --pos;
  1335. }
  1336. return prefix;
  1337. }
  1338. // @p_prefix may be longer than @p_completion.
  1339. void VEditor::insertCompletion(const QString &p_prefix, const QString &p_completion)
  1340. {
  1341. QTextCursor cursor = textCursorW();
  1342. cursor.joinPreviousEditBlock();
  1343. cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, p_prefix.size());
  1344. cursor.insertText(p_completion);
  1345. cursor.endEditBlock();
  1346. setTextCursorW(cursor);
  1347. }
  1348. QList<QTextCursor> VEditor::findTextAllInRange(const QTextDocument *p_doc,
  1349. const QString &p_text,
  1350. QTextDocument::FindFlags p_flags,
  1351. int p_start,
  1352. int p_end)
  1353. {
  1354. QList<QTextCursor> results;
  1355. if (p_text.isEmpty()) {
  1356. return results;
  1357. }
  1358. int start = p_start;
  1359. int end = p_end == -1 ? p_doc->characterCount() + 1 : p_end;
  1360. while (start < end) {
  1361. QTextCursor cursor = p_doc->find(p_text, start, p_flags);
  1362. if (cursor.isNull()) {
  1363. break;
  1364. } else {
  1365. start = cursor.selectionEnd();
  1366. if (start <= end) {
  1367. results.append(cursor);
  1368. }
  1369. }
  1370. }
  1371. return results;
  1372. }
  1373. QList<QTextCursor> VEditor::findTextAllInRange(const QTextDocument *p_doc,
  1374. const QRegExp &p_reg,
  1375. QTextDocument::FindFlags p_flags,
  1376. int p_start,
  1377. int p_end)
  1378. {
  1379. QList<QTextCursor> results;
  1380. if (!isRegularExpressionSupported(p_reg)) {
  1381. return results;
  1382. }
  1383. int start = p_start;
  1384. int end = p_end == -1 ? p_doc->characterCount() + 1 : p_end;
  1385. while (start < end) {
  1386. QTextCursor cursor = p_doc->find(p_reg, start, p_flags);
  1387. if (cursor.isNull()) {
  1388. break;
  1389. } else {
  1390. start = cursor.selectionEnd();
  1391. if (start <= end) {
  1392. results.append(cursor);
  1393. }
  1394. }
  1395. }
  1396. return results;
  1397. }
  1398. void VEditor::clearFindCache()
  1399. {
  1400. m_findInfo.clearResult();
  1401. }
  1402. void VEditor::nextMatch(bool p_forward)
  1403. {
  1404. if (m_findInfo.isNull()) {
  1405. return;
  1406. }
  1407. if (m_findInfo.m_useToken) {
  1408. findText(m_findInfo.m_token, p_forward, false);
  1409. } else {
  1410. findTextInRange(m_findInfo.m_text,
  1411. m_findInfo.m_options,
  1412. p_forward,
  1413. m_findInfo.m_start,
  1414. m_findInfo.m_end);
  1415. }
  1416. }