Source

pynoto / src / TextEditor / TextEditorWidget.cpp

Full commit
  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
#include <QDebug>
#include <QApplication>
#include <QTextBlock>
#include <QMimeData>
#include <QClipboard>
#include <QScrollBar>
#include <QPainter>
#include <QToolTip>
#include <QTimer>
#include "Include/PynotoApplication.h"
#include "TextEditorWidget.h"
#include "TextEditorMargine.h"
#include "Settings.h"
#include "TabSettings.h"
#include "TextEditorHeader.h"
#include "CustomMenu.h"
#include "Editors/FileProperty.h"
#include "BaseDocumentLayout.h"

#include "Highlighter/Manager.h"
#include "Highlighter/Highlighter.h"
#include "Highlighter/Context.h"

namespace TextEditor {

TextEditorWidget::TextEditorWidget(const QString& fileName, QWidget* parent):
    QPlainTextEdit(parent),
    _highlighter(NULL),
    _margine(NULL),
    _fileName(fileName),
    _menu(new CustomMenu(this))
{
    setFrameStyle(QFrame::NoFrame);
}

void TextEditorWidget::init()
{
    setContextMenuPolicy(Qt::CustomContextMenu);
    _margine = new TextEditorMargine(this);

    Settings set;

    QFont font = QFont(set.fontFace(), set.fontSize(), set.fontWeight());
    font.setStyle(set.fontStyle());
    font.setStyleStrategy(set.useAntialias() ? QFont::PreferAntialias : QFont::NoAntialias);
    setFont(font);

    setThemeName();

    setWordWrapMode(set.wordWrap() ? QTextOption::WordWrap : QTextOption::NoWrap);
    connect(QApplication::clipboard(), SIGNAL(dataChanged()), SLOT(onClipboardChanged()));
    connect(this, SIGNAL(cursorPositionChanged()), SLOT(onCursorPositionChanged()));
    connect(this, SIGNAL(customContextMenuRequested(QPoint)), SLOT(onCustomMenu(QPoint)));
    if (set.hightlight()){
        connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
        highlightCurrentLine();
    }
    connect(_margine, SIGNAL(foldingOpenClosed(int,bool)), SLOT(onFoldingOpenClosed(int,bool)));
    connect(Aux::app(), SIGNAL(preferencesChanged(QString)), SLOT(preferencesChanged(QString)));
    _updateTimer.setInterval(100);
    _updateTimer.setSingleShot(true);
    _updateTimer.stop();
    connect(&_updateTimer, SIGNAL(timeout()), SLOT(validateFolding()));
}

TextEditorWidget::~TextEditorWidget()
{
}

bool TextEditorWidget::load()
{
    QFile f(_fileName);
    if (f.open(QIODevice::ReadOnly)){
        setPlainText(f.readAll());
        editorLoaded();
        connect(this, SIGNAL(textChanged()), SLOT(editorTextChanged()));
        emit contentLoaded();
        _highlighter = hightlighter();
        _highlighter->init();
        QSharedPointer<HighlightDefinition> def = Manager::instance()->definition(_fileName);
        if (!def.isNull()){
            _highlighter->setDefaultContext(def->initialContext());
            _highlighter->rehighlight();
            QTimer::singleShot(10, this, SLOT(restoreState()));
        }
        return true;
    }
    return false;
}

bool TextEditorWidget::reload()
{
    saveState();
    QFile f(_fileName);
    if (f.open(QIODevice::ReadOnly)){
        setPlainText(f.readAll());
        if (_highlighter)
            _highlighter->rehighlight();
        restoreState();
        return true;
    }
    return false;
}

Highlighter* TextEditorWidget::hightlighter()
{
    return new Highlighter(document(), "default");
}

void TextEditorWidget::editorLoaded()
{
}

void TextEditorWidget::resizeEvent(QResizeEvent *e)
{
    QPlainTextEdit::resizeEvent(e);
    QRect cr = contentsRect();
    _margine->setGeometry(QRect(cr.left(), cr.top(), _margine->lineNumberAreaWidth(), cr.height()));
}

void TextEditorWidget::highlightCurrentLine()
{
    QList<QTextEdit::ExtraSelection> extra;

    if (!isReadOnly()) {
        QTextEdit::ExtraSelection selection;

        selection.format.setBackground(_lineColor);
        selection.format.setProperty(QTextFormat::FullWidthSelection, true);
        selection.cursor = textCursor();
        selection.cursor.clearSelection();
        extra.append(selection);
    }

    setExtraSelections(LineExtraKind, extra);
}


void TextEditorWidget::del()
{
    textCursor().removeSelectedText();
}

void TextEditorWidget::uppercase()
{
    if (!textCursor().hasSelection())
        return;

    QString text = textCursor().selectedText();
    replace(text, text.toUpper());
}

void TextEditorWidget::lowercase()
{
    if (!textCursor().hasSelection())
        return;

    QString text = textCursor().selectedText();
    replace(text, text.toLower());
}

void TextEditorWidget::capitalize()
{
    if (!textCursor().hasSelection())
        return;

    QString text = textCursor().selectedText();
    replace(text, text.left(1).toUpper()+text.right(text.length()-1).toLower());
}

void TextEditorWidget::camelize()
{
    if (!textCursor().hasSelection())
        return;

    QStringList its;
    QString text = textCursor().selectedText();
    foreach(QString ch, text.split(QRegExp("[-_]"))){
        foreach(QString ch1, ch.split(QRegExp("(?=[A-Z][a-z])"))){
            its.append(ch1.left(1).toUpper()+ch1.right(ch1.length()-1).toLower());
        }
    }
    QString newText = its.join("");
    newText = newText.left(1).toLower()+newText.right(newText.length()-1);

    replace(text, newText);
}

void TextEditorWidget::underlize()
{
    if (!textCursor().hasSelection())
        return;

    QString text = textCursor().selectedText();
    QStringList its;
    foreach(QString ch, text.split(QRegExp("[-_]"))){
        foreach(QString ch1, ch.split(QRegExp("(?=[A-Z][a-z])"))){
            its.append(ch1.toLower());
        }
    }
    QString newText = its.join("_");

    replace(text, newText);
}

bool TextEditorWidget::reset()
{
    return false;
}

void TextEditorWidget::jump(int line, int col)
{
    QTextCursor cur = textCursor();
    QTextBlock block = document()->findBlockByNumber(line);
    if (!block.isVisible()){
        _margine->showFoldedLine(line);
    }
    cur.setPosition(block.position()+col);
    setTextCursor(cur);
    centerCursor();
    setFocus();
}

void TextEditorWidget::jumpOffset(int offset)
{
    QTextCursor cur = textCursor();
    cur.setPosition(offset);
    setTextCursor(cur);
    if (!textCursor().block().isVisible()){
        _margine->showFoldedLine(textCursor().blockNumber());
    }
    centerCursor();
    setFocus();
}

bool TextEditorWidget::isModified()
{
    return document()->isModified();
}

bool TextEditorWidget::save()
{
    QFile file(_fileName);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)){
        file.write(toPlainText().toUtf8());
        file.flush();
        file.waitForBytesWritten(1000);
        file.close();
        document()->setModified(false);
        return true;
    }
    return false;
}

void TextEditorWidget::keyPressEvent(QKeyEvent *e)
{
    switch(e->key()){
    case Qt::Key_Tab:
    case Qt::Key_Backtab:
        indentOrUnindent(e->key() == Qt::Key_Tab);
        e->accept();
        return;
    case Qt::Key_Home:
        if (e->modifiers() == Qt::ShiftModifier) {
            handleHomeKey(true);
            e->accept();
            return;
        } else if (e->modifiers()) {
            break;
        } else {
            handleHomeKey(false);
            e->accept();
            return;
        }
    }
    QPlainTextEdit::keyPressEvent(e);
}

void TextEditorWidget::indentOrUnindent(bool doIndent)
{
    QTextCursor cursor = textCursor();
    //maybeClearSomeExtraSelections(cursor);
    cursor.beginEditBlock();
    TabSettings tabSettings;

    if (cursor.hasSelection()) {
        // Indent or unindent the selected lines
        int pos = cursor.position();
        int anchor = cursor.anchor();
        int start = qMin(anchor, pos);
        int end = qMax(anchor, pos);

        QTextDocument *doc = document();
        QTextBlock startBlock = doc->findBlock(start);
        QTextBlock endBlock = doc->findBlock(end-1).next();

        if (startBlock.next() == endBlock
                && (start > startBlock.position() || end < endBlock.position() - 1)) {
            // Only one line partially selected.
            cursor.removeSelectedText();
        } else {
            for (QTextBlock block = startBlock; block != endBlock; block = block.next()) {
                QString text = block.text();
                int indentPosition = tabSettings.lineIndentPosition(text);
                if (!doIndent && !indentPosition)
                    indentPosition = tabSettings.firstNonSpace(text);
                int targetColumn = tabSettings.indentedColumn(tabSettings.columnAt(text, indentPosition), doIndent);
                cursor.setPosition(block.position() + indentPosition);
                cursor.insertText(tabSettings.indentationString(0, targetColumn, block));
                cursor.setPosition(block.position());
                cursor.setPosition(block.position() + indentPosition, QTextCursor::KeepAnchor);
                cursor.removeSelectedText();
            }
            cursor.endEditBlock();
            return;
        }
    }

    // Indent or unindent at cursor position
    QTextBlock block = cursor.block();
    QString text = block.text();
    int indentPosition = cursor.positionInBlock();
    int spaces = tabSettings.spacesLeftFromPosition(text, indentPosition);
    int startColumn = tabSettings.columnAt(text, indentPosition - spaces);
    int targetColumn = tabSettings.indentedColumn(tabSettings.columnAt(text, indentPosition), doIndent);
    cursor.setPosition(block.position() + indentPosition);
    cursor.setPosition(block.position() + indentPosition - spaces, QTextCursor::KeepAnchor);
    cursor.removeSelectedText();
    cursor.insertText(tabSettings.indentationString(startColumn, targetColumn, block));
    cursor.endEditBlock();
    setTextCursor(cursor);
}

void TextEditorWidget::handleHomeKey(bool anchor)
{
    QTextCursor cursor = textCursor();
    QTextCursor::MoveMode mode = QTextCursor::MoveAnchor;

    if (anchor)
        mode = QTextCursor::KeepAnchor;

    const int initpos = cursor.position();
    int pos = cursor.block().position();
    QChar character = document()->characterAt(pos);
    const QLatin1Char tab = QLatin1Char('\t');

    while (character == tab || character.category() == QChar::Separator_Space) {
        ++pos;
        if (pos == initpos)
            break;
        character = document()->characterAt(pos);
    }

    // Go to the start of the block when we're already at the start of the text
    if (pos == initpos)
        pos = cursor.block().position();

    cursor.setPosition(pos, mode);
    setTextCursor(cursor);
}

QString TextEditorWidget::selectedText()
{
    return textCursor().selectedText();
}

void TextEditorWidget::onClipboardChanged()
{
    emit pasteAvailable(canPaste());
}

void TextEditorWidget::onCursorPositionChanged()
{
    QChar chr = document()->characterAt(textCursor().position());
    QChar pchr = document()->characterAt(textCursor().position()-1);
    if (chr == '(' || chr == '[' || chr == '{'){
        int found = foundNextBrace(chr);
        showBracesMatches(found);
    } else if (pchr == ')' || pchr == ']' || pchr == '}'){
        int found = foundPrevBrace(pchr);
        showBracesMatches(found, -1);
    } else {
        setExtraSelections(BracesExtraKind, QList<QTextEdit::ExtraSelection>());
    }
}

void TextEditorWidget::showBracesMatches(int found, int off)
{
    QList<QTextEdit::ExtraSelection> extra;
    setExtraSelections(BracesExtraKind, extra);
    QTextEdit::ExtraSelection sel;
    QTextCursor bcur = textCursor();
    bcur.clearSelection();
    sel.cursor = bcur;
    sel.cursor.movePosition(off >=0 ? QTextCursor::NextCharacter : QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, 1);

    sel.format.setForeground(found >= 0 ? Qt::green : Qt::red);
    extra.append(sel);

    if (found >= 0){
        sel.cursor.setPosition(found);
        sel.cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 1);
        extra.append(sel);
    }

    setExtraSelections(BracesExtraKind, extra);
    //QPlainTextEdit::setExtraSelections(extra);
}

int TextEditorWidget::foundNextBrace(const QChar& chr)
{
    QChar opposite = chr == '(' ? ')' : (chr == '[' ? ']' : (chr == '{' ? '}' : '\0'));
    QTextBlock block = textCursor().block();
    int startPos = textCursor().position() - block.position() + 1;
    int ignore = 1;
    while (block.isValid()) {
        for(int i = startPos; i < block.length(); i++){
            QChar cur = block.text()[i];
            if (cur == chr)
                ignore++;
            if (cur == opposite)
                ignore--;
            if (ignore == 0){
                return block.position()+i;
            }
        }
        block = block.next();
        startPos = 0;
    }
    return -1;
}

int TextEditorWidget::foundPrevBrace(const QChar& chr)
{
    QChar opposite = chr == ')' ? '(' : (chr == ']' ? '[' : (chr == '}' ? '{' : '\0'));
    QTextBlock block = textCursor().block();
    int startPos = textCursor().position() - block.position()-1;
    int ignore = 1;
    while (block.isValid()) {
        for(int i = startPos-1; i >= 0; --i){
            QChar cur = block.text()[i];
            if (cur == chr)
                ignore++;
            if (cur == opposite)
                ignore--;
            if (ignore == 0){
                return block.position()+i;
            }
        }
        block = block.previous();
        startPos = block.length();
    }
    return -1;
}

void TextEditorWidget::setExtraSelections(ExtraKind kind, const QList<QTextEdit::ExtraSelection>& sels)
{
    _extraSelections[kind] = sels;
    QList<QTextEdit::ExtraSelection> all;
    all += _extraSelections[LineExtraKind];
    all += _extraSelections[BracesExtraKind];
    QPlainTextEdit::setExtraSelections(all);
}

QWidget * TextEditorWidget::header()
{
    TextEditorHeader * head = new TextEditorHeader;
    head->setFileName(_fileName);
    connect(this, SIGNAL(cursorPositionChanged()), head, SLOT(cursorPositionChanged()));
    connect(this, SIGNAL(modificationChanged(bool)), head, SLOT(modificationChanged(bool)));
    //_head->setRowCol(textCursor().blockNumber(), textCursor().columnNumber());
    return head;
}

QString TextEditorWidget::fileName()
{
    return _fileName;
}

void TextEditorWidget::setFileName(const QString& fileName)
{
    _fileName = fileName;
}

void TextEditorWidget::startIncrementalFind()
{
    _incFindCursor = textCursor();
}

void TextEditorWidget::find(const QString& text, bool forward)
{
    if (_incFindCursor.isNull())
        _incFindCursor = textCursor();

    QTextCursor fc = document()->find(text, _incFindCursor, forward ? (QTextDocument::FindFlag)0 : QTextDocument::FindBackward);
    if (!fc.isNull())
        setTextCursor(fc);
    else
        setTextCursor(_incFindCursor);
}

void TextEditorWidget::replace(const QString& text, const QString& repl, bool findNext, bool forward)
{
    int pos = textCursor().position()-text.length();
    textCursor().insertText(repl);
    QTextCursor cur = textCursor();

    cur.setPosition(pos);
    cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, repl.length());
    setTextCursor(cur);
    if (findNext){
        find(text, forward);
    }
}

void TextEditorWidget::replaceAll(const QString& text, const QString& repl)
{
    QTextCursor cur = textCursor();
    int pos = cur.position();
    int top = verticalScrollBar()->value();
    int left = horizontalScrollBar()->value();
    cur.beginEditBlock();
    cur.setPosition(QTextCursor::Start);
    QTextCursor fc = document()->find(text, cur);
    while (!fc.isNull()){
        setTextCursor(fc);
        textCursor().insertText(repl);
        fc = document()->find(text, fc);
    }
    cur.endEditBlock();
    cur.setPosition(pos);
    verticalScrollBar()->setValue(top);
    horizontalScrollBar()->setValue(left);
    setTextCursor(cur);
}

void TextEditorWidget::onCustomMenu(const QPoint& point)
{
    _menu->createMenu(point);
}

void TextEditorWidget::paintEvent(QPaintEvent *event)
{
    QPlainTextEdit::paintEvent(event);
    QPainter paint(viewport());

    QTextBlock block = firstVisibleBlock();
    while(block.isValid()){
        if (block.isVisible() && _margine->foldings.contains(block.blockNumber()) && _margine->foldings[block.blockNumber()].closed){
            //paint.setPen(theme->color("common", "dsNormal", apal.color(QPalette::WindowText)));
            QRectF br = blockBoundingGeometry(block).translated(contentOffset());
            int left = viewport()->fontMetrics().width(block.text())+ 20;
            QRectF pr = QRectF(left, br.top()+1, 40, br.height()-2);
            paint.drawRoundedRect(pr, 3, 3);
            paint.drawText(pr, Qt::AlignCenter, "...");
        }
        block = block.next();
    }
}

bool TextEditorWidget::event(QEvent *e)
{
    if (e->type() == QEvent::ToolTip) {
        QHelpEvent *te = static_cast<QHelpEvent*>(e);
        QTextCursor cursor = cursorForPosition(te->pos());
        if (_margine->foldings.contains(cursor.blockNumber()) && _margine->foldings[cursor.blockNumber()].closed){
            QTextBlock block = cursor.block();
            int left = viewport()->fontMetrics().width(block.text()) + 20;
            QPoint mpos = viewport()->mapFromParent(te->pos());
            if (mpos.x() > left && mpos.x() < left+40){
                block = block.next();
                QStringList text;
                while(block.isValid() && !block.isVisible()){
                    text.append(block.text());
                    block = block.next();
                }
                QRectF br = blockBoundingGeometry(block).translated(contentOffset());
                QRectF pr = QRectF(left, br.top(), 40, br.height());
                QToolTip::showText(te->globalPos(), text.join("\n"), this, pr.toRect());
            } else {
                QToolTip::hideText();
                e->ignore();
            }
        } else {
            QToolTip::hideText();
            e->ignore();
        }
        return true;
    }
    return QPlainTextEdit::event(e);
}

int TextEditorWidget::visibleBlockCount()
{
    int count = 0;
    QTextBlock block = document()->firstBlock();
    while(block.isValid()){
        if (block.isVisible())
            count++;
        block = block.next();
    }
    return count;
}

void TextEditorWidget::onFoldingOpenClosed(int line, bool closed)
{
    BaseDocumentLayout *lay = qobject_cast<BaseDocumentLayout*>(document()->documentLayout());
    if (lay) {
        lay->requestUpdate();
        lay->emitDocumentSizeChanged();
    }
    QResizeEvent ev(QSize(1, 1), size());
    resizeEvent(&ev);
}

void TextEditorWidget::restoreState()
{
    Editors::FileProperty prop(_fileName);
    QTextCursor cur = textCursor();
    cur.setPosition(prop.cursorPos());
    setTextCursor(cur);
    _forceClosedFold = prop.closedFolds();
    verticalScrollBar()->setValue(prop.verticalScroll());
    editorTextChanged();
}

void TextEditorWidget::saveState()
{
    Editors::FileProperty prop(_fileName);
    prop.setVerticalScroll(verticalScrollBar()->value());
    prop.setCursorPos(textCursor().position());
    QList<int> fold;
    foreach(FoldInfo info, _margine->foldings)
        if (info.closed)
            fold << info.line;
    prop.setClosedFolds(fold);
    prop.save();
}

void TextEditorWidget::clearMarks()
{
    _margine->clearMarks();
}

void TextEditorWidget::setMark(int line, const QIcon& ico, const QString& message)
{
    _margine->setMark(line, ico, message);
}

QString TextEditorWidget::content()
{
    return toPlainText();
}

QPoint TextEditorWidget::pointForPosition(int position)
{
    QTextCursor cur = textCursor();
    cur.setPosition(position);
    return cursorRect(cur).translated(contentOffset().toPoint()).bottomLeft();
}

QString TextEditorWidget::text(int from, int to)
{
    QTextCursor cur = textCursor();
    cur.setPosition(from);
    cur.setPosition(to, QTextCursor::KeepAnchor);
    return cur.selectedText();
}

void TextEditorWidget::preferencesChanged(const QString& what)
{
    if (what == "editor-font"){
        Settings set;
        QFont font = QFont(set.fontFace(), set.fontSize(), set.fontWeight());
        font.setStyle(set.fontStyle());
        font.setStyleStrategy(set.useAntialias() ? QFont::PreferAntialias : QFont::NoAntialias);
        setFont(font);
    }
    if (what == "highlight-line"){
        Settings set;
        if (!set.hightlight()){
            disconnect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
            setExtraSelections(LineExtraKind, QList<QTextEdit::ExtraSelection>());
        } else {
            connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
            highlightCurrentLine();
        }
    }
    if (what == "theme"){
        setThemeName();
    }
}

void TextEditorWidget::setThemeName(const QString& name)
{
    _margine->setThemeName(name);
    Settings set;
    Theme::ITheme *theme = set.themeByName(name.isEmpty() ? set.themeName() : name);
    QPalette pal = palette();
    QPalette apal = QApplication::palette();
    pal.setColor(QPalette::Base, theme->background("common", "dsNormal", apal.color(QPalette::Base)));
    pal.setColor(QPalette::Text, theme->color("common", "dsNormal", apal.color(QPalette::WindowText)));
    setPalette(pal);
    _lineColor = theme->background("common", "dsHightlight", QColor("#F8F7F6"));

    if (_highlighter){
        _highlighter->init(name);
        _highlighter->rehighlight();
    }
}

void TextEditorWidget::editorTextChanged()
{
    _updateTimer.start();
}

void TextEditorWidget::validateFolding()
{
    QMap<int, FoldInfo> lst;
    QTextBlock block = document()->firstBlock();
    while(block.isValid()){
        TextBlockData * data = static_cast<TextBlockData*>(block.userData());
        if (!data){
            block = block.next();
            continue;
        }
        int ident = data->_foldingIndent;
        int nident = ident;
        QTextBlock next = block.next();
        if (next.isValid()){
            TextBlockData * ndata = static_cast<TextBlockData*>(next.userData());
            if (ndata)
                nident = ndata->_foldingIndent;
        }
        if (ident < nident && !block.text().trimmed().isEmpty() && !block.text().trimmed().startsWith("#")){
            FoldInfo info;
            QTextBlock nnext = next;
            info.count = 1;
            while(nnext.isValid()){
                TextBlockData * nndata = static_cast<TextBlockData*>(nnext.userData());
                if (ident >= nndata->_foldingIndent && !nnext.text().trimmed().isEmpty() && !nnext.text().trimmed().startsWith("#"))
                    break;
                ++info.count;
                nnext = nnext.next();
            }
            if (info.count > 1){
                QTextBlock prev = nnext.previous();
                while (prev.isValid() && prev.text().trimmed().isEmpty()){
                    --info.count;
                    prev = prev.previous();
                }
            }
            info.line = block.blockNumber();
            info.closed = false;
            info.hovered = false;
            if (!lst.contains(info.line))
                lst.insert(info.line, info);
        }
        if (data->_beginRegion >= 0 && !block.text().trimmed().isEmpty()){
            int numReg = data->_beginRegion;
            FoldInfo info;
            info.line = block.blockNumber();
            info.count = 1;
            info.closed = false;
            info.hovered = false;
            QTextBlock next = block;
            while (next.isValid()){
                TextBlockData * ndata = static_cast<TextBlockData*>(next.userData());
                if (ndata && numReg == ndata->_endRegion){
                    break;
                }
                ++info.count;
                next = next.next();
            }
            if (info.count > 1){
                lst.insert(info.line, info);
            }
        }
        block = block.next();
    }
    emit foldingChanged(lst.values());
}


}