-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodeeditor.cpp
493 lines (399 loc) · 14.4 KB
/
codeeditor.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
#include "codeeditor.h"
#include "linenumberarea.h"
#include "QPainter"
#include "QTextBlock"
#include <QPlainTextEdit>
#include <QTextCursor>
#include <QTextDocumentFragment>
#include <QMessageBox>
#include <QInputDialog>
#include "searchoptions.h"
#include "searchdialog.h"
CodeEditor::CodeEditor(QWidget *parent)
: QPlainTextEdit(parent)
{
lineNumberArea = new LineNumberArea(this);
connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int)));
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
lnaMargins.setLeft(4);
lnaMargins.setRight(4);
updateLineNumberAreaWidth(0);
highlightCurrentLine();
}
CodeEditor::~CodeEditor()
{
delete lineNumberArea;
}
// In the constructor we connect our slots to signals in QPlainTextEdit. It is necessary to calculate the line number area width and highlight the first line when the editor is created.
int CodeEditor::lineNumberAreaWidth()
{
int digits = 1;
int max = qMax(1, blockCount());
while (max >= 10) {
max /= 10;
++digits;
}
int space = lnaMargins.left() + lnaMargins.right() + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits;
return space;
}
// The lineNumberAreaWidth() function calculates the width of the LineNumberArea widget. We take the number of digits in the last line of the editor and multiply that with the maximum width of a digit.
void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
{
setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}
// When we update the width of the line number area, we simply call QAbstractScrollArea::setViewportMargins().
void CodeEditor::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);
}
#include <QMimeData>
#include <QUrl>
void CodeEditor::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls()){
for(QUrl &url: event->mimeData()->urls()){
if(url.isLocalFile()){
///fileInterface->openFile(url.toLocalFile());
emit CodeEditor::dropFile(url.toLocalFile());
}
}
}
else{
QPlainTextEdit::dropEvent(event);
}
}
// This slot is invoked when the editors viewport has been scrolled. The QRect given as argument is the part of the editing area that is do be updated (redrawn). dy holds the number of pixels the view has been scrolled vertically.
void CodeEditor::resizeEvent(QResizeEvent *e)
{
QPlainTextEdit::resizeEvent(e);
QRect cr = contentsRect();
lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}
// When the size of the editor changes, we also need to resize the line number area.
void CodeEditor::highlightCurrentLine()
{
QList<QTextEdit::ExtraSelection> extraSelections;
if (!isReadOnly()) {
QTextEdit::ExtraSelection selection;
QColor lineColor = QColor(Qt::yellow).lighter(160);
selection.format.setBackground(lineColor);
selection.format.setProperty(QTextFormat::FullWidthSelection, true);
selection.cursor = textCursor();
selection.cursor.clearSelection();
extraSelections.append(selection);
}
setExtraSelections(extraSelections);
}
// When the cursor position changes, we highlight the current line, i.e., the line containing the cursor.
// QPlainTextEdit gives the possibility to have more than one selection at the same time. we can set the character format (QTextCharFormat) of these selections. We clear the cursors selection before setting the new new QPlainTextEdit::ExtraSelection, else several lines would get highlighted when the user selects multiple lines with the mouse.
// One sets the selection with a text cursor. When using the FullWidthSelection property, the current cursor text block (line) will be selected. If you want to select just a portion of the text block, the cursor should be moved with QTextCursor::movePosition() from a position set with setPosition().
void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
QPainter painter(lineNumberArea);
painter.fillRect(event->rect(), Qt::lightGray);
// The lineNumberAreaPaintEvent() is called from LineNumberArea whenever it receives a paint event. We start off by painting the widget's background.
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
// We will now loop through all visible lines and paint the line numbers in the extra area for each line. Notice that in a plain text edit each line will consist of one QTextBlock; though, if line wrapping is enabled, a line may span several rows in the text edit's viewport.
// We get the top and bottom y-coordinate of the first text block, and adjust these values by the height of the current text block in each iteration in the loop.
while (block.isValid() && top <= event->rect().bottom()) {
if (block.isVisible() && bottom >= event->rect().top()) {
QString number = QString::number(blockNumber + 1);
painter.setPen(Qt::black);
painter.drawText(0, top, lineNumberArea->width() - lnaMargins.right(), fontMetrics().height(),
Qt::AlignRight, number);
}
block = block.next();
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
++blockNumber;
}
}
int searchString(QString toFind, QString substr, bool forward)
{
if(forward){
return toFind.indexOf(substr);
}
else{
return toFind.lastIndexOf(substr);
}
}
bool CodeEditor::searchInEditorOriginal(QString text)
{
QString toFind = this->toPlainText();
QString substr = text;
SearchOptions &options = searchOption;
bool forward = !options.backward;
if(substr.isEmpty()) return false;
if(!options.matchcase){
toFind = toFind.toLower();
substr = substr.toLower();
}
int len = toFind.length();
int pos = this->textCursor().position();
int nextPos = pos + 1;
QString head = (pos > 0) ? toFind.first(pos - 1) : "";
QString tail = (nextPos < len ) && (pos >= 0)? toFind.last(len - nextPos) : "";
int startpos = 0;
int index = -1;
if(forward){
index = searchString(tail,substr,true);
startpos = nextPos;
}
else{
index = searchString(head,substr,false);
startpos = 0;
}
//not find, rewind to find
if(index < 0 && options.rewind){
if(forward){
index = searchString(head,substr,true);
startpos = 0;
}
else{
index = searchString(tail,substr,false);
startpos = nextPos;
}
}
if(index < 0 ) {
////QMessageBox::information(this,"Find", QString("Fail to find %1").arg(substr));
return false;
}
////this->extraSelections().clear();
int selectPos = startpos + index;
QTextCursor cursor = this->textCursor();
cursor.setPosition(selectPos, QTextCursor::MoveAnchor); //移到key起始位置
cursor.movePosition(QTextCursor::NoMove, QTextCursor::KeepAnchor,substr.length());
cursor.select(QTextCursor::WordUnderCursor);
this->setTextCursor(cursor);
return true;
}
QTextDocument::FindFlags CodeEditor::getFindFlags(){
QTextDocument::FindFlags ret;
if(searchOption.matchcase){
ret |= QTextDocument::FindFlag::FindCaseSensitively;
}
if(searchOption.backward){
ret |= QTextDocument::FindFlag::FindBackward;
}
if(searchOption.wholeworld){
ret |= QTextDocument::FindFlag::FindWholeWords;
}
return ret;
}
bool CodeEditor::searchInEditor(QString text)
{
QTextDocument::FindFlags findFlags = getFindFlags();
bool find = this->find(text,findFlags);
QTextCursor cursor = this->textCursor();
if(!find && searchOption.rewind){
if(searchOption.backward ){
cursor.movePosition(QTextCursor::End);
}
else {
cursor.movePosition(QTextCursor::Start);
}
setTextCursor(cursor);
find = this->find(text,findFlags);
}
return find;
}
void CodeEditor::showFind(){
SearchDialog dlg(this,false);
dlg.exec();
}
void CodeEditor::showTextReplace()
{
SearchDialog dlg(this,true);
dlg.exec();
}
void CodeEditor::findPrev()
{
this->searchOption.backward = true;
QString text = this->textCursor().selectedText();
if(!text.isEmpty()){
bool find = searchInEditor(text);
emit statusMessageChange(find ? "" : this->getFindFailMsg(text));
}
else{
showFind();
}
}
void CodeEditor::findNext()
{
this->searchOption.backward = false;
QString text = this->textCursor().selectedText();
if(!text.isEmpty()){
bool find = searchInEditor(text);
emit statusMessageChange(find ? "" : this->getFindFailMsg(text));
}
else{
showFind();
}
}
void CodeEditor::showGoto(){
bool ok = false;
int ln = QInputDialog::getInt(this, "转到", "行号: ", 1, 1, this->document()->lineCount(), 1, &ok);//第一步
if(ok)
{
QString text = this->toPlainText();
QTextCursor c = this->textCursor();
int pos = 0;
int next = -1;
for(int i=0; i<ln; i++)//第二步
{
pos = next + 1;//最后一个换行符的下一个字符就是目标行的第一个字符
next = text.indexOf('\n', pos);
}
c.setPosition(pos);//第三步
this->setTextCursor(c);
}
}
QString CodeEditor::getFindFailMsg(QString toFind)
{
QString ret;
SearchOptions & options = searchOption;
if(options.rewind){
ret = QString("文件中无法找到'%1'").arg(toFind);
}
else{
if(!options.backward){
ret = QString("已经寻找到文件尾部,无法找到'%1'").arg(options.substr);
}
else{
ret = QString("已经寻找到文件首部,无法找到'%1'").arg(options.substr);
}
}
return ret;
}
void CodeEditor::duplicate_line() {
QTextCursor cursor = textCursor();
int pos(cursor.position());
cursor.beginEditBlock();
cursor.clearSelection();
cursor.movePosition(QTextCursor::EndOfLine);
cursor.select(QTextCursor::LineUnderCursor);
QTextDocumentFragment text( cursor.selection() );
cursor.clearSelection();
cursor.insertText( QString(QChar::LineSeparator) );
cursor.insertFragment( text );
cursor.setPosition(pos);
cursor.endEditBlock();
}
void CodeEditor::delete_current_line() {
QTextCursor cursor = textCursor();
cursor.beginEditBlock();
cursor.clearSelection();
cursor.movePosition(QTextCursor::StartOfLine);
int pos(cursor.position());
cursor.select(QTextCursor::LineUnderCursor);
// remove line (and line feed char)
cursor.removeSelectedText();
cursor.deleteChar();
// goto start of next line
cursor.setPosition(pos);
cursor.endEditBlock();
}
void CodeEditor::selectCursor2(int pos,int len)
{
Q_UNUSED(pos);
QList<QTextEdit::ExtraSelection> extraSelections;
QTextEdit::ExtraSelection selection;
QColor lineColor = QColor(Qt::blue).lighter(160);
selection.format.setBackground(lineColor);
///selection.format.setProperty(QTextFormat::FullWidthSelection, true);
QTextCursor cursor = textCursor();
cursor.movePosition(QTextCursor::NoMove, QTextCursor::KeepAnchor,len);
selection.cursor = cursor;
/////selection.cursor.clearSelection();
extraSelections.append(selection);
setExtraSelections(extraSelections);
}
void CodeEditor::selectCursor(int pos,int len)
{
QTextCursor cursor = textCursor();
if(pos >= 0){
cursor.setPosition(pos);
qDebug() << "select start:" << cursor.selectionStart() << ",select end:" << cursor.selectionEnd() << "len=" << len;
qDebug() << "anchor:" << cursor.anchor() << ",position:" << cursor.position() << len;
cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor,len);
setTextCursor(cursor);
}
}
QString CodeEditor::replaceAll(QString findStr, QString replaceStr)
{
QString text = findStr;
if (text.isEmpty()) {
return text;
}
auto flags = getFindFlags();
// Count instances
int found = 0;
QTextCursor cursor = textCursor();
cursor.movePosition(QTextCursor::Start);
forever {
cursor = this->document()->find(text, cursor, flags);
if (!cursor.isNull()) {
found++;
} else {
break;
}
}
if (found) {
if (QMessageBox::question(this, tr("Question"), tr("Replace %n instance(s)?", "", found), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) {
return "";
}
} else {
QMessageBox::information(this, tr("Sorry"), tr("Phrase not found."));
return "";
}
// Replace instances
QTextCursor start_cursor = textCursor();
forever {
cursor = this->document()->find(text, cursor, flags);
if (!cursor.isNull()) {
cursor.insertText(replaceStr);
setTextCursor(cursor);
} else {
break;
}
}
setTextCursor(start_cursor);
if(found > 0){
return (QString("全文替换`%1` => `%2` %3次").arg(findStr).arg(replaceStr).arg(found));
}
else{
return (QString("没有找到''").arg(findStr));
}
}
bool CodeEditor::replaceCurrent(QString findStr,QString replaceStr)
{
QTextCursor cursor = textCursor();
int pos = cursor.selectionStart();
Qt::CaseSensitivity cs = searchOption.matchcase ? Qt::CaseInsensitive : Qt::CaseSensitive;
if (QString::compare(cursor.selectedText(), findStr, cs) == 0) {
cursor.insertText(replaceStr);
setTextCursor(cursor);
selectCursor(pos,replaceStr.length());
return true;
}
return false;
}
QString CodeEditor::replace(QString findStr, QString replaceStr)
{
bool replaced = replaceCurrent(findStr,replaceStr);
bool find = searchInEditor(findStr);
if(!replaced && find){
replaceCurrent(findStr,replaceStr);
}
QString msg = find ? "" : getFindFailMsg(findStr);
return msg;
}