vmdeditoperations.cpp 31 KB

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