CompletingEdit.cpp 42.3 KB
Newer Older
1 2
/*
	This is part of TeXworks, an environment for working with TeX documents
3
	Copyright (C) 2007-2018  Jonathan Kew, Stefan Löffler, Charlie Sharpsteen
4 5 6 7 8 9 10 11 12 13 14 15 16 17

	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/>.

18
	For links to further information, or to contact the authors,
19
	see <http://www.tug.org/texworks/>.
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
*/

#include "CompletingEdit.h"
#include "TWUtils.h"
#include "TWApp.h"

#include <QCompleter>
#include <QKeyEvent>
#include <QAbstractItemView>
#include <QApplication>
#include <QModelIndex>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QTextCursor>
#include <QFileInfo>
#include <QFile>
#include <QDir>
#include <QMenu>
#include <QTextStream>
#include <QTextCodec>
#include <QAbstractTextDocumentLayout>
#include <QSignalMapper>
#include <QTextDocument>
#include <QTextBlock>
#include <QScrollBar>
#include <QTimer>
#include <QPainter>
#include <QClipboard>

CompletingEdit::CompletingEdit(QWidget *parent)
	: QTextEdit(parent),
	  clickCount(0),
52
	  wheelDelta(0),
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
	  autoIndentMode(-1), prefixLength(0),
	  smartQuotesMode(-1),
	  c(NULL), cmpCursor(QTextCursor()),
	  pHunspell(NULL), spellingCodec(NULL)
{
	if (sharedCompleter == NULL) { // initialize shared (static) members
		sharedCompleter = new QCompleter(qApp);
		sharedCompleter->setCompletionMode(QCompleter::InlineCompletion);
		sharedCompleter->setCaseSensitivity(Qt::CaseInsensitive);
		loadCompletionFiles(sharedCompleter);

		currentCompletionFormat = new QTextCharFormat;
		braceMatchingFormat = new QTextCharFormat;
		currentLineFormat = new QTextCharFormat;

		QSETTINGS_OBJECT(settings);
69 70
		highlightCurrentLine = settings.value(QString::fromLatin1("highlightCurrentLine"), true).toBool();
		autocompleteEnabled = settings.value(QString::fromLatin1("autocompleteEnabled"), true).toBool();
71
	}
72
		
73 74 75 76 77 78 79 80
	loadIndentModes();
	loadSmartQuotesModes();
	
	connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(cursorPositionChangedSlot()));
	connect(this, SIGNAL(selectionChanged()), this, SLOT(cursorPositionChangedSlot()));

	lineNumberArea = new LineNumberArea(this);
	
81
	connect(document(), SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
82 83 84 85 86 87
	connect(this, SIGNAL(updateRequest(const QRect&, int)), this, SLOT(updateLineNumberArea(const QRect&, int)));
	connect(this, SIGNAL(textChanged()), lineNumberArea, SLOT(update()));

	connect(TWApp::instance(), SIGNAL(highlightLineOptionChanged()), this, SLOT(resetExtraSelections()));
	
	cursorPositionChangedSlot();
88
	updateLineNumberAreaWidth(0);
89 90 91
	updateColors();
}

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
void CompletingEdit::prefixLines(const QString &prefix)
{
	QTextCursor cursor = textCursor();
	cursor.beginEditBlock();
	int selStart = cursor.selectionStart();
	int selEnd = cursor.selectionEnd();
	cursor.setPosition(selStart);
	if (!cursor.atBlockStart()) {
		cursor.movePosition(QTextCursor::StartOfBlock);
		selStart = cursor.position();
	}
	cursor.setPosition(selEnd);
	if (!cursor.atBlockStart() || selEnd == selStart) {
		cursor.movePosition(QTextCursor::NextBlock);
		selEnd = cursor.position();
	}
	if (selEnd == selStart)
		goto handle_end_of_doc;	// special case - cursor in blank line at end of doc
	if (!cursor.atBlockStart()) {
		cursor.movePosition(QTextCursor::StartOfBlock);
		goto handle_end_of_doc; // special case - unterminated last line
	}
	while (cursor.position() > selStart) {
		cursor.movePosition(QTextCursor::PreviousBlock);
	handle_end_of_doc:
		cursor.insertText(prefix);
		cursor.movePosition(QTextCursor::StartOfBlock);
		selEnd += prefix.length();
	}
	cursor.setPosition(selStart);
	cursor.setPosition(selEnd, QTextCursor::KeepAnchor);
	setTextCursor(cursor);
	cursor.endEditBlock();
}

void CompletingEdit::unPrefixLines(const QString &prefix)
{
	QTextCursor cursor = textCursor();
	cursor.beginEditBlock();
	int selStart = cursor.selectionStart();
	int selEnd = cursor.selectionEnd();
	cursor.setPosition(selStart);
	if (!cursor.atBlockStart()) {
		cursor.movePosition(QTextCursor::StartOfBlock);
		selStart = cursor.position();
	}
	cursor.setPosition(selEnd);
	if (!cursor.atBlockStart() || selEnd == selStart) {
		cursor.movePosition(QTextCursor::NextBlock);
		selEnd = cursor.position();
	}
	if (!cursor.atBlockStart()) {
		cursor.movePosition(QTextCursor::StartOfBlock);
		goto handle_end_of_doc; // special case - unterminated last line
	}
	while (cursor.position() > selStart) {
		cursor.movePosition(QTextCursor::PreviousBlock);
	handle_end_of_doc:
		cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
		QString		str = cursor.selectedText();
		if (str == prefix) {
			cursor.removeSelectedText();
			selEnd -= prefix.length();
		}
		else
			cursor.movePosition(QTextCursor::PreviousCharacter);
	}
	cursor.setPosition(selStart);
	cursor.setPosition(selEnd, QTextCursor::KeepAnchor);
	setTextCursor(cursor);
	cursor.endEditBlock();
}


166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
void CompletingEdit::updateColors()
{
	Q_ASSERT(currentCompletionFormat != NULL);
	Q_ASSERT(braceMatchingFormat != NULL);
	Q_ASSERT(currentLineFormat != NULL);
	Q_ASSERT(lineNumberArea != NULL);

	qreal bgR, bgG, bgB;
	qreal fgR, fgG, fgB;

	palette().color(QPalette::Active, QPalette::Base).getRgbF(&bgR, &bgG, &bgB);
	palette().color(QPalette::Active, QPalette::Text).getRgbF(&fgR, &fgG, &fgB);

	currentCompletionFormat->setBackground(QColor::fromRgbF(.75 * bgR + .25 * fgR, .75 * bgG + .25 * fgG, .75 * bgB + .25 * fgB));
	braceMatchingFormat->setBackground(QColor("orange"));

	currentLineFormat->setBackground(QColor::fromRgbF(.9 * bgR + .1 * fgR, .9 * bgG + .1 * fgG, .9 * bgB + .1 * fgB));
	currentLineFormat->setProperty(QTextFormat::FullWidthSelection, true);

	palette().color(QPalette::Window).getRgbF(&bgR, &bgG, &bgB);
	palette().color(QPalette::Text).getRgbF(&fgR, &fgG, &fgB);
	lineNumberArea->setBgColor(QColor::fromRgbF(0.75 * bgR + 0.25 * fgR, 0.75 * bgG + 0.25 * fgG, 0.75 * bgB + 0.25 * fgB));
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
}

CompletingEdit::~CompletingEdit()
{
	setCompleter(NULL);
}

void CompletingEdit::setCompleter(QCompleter *completer)
{
	c = completer;
	if (!c)
		return;

	c->setWidget(this);
}

void CompletingEdit::cursorPositionChangedSlot()
{
	setCompleter(NULL);
	if (!currentCompletionRange.isNull()) {
		QTextCursor curs = textCursor();
209
		currentCompletionRange = QTextCursor();
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
	}
	resetExtraSelections();
	prefixLength = 0;
}

void CompletingEdit::mousePressEvent(QMouseEvent *e)
{
	if (e->buttons() != Qt::LeftButton) {
		mouseMode = none;
		QTextEdit::mousePressEvent(e);
		return;
	}

	if (e->modifiers() == Qt::ControlModifier) {
		mouseMode = synctexClick;
		e->accept();
		return;
	}

229 230
	int proximityToPrev = (e->pos() - clickPos).manhattanLength();

231 232 233 234 235 236 237 238 239
	mouseMode = normalSelection;
	clickPos = e->pos();
	if (e->modifiers() & Qt::ShiftModifier) {
		mouseMode = extendingSelection;
		clickCount = 1;
		QTextEdit::mousePressEvent(e);
		return;
	}

240
	if (clickTimer.isActive() && proximityToPrev < qApp->startDragDistance())
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
		++clickCount;
	else
		clickCount = 1;
	clickTimer.start(qApp->doubleClickInterval(), this);

	QTextCursor	curs;
	switch (clickCount) {
		case 1:
			curs = cursorForPosition(clickPos);
			break;
		case 2:
			curs = wordSelectionForPos(clickPos);
			break;
		default:
			curs = blockSelectionForPos(clickPos);
			break;
	}

	if (clickCount > 1) {
		setTextCursor(curs);
		setSelectionClipboard(curs);
		mouseMode = dragSelecting;
	}
	dragStartCursor = curs;
	e->accept();
}

void CompletingEdit::mouseMoveEvent(QMouseEvent *e)
{
	switch (mouseMode) {
		case none:
			QTextEdit::mouseMoveEvent(e);
			return;
		
		case synctexClick:
		case ignoring:
			e->accept();
			return;

		case extendingSelection:
			QTextEdit::mouseMoveEvent(e);
			return;
			
		case normalSelection:
			if (clickCount == 1
				&& dragStartCursor.position() >= textCursor().selectionStart()
				&& dragStartCursor.position() < textCursor().selectionEnd()) {
				if ((e->pos() - clickPos).manhattanLength() >= qApp->startDragDistance()) {
					int sourceStart = textCursor().selectionStart();
					int sourceEnd = textCursor().selectionEnd();
					QTextCursor source = textCursor();
					QDrag *drag = new QDrag(this);
					drag->setMimeData(createMimeDataFromSelection());
					QTextCursor dropCursor = textCursor();
					textCursor().beginEditBlock();
					Qt::DropAction action = drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::MoveAction);
					if (action != Qt::IgnoreAction) {
						dropCursor.setPosition(droppedOffset);
						dropCursor.setPosition(droppedOffset + droppedLength, QTextCursor::KeepAnchor);
300 301 302 303 304
						if (action == Qt::MoveAction) {
							// If we successfully completed a "Move" action, we
							// need to make sure that the source text is removed
							// (inserting the text in the target has already
							// been completed at this point)
305
							bool insideWindow = (drag->target() && (this == drag->target() || this->isAncestorOf(qobject_cast<QWidget*>(drag->target()))));
306 307 308 309 310 311 312 313
							bool insideSelection = (insideWindow && droppedOffset >= sourceStart && droppedOffset <= sourceEnd);
							if (insideSelection) {
								// The text was dropped into the same window at
								// an overlapping position.
								// First, remove everything that is left from
								// the source text *after* the inserted text
								// (note that every position after droppedOffset
								// needs to be translated by droppedLength)
314 315 316
								source.setPosition(droppedOffset + droppedLength);
								source.setPosition(sourceEnd + droppedLength, QTextCursor::KeepAnchor);
								source.removeSelectedText();
317 318
								// Second, remove everything that is left from
								// the source text *before* the inserted text
319 320 321 322
								source.setPosition(sourceStart);
								source.setPosition(droppedOffset, QTextCursor::KeepAnchor);
								source.removeSelectedText();
							}
323 324
							else {
								// Otherwise, simply remove the source text
325
								source.removeSelectedText();
326 327 328 329 330 331 332 333 334
							}
							
							if (!insideWindow) {
								// The selection was moved to a different window,
								// so dropCursor has no sensible data here. Thus,
								// we collapse the cursor to where the selection
								// was before the move action.
								dropCursor.setPosition(sourceStart);
							}
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
						}
					}
					textCursor().endEditBlock();
					setTextCursor(dropCursor);
					mouseMode = ignoring;
				}
				e->accept();
				return;
			}
			setTextCursor(dragStartCursor);
			mouseMode = dragSelecting;
			// fall through to dragSelecting

		case dragSelecting:
			QPoint pos = e->pos();
			int scrollValue = -1;
			if (verticalScrollBar() != NULL) {
				if (pos.y() < frameRect().top())
					verticalScrollBar()->triggerAction(QScrollBar::SliderSingleStepSub);
				else if (pos.y() > frameRect().bottom())
					verticalScrollBar()->triggerAction(QScrollBar::SliderSingleStepAdd);
				scrollValue = verticalScrollBar()->value();
			}
			QTextCursor curs;
			switch (clickCount) {
				case 1:
					curs = cursorForPosition(pos);
					break;
				case 2:
					curs = wordSelectionForPos(pos);
					break;
				default:
					curs = blockSelectionForPos(pos);
					break;
			}
			int start = qMin(dragStartCursor.selectionStart(), curs.selectionStart());
			int end = qMax(dragStartCursor.selectionEnd(), curs.selectionEnd());
372 373 374 375 376 377 378
			if (dragStartCursor.selectionStart() > curs.selectionStart()) {
				// If the user is selecting from right to left (moving towards
				// smaller positions), we reverse start and end so that the
				// selection anchor is placed at the proper place (the
				// left-most end of the selection).
				qSwap(start, end);
			}
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
			curs.setPosition(start);
			curs.setPosition(end, QTextCursor::KeepAnchor);
			setTextCursor(curs);
			setSelectionClipboard(curs);
			if (scrollValue != -1)
				verticalScrollBar()->setValue(scrollValue);
			e->accept();
			return;
	}
}

void CompletingEdit::mouseReleaseEvent(QMouseEvent *e)
{
	switch (mouseMode) {
		case none:
			QTextEdit::mouseReleaseEvent(e);
			return;
		case ignoring:
			e->accept();
			return;
		case synctexClick:
			{
				QTextCursor curs = cursorForPosition(e->pos());
402 403 404 405 406
#if QT_VERSION < 0x040700
				emit syncClick(curs.blockNumber() + 1, curs.position() - curs.block().position());
#else
				emit syncClick(curs.blockNumber() + 1, curs.positionInBlock());
#endif
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
			}
			e->accept();
			return;
		case dragSelecting:
			e->accept();
			return;
		case normalSelection:
			setTextCursor(dragStartCursor);
			setSelectionClipboard(dragStartCursor);
			e->accept();
			return;
		case extendingSelection:
			QTextEdit::mouseReleaseEvent(e);
			return;
	}
}

QTextCursor CompletingEdit::blockSelectionForPos(const QPoint& pos)
{
	QTextCursor curs = cursorForPosition(pos);
	curs.setPosition(curs.block().position());
428
	curs.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
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
	return curs;
}

bool CompletingEdit::selectWord(QTextCursor& cursor)
{
	if (cursor.selectionEnd() - cursor.selectionStart() > 1)
		return false;	// actually an error by the caller

	const QTextBlock block = document()->findBlock(cursor.selectionStart());
	const QString text = block.text();
	if (text.length() < 1) // empty line
		return false;

	int start, end;
	bool result = TWUtils::findNextWord(text, cursor.selectionStart() - block.position(), start, end);
	cursor.setPosition(block.position() + start);
	cursor.setPosition(block.position() + end, QTextCursor::KeepAnchor);

	return result;
}

QTextCursor CompletingEdit::wordSelectionForPos(const QPoint& mousePos)
{
	QTextCursor cursor;
	QPoint	pos = mousePos + QPoint(horizontalScrollBar()->value(), verticalScrollBar()->value());
	int cursorPos = document()->documentLayout()->hitTest(pos, Qt::FuzzyHit);
	if (cursorPos == -1)
		return cursor;

	cursor = QTextCursor(document());
	cursor.setPosition(cursorPos);
460
	cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482

	// check if click was within the char to the right of cursor; if so we select forwards
	QRect r = cursorRect(cursor);
	if (r.contains(pos)) {
		// Currently I don't seem to be getting a useful answer from cursorRect(), it's always zero-width :-(
		// and so this path will not be used, but leaving it here in hopes of fixing it some day
		//			QString s = cursor.selectedText();
		//			if (isPairedChar(s)) ...
		(void)selectWord(cursor);
		return cursor;
	}

	if (cursorPos > 0) {
		cursorPos -= 1;
		cursor.setPosition(cursorPos);
		cursor.setPosition(cursorPos + 1, QTextCursor::KeepAnchor);
		// don't test because the rect will be zero width (see above)!
		//		r = cursorRect(cursor);
		//		if (r.contains(pos)) {
		const QString plainText = toPlainText();
		QChar curChr = plainText[cursorPos];
		QChar c;
483
		if (!(c = TWUtils::closerMatching(curChr)).isNull()) {
484 485 486 487 488
			int balancePos = TWUtils::balanceDelim(plainText, cursorPos + 1, c, 1);
			if (balancePos < 0)
				QApplication::beep();
			else
				cursor.setPosition(balancePos + 1, QTextCursor::KeepAnchor);
489 490
		}
		else if (!(c = TWUtils::openerMatching(curChr)).isNull()) {
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
			int balancePos = TWUtils::balanceDelim(plainText, cursorPos - 1, c, -1);
			if (balancePos < 0)
				QApplication::beep();
			else {
				cursor.setPosition(balancePos);
				cursor.setPosition(cursorPos + 1, QTextCursor::KeepAnchor);
			}
		}
		else
			(void)selectWord(cursor);
	//		}
	}
	return cursor;
}

void CompletingEdit::mouseDoubleClickEvent(QMouseEvent *e)
{
	if (e->modifiers() == Qt::ControlModifier)
		e->accept();
	else if (e->modifiers() != Qt::NoModifier)
		QTextEdit::mouseDoubleClickEvent(e);
	else
		mousePressEvent(e); // don't like QTextEdit's selection behavior, so we try to improve it
}

void
CompletingEdit::setSelectionClipboard(const QTextCursor& curs)
{
	if (!curs.hasSelection())
		return;
	QClipboard *c = QApplication::clipboard();
	if (!c->supportsSelection())
		return;
524
	c->setText(curs.selectedText().replace(QChar(0x2019), QChar::fromLatin1('\n')),
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
		QClipboard::Selection);
}

void CompletingEdit::timerEvent(QTimerEvent *e)
{
	if (e->timerId() == clickTimer.timerId()) {
		clickTimer.stop();
		e->accept();
	}
	else
		QTextEdit::timerEvent(e);
}
	
void CompletingEdit::focusInEvent(QFocusEvent *e)
{
	if (c)
		c->setWidget(this);
	QTextEdit::focusInEvent(e);
}

void CompletingEdit::resetExtraSelections()
{
	QList<ExtraSelection> selections;
	if (highlightCurrentLine && !textCursor().hasSelection()) {
		ExtraSelection sel;
		sel.format = *currentLineFormat;
		sel.cursor = textCursor();
		selections.append(sel);
	}
	if (!currentCompletionRange.isNull()) {
		ExtraSelection sel;
		sel.cursor = currentCompletionRange;
		sel.format = *currentCompletionFormat;
		selections.append(sel);
	}
	setExtraSelections(selections);
}

void CompletingEdit::keyPressEvent(QKeyEvent *e)
{
	// Shortcut key for command completion
	bool isShortcut = (e->key() == Qt::Key_Tab || e->key() == Qt::Key_Backtab);
567
	if (isShortcut && autocompleteEnabled) {
568 569 570 571
		handleCompletionShortcut(e);
		return;
	}

572
	if (!e->text().isEmpty())
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
		cmpCursor = QTextCursor();

	switch (e->key()) {
		case Qt::Key_Return:
			handleReturn(e);
			break;

		case Qt::Key_Backspace:
			handleBackspace(e);
			break;

		default:
			handleOtherKey(e);
			break;
	}
}

void CompletingEdit::handleReturn(QKeyEvent *e)
{
	QString prefix;
593
	// Check if auto indent is on and applicable
594 595
	if (autoIndentMode >= 0 && autoIndentMode < indentModes->count() && e->modifiers() == Qt::NoModifier) {
		QRegExp &re = (*indentModes)[autoIndentMode].regex;
596 597 598 599 600 601 602 603 604 605 606 607 608
		// Only apply prefix recognition to characters in front of the cursor.
		// Otherwise, we would accumulate characters if the cursor is inside the
		// region matched by the regexp.
		QTextCursor curs = textCursor();
		// Collaps the selection (if any) in the direction of the beginning of
		// the line (as the selection gets replaced by \n, there's no point in
		// including it in the prefix calculation)
		if (curs.hasSelection())
			curs.setPosition(curs.selectionStart());
		// Get the (possible) prefix text to check
		curs.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
		QString blockText = curs.selectedText();
		// Check if the prefix matches the regexp of the current auto indent mode
609 610 611
		if (blockText.indexOf(re) == 0 && re.matchedLength() > 0)
			prefix = blockText.left(re.matchedLength());
	}
612 613
	// Propagate the key press event to the base class so that the text is
	// actually modified
614
	QTextEdit::keyPressEvent(e);
615
	// Insert the appropriate prefix if necessary
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
	if (!prefix.isEmpty()) {
		insertPlainText(prefix);
		prefixLength = prefix.length();
	}
}

void CompletingEdit::handleBackspace(QKeyEvent *e)
{
	QTextCursor curs = textCursor();
	if (e->modifiers() == Qt::NoModifier && prefixLength > 0 && !curs.hasSelection()) {
		curs.beginEditBlock();
		// note that prefixLength will get reset on the first deletion,
		// so it is important that the loop counts down rather than up!
		for (int i = prefixLength; i > 0; --i)
			curs.deletePreviousChar();
		curs.endEditBlock();
	}
	else
		QTextEdit::keyPressEvent(e);
635 636 637 638 639

	// Without the following, when pressing Up or Down immediately
	// after Backspace the cursor ends up in the wrong column.
	curs.setPosition(curs.position());
	setTextCursor(curs);
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
}

void CompletingEdit::handleOtherKey(QKeyEvent *e)
{
	QTextCursor cursor = textCursor();
	int pos = textCursor().selectionStart(); // remember cursor before the keystroke
	int end = textCursor().selectionEnd();
	QTextEdit::keyPressEvent(e);
	cursor = textCursor();
	bool arrowKey = false;
	if (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right) {
		arrowKey = true;
		if (pos < end && !cursor.hasSelection()) { // collapsed selection
			if (cursor.position() == end + 1)
				pos = end;
			cursor.setPosition(pos);
			setTextCursor(cursor);
		}
	}
	if ((e->modifiers() & Qt::ControlModifier) == 0) {
		// not a command key - maybe do brace matching or smart quotes
		if (!cursor.hasSelection()) {
			if (!arrowKey && cursor.selectionStart() == pos + 1) {
				if (smartQuotesMode >= 0)
					maybeSmartenQuote(cursor.position() - 1);
			}
			if (cursor.selectionStart() == pos + 1 || cursor.selectionStart() == pos - 1) {
				if (cursor.selectionStart() == pos - 1) // we moved backward, set pos to look at the char we just passed over
					--pos;
				const QString text = document()->toPlainText();
				int match = -2;
				QChar c;
672
				if (pos > 0 && pos < text.length() && !(c = TWUtils::openerMatching(text[pos])).isNull())
673
					match = TWUtils::balanceDelim(text, pos - 1, c, -1);
674
				else if (pos < text.length() - 1 && !(c = TWUtils::closerMatching(text[pos])).isNull())
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
					match = TWUtils::balanceDelim(text, pos + 1, c, 1);
				if (match >= 0) {
					QList<ExtraSelection> selList = extraSelections();
					ExtraSelection	sel;
					sel.cursor = QTextCursor(document());
					sel.cursor.setPosition(match);
					sel.cursor.setPosition(match + 1, QTextCursor::KeepAnchor);
					sel.format = *braceMatchingFormat;
					selList.append(sel);
					setExtraSelections(selList);
					QTimer::singleShot(250, this, SLOT(resetExtraSelections()));
				}
			}
		}
	}	
}

void CompletingEdit::setSmartQuotesMode(int index)
{
	smartQuotesMode = (index >= 0 && index < quotesModes->count()) ? index : -1;
}

QStringList CompletingEdit::smartQuotesModes()
{
	loadSmartQuotesModes();
	
	QStringList modes;
	foreach (const QuotesMode& mode, *quotesModes)
		modes << mode.name;
	return modes;
}

void CompletingEdit::loadSmartQuotesModes()
{
	if (quotesModes == NULL) {
710
		QDir configDir(TWUtils::getLibraryPath(QString::fromLatin1("configuration")));
711
		quotesModes = new QList<QuotesMode>;
712
		QFile quotesModesFile(configDir.filePath(QString::fromLatin1("smart-quotes-modes.txt")));
713
		if (quotesModesFile.open(QIODevice::ReadOnly)) {
714 715
			QRegExp modeName(QString::fromLatin1("\\[([^]]+)\\]"));
			QRegExp quoteLine(QString::fromLatin1("([^ \\t])\\s+([^ \\t]+)\\s+([^ \\t]+)"));
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
			QuotesMode newMode;
			while (1) {
				QByteArray ba = quotesModesFile.readLine();
				if (ba.size() == 0)
					break;
				if (ba[0] == '#' || ba[0] == '\n')
					continue;
				QString line = QString::fromUtf8(ba.data(), ba.size()).trimmed();
				if (modeName.exactMatch(line)) {
					if (newMode.mappings.count() > 0) {
						quotesModes->append(newMode);
						newMode.mappings.clear();
					}
					newMode.name = modeName.cap(1);
					continue;
				}
				if (quoteLine.exactMatch(line) && newMode.name.length() > 0) {
					QChar key = quoteLine.cap(1)[0];
					const QString& open = quoteLine.cap(2);
					const QString& close = quoteLine.cap(3);
					newMode.mappings[key] = QuotePair(open,close);
					continue;
				}
			}
			if (newMode.mappings.count() > 0) {
				quotesModes->append(newMode);
			}
		}
	}
}

void CompletingEdit::maybeSmartenQuote(int offset)
{
	if (smartQuotesMode < 0 || smartQuotesMode >= quotesModes->count())
		return;
	const QuoteMapping& mappings = quotesModes->at(smartQuotesMode).mappings;
752
	QString replacement;
753 754 755 756 757 758 759 760 761 762 763 764 765

	const QString& text = document()->toPlainText();
	if (offset < 0 || offset >= text.length())
		return;
	QTextCursor cursor(document());
	cursor.setPosition(offset);
	cursor.setPosition(offset + 1, QTextCursor::KeepAnchor);

	QChar keyChar = cursor.selectedText()[0];
	QuoteMapping::const_iterator iter = mappings.find(keyChar);
	if (iter == mappings.end())
		return;
	
766 767 768 769 770 771 772 773 774 775
	replacement = iter.value().second;
	if (offset == 0) {
		// always use opening quotes at the beginning of the document
		replacement = iter.value().first;
	}
	else {
		if (text[offset - 1].isSpace())
			replacement = iter.value().first;
		
		// after opening brackets, also use opening quotes
776
		if (text[offset - 1] == QChar::fromLatin1('{') || text[offset - 1] == QChar::fromLatin1('[') || text[offset - 1] == QChar::fromLatin1('('))
777 778 779 780
			replacement = iter.value().first;
	}
	
	cursor.insertText(replacement);
781 782 783 784 785
}

void CompletingEdit::smartenQuotes()
{
	if (smartQuotesMode < 0 || smartQuotesMode >= quotesModes->count())
786
		return;
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
	const QuoteMapping& mappings = quotesModes->at(smartQuotesMode).mappings;

	const QString& text = document()->toPlainText();

	QTextCursor curs = textCursor();
	int selStart = curs.selectionStart();
	int selEnd = curs.selectionEnd();
	bool changed = false;
	for (int offset = selEnd; offset > selStart; ) {
		--offset;
		QChar ch = text[offset];
		QuoteMapping::const_iterator iter = mappings.find(ch);
		if (iter == mappings.end())
			continue;

		if (!changed) {
			curs.beginEditBlock();
			changed = true;
		}
		curs.setPosition(offset, QTextCursor::MoveAnchor);
		curs.setPosition(offset + 1, QTextCursor::KeepAnchor);
		const QString& replacement((offset == 0 || text[offset - 1].isSpace()) ?
								   iter.value().first : iter.value().second);
		curs.insertText(replacement);
		selEnd += replacement.length() - 1;
812
	}
813 814 815 816 817
	if (changed) {
		curs.endEditBlock();
		curs.setPosition(selStart, QTextCursor::MoveAnchor);
		curs.setPosition(selEnd, QTextCursor::KeepAnchor);
		setTextCursor(curs);
818 819 820 821 822 823 824 825 826 827 828
	}
}

void CompletingEdit::handleCompletionShortcut(QKeyEvent *e)
{
// usage:
//   unmodified: next completion
//   shift     : previous completion
//   ctl/alt       : skip to next placeholder (alt on Mac, ctl elsewhere)
//   ctl/alt-shift : skip to previous placeholder

829
#if defined(Q_OS_DARWIN)
830 831 832 833 834 835 836 837 838 839
	if ((e->modifiers() & ~Qt::ShiftModifier) == Qt::AltModifier)
#else
	if ((e->modifiers() & ~Qt::ShiftModifier) == Qt::ControlModifier)
#endif
	{
		if (!find(QString(0x2022), (e->modifiers() & Qt::ShiftModifier)
									? QTextDocument::FindBackward : (QTextDocument::FindFlags)0))
			QApplication::beep();
		return;
	}
840 841 842 843

	// if we are at the beginning of the line (i.e., only whitespaces before a
	// caret cursor), insert a tab (for indentation) instead of doing completion
	bool atLineStart = false;
844

845
	QTextCursor lineStartCursor = textCursor();
846 847 848
	bool noSelection = lineStartCursor.selectionEnd() == lineStartCursor.selectionStart();

	if (noSelection) {
849 850 851 852
		lineStartCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
		if(lineStartCursor.selectedText().trimmed().isEmpty())
			atLineStart = true;
	}
853
	
854
	if (c == NULL && !atLineStart) {
855 856 857 858 859 860 861 862 863
		cmpCursor = textCursor();
		if (!selectWord(cmpCursor) && textCursor().selectionStart() > 0) {
			cmpCursor.setPosition(textCursor().selectionStart() - 1);
			selectWord(cmpCursor);
		}
		// check if the word is preceded by open-brace; if so try with that included
		int start = cmpCursor.selectionStart();
		int end = cmpCursor.selectionEnd();
		if (start > 0) { // special cases: possibly look back to include brace or hyphen(s)
864
			if (cmpCursor.selectedText() == QLatin1String("-")) {
865 866 867 868 869
				QTextCursor hyphCursor(cmpCursor);
				int hyphPos = start;
				while (hyphPos > 0) {
					hyphCursor.setPosition(hyphPos - 1);
					hyphCursor.setPosition(hyphPos, QTextCursor::KeepAnchor);
870
					if (hyphCursor.selectedText() != QLatin1String("-"))
871 872 873 874 875 876
						break;
					--hyphPos;
				}
				cmpCursor.setPosition(hyphPos);
				cmpCursor.setPosition(end, QTextCursor::KeepAnchor);
			}
877
			else if (cmpCursor.selectedText() != QLatin1String("{")) {
878 879 880
				QTextCursor braceCursor(cmpCursor);
				braceCursor.setPosition(start - 1);
				braceCursor.setPosition(start, QTextCursor::KeepAnchor);
881
				if (braceCursor.selectedText() == QLatin1String("{")) {
882 883 884
					cmpCursor.setPosition(start - 1);
					cmpCursor.setPosition(end, QTextCursor::KeepAnchor);
				}
885
			}
886 887 888 889
		}
		
		while (1) {
			QString completionPrefix = cmpCursor.selectedText();
890
			if (!completionPrefix.isEmpty()) {
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
				setCompleter(sharedCompleter);
				c->setCompletionPrefix(completionPrefix);
				if (c->completionCount() == 0) {
					if (cmpCursor.selectionStart() < start) {
						// we must have included a preceding brace or hyphen; now try without it
						cmpCursor.setPosition(start);
						cmpCursor.setPosition(end, QTextCursor::KeepAnchor);
						continue;
					}
					setCompleter(NULL);
				}
				else {
					if (e->modifiers() == Qt::ShiftModifier)
						c->setCurrentRow(c->completionCount() - 1);
					showCurrentCompletion();
					return;
				}
			}
			break;
		}
	}
	
	if (c != NULL && c->completionCount() > 0) {
		if (e->modifiers() == Qt::ShiftModifier)  {
			if (c->currentRow() == 0) {
				showCompletion(c->completionPrefix());
				setCompleter(NULL);
			}
			else {
				c->setCurrentRow(c->currentRow() - 1);
				showCurrentCompletion();
			}
		}
		else {
			if (c->currentRow() == c->completionCount() - 1) {
				showCompletion(c->completionPrefix());
				setCompleter(NULL);
			}
			else {
				c->setCurrentRow(c->currentRow() + 1);
				showCurrentCompletion();
			}
		}
		return;
	}
	
937 938 939 940 941 942 943 944 945
	if(!noSelection) {
		if(e->modifiers() == Qt::ShiftModifier) {
			unPrefixLines(QString::fromLatin1("\t"));
		} else {
			prefixLines(QString::fromLatin1("\t"));
		}
	} else {
		QTextEdit::keyPressEvent(e);
	}
946 947 948 949 950 951 952 953 954 955 956 957
}

void CompletingEdit::showCompletion(const QString& completion, int insOffset)
{
	disconnect(this, SIGNAL(cursorPositionChanged()), this, SLOT(cursorPositionChangedSlot()));

	if (c->widget() != this)
		return;

	QTextCursor tc = cmpCursor;
	if (tc.isNull()) {
		tc = textCursor();
958
		tc.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, c->completionPrefix().length());
959 960 961 962
	}

	tc.insertText(completion);
	cmpCursor = tc;
963
	cmpCursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, completion.length());
964 965

	if (insOffset != -1)
966
		tc.movePosition(QTextCursor::PreviousCharacter, QTextCursor::MoveAnchor, completion.length() - insOffset);
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
	setTextCursor(tc);

	currentCompletionRange = cmpCursor;
	resetExtraSelections();

	connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(cursorPositionChangedSlot()));
}

void CompletingEdit::showCurrentCompletion()
{
	if (c->widget() != this)
		return;

	QStandardItemModel *model = qobject_cast<QStandardItemModel*>(c->model());
	QList<QStandardItem*> items = model->findItems(c->currentCompletion());

	if (items.count() > 1) {
		if (c->currentCompletion() == prevCompletion) {
			if (c->currentIndex().row() > prevRow)
				++itemIndex;
			else
				--itemIndex;
			if (itemIndex < 0)
				itemIndex = items.count() - 1;
			else if (itemIndex > items.count() - 1)
				itemIndex = 0;
		}
		else
			itemIndex = 0;
		prevRow = c->currentIndex().row();
		prevCompletion = c->currentCompletion();
	}
	else {
		prevCompletion = QString();
		itemIndex = 0;
	}

	QString completion = model->item(items[itemIndex]->row(), 1)->text();
	
1006
	int insOffset = completion.indexOf(QLatin1String("#INS#"));
1007
	if (insOffset != -1)
1008
		completion.replace(QLatin1String("#INS#"), QLatin1String(""));
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024

	showCompletion(completion, insOffset);
}

void CompletingEdit::loadCompletionsFromFile(QStandardItemModel *model, const QString& filename)
{
	QFile	completionFile(filename);
	if (completionFile.exists() && completionFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
		QTextStream in(&completionFile);
		in.setCodec("UTF-8");
		in.setAutoDetectUnicode(true);
		QList<QStandardItem*> row;
		while (1) {
			QString	line = in.readLine();
			if (line.isNull())
				break;
1025
			if (line[0] == QChar::fromLatin1('%'))
1026
				continue;
1027 1028
			line.replace(QLatin1String("#RET#"), QLatin1String("\n"));
			QStringList parts = line.split(QString::fromLatin1(":="));
1029 1030 1031 1032
			if (parts.count() > 2)
				continue;
			if (parts.count() == 1)
				parts.append(parts[0]);
1033
			parts[0].replace(QLatin1String("#INS#"), QLatin1String(""));
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
			row.append(new QStandardItem(parts[0]));
			row.append(new QStandardItem(parts[1]));
			model->appendRow(row);
			row.clear();
		}
		completionFile.close();
	}
}

void CompletingEdit::loadCompletionFiles(QCompleter *theCompleter)
{
	QStandardItemModel *model = new QStandardItemModel(0, 2, theCompleter); // columns are abbrev, expansion

1047
	QDir completionDir(TWUtils::getLibraryPath(QString::fromLatin1("completion")));
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
	foreach (QFileInfo fileInfo, completionDir.entryInfoList(QDir::Files | QDir::Readable, QDir::Name)) {
		loadCompletionsFromFile(model, fileInfo.canonicalFilePath());
	}

	theCompleter->setModel(model);
}

void CompletingEdit::jumpToPdf()
{
	QAction *act = qobject_cast<QAction*>(sender());
1058 1059 1060 1061
	if (act != NULL) {
		QPoint pt = act->data().toPoint();
		emit syncClick(pt.y(), pt.x());
	}
1062 1063 1064 1065 1066
}

void CompletingEdit::contextMenuEvent(QContextMenuEvent *event)
{
	QMenu *menu = createStandardContextMenu();
1067
	QAction *defaultAction = NULL;
1068
	QAction *act = new QAction(tr("Jump to PDF"), menu);
1069 1070 1071 1072 1073 1074 1075
	QTextCursor cur = cursorForPosition(event->pos());

#if QT_VERSION < 0x040700
	act->setData(QVariant(QPoint(cur.position() - cur.block().position(), cur.blockNumber() + 1)));
#else
	act->setData(QVariant(QPoint(cur.positionInBlock(), cur.blockNumber() + 1)));
#endif
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
	connect(act, SIGNAL(triggered()), this, SLOT(jumpToPdf()));
	menu->insertSeparator(menu->actions().first());
	menu->insertAction(menu->actions().first(), act);
	
	if (pHunspell != NULL) {
		currentWord = cursorForPosition(event->pos());
		currentWord.setPosition(currentWord.position());
		if (selectWord(currentWord)) {
			QByteArray word = spellingCodec->fromUnicode(currentWord.selectedText());
			int spellResult = Hunspell_spell(pHunspell, word.data());
			if (spellResult == 0) {
				char **suggestionList;
				int count = Hunspell_suggest(pHunspell, &suggestionList, word.data());
				QAction *sep = menu->insertSeparator(menu->actions().first());
				if (count == 0)
					menu->insertAction(sep, new QAction(tr("No suggestions"), menu));
				else {
					QSignalMapper *mapper = new QSignalMapper(menu);
					for (int i = 0; i < count; ++i) {
						QString str = spellingCodec->toUnicode(suggestionList[i]);
						act = new QAction(str, menu);
						connect(act, SIGNAL(triggered()), mapper, SLOT(map()));
						mapper->setMapping(act, str);
						menu->insertAction(sep, act);
						free(suggestionList[i]);
1101 1102
						if (!defaultAction)
							defaultAction = act;
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
					}
					free(suggestionList);
					connect(mapper, SIGNAL(mapped(const QString&)), this, SLOT(correction(const QString&)));
				}
				sep = menu->insertSeparator(menu->actions().first());
//				QAction *add = new QAction(tr("Add to dictionary"), menu);
//				connect(add, SIGNAL(triggered()), this, SLOT(addToDictionary()));
//				menu->insertAction(sep, add);
				QAction *ignore = new QAction(tr("Ignore word"), menu);
				connect(ignore, SIGNAL(triggered()), this, SLOT(ignoreWord()));
				menu->insertAction(sep, ignore);
			}
		}
	}
	
1118
	menu->exec(event->globalPos(), defaultAction);
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
	delete menu;
}

void CompletingEdit::setSpellChecker(Hunhandle* h, QTextCodec *codec)
{
	pHunspell = h;
	spellingCodec = codec;
}

void CompletingEdit::setAutoIndentMode(int index)
{
	autoIndentMode = (index >= 0 && index < indentModes->count()) ? index : -1;
}

void CompletingEdit::correction(const QString& suggestion)
{
	currentWord.insertText(suggestion);
}

void CompletingEdit::addToDictionary()
{
	// For this to be useful, we need to be able to store a user dictionary (per language).
	// Prefer to switch to Enchant first, before looking into this further.
}

void CompletingEdit::ignoreWord()
{
	// note that this is not persistent after quitting TW
	QByteArray word = spellingCodec->fromUnicode(currentWord.selectedText());
	(void)Hunspell_add(pHunspell, word.data());
	emit rehighlight();
}

void CompletingEdit::loadIndentModes()
{
	if (indentModes == NULL) {
1155
		QDir configDir(TWUtils::getLibraryPath(QString::fromLatin1("configuration")));
1156
		indentModes = new QList<IndentMode>;
1157
		QFile indentPatternFile(configDir.filePath(QString::fromLatin1("auto-indent-patterns.txt")));
1158
		if (indentPatternFile.open(QIODevice::ReadOnly)) {
1159
			QRegExp re(QString::fromLatin1("\"([^\"]+)\"\\s+(.+)"));
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
			while (1) {
				QByteArray ba = indentPatternFile.readLine();
				if (ba.size() == 0)
					break;
				if (ba[0] == '#' || ba[0] == '\n')
					continue;
				QString line = QString::fromUtf8(ba.data(), ba.size()).trimmed();
				if (re.exactMatch(line)) {
					IndentMode mode;
					mode.name = re.cap(1);
					mode.regex = QRegExp(re.cap(2).trimmed());
					if (!mode.name.isEmpty() && mode.regex.isValid())
						indentModes->append(mode);
				}
			}
		}
	}
}

QStringList CompletingEdit::autoIndentModes()
{
	loadIndentModes();
	
	QStringList modes;
	foreach (const IndentMode& mode, *indentModes)
		modes << mode.name;
	return modes;
}

void CompletingEdit::dragEnterEvent(QDragEnterEvent *event)
{
	if (event->mimeData()->hasUrls())
		event->ignore();
	else
		QTextEdit::dragEnterEvent(event);
}

void CompletingEdit::dropEvent(QDropEvent *event)
{
	QTextCursor dropCursor = cursorForPosition(event->pos());
	if (!dropCursor.isNull()) {
		droppedOffset = dropCursor.position();
		droppedLength = event->mimeData()->text().length();
	}
	else
		droppedOffset = -1;

	int scrollX = horizontalScrollBar()->value();
	int scrollY = verticalScrollBar()->value();
	QTextEdit::dropEvent(event);
	verticalScrollBar()->setValue(scrollY);
	horizontalScrollBar()->setValue(scrollX);
}

void CompletingEdit::insertFromMimeData(const QMimeData *source)
{
	if (source->hasText()) {
		QTextCursor curs = textCursor();
		curs.insertText(source->text());
	}
}

bool CompletingEdit::canInsertFromMimeData(const QMimeData *source) const
{
	return source->hasText();
}

// support for the line-number area
// from Qt tutorial "Code Editor"

void CompletingEdit::setLineNumberDisplay(bool displayNumbers)
{
	lineNumberArea->setVisible(displayNumbers);
1233
	updateLineNumberAreaWidth(0);
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
}

int CompletingEdit::lineNumberAreaWidth()
{
	int digits = 1;
	int max = qMax(1, document()->blockCount());
	while (max >= 10) {
		max /= 10;
		++digits;
	}
	
1245
	int space = 3 + fontMetrics().width(QChar::fromLatin1('9')) * digits;
1246 1247 1248 1249
	
	return space;
}

1250 1251 1252 1253 1254
bool CompletingEdit::getLineNumbersVisible() const
{
	return lineNumberArea->isVisible();
}

1255
void CompletingEdit::updateLineNumberAreaWidth(int /* newBlockCount */)
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
{
	if (lineNumberArea->isVisible()) {
		setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
		lineNumberArea->update();
	}
	else {
		setViewportMargins(0, 0, 0, 0);
	}
}

void CompletingEdit::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()))
1274
		updateLineNumberAreaWidth(0);
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
}

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

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
void CompletingEdit::wheelEvent(QWheelEvent *e)
{
	if (e->modifiers() & Qt::ControlModifier)
	{
		wheelDelta += e->delta();  // accumulate wheelDelta for high-resolution mice, which might pass small values.
		int sign = (wheelDelta < 0) ? -1 : 1;
		const int stepSize = 120;  // according to Qt docs a standard wheel step corresponds to a delta of 120.
		int steps = (sign * wheelDelta) / stepSize;  // abs value to guarantee rounding towards 0.
		if (steps > 0) {
			QFont ft = font();
			const int minFontSize = 4;
			ft.setPointSize(qMax(ft.pointSize() + sign * steps, minFontSize));
			setFont(ft);
			wheelDelta = 0;
		}
		e->accept();
		return;
	}

	QTextEdit::wheelEvent(e);
}

1307 1308
void CompletingEdit::lineNumberAreaPaintEvent(QPaintEvent *event)
{
1309 1310
	Q_ASSERT(lineNumberArea != NULL);

1311
	QPainter painter(lineNumberArea);
1312
	painter.fillRect(event->rect(), lineNumberArea->bgColor());
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
	
	QTextBlock block = document()->begin();
	int blockNumber = 1;

	QAbstractTextDocumentLayout *layout = document()->documentLayout();
	int top = layout->blockBoundingRect(block).top() - verticalScrollBar()->value();
	int bottom = top + layout->blockBoundingRect(block).height();
	
	while (block.isValid() && top <= event->rect().bottom()) {
		if (bottom >= event->rect().top()) {
			QString number = QString::number(blockNumber);
			painter.drawText(0, top, lineNumberArea->width() - 1, fontMetrics().height(),
							 Qt::AlignRight, number);
		}

		block = block.next();
		if (block == document()->end())
			break;
		top = bottom;
		bottom = top + (int)layout->blockBoundingRect(block).height();
		++blockNumber;
	}
}

1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
void CompletingEdit::setTextCursor(const QTextCursor & cursor)
{
	// QTextEdit::setTextCursor only scrolls to cursor.position(). If 
	// position() > anchor(), the two are on different lines, and the view has
	// to scroll up, this means that not the whole selection is visible.
	// By manually setting the cursor to anchor() first, we ensure that the
	// anchor is visible. Only then we set the final cursor (which may scroll to
	// position() as it should, but at least a large part of the selection will
	// be visible).
	QTextCursor c(cursor);
	c.setPosition(c.anchor());
	QTextEdit::setTextCursor(c);
	QTextEdit::setTextCursor(cursor);
}

1352 1353 1354 1355 1356 1357 1358
bool CompletingEdit::event(QEvent *e)
{
	if (e->type() == QEvent::UpdateRequest) {
		// should be limiting the rect to what actually needs updating
		// but don't know how to get that from the event :(
		emit updateRequest(viewport()->rect(), 0);
	}
1359 1360 1361 1362
	// Alternatively, we could use QEvent::ApplicationPaletteChange if we'd
	// derive the colors from the application's palette
	if (e->type() == QEvent::PaletteChange)
		updateColors();
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
	return QTextEdit::event(e);
}

void CompletingEdit::scrollContentsBy(int dx, int dy)
{
	if (dy != 0) {
		emit updateRequest(viewport()->rect(), dy);
	}
	QTextEdit::scrollContentsBy(dx, dy);
}

void CompletingEdit::setHighlightCurrentLine(bool highlight)
{
	if (highlight != highlightCurrentLine) {
		highlightCurrentLine = highlight;
		TWApp::instance()->emitHighlightLineOptionChanged();
	}
}

1382 1383 1384
void CompletingEdit::setAutocompleteEnabled(bool autocomplete)
{
	if (autocomplete != autocompleteEnabled) {
1385
		autocompleteEnabled = autocomplete;
1386 1387 1388
	}
}

1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
void CompletingEdit::setFont(const QFont & font)
{
	QTextEdit::setFont(font);
	updateLineNumberAreaWidth((document() ? document()->blockCount() : 0));
}

void CompletingEdit::setFontFamily(const QString & fontFamily)
{
	QTextEdit::setFontFamily(fontFamily);
	updateLineNumberAreaWidth((document() ? document()->blockCount() : 0));
}

void CompletingEdit::setFontItalic(bool italic)
{
	QTextEdit::setFontItalic(italic);
	updateLineNumberAreaWidth((document() ? document()->blockCount() : 0));
}

void CompletingEdit::setFontPointSize(qreal s)
{
	QTextEdit::setFontPointSize(s);
	updateLineNumberAreaWidth((document() ? document()->blockCount() : 0));
}

void CompletingEdit::setFontWeight(int weight)
{
	QTextEdit::setFontWeight(weight);
	updateLineNumberAreaWidth((document() ? document()->blockCount() : 0));
}


1420 1421 1422 1423
QTextCharFormat	*CompletingEdit::currentCompletionFormat = NULL;
QTextCharFormat	*CompletingEdit::braceMatchingFormat = NULL;
QTextCharFormat	*CompletingEdit::currentLineFormat = NULL;
bool CompletingEdit::highlightCurrentLine = true;
1424
bool CompletingEdit::autocompleteEnabled = true;
1425 1426 1427 1428 1429

QCompleter	*CompletingEdit::sharedCompleter = NULL;

QList<CompletingEdit::IndentMode> *CompletingEdit::indentModes = NULL;
QList<CompletingEdit::QuotesMode> *CompletingEdit::quotesModes = NULL;