forked from cloose/CuteMarkEd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkdowneditor.cpp
More file actions
559 lines (446 loc) · 15.7 KB
/
markdowneditor.cpp
File metadata and controls
559 lines (446 loc) · 15.7 KB
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
/*
* Copyright 2013-2014 Christian Loose <christian.loose@hamburg.de>
*
* 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, either version 2 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "markdowneditor.h"
#include <QAction>
#include <QApplication>
#include <QMenu>
#include <QMimeData>
#include <QPainter>
#include <QShortcut>
#include <QStyle>
#include <QTextBlock>
#include <QTextStream>
#include <controls/linenumberarea.h>
#include <peg-markdown-highlight/styleparser.h>
#include <markdownhighlighter.h>
#include "markdownmanipulator.h"
#include "snippetcompleter.h"
#include <spellchecker/dictionary.h>
#include "hunspell/spellchecker.h"
using hunspell::SpellChecker;
#include <QScrollBar>
class ScrollBarFix : public QScrollBar {
public:
ScrollBarFix(Qt::Orientation orient, QWidget *parent=0)
: QScrollBar(orient, parent) {}
protected:
void sliderChange(SliderChange change) {
if (signalsBlocked() && change == QAbstractSlider::SliderValueChange)
blockSignals(false);
QScrollBar::sliderChange(change);
}
};
MarkdownEditor::MarkdownEditor(QWidget *parent) :
QPlainTextEdit(parent),
lineNumberArea(new LineNumberArea(this)),
spellChecker(new SpellChecker()),
completer(0),
showHardLinebreaks(false)
{
highlighter = new MarkdownHighlighter(this->document(), spellChecker);
QFont font("Monospace", 10);
font.setStyleHint(QFont::TypeWriter);
lineNumberArea->setFont(font);
setFont(font);
setVerticalScrollBar(new ScrollBarFix(Qt::Vertical, this));
connect(this, SIGNAL(blockCountChanged(int)),
this, SLOT(updateLineNumberAreaWidth(int)));
connect(this, SIGNAL(updateRequest(QRect, int)),
this, SLOT(updateLineNumberArea(QRect, int)));
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(showContextMenu(QPoint)));
updateLineNumberAreaWidth(0);
QAction * actionComplete = new QAction(tr("Snippet Complete"), this);
actionComplete->setObjectName("actionComplete");
actionComplete->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Space));
actionComplete->setProperty("defaultshortcut", actionComplete->shortcut());
connect(actionComplete, SIGNAL(triggered()),
this, SLOT(performCompletion()));
this->addAction(actionComplete);
}
MarkdownEditor::~MarkdownEditor()
{
delete spellChecker;
}
void MarkdownEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
QPainter painter(lineNumberArea);
int selStart = textCursor().selectionStart();
int selEnd = textCursor().selectionEnd();
QPalette palette = lineNumberArea->palette();
palette.setCurrentColorGroup(QPalette::Active);
painter.fillRect(event->rect(), palette.color(QPalette::Background));
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
qreal top = blockBoundingGeometry(block).translated(contentOffset()).top();
qreal bottom = top;
while (block.isValid() && top <= event->rect().bottom()) {
top = bottom;
const qreal height = blockBoundingRect(block).height();
bottom = top + height;
if (block.isVisible() && bottom >= event->rect().top()) {
painter.setPen(palette.windowText().color());
bool selected = (
(selStart < block.position() + block.length() && selEnd > block.position())
|| (selStart == selEnd && selStart == block.position())
);
if (selected) {
painter.save();
painter.setPen(palette.highlight().color());
}
const QString number = QString::number(blockNumber + 1);
painter.drawText(0, top, lineNumberArea->width() - 4, height, Qt::AlignRight, number);
if (selected)
painter.restore();
}
block = block.next();
++blockNumber;
}
}
int MarkdownEditor::lineNumberAreaWidth()
{
int digits = 2;
int max = qMax(1, blockCount());
while (max >= 100) {
max /= 10;
++digits;
}
QFont font = lineNumberArea->font();
const QFontMetrics linefmt(font);
int space = 10 + linefmt.width(QLatin1Char('9')) * digits;
return space;
}
void MarkdownEditor::resetHighlighting()
{
highlighter->reset();
}
void MarkdownEditor::paintEvent(QPaintEvent *e)
{
QPlainTextEdit::paintEvent(e);
// draw line end markers if enabled
if (showHardLinebreaks) {
drawLineEndMarker(e);
}
}
void MarkdownEditor::resizeEvent(QResizeEvent *event)
{
QPlainTextEdit::resizeEvent(event);
// update line number area
QRect cr = contentsRect();
lineNumberArea->setGeometry(QStyle::visualRect(layoutDirection(), cr,
QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height())));
}
void MarkdownEditor::keyPressEvent(QKeyEvent *e)
{
if (completer && completer->isPopupVisible()) {
// The following keys are forwarded by the completer to the widget
switch (e->key()) {
case Qt::Key_Enter:
case Qt::Key_Return:
case Qt::Key_Escape:
case Qt::Key_Tab:
case Qt::Key_Backtab:
e->ignore();
return; // let the completer do default behavior
default:
break;
}
}
if (completer)
completer->hidePopup();
QPlainTextEdit::keyPressEvent(e);
}
bool MarkdownEditor::canInsertFromMimeData(const QMimeData *source) const
{
if (isUrlToLocalFile(source)) {
return true;
}
return QPlainTextEdit::canInsertFromMimeData(source);
}
void MarkdownEditor::insertFromMimeData(const QMimeData *source)
{
if (isUrlToLocalFile(source)) {
emit loadDroppedFile(source->urls().first().toLocalFile());
} else {
QPlainTextEdit::insertFromMimeData(source);
}
}
void MarkdownEditor::updateLineNumberAreaWidth(int newBlockCount)
{
Q_UNUSED(newBlockCount)
setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}
void MarkdownEditor::updateLineNumberArea(const QRect &rect, int dy)
{
if (dy)
lineNumberArea->scroll(0, dy);
else
lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
if (rect.contains(viewport()->rect()))
updateLineNumberAreaWidth(0);
}
void MarkdownEditor::editorFontChanged(const QFont &font)
{
lineNumberArea->setFont(font);
setFont(font);
}
void MarkdownEditor::tabWidthChanged(int tabWidth)
{
QFontMetrics fm(font());
setTabStopWidth(tabWidth*fm.width(' '));
}
void MarkdownEditor::showContextMenu(const QPoint &pos)
{
QMenu *contextMenu = createStandardContextMenu();
QTextCursor cursor = cursorForPosition(pos);
int cursorPosition = cursor.position();
cursor.select(QTextCursor::WordUnderCursor);
// if word under cursor not spelled correctly, add suggestions to context menu
if (cursor.hasSelection() && !spellChecker->isCorrect(cursor.selectedText())) {
contextMenu->addSeparator();
// add new submenu for the suggestions
QMenu *subMenu = new QMenu(tr("Suggestions"), contextMenu);
contextMenu->addMenu(subMenu);
// add action for each suggested replacement
QStringList suggestions = spellChecker->suggestions(cursor.selectedText());
foreach (const QString &suggestion, suggestions) {
QAction *action = subMenu->addAction(suggestion);
action->setData(cursorPosition);
connect(action, SIGNAL(triggered()),
this, SLOT(replaceWithSuggestion()));
}
// disable submenu when no suggestions available
if (suggestions.isEmpty()) {
subMenu->setEnabled(false);
}
QAction *userWordlistAction = contextMenu->addAction(tr("Add to User Dictionary"));
userWordlistAction->setData(cursor.selectedText());
connect(userWordlistAction, SIGNAL(triggered()),
this, SLOT(addWordToUserWordlist()));
}
// show context menu
contextMenu->exec(mapToGlobal(pos));
delete contextMenu;
}
void MarkdownEditor::replaceWithSuggestion()
{
QAction *action = qobject_cast<QAction*>(sender());
QTextCursor cursor = textCursor();
cursor.beginEditBlock();
// replace wrong spelled word with suggestion
cursor.setPosition(action->data().toInt());
cursor.select(QTextCursor::WordUnderCursor);
cursor.insertText(action->text());
cursor.endEditBlock();
}
void MarkdownEditor::performCompletion()
{
if (!completer) return;
QRect popupRect = cursorRect();
popupRect.setLeft(popupRect.left() + lineNumberAreaWidth());
QStringList words = extractDistinctWordsFromDocument();
completer->performCompletion(textUnderCursor(), words, popupRect);
}
void MarkdownEditor::insertSnippet(const QString &completionPrefix, const QString &completion, int newCursorPos)
{
QTextCursor cursor = this->textCursor();
// select the completion prefix
cursor.clearSelection();
cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, completionPrefix.length());
int pos = cursor.position();
// replace completion prefix with snippet
cursor.insertText(completion);
// move cursor to requested position
cursor.setPosition(pos);
cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, newCursorPos);
this->setTextCursor(cursor);
}
void MarkdownEditor::addWordToUserWordlist()
{
QAction *action = qobject_cast<QAction*>(sender());
QString word = action->data().toString();
spellChecker->addToUserWordlist(word);
}
bool MarkdownEditor::isUrlToLocalFile(const QMimeData *source) const
{
return source->hasUrls() && (source->urls().count() == 1) && source->urls().first().isLocalFile();
}
void MarkdownEditor::loadStyleFromStylesheet(const QString &fileName)
{
QFile f(fileName);
if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {
return;
}
QTextStream ts(&f);
QString input = ts.readAll();
// parse the stylesheet
PegMarkdownHighlight::StyleParser parser(input);
QVector<PegMarkdownHighlight::HighlightingStyle> styles = parser.highlightingStyles(this->font());
// set new style & rehighlight markdown document
highlighter->setStyles(styles);
highlighter->rehighlight();
// update color palette
this->setPalette(parser.editorPalette());
this->viewport()->setPalette(this->palette());
}
int MarkdownEditor::countWords() const
{
QString text = toPlainText();
// empty or only whitespaces?
if (text.trimmed().isEmpty()) {
return 0;
}
int words = 0;
bool lastWasWhitespace = false;
bool firstCharacter = false;
for (int i = 0; i < text.count(); ++i) {
if (text.at(i).isSpace()) {
if (firstCharacter && !lastWasWhitespace) {
words++;
}
lastWasWhitespace = true;
}
else
{
firstCharacter = true;
lastWasWhitespace = false;
}
}
if (!lastWasWhitespace && text.count() > 0) {
words++;
}
return words;
}
void MarkdownEditor::setShowSpecialCharacters(bool enabled)
{
showHardLinebreaks = enabled;
QTextOption textOption = document()->defaultTextOption();
QTextOption::Flags optionFlags = textOption.flags();
if (enabled) {
optionFlags |= QTextOption::ShowLineAndParagraphSeparators;
optionFlags |= QTextOption::ShowTabsAndSpaces;
} else {
optionFlags &= ~QTextOption::ShowLineAndParagraphSeparators;
optionFlags &= ~QTextOption::ShowTabsAndSpaces;
}
textOption.setFlags(optionFlags);
document()->setDefaultTextOption(textOption);
// repaint
viewport()->update();
}
void MarkdownEditor::setSpellingCheckEnabled(bool enabled)
{
highlighter->setSpellingCheckEnabled(enabled);
// rehighlight markdown document
highlighter->reset();
highlighter->rehighlight();
}
void MarkdownEditor::setSpellingDictionary(const Dictionary &dictionary)
{
spellChecker->loadDictionary(dictionary.filePath());
// rehighlight markdown document
highlighter->reset();
highlighter->rehighlight();
}
void MarkdownEditor::setSnippetCompleter(SnippetCompleter *completer)
{
this->completer = completer;
connect(completer, SIGNAL(snippetSelected(QString,QString, int)),
this, SLOT(insertSnippet(QString,QString, int)));
}
void MarkdownEditor::setYamlHeaderSupportEnabled(bool enabled)
{
highlighter->setYamlHeaderSupportEnabled(enabled);
// rehighlight markdown document
highlighter->reset();
highlighter->rehighlight();
}
void MarkdownEditor::gotoLine(int line)
{
QTextCursor cursor(document()->findBlockByNumber(line-1));
this->setTextCursor(cursor);
}
void MarkdownEditor::drawLineEndMarker(QPaintEvent *e)
{
QPainter painter(viewport());
int leftMargin = qRound(fontMetrics().width(" ") / 2.0);
int lineEndCharWidth = fontMetrics().width("\u00B6");
int fontHeight = fontMetrics().height();
QTextBlock block = firstVisibleBlock();
while (block.isValid()) {
QRectF blockGeometry = blockBoundingGeometry(block).translated(contentOffset());
if (blockGeometry.top() > e->rect().bottom())
break;
if (block.isVisible() && blockGeometry.toRect().intersects(e->rect())) {
QString text = block.text();
if (text.endsWith(" ")) {
painter.drawText(blockGeometry.left() + fontMetrics().width(text) + leftMargin,
blockGeometry.top(),
lineEndCharWidth,
fontHeight,
Qt::AlignLeft | Qt::AlignVCenter,
"\u00B6");
}
}
block = block.next();
}
}
QString MarkdownEditor::textUnderCursor() const
{
QTextCursor cursor = this->textCursor();
QTextDocument *document = this->document();
// empty text if cursor at start of line
if (cursor.atBlockStart()) {
return QString();
}
cursor.clearSelection();
// move left until we find a space or reach the start of line
while(!document->characterAt(cursor.position()-1).isSpace() && !cursor.atBlockStart()) {
cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor);
}
return cursor.selectedText();
}
bool GreaterThanMinimumWordLength(const QString &word)
{
static const int MINIMUM_WORD_LENGTH = 3;
return word.length() > MINIMUM_WORD_LENGTH;
}
QStringList MarkdownEditor::extractDistinctWordsFromDocument() const
{
QStringList allWords = retrieveAllWordsFromDocument();
allWords.removeDuplicates();
QStringList words = filterWordList(allWords, GreaterThanMinimumWordLength);
words.sort(Qt::CaseInsensitive);
return words;
}
QStringList MarkdownEditor::retrieveAllWordsFromDocument() const
{
return toPlainText().split(QRegExp("\\W+"), QString::SkipEmptyParts);
}
template <class UnaryPredicate>
QStringList MarkdownEditor::filterWordList(const QStringList &words, UnaryPredicate predicate) const
{
QStringList filteredWordList;
foreach (const QString &word, words) {
if (predicate(word))
{
filteredWordList << word;
}
}
return filteredWordList;
}