vmdeditoperations.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. #include <QtDebug>
  2. #include <QImage>
  3. #include <QVariant>
  4. #include <QMimeData>
  5. #include <QWidget>
  6. #include <QImageReader>
  7. #include <QDir>
  8. #include <QMessageBox>
  9. #include <QKeyEvent>
  10. #include <QTextCursor>
  11. #include <QTimer>
  12. #include <QGuiApplication>
  13. #include <QApplication>
  14. #include <QClipboard>
  15. #include "vmdeditoperations.h"
  16. #include "dialog/vinsertimagedialog.h"
  17. #include "dialog/vselectdialog.h"
  18. #include "utils/vutils.h"
  19. #include "veditor.h"
  20. #include "vdownloader.h"
  21. #include "vfile.h"
  22. #include "vmdeditor.h"
  23. #include "vconfigmanager.h"
  24. #include "utils/vvim.h"
  25. #include "utils/veditutils.h"
  26. extern VConfigManager *g_config;
  27. const QString VMdEditOperations::c_defaultImageTitle = "";
  28. VMdEditOperations::VMdEditOperations(VEditor *p_editor, VFile *p_file)
  29. : VEditOperations(p_editor, p_file), m_autoIndentPos(-1)
  30. {
  31. }
  32. bool VMdEditOperations::insertImageFromMimeData(const QMimeData *source)
  33. {
  34. QImage image = qvariant_cast<QImage>(source->imageData());
  35. if (image.isNull()) {
  36. return false;
  37. }
  38. VInsertImageDialog dialog(tr("Insert Image From Clipboard"),
  39. c_defaultImageTitle,
  40. "",
  41. m_editor->getEditor());
  42. dialog.setBrowseable(false);
  43. dialog.setImage(image);
  44. if (dialog.exec() == QDialog::Accepted) {
  45. insertImageFromQImage(dialog.getImageTitleInput(),
  46. m_file->fetchImageFolderPath(),
  47. m_file->getImageFolderInLink(),
  48. image);
  49. }
  50. return true;
  51. }
  52. void VMdEditOperations::insertImageFromQImage(const QString &title, const QString &path,
  53. const QString &folderInLink, const QImage &image)
  54. {
  55. QString fileName = VUtils::generateImageFileName(path, title);
  56. QString filePath = QDir(path).filePath(fileName);
  57. V_ASSERT(!QFile(filePath).exists());
  58. QString errStr;
  59. bool ret = VUtils::makePath(path);
  60. if (!ret) {
  61. errStr = tr("Fail to create image folder <span style=\"%1\">%2</span>.")
  62. .arg(g_config->c_dataTextStyle).arg(path);
  63. } else {
  64. ret = image.save(filePath);
  65. if (!ret) {
  66. errStr = tr("Fail to save image <span style=\"%1\">%2</span>.")
  67. .arg(g_config->c_dataTextStyle).arg(filePath);
  68. }
  69. }
  70. if (!ret) {
  71. VUtils::showMessage(QMessageBox::Warning, tr("Warning"),
  72. tr("Fail to insert image <span style=\"%1\">%2</span>.").arg(g_config->c_dataTextStyle).arg(title),
  73. errStr,
  74. QMessageBox::Ok,
  75. QMessageBox::Ok,
  76. m_editor->getEditor());
  77. return;
  78. }
  79. QString md = QString("![%1](%2/%3)").arg(title).arg(folderInLink).arg(fileName);
  80. insertTextAtCurPos(md);
  81. qDebug() << "insert image" << title << filePath;
  82. VMdEditor *mdEditor = dynamic_cast<VMdEditor *>(m_editor);
  83. Q_ASSERT(mdEditor);
  84. mdEditor->imageInserted(filePath);
  85. }
  86. void VMdEditOperations::insertImageFromPath(const QString &title, const QString &path,
  87. const QString &folderInLink, const QString &oriImagePath)
  88. {
  89. QString fileName = VUtils::generateImageFileName(path, title, QFileInfo(oriImagePath).suffix());
  90. QString filePath = QDir(path).filePath(fileName);
  91. V_ASSERT(!QFile(filePath).exists());
  92. QString errStr;
  93. bool ret = VUtils::makePath(path);
  94. if (!ret) {
  95. errStr = tr("Fail to create image folder <span style=\"%1\">%2</span>.")
  96. .arg(g_config->c_dataTextStyle).arg(path);
  97. } else {
  98. ret = QFile::copy(oriImagePath, filePath);
  99. if (!ret) {
  100. errStr = tr("Fail to copy image <span style=\"%1\">%2</span>.")
  101. .arg(g_config->c_dataTextStyle).arg(filePath);
  102. }
  103. }
  104. if (!ret) {
  105. VUtils::showMessage(QMessageBox::Warning, tr("Warning"),
  106. tr("Fail to insert image <span style=\"%1\">%2</span>.").arg(g_config->c_dataTextStyle).arg(title),
  107. errStr,
  108. QMessageBox::Ok,
  109. QMessageBox::Ok,
  110. m_editor->getEditor());
  111. return;
  112. }
  113. QString md = QString("![%1](%2/%3)").arg(title).arg(folderInLink).arg(fileName);
  114. insertTextAtCurPos(md);
  115. qDebug() << "insert image" << title << filePath;
  116. VMdEditor *mdEditor = dynamic_cast<VMdEditor *>(m_editor);
  117. Q_ASSERT(mdEditor);
  118. mdEditor->imageInserted(filePath);
  119. }
  120. bool VMdEditOperations::insertImageFromURL(const QUrl &imageUrl)
  121. {
  122. QString imagePath;
  123. QImage image;
  124. bool isLocal = imageUrl.isLocalFile();
  125. QString title;
  126. // Whether it is a local file or web URL
  127. if (isLocal) {
  128. imagePath = imageUrl.toLocalFile();
  129. image = QImage(imagePath);
  130. if (image.isNull()) {
  131. qWarning() << "image is null";
  132. return false;
  133. }
  134. title = "Insert Image From File";
  135. } else {
  136. imagePath = imageUrl.toString();
  137. title = "Insert Image From Network";
  138. }
  139. VInsertImageDialog dialog(title, c_defaultImageTitle,
  140. imagePath, m_editor->getEditor());
  141. dialog.setBrowseable(false, true);
  142. if (isLocal) {
  143. dialog.setImage(image);
  144. } else {
  145. // Download it to a QImage
  146. VDownloader *downloader = new VDownloader(&dialog);
  147. connect(downloader, &VDownloader::downloadFinished,
  148. &dialog, &VInsertImageDialog::imageDownloaded);
  149. downloader->download(imageUrl.toString());
  150. }
  151. if (dialog.exec() == QDialog::Accepted) {
  152. if (isLocal) {
  153. insertImageFromPath(dialog.getImageTitleInput(),
  154. m_file->fetchImageFolderPath(),
  155. m_file->getImageFolderInLink(),
  156. imagePath);
  157. } else {
  158. insertImageFromQImage(dialog.getImageTitleInput(),
  159. m_file->fetchImageFolderPath(),
  160. m_file->getImageFolderInLink(),
  161. dialog.getImage());
  162. }
  163. }
  164. return true;
  165. }
  166. bool VMdEditOperations::insertImage()
  167. {
  168. VInsertImageDialog dialog(tr("Insert Image From File"),
  169. c_defaultImageTitle, "", m_editor->getEditor());
  170. if (dialog.exec() == QDialog::Accepted) {
  171. QString title = dialog.getImageTitleInput();
  172. QString imagePath = dialog.getPathInput();
  173. qDebug() << "insert image from" << imagePath << "as" << title;
  174. insertImageFromPath(title,
  175. m_file->fetchImageFolderPath(),
  176. m_file->getImageFolderInLink(),
  177. imagePath);
  178. }
  179. return true;
  180. }
  181. bool VMdEditOperations::handleKeyPressEvent(QKeyEvent *p_event)
  182. {
  183. if (m_editConfig->m_enableVimMode
  184. && m_vim->handleKeyPressEvent(p_event, &m_autoIndentPos)) {
  185. return true;
  186. }
  187. bool ret = false;
  188. int key = p_event->key();
  189. int modifiers = p_event->modifiers();
  190. switch (key) {
  191. case Qt::Key_1:
  192. case Qt::Key_2:
  193. case Qt::Key_3:
  194. case Qt::Key_4:
  195. case Qt::Key_5:
  196. case Qt::Key_6:
  197. case Qt::Key_7:
  198. {
  199. if (modifiers == Qt::ControlModifier) {
  200. // Ctrl + <N>: insert title at level <N>.
  201. if (decorateHeading(key == Qt::Key_7 ? 0 : key - Qt::Key_0)) {
  202. p_event->accept();
  203. ret = true;
  204. goto exit;
  205. }
  206. }
  207. break;
  208. }
  209. case Qt::Key_Tab:
  210. {
  211. if (handleKeyTab(p_event)) {
  212. ret = true;
  213. goto exit;
  214. }
  215. break;
  216. }
  217. case Qt::Key_Backtab:
  218. {
  219. if (handleKeyBackTab(p_event)) {
  220. ret = true;
  221. goto exit;
  222. }
  223. break;
  224. }
  225. case Qt::Key_B:
  226. {
  227. if (modifiers == Qt::ControlModifier) {
  228. decorateBold();
  229. p_event->accept();
  230. ret = true;
  231. }
  232. break;
  233. }
  234. case Qt::Key_H:
  235. {
  236. if (handleKeyH(p_event)) {
  237. ret = true;
  238. goto exit;
  239. }
  240. break;
  241. }
  242. case Qt::Key_I:
  243. {
  244. if (modifiers == Qt::ControlModifier) {
  245. decorateItalic();
  246. p_event->accept();
  247. ret = true;
  248. }
  249. break;
  250. }
  251. case Qt::Key_L:
  252. {
  253. if (modifiers == Qt::ControlModifier) {
  254. m_editor->insertLink();
  255. p_event->accept();
  256. ret = true;
  257. }
  258. break;
  259. }
  260. case Qt::Key_M:
  261. {
  262. if (modifiers == Qt::ControlModifier) {
  263. decorateCodeBlock();
  264. p_event->accept();
  265. ret = true;
  266. }
  267. break;
  268. }
  269. case Qt::Key_K:
  270. {
  271. if (modifiers == Qt::ControlModifier) {
  272. decorateInlineCode();
  273. p_event->accept();
  274. ret = true;
  275. }
  276. break;
  277. }
  278. case Qt::Key_U:
  279. {
  280. if (handleKeyU(p_event)) {
  281. ret = true;
  282. goto exit;
  283. }
  284. break;
  285. }
  286. case Qt::Key_W:
  287. {
  288. if (handleKeyW(p_event)) {
  289. ret = true;
  290. goto exit;
  291. }
  292. break;
  293. }
  294. case Qt::Key_BracketLeft:
  295. {
  296. if (handleKeyBracketLeft(p_event)) {
  297. ret = true;
  298. goto exit;
  299. }
  300. break;
  301. }
  302. case Qt::Key_Escape:
  303. {
  304. if (handleKeyEsc(p_event)) {
  305. ret = true;
  306. goto exit;
  307. }
  308. break;
  309. }
  310. case Qt::Key_Enter:
  311. // Fall through.
  312. case Qt::Key_Return:
  313. {
  314. if (handleKeyReturn(p_event)) {
  315. ret = true;
  316. goto exit;
  317. }
  318. break;
  319. }
  320. case Qt::Key_D:
  321. {
  322. if (modifiers == Qt::ControlModifier) {
  323. decorateStrikethrough();
  324. p_event->accept();
  325. ret = true;
  326. }
  327. break;
  328. }
  329. default:
  330. break;
  331. }
  332. exit:
  333. // Qt::Key_Return, Qt::Key_Tab and Qt::Key_Backtab will handle m_autoIndentPos.
  334. if (key != Qt::Key_Return
  335. && key != Qt::Key_Enter
  336. && key != Qt::Key_Tab
  337. && key != Qt::Key_Backtab
  338. && key != Qt::Key_Shift
  339. && key != Qt::Key_Control) {
  340. m_autoIndentPos = -1;
  341. }
  342. return ret;
  343. }
  344. // Let Ctrl+[ behave exactly like ESC.
  345. bool VMdEditOperations::handleKeyBracketLeft(QKeyEvent *p_event)
  346. {
  347. // 1. If there is any selection, clear it.
  348. // 2. Otherwise, ignore this event and let parent handles it.
  349. if (p_event->modifiers() == Qt::ControlModifier) {
  350. QTextCursor cursor = m_editor->textCursorW();
  351. if (cursor.hasSelection()) {
  352. cursor.clearSelection();
  353. m_editor->setTextCursorW(cursor);
  354. p_event->accept();
  355. return true;
  356. }
  357. }
  358. return false;
  359. }
  360. bool VMdEditOperations::handleKeyTab(QKeyEvent *p_event)
  361. {
  362. QString text(m_editConfig->m_tabSpaces);
  363. if (p_event->modifiers() == Qt::NoModifier) {
  364. QTextCursor cursor = m_editor->textCursorW();
  365. if (cursor.hasSelection()) {
  366. m_autoIndentPos = -1;
  367. cursor.beginEditBlock();
  368. // Indent each selected line.
  369. VEditUtils::indentSelectedBlocks(cursor, text, true);
  370. cursor.endEditBlock();
  371. m_editor->setTextCursorW(cursor);
  372. } else {
  373. // If it is a Tab key following auto list, increase the indent level.
  374. QTextBlock block = cursor.block();
  375. int seq = -1;
  376. if (m_autoIndentPos == cursor.position()
  377. && VEditUtils::isListBlock(block, &seq)) {
  378. QTextCursor blockCursor(block);
  379. blockCursor.beginEditBlock();
  380. blockCursor.insertText(text);
  381. if (seq != -1) {
  382. changeListBlockSeqNumber(block, 1);
  383. }
  384. blockCursor.endEditBlock();
  385. // Change m_autoIndentPos to let it can be repeated.
  386. m_autoIndentPos = m_editor->textCursorW().position();
  387. } else {
  388. // Just insert "tab".
  389. insertTextAtCurPos(text);
  390. m_autoIndentPos = -1;
  391. }
  392. }
  393. } else {
  394. m_autoIndentPos = -1;
  395. return false;
  396. }
  397. p_event->accept();
  398. return true;
  399. }
  400. bool VMdEditOperations::handleKeyBackTab(QKeyEvent *p_event)
  401. {
  402. if (p_event->modifiers() != Qt::ShiftModifier) {
  403. m_autoIndentPos = -1;
  404. return false;
  405. }
  406. QTextCursor cursor = m_editor->textCursorW();
  407. QTextBlock block = m_editor->documentW()->findBlock(cursor.selectionStart());
  408. bool continueAutoIndent = false;
  409. int seq = -1;
  410. if (cursor.position() == m_autoIndentPos
  411. && VEditUtils::isListBlock(block, &seq) &&
  412. !cursor.hasSelection()) {
  413. continueAutoIndent = true;
  414. }
  415. cursor.beginEditBlock();
  416. if (continueAutoIndent && seq != -1) {
  417. changeListBlockSeqNumber(block, 1);
  418. }
  419. VEditUtils::indentSelectedBlocks(cursor, m_editConfig->m_tabSpaces, false);
  420. cursor.endEditBlock();
  421. if (continueAutoIndent) {
  422. m_autoIndentPos = m_editor->textCursorW().position();
  423. } else {
  424. m_autoIndentPos = -1;
  425. }
  426. p_event->accept();
  427. return true;
  428. }
  429. bool VMdEditOperations::handleKeyH(QKeyEvent *p_event)
  430. {
  431. if (p_event->modifiers() == Qt::ControlModifier) {
  432. // Ctrl+H, equal to backspace.
  433. QTextCursor cursor = m_editor->textCursorW();
  434. cursor.deletePreviousChar();
  435. p_event->accept();
  436. return true;
  437. }
  438. return false;
  439. }
  440. bool VMdEditOperations::handleKeyU(QKeyEvent *p_event)
  441. {
  442. if (p_event->modifiers() == Qt::ControlModifier) {
  443. // Ctrl+U, delete till the start of line.
  444. QTextCursor cursor = m_editor->textCursorW();
  445. bool ret;
  446. if (cursor.atBlockStart()) {
  447. ret = cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor);
  448. } else {
  449. ret = cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
  450. }
  451. if (ret) {
  452. cursor.removeSelectedText();
  453. }
  454. p_event->accept();
  455. return true;
  456. }
  457. return false;
  458. }
  459. bool VMdEditOperations::handleKeyW(QKeyEvent *p_event)
  460. {
  461. if (p_event->modifiers() == Qt::ControlModifier) {
  462. // Ctrl+W, delete till the start of previous word.
  463. QTextCursor cursor = m_editor->textCursorW();
  464. if (cursor.hasSelection()) {
  465. cursor.removeSelectedText();
  466. } else {
  467. bool ret = cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor);
  468. if (ret) {
  469. cursor.removeSelectedText();
  470. }
  471. }
  472. p_event->accept();
  473. return true;
  474. }
  475. return false;
  476. }
  477. bool VMdEditOperations::handleKeyEsc(QKeyEvent *p_event)
  478. {
  479. // 1. If there is any selection, clear it.
  480. // 2. Otherwise, ignore this event and let parent handles it.
  481. QTextCursor cursor = m_editor->textCursorW();
  482. if (cursor.hasSelection()) {
  483. cursor.clearSelection();
  484. m_editor->setTextCursorW(cursor);
  485. p_event->accept();
  486. return true;
  487. }
  488. return false;
  489. }
  490. bool VMdEditOperations::handleKeyReturn(QKeyEvent *p_event)
  491. {
  492. bool autolist = true;
  493. if (p_event->modifiers() & Qt::ControlModifier) {
  494. m_autoIndentPos = -1;
  495. return false;
  496. } else if (p_event->modifiers() & Qt::ShiftModifier) {
  497. // Insert two spaces and a new line.
  498. m_autoIndentPos = -1;
  499. QTextCursor cursor = m_editor->textCursorW();
  500. cursor.beginEditBlock();
  501. cursor.removeSelectedText();
  502. cursor.insertText(" ");
  503. cursor.endEditBlock();
  504. // Let remaining logics handle inserting the new block except that we
  505. // do not need to insert auto list.
  506. autolist = false;
  507. }
  508. // See if we need to cancel auto indent.
  509. if (m_autoIndentPos > -1) {
  510. // Cancel the auto indent/list if the pos is the same and cursor is at
  511. // the end of a block.
  512. QTextCursor cursor = m_editor->textCursorW();
  513. if (VEditUtils::needToCancelAutoIndent(m_autoIndentPos, cursor)) {
  514. m_autoIndentPos = -1;
  515. VEditUtils::deleteIndentAndListMark(cursor);
  516. m_editor->setTextCursorW(cursor);
  517. return true;
  518. }
  519. }
  520. bool handled = false;
  521. m_autoIndentPos = -1;
  522. if (g_config->getAutoIndent()) {
  523. handled = true;
  524. QTextCursor cursor = m_editor->textCursorW();
  525. bool textInserted = false;
  526. cursor.beginEditBlock();
  527. cursor.removeSelectedText();
  528. // Indent the new line as previous line.
  529. textInserted = VEditUtils::insertBlockWithIndent(cursor);
  530. // Continue the list from previous line.
  531. if (g_config->getAutoList() && autolist) {
  532. textInserted = VEditUtils::insertListMarkAsPreviousBlock(cursor) || textInserted;
  533. }
  534. cursor.endEditBlock();
  535. m_editor->setTextCursorW(cursor);
  536. if (textInserted) {
  537. m_autoIndentPos = m_editor->textCursorW().position();
  538. }
  539. }
  540. return handled;
  541. }
  542. void VMdEditOperations::changeListBlockSeqNumber(QTextBlock &p_block, int p_seq)
  543. {
  544. QString text = p_block.text();
  545. QRegExp regExp("^(\\s*)(\\d+)\\.\\s");
  546. int idx = regExp.indexIn(text);
  547. if (idx == -1 || regExp.captureCount() != 2) {
  548. return;
  549. }
  550. int oriSeq = -1;
  551. bool ok = false;
  552. oriSeq = regExp.capturedTexts()[2].toInt(&ok);
  553. if (ok && oriSeq == p_seq) {
  554. return;
  555. }
  556. QTextCursor cursor(p_block);
  557. bool ret = cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor,
  558. regExp.capturedTexts()[1].size());
  559. if (!ret) {
  560. return;
  561. }
  562. ret = cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor,
  563. regExp.capturedTexts()[2].size());
  564. if (!ret) {
  565. return;
  566. }
  567. cursor.removeSelectedText();
  568. cursor.insertText(QString::number(p_seq));
  569. }
  570. bool VMdEditOperations::decorateHeading(int p_level)
  571. {
  572. QTextDocument *doc = m_editor->documentW();
  573. QTextCursor cursor = m_editor->textCursorW();
  574. int firstBlock = cursor.block().blockNumber();
  575. int lastBlock = firstBlock;
  576. if (cursor.hasSelection()) {
  577. // Insert title # in front of the selected blocks.
  578. int start = cursor.selectionStart();
  579. int end = cursor.selectionEnd();
  580. firstBlock = doc->findBlock(start).blockNumber();
  581. lastBlock = doc->findBlock(end).blockNumber();
  582. }
  583. cursor.beginEditBlock();
  584. for (int i = firstBlock; i <= lastBlock; ++i) {
  585. VEditUtils::insertTitleMark(cursor, doc->findBlockByNumber(i), p_level);
  586. }
  587. cursor.endEditBlock();
  588. m_editor->setTextCursorW(cursor);
  589. return true;
  590. }
  591. void VMdEditOperations::decorateText(TextDecoration p_decoration, int p_level)
  592. {
  593. if (p_decoration == TextDecoration::None) {
  594. return;
  595. }
  596. bool validDecoration = true;
  597. switch (p_decoration) {
  598. case TextDecoration::Bold:
  599. decorateBold();
  600. break;
  601. case TextDecoration::Italic:
  602. decorateItalic();
  603. break;
  604. case TextDecoration::Strikethrough:
  605. decorateStrikethrough();
  606. break;
  607. case TextDecoration::InlineCode:
  608. decorateInlineCode();
  609. break;
  610. case TextDecoration::CodeBlock:
  611. decorateCodeBlock();
  612. break;
  613. case TextDecoration::Heading:
  614. decorateHeading(p_level);
  615. break;
  616. default:
  617. validDecoration = false;
  618. qDebug() << "decoration" << (int)p_decoration << "is not implemented yet";
  619. break;
  620. }
  621. if (validDecoration && m_editConfig->m_enableVimMode) {
  622. Q_ASSERT(m_vim);
  623. m_vim->setMode(VimMode::Insert, false);
  624. }
  625. }
  626. void VMdEditOperations::decorateBold()
  627. {
  628. QTextCursor cursor = m_editor->textCursorW();
  629. cursor.beginEditBlock();
  630. if (cursor.hasSelection()) {
  631. // Insert ** around the selected text.
  632. int start = cursor.selectionStart();
  633. int end = cursor.selectionEnd();
  634. cursor.clearSelection();
  635. cursor.setPosition(start, QTextCursor::MoveAnchor);
  636. cursor.insertText("**");
  637. cursor.setPosition(end + 2, QTextCursor::MoveAnchor);
  638. cursor.insertText("**");
  639. } else {
  640. // Insert **** and place cursor in the middle.
  641. // Or if there are two * after current cursor, just skip them or delete
  642. // them if four * appear.
  643. int pos = cursor.positionInBlock();
  644. bool hasStars = false;
  645. bool emptyMarkers = false;
  646. QString text = cursor.block().text();
  647. if (pos <= text.size() - 2) {
  648. if (text[pos] == '*' && text[pos + 1] == '*') {
  649. hasStars = true;
  650. if (pos >= 2
  651. && text[pos - 1] == '*'
  652. && text[pos - 2] == '*') {
  653. emptyMarkers = true;
  654. }
  655. }
  656. }
  657. if (hasStars) {
  658. if (emptyMarkers) {
  659. cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::MoveAnchor, 2);
  660. cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 4);
  661. cursor.removeSelectedText();
  662. } else {
  663. cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 2);
  664. }
  665. } else {
  666. cursor.insertText("****");
  667. cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 2);
  668. }
  669. }
  670. cursor.endEditBlock();
  671. m_editor->setTextCursorW(cursor);
  672. }
  673. void VMdEditOperations::decorateItalic()
  674. {
  675. QTextCursor cursor = m_editor->textCursorW();
  676. cursor.beginEditBlock();
  677. if (cursor.hasSelection()) {
  678. // Insert * around the selected text.
  679. int start = cursor.selectionStart();
  680. int end = cursor.selectionEnd();
  681. cursor.clearSelection();
  682. cursor.setPosition(start, QTextCursor::MoveAnchor);
  683. cursor.insertText("*");
  684. cursor.setPosition(end + 1, QTextCursor::MoveAnchor);
  685. cursor.insertText("*");
  686. } else {
  687. // Insert ** and place cursor in the middle.
  688. // Or if there are one * after current cursor, just skip them or delete
  689. // them if two * appear.
  690. int pos = cursor.positionInBlock();
  691. bool hasStar = false;
  692. bool emptyMarkers = false;
  693. QString text = cursor.block().text();
  694. if (pos <= text.size() - 1) {
  695. if (text[pos] == '*'
  696. && (pos == text.size() - 1 || text[pos + 1] != '*')) {
  697. hasStar = true;
  698. if (pos >= 1 && text[pos - 1] == '*') {
  699. emptyMarkers = true;
  700. }
  701. }
  702. }
  703. if (hasStar) {
  704. if (emptyMarkers) {
  705. cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::MoveAnchor, 1);
  706. cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 2);
  707. cursor.removeSelectedText();
  708. } else {
  709. cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 1);
  710. }
  711. } else {
  712. cursor.insertText("**");
  713. cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 1);
  714. }
  715. }
  716. cursor.endEditBlock();
  717. m_editor->setTextCursorW(cursor);
  718. }
  719. void VMdEditOperations::decorateInlineCode()
  720. {
  721. QTextCursor cursor = m_editor->textCursorW();
  722. cursor.beginEditBlock();
  723. if (cursor.hasSelection()) {
  724. // Insert ` around the selected text.
  725. int start = cursor.selectionStart();
  726. int end = cursor.selectionEnd();
  727. cursor.clearSelection();
  728. cursor.setPosition(start, QTextCursor::MoveAnchor);
  729. cursor.insertText("`");
  730. cursor.setPosition(end + 1, QTextCursor::MoveAnchor);
  731. cursor.insertText("`");
  732. } else {
  733. // Insert `` and place cursor in the middle.
  734. // Or if there are one ` after current cursor, just skip them or delete
  735. // them if two ` appear.
  736. int pos = cursor.positionInBlock();
  737. bool hasBackquote = false;
  738. bool emptyMarkers = false;
  739. QString text = cursor.block().text();
  740. if (pos <= text.size() - 1) {
  741. if (text[pos] == '`') {
  742. hasBackquote = true;
  743. if (pos >= 1 && text[pos - 1] == '`') {
  744. emptyMarkers = true;
  745. }
  746. }
  747. }
  748. if (hasBackquote) {
  749. if (emptyMarkers) {
  750. cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::MoveAnchor, 1);
  751. cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 2);
  752. cursor.removeSelectedText();
  753. } else {
  754. cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 1);
  755. }
  756. } else {
  757. cursor.insertText("``");
  758. cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 1);
  759. }
  760. }
  761. cursor.endEditBlock();
  762. m_editor->setTextCursorW(cursor);
  763. }
  764. void VMdEditOperations::decorateCodeBlock()
  765. {
  766. const QString marker("```");
  767. QTextCursor cursor = m_editor->textCursorW();
  768. cursor.beginEditBlock();
  769. if (cursor.hasSelection()) {
  770. // Insert ``` around the selected text.
  771. int start = cursor.selectionStart();
  772. int end = cursor.selectionEnd();
  773. QString indentation = VEditUtils::fetchIndentSpaces(cursor.block());
  774. // Insert the end marker first.
  775. cursor.setPosition(end, QTextCursor::MoveAnchor);
  776. VEditUtils::insertBlock(cursor, false);
  777. VEditUtils::indentBlock(cursor, indentation);
  778. cursor.insertText(marker);
  779. // Insert the start marker.
  780. cursor.setPosition(start, QTextCursor::MoveAnchor);
  781. VEditUtils::insertBlock(cursor, true);
  782. VEditUtils::indentBlock(cursor, indentation);
  783. cursor.insertText(marker);
  784. } else {
  785. // Insert ``` ``` and place cursor after the first marker.
  786. // Or if current block or next block is ```, we will skip it.
  787. QTextBlock block = cursor.block();
  788. int state = block.userState();
  789. if (state == HighlightBlockState::CodeBlock
  790. || state == HighlightBlockState::CodeBlockStart
  791. || state == HighlightBlockState::CodeBlockEnd) {
  792. // Find the block end.
  793. QTextBlock endBlock = block;
  794. while (endBlock.isValid()) {
  795. if (endBlock.userState() == HighlightBlockState::CodeBlockEnd) {
  796. break;
  797. }
  798. endBlock = endBlock.next();
  799. }
  800. if (endBlock.isValid()) {
  801. // It is CodeBlockEnd.
  802. if (endBlock.previous().isValid()
  803. && endBlock.previous().userState() == HighlightBlockState::CodeBlockStart) {
  804. // Delete empty code blocks.
  805. cursor.setPosition(endBlock.previous().position());
  806. cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor);
  807. cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
  808. cursor.removeSelectedText();
  809. } else {
  810. cursor.setPosition(endBlock.position());
  811. if (endBlock.next().isValid()) {
  812. cursor.movePosition(QTextCursor::NextBlock);
  813. cursor.movePosition(QTextCursor::StartOfBlock);
  814. } else {
  815. cursor.movePosition(QTextCursor::EndOfBlock);
  816. }
  817. }
  818. } else {
  819. // Reach the end of the document.
  820. cursor.movePosition(QTextCursor::End);
  821. }
  822. } else {
  823. bool insertInline = false;
  824. if (!cursor.atBlockEnd()) {
  825. cursor.insertBlock();
  826. cursor.movePosition(QTextCursor::PreviousBlock);
  827. } else if (cursor.atBlockStart() || VEditUtils::isSpaceBlock(block)) {
  828. insertInline = true;
  829. }
  830. if (!insertInline) {
  831. VEditUtils::insertBlock(cursor, false);
  832. VEditUtils::indentBlockAsBlock(cursor, false);
  833. }
  834. cursor.insertText(marker);
  835. VEditUtils::insertBlock(cursor, true);
  836. VEditUtils::indentBlockAsBlock(cursor, true);
  837. cursor.insertText(marker);
  838. }
  839. }
  840. cursor.endEditBlock();
  841. m_editor->setTextCursorW(cursor);
  842. }
  843. void VMdEditOperations::decorateStrikethrough()
  844. {
  845. QTextCursor cursor = m_editor->textCursorW();
  846. cursor.beginEditBlock();
  847. if (cursor.hasSelection()) {
  848. // Insert ~~ around the selected text.
  849. int start = cursor.selectionStart();
  850. int end = cursor.selectionEnd();
  851. cursor.clearSelection();
  852. cursor.setPosition(start, QTextCursor::MoveAnchor);
  853. cursor.insertText("~~");
  854. cursor.setPosition(end + 2, QTextCursor::MoveAnchor);
  855. cursor.insertText("~~");
  856. } else {
  857. // Insert ~~~~ and place cursor in the middle.
  858. // Or if there are one ~~ after current cursor, just skip it or delete
  859. // it if for ~ appear.
  860. int pos = cursor.positionInBlock();
  861. bool hasStrikethrough = false;
  862. bool emptyMarkers = false;
  863. QString text = cursor.block().text();
  864. if (pos <= text.size() - 2) {
  865. if (text[pos] == '~' && text[pos + 1] == '~') {
  866. hasStrikethrough = true;
  867. if (pos >= 2
  868. && text[pos - 1] == '~'
  869. && text[pos - 2] == '~') {
  870. emptyMarkers = true;
  871. }
  872. }
  873. }
  874. if (hasStrikethrough) {
  875. if (emptyMarkers) {
  876. cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::MoveAnchor, 2);
  877. cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 4);
  878. cursor.removeSelectedText();
  879. } else {
  880. cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 2);
  881. }
  882. } else {
  883. cursor.insertText("~~~~");
  884. cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 2);
  885. }
  886. }
  887. cursor.endEditBlock();
  888. m_editor->setTextCursorW(cursor);
  889. }
  890. bool VMdEditOperations::insertLink(const QString &p_linkText,
  891. const QString &p_linkUrl)
  892. {
  893. QString link = QString("[%1](%2)").arg(p_linkText).arg(p_linkUrl);
  894. QTextCursor cursor = m_editor->textCursorW();
  895. cursor.insertText(link);
  896. m_editor->setTextCursorW(cursor);
  897. setVimMode(VimMode::Insert);
  898. return true;
  899. }