Newer
Older
cursor.beginEditBlock();
cursor.deleteChar();
cursor.deletePreviousChar();
cursor.endEditBlock();
return true;
}
}
int BaseTextEditor::paragraphSeparatorAboutToBeInserted(QTextCursor &cursor)
if (!d->m_autoParenthesesEnabled)
return 0;
if (characterAt(cursor.position() - 1) != QLatin1Char('{'))
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
return 0;
if (!contextAllowsAutoParentheses(cursor))
return 0;
// verify that we indeed do have an extra opening brace in the document
int braceDepth = document()->lastBlock().userState();
if (braceDepth >= 0)
braceDepth >>= 8;
else
braceDepth= 0;
if (braceDepth <= 0)
return 0; // braces are all balanced or worse, no need to do anything
// we have an extra brace , let's see if we should close it
/* verify that the next block is not further intended compared to the current block.
This covers the following case:
if (condition) {|
statement;
*/
const TabSettings &ts = tabSettings();
QTextBlock block = cursor.block();
int indentation = ts.indentationColumn(block.text());
if (block.next().isValid()
&& ts.indentationColumn(block.next().text()) > indentation)
return 0;
int pos = cursor.position();
const QString textToInsert = insertParagraphSeparator(cursor);
cursor.insertText(textToInsert);
cursor.setPosition(pos);
if (ts.m_autoIndent) {
cursor.insertBlock();
indent(document(), cursor, QChar::Null);
} else {
QString previousBlockText = cursor.block().text();
cursor.insertBlock();
cursor.insertText(ts.indentationString(previousBlockText));
}
cursor.setPosition(pos);
d->m_allowSkippingOfBlockEnd = true;
return 1;
}
void BaseTextEditor::indentBlock(QTextDocument *, QTextBlock, QChar)
{
}
void BaseTextEditor::indent(QTextDocument *doc, const QTextCursor &cursor, QChar typedChar)
{
if (cursor.hasSelection()) {
QTextBlock block = doc->findBlock(cursor.selectionStart());
const QTextBlock end = doc->findBlock(cursor.selectionEnd()).next();
do {
indentBlock(doc, block, typedChar);
block = block.next();
} while (block.isValid() && block != end);
} else {
indentBlock(doc, cursor.block(), typedChar);
}
}
void BaseTextEditor::reindent(QTextDocument *doc, const QTextCursor &cursor)
{
if (cursor.hasSelection()) {
QTextBlock block = doc->findBlock(cursor.selectionStart());
const QTextBlock end = doc->findBlock(cursor.selectionEnd()).next();
const TabSettings &ts = d->m_document->tabSettings();
// skip empty blocks
while (block.isValid() && block != end) {
QString bt = block.text();
if (ts.firstNonSpace(bt) < bt.size())
break;
indentBlock(doc, block, QChar::Null);
block = block.next();
}
int previousIndentation = ts.indentationColumn(block.text());
indentBlock(doc, block, QChar::Null);
int currentIndentation = ts.indentationColumn(block.text());
int delta = currentIndentation - previousIndentation;
block = block.next();
while (block.isValid() && block != end) {
ts.reindentLine(block, delta);
block = block.next();
}
} else {
indentBlock(doc, cursor.block(), QChar::Null);
}
}
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
BaseTextEditor::Link BaseTextEditor::findLinkAt(const QTextCursor &, bool)
{
return Link();
}
bool BaseTextEditor::openLink(const Link &link)
{
if (link.fileName.isEmpty())
return false;
if (baseTextDocument()->fileName() == link.fileName) {
Core::EditorManager *editorManager = Core::EditorManager::instance();
editorManager->addCurrentPositionToNavigationHistory();
gotoLine(link.line, link.column);
setFocus();
return true;
}
return openEditorAt(link.fileName, link.line, link.column);
}
void BaseTextEditor::updateLink(QMouseEvent *e)
{
bool linkFound = false;
if (mouseNavigationEnabled() && e->modifiers() & Qt::ControlModifier) {
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
// Link emulation behaviour for 'go to definition'
const QTextCursor cursor = cursorForPosition(e->pos());
// Check that the mouse was actually on the text somewhere
bool onText = cursorRect(cursor).right() >= e->x();
if (!onText) {
QTextCursor nextPos = cursor;
nextPos.movePosition(QTextCursor::Right);
onText = cursorRect(nextPos).right() >= e->x();
}
const Link link = findLinkAt(cursor, false);
if (onText && link.isValid()) {
showLink(link);
linkFound = true;
}
}
if (!linkFound)
clearLink();
}
void BaseTextEditor::showLink(const Link &link)
{
if (d->m_currentLink == link)
return;
QTextEdit::ExtraSelection sel;
sel.cursor = textCursor();

Roberto Raggi
committed
sel.cursor.setPosition(link.begin);
sel.cursor.setPosition(link.end, QTextCursor::KeepAnchor);
sel.format = d->m_linkFormat;
sel.format.setFontUnderline(true);
setExtraSelections(OtherSelection, QList<QTextEdit::ExtraSelection>() << sel);
viewport()->setCursor(Qt::PointingHandCursor);
d->m_currentLink = link;
d->m_linkPressed = false;
}
void BaseTextEditor::clearLink()
{
if (!d->m_currentLink.isValid())
return;
setExtraSelections(OtherSelection, QList<QTextEdit::ExtraSelection>());
viewport()->setCursor(Qt::IBeamCursor);
d->m_currentLink = Link();
d->m_linkPressed = false;
}
void BaseTextEditorPrivate::updateMarksBlock(const QTextBlock &block)
{
if (const TextBlockUserData *userData = BaseTextDocumentLayout::testUserData(block))
foreach (ITextMark *mrk, userData->marks())
mrk->updateBlock(block);
}
void BaseTextEditorPrivate::updateMarksLineNumber()
{
QTextDocument *doc = q->document();
QTextBlock block = doc->begin();
int blockNumber = 0;
while (block.isValid()) {
if (const TextBlockUserData *userData = BaseTextDocumentLayout::testUserData(block))
foreach (ITextMark *mrk, userData->marks()) {
mrk->updateLineNumber(blockNumber + 1);
}
block = block.next();
++blockNumber;
}
}
void BaseTextEditor::markBlocksAsChanged(QList<int> blockNumbers)
{
QTextBlock block = document()->begin();
while (block.isValid()) {
if (block.revision() < 0)
block.setRevision(-block.revision() - 1);
block = block.next();
}
foreach (const int blockNumber, blockNumbers) {
QTextBlock block = document()->findBlockByNumber(blockNumber);
if (block.isValid())
block.setRevision(-block.revision() - 1);
}
}
void BaseTextEditor::highlightSearchResults(const QString &txt, Find::IFindSupport::FindFlags findFlags)
QString pattern = txt;
if (pattern.size() < 2)
pattern.clear(); // highlighting single characters is a bit pointless
if (d->m_searchExpr.pattern() == pattern)
d->m_searchExpr.setPattern(pattern);
d->m_searchExpr.setPatternSyntax((findFlags & Find::IFindSupport::FindRegularExpression) ?
QRegExp::RegExp : QRegExp::FixedString);
d->m_searchExpr.setCaseSensitivity((findFlags & Find::IFindSupport::FindCaseSensitively) ?
Qt::CaseSensitive : Qt::CaseInsensitive);
d->m_findFlags = findFlags;
d->m_delayedUpdateTimer->start(10);
}
int BaseTextEditor::verticalBlockSelection() const
{
if (!d->m_inBlockSelectionMode)
return 0;
QTextCursor b = textCursor();
QTextCursor e = b;
b.setPosition(b.selectionStart());
e.setPosition(e.selectionEnd());
return qAbs(b.positionInBlock() - e.positionInBlock()) + d->m_blockSelectionExtraX;
}
void BaseTextEditor::setFindScope(const QTextCursor &start, const QTextCursor &end, int verticalBlockSelection)
if (start != d->m_findScopeStart || end != d->m_findScopeEnd) {
d->m_findScopeStart = start;
d->m_findScopeEnd = end;
d->m_findScopeVerticalBlockSelection = verticalBlockSelection;
void BaseTextEditor::_q_animateUpdate(int position, QPointF lastPos, QRectF rect)

mae
committed
{
QTextCursor cursor(textCursor());
cursor.setPosition(position);
viewport()->update(QRectF(cursorRect(cursor).topLeft() + rect.topLeft(), rect.size()).toAlignedRect());
if (!lastPos.isNull())
viewport()->update(QRectF(lastPos + rect.topLeft(), rect.size()).toAlignedRect());

mae
committed
}
BaseTextEditorAnimator::BaseTextEditorAnimator(QObject *parent)
:QObject(parent)
{
m_value = 0;
m_timeline = new QTimeLine(256, this);

mae
committed
m_timeline->setCurveShape(QTimeLine::SineCurve);
connect(m_timeline, SIGNAL(valueChanged(qreal)), this, SLOT(step(qreal)));
connect(m_timeline, SIGNAL(finished()), this, SLOT(deleteLater()));
m_timeline->start();
}
void BaseTextEditorAnimator::setData(QFont f, QPalette pal, const QString &text)
{
m_font = f;
m_palette = pal;
m_text = text;
QFontMetrics fm(m_font);
m_size = QSizeF(fm.width(m_text), fm.height());
}

mae
committed
void BaseTextEditorAnimator::draw(QPainter *p, const QPointF &pos)
{
m_lastDrawPos = pos;

mae
committed
p->setPen(m_palette.text().color());
QFont f = m_font;
f.setPointSizeF(f.pointSizeF() * (1.0 + m_value/2));

mae
committed
QFontMetrics fm(f);
int width = fm.width(m_text);
QRectF r((m_size.width()-width)/2, (m_size.height() - fm.height())/2, width, fm.height());
r.translate(pos);
p->fillRect(r, m_palette.base());
p->setFont(f);
p->drawText(r, m_text);
}
bool BaseTextEditorAnimator::isRunning() const
{
return m_timeline->state() == QTimeLine::Running;
}

mae
committed
QRectF BaseTextEditorAnimator::rect() const
{
QFont f = m_font;
f.setPointSizeF(f.pointSizeF() * (1.0 + m_value/2));

mae
committed
QFontMetrics fm(f);
int width = fm.width(m_text);
return QRectF((m_size.width()-width)/2, (m_size.height() - fm.height())/2, width, fm.height());
}
void BaseTextEditorAnimator::step(qreal v)
{
QRectF before = rect();
m_value = v;
QRectF after = rect();
emit updateRequest(m_position, m_lastDrawPos, before.united(after));

mae
committed
}
void BaseTextEditorAnimator::finish()
{
m_timeline->stop();

mae
committed
step(0);
deleteLater();
}
void BaseTextEditor::_q_matchParentheses()
{
if (isReadOnly())
return;
QTextCursor backwardMatch = textCursor();
QTextCursor forwardMatch = textCursor();
const TextBlockUserData::MatchType backwardMatchType = TextBlockUserData::matchCursorBackward(&backwardMatch);
const TextBlockUserData::MatchType forwardMatchType = TextBlockUserData::matchCursorForward(&forwardMatch);
QList<QTextEdit::ExtraSelection> extraSelections;
if (backwardMatchType == TextBlockUserData::NoMatch && forwardMatchType == TextBlockUserData::NoMatch) {
setExtraSelections(ParenthesesMatchingSelection, extraSelections); // clear
return;
}

mae
committed
int animatePosition = -1;
if (backwardMatch.hasSelection()) {
QTextEdit::ExtraSelection sel;
if (backwardMatchType == TextBlockUserData::Mismatch) {
sel.cursor = backwardMatch;
sel.format = d->m_mismatchFormat;
} else {
if (d->m_displaySettings.m_animateMatchingParentheses) {
animatePosition = backwardMatch.selectionStart();
} else if (d->m_formatRange) {
sel.cursor = backwardMatch;
sel.format = d->m_rangeFormat;
extraSelections.append(sel);
}
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
sel.cursor = backwardMatch;
sel.format = d->m_matchFormat;
sel.cursor.setPosition(backwardMatch.selectionStart());
sel.cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
extraSelections.append(sel);
sel.cursor.setPosition(backwardMatch.selectionEnd());
sel.cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor);
}
extraSelections.append(sel);
}
if (forwardMatch.hasSelection()) {
QTextEdit::ExtraSelection sel;
if (forwardMatchType == TextBlockUserData::Mismatch) {
sel.cursor = forwardMatch;
sel.format = d->m_mismatchFormat;
} else {
if (d->m_displaySettings.m_animateMatchingParentheses) {
animatePosition = forwardMatch.selectionEnd()-1;
} else if (d->m_formatRange) {
sel.cursor = forwardMatch;
sel.format = d->m_rangeFormat;
extraSelections.append(sel);
}
sel.cursor = forwardMatch;
sel.format = d->m_matchFormat;
sel.cursor.setPosition(forwardMatch.selectionStart());
sel.cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
extraSelections.append(sel);
sel.cursor.setPosition(forwardMatch.selectionEnd());
sel.cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor);
}
extraSelections.append(sel);
}

mae
committed
if (animatePosition >= 0) {
foreach (const QTextEdit::ExtraSelection &sel, BaseTextEditor::extraSelections(ParenthesesMatchingSelection)) {
if (sel.cursor.selectionStart() == animatePosition
|| sel.cursor.selectionEnd() - 1 == animatePosition) {
animatePosition = -1;
break;
}
}
}

mae
committed
if (animatePosition >= 0) {
if (d->m_animator)
d->m_animator->finish(); // one animation is enough
d->m_animator = new BaseTextEditorAnimator(this);
d->m_animator->setPosition(animatePosition);
QPalette pal;
pal.setBrush(QPalette::Text, d->m_matchFormat.foreground());
pal.setBrush(QPalette::Base, d->m_rangeFormat.background());
d->m_animator->setData(font(), pal, characterAt(d->m_animator->position()));
connect(d->m_animator, SIGNAL(updateRequest(int,QPointF,QRectF)),
this, SLOT(_q_animateUpdate(int,QPointF,QRectF)));

mae
committed
setExtraSelections(ParenthesesMatchingSelection, extraSelections);
void BaseTextEditor::_q_highlightBlocks()
{
BaseTextEditorPrivateHighlightBlocks highlightBlocksInfo;
if (d->extraAreaHighlightCollapseBlockNumber >= 0) {
QTextBlock block = document()->findBlockByNumber(d->extraAreaHighlightCollapseBlockNumber);
if (block.isValid()) {
QTextCursor cursor(block);
if (d->extraAreaHighlightCollapseColumn >= 0)
cursor.setPosition(cursor.position() + qMin(d->extraAreaHighlightCollapseColumn,
while (TextBlockUserData::findPreviousBlockOpenParenthesis(&cursor, firstRun)) {
highlightBlocksInfo.open.prepend(cursor.blockNumber());

mae
committed
int visualIndent = d->visualIndent(cursor.block());
if (closeCursor.isNull())
closeCursor = cursor;

mae
committed
if (TextBlockUserData::findNextBlockClosingParenthesis(&closeCursor)) {
highlightBlocksInfo.close.append(closeCursor.blockNumber());

mae
committed
visualIndent = qMin(visualIndent, d->visualIndent(closeCursor.block()));
}
highlightBlocksInfo.visualIndent.prepend(visualIndent);
if (d->m_highlightBlocksInfo != highlightBlocksInfo) {
d->m_highlightBlocksInfo = highlightBlocksInfo;
viewport()->update();
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
void BaseTextEditor::setActionHack(QObject *hack)
{
d->m_actionHack = hack;
}
QObject *BaseTextEditor::actionHack() const
{
return d->m_actionHack;
}
void BaseTextEditor::changeEvent(QEvent *e)
{
QPlainTextEdit::changeEvent(e);
if (e->type() == QEvent::ApplicationFontChange
|| e->type() == QEvent::FontChange) {
if (d->m_extraArea) {
QFont f = d->m_extraArea->font();
f.setPointSize(font().pointSize());
d->m_extraArea->setFont(f);
slotUpdateExtraAreaWidth();
d->m_extraArea->update();
}
}
}
void BaseTextEditor::focusInEvent(QFocusEvent *e)
{
QPlainTextEdit::focusInEvent(e);
void BaseTextEditor::focusOutEvent(QFocusEvent *e)
{
QPlainTextEdit::focusOutEvent(e);
if (viewport()->cursor().shape() == Qt::BlankCursor)
viewport()->setCursor(Qt::IBeamCursor);
}
void BaseTextEditor::maybeSelectLine()
{
QTextCursor cursor = textCursor();
if (!cursor.hasSelection()) {
const QTextBlock &block = cursor.block();
if (block.next().isValid()) {
cursor.setPosition(block.position());
cursor.setPosition(block.next().position(), QTextCursor::KeepAnchor);
} else {
cursor.movePosition(QTextCursor::EndOfBlock);
cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor);
}
setTextCursor(cursor);
}
}
// shift+del
void BaseTextEditor::cutLine()
{
maybeSelectLine();
void BaseTextEditor::deleteLine()
{
maybeSelectLine();
textCursor().removeSelectedText();
}
void BaseTextEditor::setExtraSelections(ExtraSelectionKind kind, const QList<QTextEdit::ExtraSelection> &selections)
if (selections.isEmpty() && d->m_extraSelections[kind].isEmpty())
return;
d->m_extraSelections[kind] = selections;
if (kind == CodeSemanticsSelection) {
d->m_overlay->clear();
foreach (const QTextEdit::ExtraSelection &selection, d->m_extraSelections[kind]) {
d->m_overlay->addOverlaySelection(selection.cursor,
selection.format.background().color(),
selection.format.background().color(),
}
d->m_overlay->setVisible(!d->m_overlay->isEmpty());
} else if (kind == SnippetPlaceholderSelection) {
d->m_snippetOverlay->clear();
foreach (const QTextEdit::ExtraSelection &selection, d->m_extraSelections[kind]) {
d->m_snippetOverlay->addOverlaySelection(selection.cursor,
selection.format.background().color(),
selection.format.background().color(),
TextEditorOverlay::ExpandBegin);
}
d->m_snippetOverlay->setVisible(!d->m_snippetOverlay->isEmpty());
} else {
QList<QTextEdit::ExtraSelection> all;
for (int i = 0; i < NExtraSelectionKinds; ++i) {
if (i == CodeSemanticsSelection || i == SnippetPlaceholderSelection)
continue;
all += d->m_extraSelections[i];
}
QPlainTextEdit::setExtraSelections(all);
}
QList<QTextEdit::ExtraSelection> BaseTextEditor::extraSelections(ExtraSelectionKind kind) const
return d->m_extraSelections[kind];
QString BaseTextEditor::extraSelectionTooltip(int pos) const
{
QList<QTextEdit::ExtraSelection> all;
for (int i = 0; i < NExtraSelectionKinds; ++i) {
const QList<QTextEdit::ExtraSelection> &sel = d->m_extraSelections[i];
for (int j = 0; j < sel.size(); ++j) {
const QTextEdit::ExtraSelection &s = sel.at(j);
if (s.cursor.selectionStart() <= pos
&& s.cursor.selectionEnd() >= pos
&& !s.format.toolTip().isEmpty())
return s.format.toolTip();
}
}
return QString();
}
// the blocks list must be sorted
void BaseTextEditor::setIfdefedOutBlocks(const QList<BaseTextEditor::BlockRange> &blocks)
{
QTextDocument *doc = document();
BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(doc->documentLayout());
bool needUpdate = false;
QTextBlock block = doc->firstBlock();
int rangeNumber = 0;
bool cleared = false;
bool set = false;
if (rangeNumber < blocks.size()) {
const BlockRange &range = blocks.at(rangeNumber);
if (block.position() >= range.first && ((block.position() + block.length() - 1) <= range.last || !range.last)) {
set = BaseTextDocumentLayout::setIfdefedOut(block);
cleared = BaseTextDocumentLayout::clearIfdefedOut(block);
}
if (block.contains(range.last))
++rangeNumber;
} else {
cleared = BaseTextDocumentLayout::clearIfdefedOut(block);
if (cleared || set) {
needUpdate = true;
int delta = BaseTextDocumentLayout::braceDepthDelta(block);
if (cleared)
braceDepthDelta += delta;
else if (set)
braceDepthDelta -= delta;
}
if (braceDepthDelta)
BaseTextDocumentLayout::changeBraceDepth(block,braceDepthDelta);
block = block.next();
}
if (needUpdate)
documentLayout->requestUpdate();
}
void BaseTextEditor::format()
{
QTextCursor cursor = textCursor();
cursor.beginEditBlock();
indent(document(), cursor, QChar::Null);
cursor.endEditBlock();
}
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
void BaseTextEditor::rewrapParagraph()
{
const int paragraphWidth = displaySettings().m_wrapColumn;
const QRegExp anyLettersOrNumbers = QRegExp("\\w");
const int tabSize = tabSettings().m_tabSize;
QTextCursor cursor = textCursor();
cursor.beginEditBlock();
// Find start of paragraph.
while (cursor.movePosition(QTextCursor::PreviousBlock, QTextCursor::MoveAnchor)) {
QTextBlock block = cursor.block();
QString text = block.text();
// If this block is empty, move marker back to previous and terminate.
if (!text.contains(anyLettersOrNumbers)) {
cursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor);
break;
}
}
cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);
// Find indent level of current block.
int indentLevel = 0;
QString text = cursor.block().text();
for (int i = 0; i < text.length(); i++) {
const QChar ch = text.at(i);
if (ch == QLatin1Char(' '))
indentLevel++;
else if (ch == QLatin1Char('\t'))
indentLevel += tabSize - (indentLevel % tabSize);
else
break;
}
// If there is a common prefix, it should be kept and expanded to all lines.
// this allows nice reflowing of doxygen style comments.
QTextCursor nextBlock = cursor;
QString commonPrefix;
if (nextBlock.movePosition(QTextCursor::NextBlock))
{
QString nText = nextBlock.block().text();
int maxLength = qMin(text.length(), nText.length());
for (int i = 0; i < maxLength; ++i) {
const QChar ch = text.at(i);
if (ch != nText[i] || ch.isLetterOrNumber())
break;
commonPrefix.append(ch);
}
}
// Find end of paragraph.
while (cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor)) {
QString text = cursor.block().text();
if (!text.contains(anyLettersOrNumbers))
break;
}
QString selectedText = cursor.selectedText();
// Preserve initial indent level.or common prefix.
QString spacing;
if (commonPrefix.isEmpty()) {

Roopesh Chander
committed
spacing = tabSettings().indentationString(0, indentLevel, textCursor().block());
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
} else {
spacing = commonPrefix;
indentLevel = commonPrefix.length();
}
int currentLength = indentLevel;
QString result;
result.append(spacing);
// Remove existing instances of any common prefix from paragraph to
// reflow.
selectedText.remove(0, commonPrefix.length());
commonPrefix.prepend(QChar::ParagraphSeparator);
selectedText.replace(commonPrefix, QLatin1String("\n"));
// remove any repeated spaces, trim lines to PARAGRAPH_WIDTH width and
// keep the same indentation level as first line in paragraph.
QString currentWord;
for (int i = 0; i < selectedText.length(); ++i) {
QChar ch = selectedText.at(i);
if (ch.isSpace()) {
if (!currentWord.isEmpty()) {
currentLength += currentWord.length() + 1;
if (currentLength > paragraphWidth) {
currentLength = currentWord.length() + 1 + indentLevel;
result.chop(1); // remove trailing space
result.append(QChar::ParagraphSeparator);
result.append(spacing);
}
result.append(currentWord);
result.append(QLatin1Char(' '));
currentWord.clear();
}
continue;
}
currentWord.append(ch);
}
result.chop(1);
result.append(QChar::ParagraphSeparator);
cursor.insertText(result);
cursor.endEditBlock();
}
void BaseTextEditor::unCommentSelection()
void BaseTextEditor::showEvent(QShowEvent* e)
{
if (!d->m_fontSettings.isEmpty()) {
setFontSettings(d->m_fontSettings);
d->m_fontSettings.clear();
}
QPlainTextEdit::showEvent(e);
}
void BaseTextEditor::setFontSettingsIfVisible(const TextEditor::FontSettings &fs)
{
if (!isVisible()) {
d->m_fontSettings = fs;
return;
void BaseTextEditor::setFontSettings(const TextEditor::FontSettings &fs)
{
const QTextCharFormat textFormat = fs.toTextCharFormat(QLatin1String(Constants::C_TEXT));
const QTextCharFormat selectionFormat = fs.toTextCharFormat(QLatin1String(Constants::C_SELECTION));
const QTextCharFormat lineNumberFormat = fs.toTextCharFormat(QLatin1String(Constants::C_LINE_NUMBER));
const QTextCharFormat searchResultFormat = fs.toTextCharFormat(QLatin1String(Constants::C_SEARCH_RESULT));
d->m_searchScopeFormat = fs.toTextCharFormat(QLatin1String(Constants::C_SEARCH_SCOPE));
const QTextCharFormat parenthesesFormat = fs.toTextCharFormat(QLatin1String(Constants::C_PARENTHESES));
d->m_currentLineFormat = fs.toTextCharFormat(QLatin1String(Constants::C_CURRENT_LINE));
d->m_currentLineNumberFormat = fs.toTextCharFormat(QLatin1String(Constants::C_CURRENT_LINE_NUMBER));
d->m_linkFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_LINK));
d->m_ifdefedOutFormat = fs.toTextCharFormat(QLatin1String(Constants::C_DISABLED_CODE));
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
QFont font(textFormat.font());
const QColor foreground = textFormat.foreground().color();
const QColor background = textFormat.background().color();
QPalette p = palette();
p.setColor(QPalette::Text, foreground);
p.setColor(QPalette::Foreground, foreground);
p.setColor(QPalette::Base, background);
p.setColor(QPalette::Highlight, (selectionFormat.background().style() != Qt::NoBrush) ?
selectionFormat.background().color() :
QApplication::palette().color(QPalette::Highlight));
p.setColor(QPalette::HighlightedText, selectionFormat.foreground().color());
p.setBrush(QPalette::Inactive, QPalette::Highlight, p.highlight());
p.setBrush(QPalette::Inactive, QPalette::HighlightedText, p.highlightedText());
setPalette(p);
setFont(font);
setTabSettings(d->m_document->tabSettings()); // update tabs, they depend on the font
// Line numbers
QPalette ep = d->m_extraArea->palette();
ep.setColor(QPalette::Dark, lineNumberFormat.foreground().color());
ep.setColor(QPalette::Background, lineNumberFormat.background().style() != Qt::NoBrush ?
lineNumberFormat.background().color() : background);
d->m_extraArea->setPalette(ep);
// Search results
d->m_searchResultFormat.setBackground(searchResultFormat.background());
// Matching braces
d->m_matchFormat.setForeground(parenthesesFormat.foreground());
d->m_rangeFormat.setBackground(parenthesesFormat.background());
// snippests
d->m_occurrencesFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_OCCURRENCES));
d->m_occurrencesFormat.clearForeground();
d->m_occurrenceRenameFormat = fs.toTextCharFormat(QLatin1String(TextEditor::Constants::C_OCCURRENCES_RENAME));
d->m_occurrenceRenameFormat.clearForeground();
slotUpdateExtraAreaWidth(); // Adjust to new font width
updateCurrentLineHighlight(); // Make sure it takes the new color
}
void BaseTextEditor::setTabSettings(const TabSettings &ts)
{
d->m_document->setTabSettings(ts);
int charWidth = QFontMetrics(font()).width(QChar(' '));
setTabStopWidth(charWidth * ts.m_tabSize);
}
void BaseTextEditor::setDisplaySettings(const DisplaySettings &ds)
{
setLineWrapMode(ds.m_textWrapping ? QPlainTextEdit::WidgetWidth : QPlainTextEdit::NoWrap);
setLineNumbersVisible(ds.m_displayLineNumbers);
setVisibleWrapColumn(ds.m_showWrapColumn ? ds.m_wrapColumn : 0);
setCodeFoldingVisible(ds.m_displayFoldingMarkers);
setHighlightCurrentLine(ds.m_highlightCurrentLine);
setRevisionsVisible(ds.m_markTextChanges);
setCenterOnScroll(ds.m_centerCursorOnScroll);
if (d->m_displaySettings.m_visualizeWhitespace != ds.m_visualizeWhitespace) {
if (QSyntaxHighlighter *highlighter = baseTextDocument()->syntaxHighlighter())
highlighter->rehighlight();
QTextOption option = document()->defaultTextOption();
if (ds.m_visualizeWhitespace)
option.setFlags(option.flags() | QTextOption::ShowTabsAndSpaces);
else
option.setFlags(option.flags() & ~QTextOption::ShowTabsAndSpaces);
option.setFlags(option.flags() | QTextOption::AddSpaceForLineAndParagraphSeparators);
document()->setDefaultTextOption(option);
d->m_displaySettings = ds;
if (!ds.m_highlightBlocks) {
d->extraAreaHighlightCollapseBlockNumber = d->extraAreaHighlightCollapseColumn = -1;
d->m_highlightBlocksInfo = BaseTextEditorPrivateHighlightBlocks();
}
void BaseTextEditor::setBehaviorSettings(const TextEditor::BehaviorSettings &bs)
{
setMouseNavigationEnabled(bs.m_mouseNavigation);
setScrollWheelZoomingEnabled(bs.m_scrollWheelZooming);
}
void BaseTextEditor::setStorageSettings(const StorageSettings &storageSettings)
{
d->m_document->setStorageSettings(storageSettings);
void BaseTextEditor::setCompletionSettings(const TextEditor::CompletionSettings &completionSettings)
{
setAutoParenthesesEnabled(completionSettings.m_autoInsertBrackets);
}
void BaseTextEditor::collapse()
{
QTextDocument *doc = document();
BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(doc->documentLayout());
QTextBlock curBlock = block;
if (TextBlockUserData::canCollapse(block) && block.next().isVisible()) {
break;
if ((block.next().userState()) >> 8 <= (curBlock.previous().userState() >> 8))
break;
}
block = block.previous();
}
if (block.isValid()) {
TextBlockUserData::doCollapse(block, false);
d->moveCursorVisible();
documentLayout->requestUpdate();
documentLayout->emitDocumentSizeChanged();
}
}
void BaseTextEditor::expand()
{
QTextDocument *doc = document();
BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(doc->documentLayout());
QTextBlock block = textCursor().block();
while (block.isValid() && !block.isVisible())
block = block.previous();
TextBlockUserData::doCollapse(block, true);
d->moveCursorVisible();
documentLayout->requestUpdate();
documentLayout->emitDocumentSizeChanged();
}
void BaseTextEditor::unCollapseAll()
{
QTextDocument *doc = document();
BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(doc->documentLayout());
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
QTextBlock block = doc->firstBlock();
bool makeVisible = true;
while (block.isValid()) {
if (block.isVisible() && TextBlockUserData::canCollapse(block) && block.next().isVisible()) {
makeVisible = false;
break;
}
block = block.next();
}
block = doc->firstBlock();
while (block.isValid()) {
if (TextBlockUserData::canCollapse(block))
TextBlockUserData::doCollapse(block, makeVisible);
block = block.next();
}
d->moveCursorVisible();
documentLayout->requestUpdate();
documentLayout->emitDocumentSizeChanged();