forked from pbek/qmarkdowntextedit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qmarkdowntextedit.cpp
1871 lines (1601 loc) · 65.3 KB
/
qmarkdowntextedit.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2014-2023 Patrizio Bekerle -- <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
*/
#include "qmarkdowntextedit.h"
#include <QClipboard>
#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QGuiApplication>
#include <QKeyEvent>
#include <QLayout>
#include <QPainter>
#include <QPainterPath>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QRegularExpressionMatchIterator>
#include <QScrollBar>
#include <QSettings>
#include <QTextBlock>
#include <QTimer>
#include <QWheelEvent>
#include <utility>
#include "linenumberarea.h"
#include "markdownhighlighter.h"
static const QByteArray _openingCharacters = QByteArrayLiteral("([{<*\"'_~");
static const QByteArray _closingCharacters = QByteArrayLiteral(")]}>*\"'_~");
QMarkdownTextEdit::QMarkdownTextEdit(QWidget *parent, bool initHighlighter)
: QPlainTextEdit(parent) {
installEventFilter(this);
viewport()->installEventFilter(this);
_autoTextOptions = AutoTextOption::BracketClosing;
_lineNumArea = new LineNumArea(this);
updateLineNumberAreaWidth(0);
// markdown highlighting is enabled by default
_highlightingEnabled = initHighlighter;
if (initHighlighter) {
_highlighter = new MarkdownHighlighter(document());
}
QFont font = this->font();
// set the tab stop to the width of 4 spaces in the editor
constexpr int tabStop = 4;
QFontMetrics metrics(font);
#if QT_VERSION < QT_VERSION_CHECK(5, 11, 0)
setTabStopWidth(tabStop * metrics.width(' '));
#else
setTabStopDistance(tabStop * metrics.horizontalAdvance(QLatin1Char(' ')));
#endif
// add shortcuts for duplicating text
// new QShortcut( QKeySequence( "Ctrl+D" ), this, SLOT( duplicateText() )
// ); new QShortcut( QKeySequence( "Ctrl+Alt+Down" ), this, SLOT(
// duplicateText() ) );
// add a layout to the widget
auto *layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->addStretch();
this->setLayout(layout);
// add the hidden search widget
_searchWidget = new QPlainTextEditSearchWidget(this);
this->layout()->addWidget(_searchWidget);
connect(this, &QPlainTextEdit::textChanged, this,
&QMarkdownTextEdit::adjustRightMargin);
connect(this, &QPlainTextEdit::cursorPositionChanged, this,
&QMarkdownTextEdit::centerTheCursor);
connect(verticalScrollBar(), &QScrollBar::valueChanged, this, [this](int) {
_lineNumArea->update();
});
connect(this, &QPlainTextEdit::cursorPositionChanged, this, [this]() {
_lineNumArea->update();
auto oldArea = blockBoundingGeometry(_textCursor.block()).translated(contentOffset());
_textCursor = textCursor();
auto newArea = blockBoundingGeometry(_textCursor.block()).translated(contentOffset());
auto areaToUpdate = oldArea | newArea;
viewport()->update(areaToUpdate.toRect());
});
connect(document(), &QTextDocument::blockCountChanged,
this, &QMarkdownTextEdit::updateLineNumberAreaWidth);
connect(this, &QPlainTextEdit::updateRequest,
this, &QMarkdownTextEdit::updateLineNumberArea);
updateSettings();
// workaround for disabled signals up initialization
QTimer::singleShot(300, this, &QMarkdownTextEdit::adjustRightMargin);
}
void QMarkdownTextEdit::setLineNumbersCurrentLineColor(QColor color) {
_lineNumArea->setCurrentLineColor(std::move(color));
}
void QMarkdownTextEdit::setLineNumbersOtherLineColor(QColor color) {
_lineNumArea->setOtherLineColor(std::move(color));
}
void QMarkdownTextEdit::setSearchWidgetDebounceDelay(uint debounceDelay)
{
_debounceDelay = debounceDelay;
searchWidget()->setDebounceDelay(_debounceDelay);
}
void QMarkdownTextEdit::setHighlightCurrentLine(bool set)
{
_highlightCurrentLine = set;
}
bool QMarkdownTextEdit::highlightCurrentLine()
{
return _highlightCurrentLine;
}
void QMarkdownTextEdit::setCurrentLineHighlightColor(const QColor &color)
{
_currentLineHighlightColor = color;
}
QColor QMarkdownTextEdit::currentLineHighlightColor()
{
return _currentLineHighlightColor;
}
/**
* Enables or disables the markdown highlighting
*
* @param enabled
*/
void QMarkdownTextEdit::setHighlightingEnabled(bool enabled) {
if (_highlightingEnabled == enabled || _highlighter == nullptr) {
return;
}
_highlightingEnabled = enabled;
_highlighter->setDocument(enabled ? document() : Q_NULLPTR);
if (enabled) {
_highlighter->rehighlight();
}
}
/**
* @brief Returns if highlighting is enabled
* @return Returns true if highlighting is enabled, otherwise false
*/
bool QMarkdownTextEdit::highlightingEnabled() const {
return _highlightingEnabled && _highlighter != nullptr;
}
/**
* Leave a little space on the right side if the document is too long, so
* that the search buttons don't get visually blocked by the scroll bar
*/
void QMarkdownTextEdit::adjustRightMargin() {
QMargins margins = layout()->contentsMargins();
const int rightMargin =
document()->size().height() > viewport()->size().height() ? 24 : 0;
margins.setRight(rightMargin);
layout()->setContentsMargins(margins);
}
bool QMarkdownTextEdit::eventFilter(QObject *obj, QEvent *event) {
// qDebug() << event->type();
if (event->type() == QEvent::HoverMove) {
auto *mouseEvent = static_cast<QMouseEvent *>(event);
QWidget *viewPort = this->viewport();
// toggle cursor when control key has been pressed or released
viewPort->setCursor(
mouseEvent->modifiers().testFlag(Qt::ControlModifier)
? Qt::PointingHandCursor
: Qt::IBeamCursor);
} else if (event->type() == QEvent::KeyPress) {
auto *keyEvent = static_cast<QKeyEvent *>(event);
// set cursor to pointing hand if control key was pressed
if (keyEvent->modifiers().testFlag(Qt::ControlModifier)) {
QWidget *viewPort = this->viewport();
viewPort->setCursor(Qt::PointingHandCursor);
}
// disallow keys if text edit hasn't focus
if (!this->hasFocus()) {
return true;
}
if ((keyEvent->key() == Qt::Key_Escape) && _searchWidget->isVisible()) {
_searchWidget->deactivate();
return true;
} else if ((keyEvent->key() == Qt::Key_Tab) ||
(keyEvent->key() == Qt::Key_Backtab)) {
// handle entered tab and reverse tab keys
return handleTabEntered(keyEvent->key() == Qt::Key_Backtab);
} else if ((keyEvent->key() == Qt::Key_F) &&
keyEvent->modifiers().testFlag(Qt::ControlModifier)) {
_searchWidget->activate();
return true;
} else if ((keyEvent->key() == Qt::Key_R) &&
keyEvent->modifiers().testFlag(Qt::ControlModifier)) {
_searchWidget->activateReplace();
return true;
// } else if (keyEvent->key() == Qt::Key_Delete) {
} else if (keyEvent->key() == Qt::Key_Backspace) {
return handleBackspaceEntered();
} else if (keyEvent->key() == Qt::Key_Asterisk) {
return handleBracketClosing(QLatin1Char('*'));
} else if (keyEvent->key() == Qt::Key_QuoteDbl) {
return quotationMarkCheck(QLatin1Char('"'));
// apostrophe bracket closing is temporary disabled because
// apostrophes are used in different contexts
// } else if (keyEvent->key() == Qt::Key_Apostrophe) {
// return handleBracketClosing("'");
// underline bracket closing is temporary disabled because
// underlines are used in different contexts
// } else if (keyEvent->key() == Qt::Key_Underscore) {
// return handleBracketClosing("_");
} else if (keyEvent->key() == Qt::Key_QuoteLeft) {
return quotationMarkCheck(QLatin1Char('`'));
} else if (keyEvent->key() == Qt::Key_AsciiTilde) {
return handleBracketClosing(QLatin1Char('~'));
#ifdef Q_OS_MAC
} else if (keyEvent->modifiers().testFlag(Qt::AltModifier) &&
keyEvent->key() == Qt::Key_ParenLeft) {
// bracket closing for US keyboard on macOS
return handleBracketClosing(QLatin1Char('{'), QLatin1Char('}'));
#endif
} else if (keyEvent->key() == Qt::Key_ParenLeft) {
return handleBracketClosing(QLatin1Char('('), QLatin1Char(')'));
} else if (keyEvent->key() == Qt::Key_BraceLeft) {
return handleBracketClosing(QLatin1Char('{'), QLatin1Char('}'));
} else if (keyEvent->key() == Qt::Key_BracketLeft) {
return handleBracketClosing(QLatin1Char('['), QLatin1Char(']'));
} else if (keyEvent->key() == Qt::Key_Less) {
return handleBracketClosing(QLatin1Char('<'), QLatin1Char('>'));
#ifdef Q_OS_MAC
} else if (keyEvent->modifiers().testFlag(Qt::AltModifier) &&
keyEvent->key() == Qt::Key_ParenRight) {
// bracket closing for US keyboard on macOS
return bracketClosingCheck(QLatin1Char('{'), QLatin1Char('}'));
#endif
} else if (keyEvent->key() == Qt::Key_ParenRight) {
return bracketClosingCheck(QLatin1Char('('), QLatin1Char(')'));
} else if (keyEvent->key() == Qt::Key_BraceRight) {
return bracketClosingCheck(QLatin1Char('{'), QLatin1Char('}'));
} else if (keyEvent->key() == Qt::Key_BracketRight) {
return bracketClosingCheck(QLatin1Char('['), QLatin1Char(']'));
} else if (keyEvent->key() == Qt::Key_Greater) {
return bracketClosingCheck(QLatin1Char('<'), QLatin1Char('>'));
} else if ((keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) &&
keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {
QTextCursor cursor = this->textCursor();
cursor.insertText(" \n");
return true;
} else if ((keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) &&
keyEvent->modifiers().testFlag(Qt::ControlModifier)) {
QTextCursor cursor = this->textCursor();
cursor.movePosition(QTextCursor::EndOfBlock);
cursor.insertText(QStringLiteral("\n"));
setTextCursor(cursor);
return true;
} else if (keyEvent == QKeySequence::Copy ||
keyEvent == QKeySequence::Cut) {
QTextCursor cursor = this->textCursor();
if (!cursor.hasSelection()) {
QString text;
if (cursor.block().length() <= 1) // no content
text = "\n";
else {
// cursor.select(QTextCursor::BlockUnderCursor); //
// negative, it will include the previous paragraph
// separator
cursor.movePosition(QTextCursor::StartOfBlock);
cursor.movePosition(QTextCursor::EndOfBlock,
QTextCursor::KeepAnchor);
text = cursor.selectedText();
if (!cursor.atEnd()) {
text += "\n";
// this is the paragraph separator
cursor.movePosition(QTextCursor::NextCharacter,
QTextCursor::KeepAnchor, 1);
}
}
if (keyEvent == QKeySequence::Cut) {
if (!cursor.atEnd() && text == "\n")
cursor.deletePreviousChar();
else
cursor.removeSelectedText();
cursor.movePosition(QTextCursor::StartOfBlock);
setTextCursor(cursor);
}
qApp->clipboard()->setText(text);
return true;
}
} else if ((keyEvent->key() == Qt::Key_Down) &&
keyEvent->modifiers().testFlag(Qt::ControlModifier) &&
keyEvent->modifiers().testFlag(Qt::AltModifier)) {
// duplicate text with `Ctrl + Alt + Down`
duplicateText();
return true;
#ifndef Q_OS_MAC
} else if ((keyEvent->key() == Qt::Key_Down) &&
keyEvent->modifiers().testFlag(Qt::ControlModifier) &&
!keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {
// scroll the page down
auto *scrollBar = verticalScrollBar();
scrollBar->setSliderPosition(scrollBar->sliderPosition() + 1);
return true;
} else if ((keyEvent->key() == Qt::Key_Up) &&
keyEvent->modifiers().testFlag(Qt::ControlModifier) &&
!keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {
// scroll the page up
auto *scrollBar = verticalScrollBar();
scrollBar->setSliderPosition(scrollBar->sliderPosition() - 1);
return true;
#endif
} else if ((keyEvent->key() == Qt::Key_Down) &&
keyEvent->modifiers().testFlag(Qt::NoModifier)) {
// if you are in the last line and press cursor down the cursor will
// jump to the end of the line
QTextCursor cursor = textCursor();
if (cursor.position() >= document()->lastBlock().position()) {
cursor.movePosition(QTextCursor::EndOfLine);
// check if we are really in the last line, not only in
// the last block
if (cursor.atBlockEnd()) {
setTextCursor(cursor);
}
}
return QPlainTextEdit::eventFilter(obj, event);
} else if ((keyEvent->key() == Qt::Key_Up) &&
keyEvent->modifiers().testFlag(Qt::NoModifier)) {
// if you are in the first line and press cursor up the cursor will
// jump to the start of the line
QTextCursor cursor = textCursor();
QTextBlock block = document()->firstBlock();
int endOfFirstLinePos = block.position() + block.length();
if (cursor.position() <= endOfFirstLinePos) {
cursor.movePosition(QTextCursor::StartOfLine);
// check if we are really in the first line, not only in
// the first block
if (cursor.atBlockStart()) {
setTextCursor(cursor);
}
}
return QPlainTextEdit::eventFilter(obj, event);
} else if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) {
return handleReturnEntered();
} else if ((keyEvent->key() == Qt::Key_F3)) {
_searchWidget->doSearch(
!keyEvent->modifiers().testFlag(Qt::ShiftModifier));
return true;
} else if ((keyEvent->key() == Qt::Key_Z) &&
(keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&
!(keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {
undo();
return true;
} else if ((keyEvent->key() == Qt::Key_Down) &&
(keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&
(keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {
moveTextUpDown(false);
return true;
} else if ((keyEvent->key() == Qt::Key_Up) &&
(keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&
(keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {
moveTextUpDown(true);
return true;
#ifdef Q_OS_MAC
// https://github.com/pbek/QOwnNotes/issues/1593
// https://github.com/pbek/QOwnNotes/issues/2643
} else if (keyEvent->key() == Qt::Key_Home) {
QTextCursor cursor = textCursor();
// Meta is Control on macOS
cursor.movePosition(
keyEvent->modifiers().testFlag(Qt::MetaModifier) ?
QTextCursor::Start : QTextCursor::StartOfLine,
keyEvent->modifiers().testFlag(Qt::ShiftModifier) ?
QTextCursor::KeepAnchor : QTextCursor::MoveAnchor);
this->setTextCursor(cursor);
return true;
} else if (keyEvent->key() == Qt::Key_End) {
QTextCursor cursor = textCursor();
// Meta is Control on macOS
cursor.movePosition(
keyEvent->modifiers().testFlag(Qt::MetaModifier) ?
QTextCursor::End : QTextCursor::EndOfLine,
keyEvent->modifiers().testFlag(Qt::ShiftModifier) ?
QTextCursor::KeepAnchor : QTextCursor::MoveAnchor);
this->setTextCursor(cursor);
return true;
#endif
}
return QPlainTextEdit::eventFilter(obj, event);
} else if (event->type() == QEvent::KeyRelease) {
auto *keyEvent = static_cast<QKeyEvent *>(event);
// reset cursor if control key was released
if (keyEvent->key() == Qt::Key_Control) {
resetMouseCursor();
}
return QPlainTextEdit::eventFilter(obj, event);
} else if (event->type() == QEvent::MouseButtonRelease) {
_mouseButtonDown = false;
auto *mouseEvent = static_cast<QMouseEvent *>(event);
// track `Ctrl + Click` in the text edit
if ((obj == this->viewport()) &&
(mouseEvent->button() == Qt::LeftButton) &&
(QGuiApplication::keyboardModifiers() == Qt::ExtraButton24)) {
// open the link (if any) at the current position
// in the noteTextEdit
openLinkAtCursorPosition();
return true;
}
} else if (event->type() == QEvent::MouseButtonPress) {
_mouseButtonDown = true;
} else if (event->type() == QEvent::MouseButtonDblClick) {
_mouseButtonDown = true;
} else if (event->type() == QEvent::Wheel) {
auto *wheel = dynamic_cast<QWheelEvent*>(event);
// emit zoom signals
if (wheel->modifiers() == Qt::ControlModifier) {
if (wheel->angleDelta().y() > 0) {
Q_EMIT zoomIn();
} else {
Q_EMIT zoomOut();
}
return true;
}
}
return QPlainTextEdit::eventFilter(obj, event);
}
void QMarkdownTextEdit::centerTheCursor() {
if (_mouseButtonDown || !_centerCursor) {
return;
}
// centers the cursor every time, but not on the top and bottom
// bottom is done by setCenterOnScroll() in updateSettings()
centerCursor();
/*
QRect cursor = cursorRect();
QRect vp = viewport()->rect();
qDebug() << __func__ << " - 'cursor.top': " << cursor.top();
qDebug() << __func__ << " - 'cursor.bottom': " << cursor.bottom();
qDebug() << __func__ << " - 'vp': " << vp.bottom();
int bottom = 0;
int top = 0;
qDebug() << __func__ << " - 'viewportMargins().top()': "
<< viewportMargins().top();
qDebug() << __func__ << " - 'viewportMargins().bottom()': "
<< viewportMargins().bottom();
int vpBottom = viewportMargins().top() + viewportMargins().bottom() +
vp.bottom(); int vpCenter = vpBottom / 2; int cBottom = cursor.bottom() +
viewportMargins().top();
qDebug() << __func__ << " - 'vpBottom': " << vpBottom;
qDebug() << __func__ << " - 'vpCenter': " << vpCenter;
qDebug() << __func__ << " - 'cBottom': " << cBottom;
if (cBottom >= vpCenter) {
bottom = cBottom + viewportMargins().top() / 2 +
viewportMargins().bottom() / 2 - (vp.bottom() / 2);
// bottom = cBottom - (vp.bottom() / 2);
// bottom *= 1.5;
}
// setStyleSheet(QString("QPlainTextEdit {padding-bottom:
%1px;}").arg(QString::number(bottom)));
// if (cursor.top() < (vp.bottom() / 2)) {
// top = (vp.bottom() / 2) - cursor.top() + viewportMargins().top() /
2 + viewportMargins().bottom() / 2;
//// top *= -1;
//// bottom *= 1.5;
// }
qDebug() << __func__ << " - 'top': " << top;
qDebug() << __func__ << " - 'bottom': " << bottom;
setViewportMargins(0,top,0, bottom);
// QScrollBar* scrollbar = verticalScrollBar();
//
// qDebug() << __func__ << " - 'scrollbar->value();': " <<
scrollbar->value();;
// qDebug() << __func__ << " - 'scrollbar->maximum();': "
// << scrollbar->maximum();;
// scrollbar->setValue(scrollbar->value() - offset.y());
//
// setViewportMargins
// setViewportMargins(0, 0, 0, bottom);
*/
}
/*
* Handle the undo event ourselves
* Retains the selected text as selected after undo if
* bracket closing was used otherwise performs normal undo
*/
void QMarkdownTextEdit::undo() {
QTextCursor cursor = textCursor();
// if no text selected, call undo
if (!cursor.hasSelection()) {
QPlainTextEdit::undo();
return;
}
// if text is selected and bracket closing was used
// we retain our selection
if (_handleBracketClosingUsed) {
// get the selection
int selectionEnd = cursor.selectionEnd();
int selectionStart = cursor.selectionStart();
// call undo
QPlainTextEdit::undo();
// select again
cursor.setPosition(selectionStart - 1);
cursor.setPosition(selectionEnd - 1, QTextCursor::KeepAnchor);
this->setTextCursor(cursor);
_handleBracketClosingUsed = false;
} else {
// if text was selected but bracket closing wasn't used
// do normal undo
QPlainTextEdit::undo();
return;
}
}
void QMarkdownTextEdit::moveTextUpDown(bool up) {
QTextCursor cursor = textCursor();
QTextCursor move = cursor;
move.setVisualNavigation(false);
move.beginEditBlock(); // open an edit block to keep undo operations sane
bool hasSelection = cursor.hasSelection();
if (hasSelection) {
// if there's a selection inside the block, we select the whole block
move.setPosition(cursor.selectionStart());
move.movePosition(QTextCursor::StartOfBlock);
move.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor);
move.movePosition(
move.atBlockStart() ? QTextCursor::Left : QTextCursor::EndOfBlock,
QTextCursor::KeepAnchor);
} else {
move.movePosition(QTextCursor::StartOfBlock);
move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
}
// get the text of the current block
QString text = move.selectedText();
move.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
move.removeSelectedText();
if (up) { // up key
move.movePosition(QTextCursor::PreviousBlock);
move.insertBlock();
move.movePosition(QTextCursor::Left);
} else { // down key
move.movePosition(QTextCursor::EndOfBlock);
if (move.atBlockStart()) { // empty block
move.movePosition(QTextCursor::NextBlock);
move.insertBlock();
move.movePosition(QTextCursor::Left);
} else {
move.insertBlock();
}
}
int start = move.position();
move.clearSelection();
move.insertText(text);
int end = move.position();
// reselect
if (hasSelection) {
move.setPosition(end);
move.setPosition(start, QTextCursor::KeepAnchor);
} else {
move.setPosition(start);
}
move.endEditBlock();
setTextCursor(move);
}
void QMarkdownTextEdit::setLineNumberEnabled(bool enabled)
{
_lineNumArea->setLineNumAreaEnabled(enabled);
updateLineNumberAreaWidth(0);
}
/**
* Resets the cursor to Qt::IBeamCursor
*/
void QMarkdownTextEdit::resetMouseCursor() const {
QWidget *viewPort = viewport();
viewPort->setCursor(Qt::IBeamCursor);
}
/**
* Resets the cursor to Qt::IBeamCursor if the widget looses the focus
*/
void QMarkdownTextEdit::focusOutEvent(QFocusEvent *event) {
resetMouseCursor();
QPlainTextEdit::focusOutEvent(event);
}
/**
* Enters a closing character after an opening character if needed
*
* @param openingCharacter
* @param closingCharacter
* @return
*/
bool QMarkdownTextEdit::handleBracketClosing(const QChar openingCharacter,
QChar closingCharacter) {
// check if bracket closing or read-only are enabled
if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {
return false;
}
QTextCursor cursor = textCursor();
if (closingCharacter.isNull()) {
closingCharacter = openingCharacter;
}
const QString selectedText = cursor.selectedText();
// When user currently has text selected, we prepend the openingCharacter
// and append the closingCharacter. E.g. 'text' -> '(text)'. We keep the
// current selectedText selected.
if (!selectedText.isEmpty()) {
// Insert. The selectedText is overwritten.
const QString newText =
openingCharacter + selectedText + closingCharacter;
cursor.insertText(newText);
// Re-select the selectedText.
const int selectionEnd = cursor.position() - 1;
const int selectionStart = selectionEnd - selectedText.length();
cursor.setPosition(selectionStart);
cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);
this->setTextCursor(cursor);
_handleBracketClosingUsed = true;
return true;
}
// get the current text from the block (inserted character not included)
// Remove whitespace at start of string (e.g. in multilevel-lists).
const QString text = cursor.block().text().remove(QRegularExpression("^\\s+"));
const int pib = cursor.positionInBlock();
bool isPreviousAsterisk = pib > 0 && pib < text.length() && text.at(pib - 1) == '*';
bool isNextAsterisk = pib < text.length() && text.at(pib) == '*';
bool isMaybeBold = isPreviousAsterisk && isNextAsterisk;
if (pib < text.length() && !isMaybeBold && !text.at(pib).isSpace()) {
return false;
}
// Default positions to move the cursor back.
int cursorSubtract = 1;
// Special handling for `*` opening character, as this could be:
// - start of a list (or sublist);
// - start of a bold text;
if (openingCharacter == QLatin1Char('*')) {
// don't auto complete in code block
bool isInCode =
MarkdownHighlighter::isCodeBlock(cursor.block().userState());
// we only do auto completion if there is a space before the cursor pos
bool hasSpaceOrAsteriskBefore = !text.isEmpty() && pib > 0 &&
(text.at(pib - 1).isSpace() ||
text.at(pib - 1) == QLatin1Char('*'));
// This could be the start of a list, don't autocomplete.
bool isEmpty = text.isEmpty();
if (isInCode || !hasSpaceOrAsteriskBefore || isEmpty) {
return false;
}
// bold
if (isPreviousAsterisk && isNextAsterisk) {
cursorSubtract = 1;
}
// User wants: '**'.
// Not the start of a list, probably bold text. We autocomplete with
// extra closingCharacter and cursorSubtract to 'catchup'.
if (text == QLatin1String("*")) {
cursor.insertText(QStringLiteral("*"));
cursorSubtract = 2;
}
}
// Auto completion for ``` pair
if (openingCharacter == QLatin1Char('`')) {
#if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)
if (QRegExp(QStringLiteral("[^`]*``")).exactMatch(text)) {
#else
if (QRegularExpression(QRegularExpression::anchoredPattern(QStringLiteral("[^`]*``"))).match(text).hasMatch()) {
#endif
cursor.insertText(QStringLiteral("``"));
cursorSubtract = 3;
}
}
// don't auto complete in code block
if (openingCharacter == QLatin1Char('<') &&
MarkdownHighlighter::isCodeBlock(cursor.block().userState())) {
return false;
}
cursor.beginEditBlock();
cursor.insertText(openingCharacter);
cursor.insertText(closingCharacter);
cursor.setPosition(cursor.position() - cursorSubtract);
cursor.endEditBlock();
setTextCursor(cursor);
return true;
}
/**
* Checks if the closing character should be output or not
*
* @param openingCharacter
* @param closingCharacter
* @return
*/
bool QMarkdownTextEdit::bracketClosingCheck(const QChar openingCharacter,
QChar closingCharacter) {
// check if bracket closing or read-only are enabled
if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {
return false;
}
if (closingCharacter.isNull()) {
closingCharacter = openingCharacter;
}
QTextCursor cursor = textCursor();
const int positionInBlock = cursor.positionInBlock();
// get the current text from the block
const QString text = cursor.block().text();
const int textLength = text.length();
// if we are at the end of the line we just want to enter the character
if (positionInBlock >= textLength) {
return false;
}
const QChar currentChar = text.at(positionInBlock);
// if (closingCharacter == openingCharacter) {
// }
qDebug() << __func__ << " - 'currentChar': " << currentChar;
// if the current character is not the closing character we just want to
// enter the character
if (currentChar != closingCharacter) {
return false;
}
const QString leftText = text.left(positionInBlock);
const int openingCharacterCount = leftText.count(openingCharacter);
const int closingCharacterCount = leftText.count(closingCharacter);
// if there were enough opening characters just enter the character
if (openingCharacterCount < (closingCharacterCount + 1)) {
return false;
}
// move the cursor to the right and don't enter the character
cursor.movePosition(QTextCursor::Right);
setTextCursor(cursor);
return true;
}
/**
* Checks if the closing character should be output or not or if a closing
* character after an opening character if needed
*
* @param quotationCharacter
* @return
*/
bool QMarkdownTextEdit::quotationMarkCheck(const QChar quotationCharacter) {
// check if bracket closing or read-only are enabled
if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {
return false;
}
QTextCursor cursor = textCursor();
const int positionInBlock = cursor.positionInBlock();
// get the current text from the block
const QString text = cursor.block().text();
const int textLength = text.length();
// if last char is not space, we are at word end, no autocompletion
const bool isBacktick = quotationCharacter == '`';
if (!isBacktick && positionInBlock != 0 &&
!text.at(positionInBlock - 1).isSpace()) {
return false;
}
// if we are at the end of the line we just want to enter the character
if (positionInBlock >= textLength) {
return handleBracketClosing(quotationCharacter);
}
const QChar currentChar = text.at(positionInBlock);
// if the current character is not the quotation character we just want to
// enter the character
if (currentChar != quotationCharacter) {
return handleBracketClosing(quotationCharacter);
}
// move the cursor to the right and don't enter the character
cursor.movePosition(QTextCursor::Right);
setTextCursor(cursor);
return true;
}
/***********************************
* helper methods for char removal
* Rules for (') and ("):
* if [sp]" -> opener (sp = space)
* if "[sp] -> closer
***********************************/
bool isQuotOpener(int position, const QString &text) {
if (position == 0) return true;
const int prevCharPos = position - 1;
return text.at(prevCharPos).isSpace();
}
bool isQuotCloser(int position, const QString &text) {
const int nextCharPos = position + 1;
if (nextCharPos >= text.length()) return true;
return text.at(nextCharPos).isSpace();
}
/**
* Handles removing of matching brackets and other markdown characters
* Only works with backspace to remove text
*
* @return
*/
bool QMarkdownTextEdit::handleBackspaceEntered() {
if (!(_autoTextOptions & AutoTextOption::BracketRemoval) || isReadOnly()) {
return false;
}
QTextCursor cursor = textCursor();
// return if some text was selected
if (!cursor.selectedText().isEmpty()) {
return false;
}
int position = cursor.position();
const int positionInBlock = cursor.positionInBlock();
int block = cursor.block().blockNumber();
if (_highlighter)
if (_highlighter->isPosInACodeSpan(block, positionInBlock - 1))
return false;
// return if backspace was pressed at the beginning of a block
if (positionInBlock == 0) {
return false;
}
// get the current text from the block
const QString text = cursor.block().text();
char charToRemove{};
// current char
const char charInFront = text.at(positionInBlock - 1).toLatin1();
if (charInFront == '*')
return handleCharRemoval(MarkdownHighlighter::RangeType::Emphasis,
block, positionInBlock - 1);
else if (charInFront == '`')
return handleCharRemoval(MarkdownHighlighter::RangeType::CodeSpan,
block, positionInBlock - 1);
//handle removal of ", ', and brackets
// is it opener?
int pos = _openingCharacters.indexOf(charInFront);
// for " and '
bool isOpener = false;
bool isCloser = false;
if (pos == 5 || pos == 6) {
isOpener = isQuotOpener(positionInBlock - 1, text);
} else {
isOpener = pos != -1;
}
if (isOpener) {
charToRemove = _closingCharacters.at(pos);
} else {
// is it closer?
pos = _closingCharacters.indexOf(charInFront);
if (pos == 5 || pos == 6)
isCloser = isQuotCloser(positionInBlock - 1, text);
else
isCloser = pos != -1;
if (isCloser)
charToRemove = _openingCharacters.at(pos);
else
return false;
}
int charToRemoveIndex = -1;
if (isOpener) {
bool closer = true;
charToRemoveIndex = text.indexOf(charToRemove, positionInBlock);
if (charToRemoveIndex == -1) return false;
if (pos == 5 || pos == 6)
closer = isQuotCloser(charToRemoveIndex, text);
if (!closer) return false;
cursor.setPosition(position + (charToRemoveIndex - positionInBlock));
cursor.deleteChar();
} else if (isCloser) {
charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);
if (charToRemoveIndex == -1) return false;
bool opener = true;
if (pos == 5 || pos == 6)
opener = isQuotOpener(charToRemoveIndex, text);
if (!opener) return false;
const int pos = position - (positionInBlock - charToRemoveIndex);
cursor.setPosition(pos);
cursor.deleteChar();
position -= 1;
} else {
charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);
if (charToRemoveIndex == -1) return false;
const int pos = position - (positionInBlock - charToRemoveIndex);
cursor.setPosition(pos);
cursor.deleteChar();
position -= 1;
}
// moving the cursor back to the old position so the previous character
// can be removed
cursor.setPosition(position);
setTextCursor(cursor);
return false;
}
bool QMarkdownTextEdit::handleCharRemoval(MarkdownHighlighter::RangeType type,
int block, int position)