3 #include "codeeditor.h"
5 extern bool usingDarkTheme;
7 CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent)
9 lineNumberArea = new LineNumberArea(this);
11 connect(this, SIGNAL(blockCountChanged(int)), this,
12 SLOT(updateLineNumberAreaWidth(int)));
13 connect(this, SIGNAL(updateRequest(QRect, int)), this,
14 SLOT(updateLineNumberArea(QRect, int)));
15 connect(this, SIGNAL(cursorPositionChanged()), this,
16 SLOT(highlightCurrentLine()));
18 updateLineNumberAreaWidth(0);
19 highlightCurrentLine();
22 int CodeEditor::lineNumberAreaWidth()
25 int max = qMax(1, blockCount());
31 int space = 3 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits;
36 void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
38 setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
41 void CodeEditor::updateLineNumberArea(const QRect &rect, int dy)
44 lineNumberArea->scroll(0, dy);
46 lineNumberArea->update(0, rect.y(), lineNumberArea->width(),
49 if (rect.contains(viewport()->rect()))
50 updateLineNumberAreaWidth(0);
53 void CodeEditor::resizeEvent(QResizeEvent *e)
55 QPlainTextEdit::resizeEvent(e);
57 QRect cr = contentsRect();
58 lineNumberArea->setGeometry(
59 QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
62 void CodeEditor::highlightCurrentLine()
64 QList<QTextEdit::ExtraSelection> extraSelections;
67 QTextEdit::ExtraSelection selection;
71 lineColor = QColor(Qt::darkGray).darker(150);
73 lineColor = QColor(Qt::yellow).lighter(160);
75 selection.format.setBackground(lineColor);
76 selection.format.setProperty(QTextFormat::FullWidthSelection, true);
77 selection.cursor = textCursor();
78 selection.cursor.clearSelection();
79 extraSelections.append(selection);
82 setExtraSelections(extraSelections);
85 void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
87 QPainter painter(lineNumberArea);
89 painter.fillRect(event->rect(), QColor(Qt::darkGray).darker(150));
91 painter.fillRect(event->rect(), Qt::lightGray);
93 QTextBlock block = firstVisibleBlock();
94 int blockNumber = block.blockNumber();
96 (int)blockBoundingGeometry(block).translated(contentOffset()).top();
97 int bottom = top + (int)blockBoundingRect(block).height();
101 penColor = Qt::lightGray;
103 penColor = Qt::black;
105 while (block.isValid() && top <= event->rect().bottom()) {
106 if (block.isVisible() && bottom >= event->rect().top()) {
107 QString number = QString::number(blockNumber + 1);
108 painter.setPen(penColor);
109 painter.drawText(0, top, lineNumberArea->width(),
110 fontMetrics().height(), Qt::AlignRight, number);
113 block = block.next();
115 bottom = top + (int)blockBoundingRect(block).height();