/* charPos is positive position */ int Wt_TextEdit::wt_findPairChar(int charPos, QChar pairChar, bool findBefore) { QTextCursor textCursor = this->textCursor(); textCursor.setPosition(charPos, QTextCursor::KeepAnchor); int charBlockPos = textCursor.positionInBlock(); QString line = textCursor.block().text(); QChar curChar = line[charBlockPos]; printf("wt_findPairChar char:%c | toChar:%c \n" , curChar.cell(), pairChar.cell()); int pair = 0; //int findBlockPos = -1; int findPositivePos = -1; int curPos = -1; QString curString = ""; QTextCursor::MoveOperation direction = findBefore == true ? QTextCursor::PreviousCharacter : QTextCursor::NextCharacter; for (int i = 0 ; textCursor.movePosition(direction, QTextCursor::KeepAnchor) ; i++) { curPos = textCursor.positionInBlock(); curString = textCursor.block().text(); if(curString[curPos] == curChar) { pair += 1; } if(curString[curPos] == pairChar) { pair -= 1; } if(pair < 0) { //findBlockPos = curPos; findPositivePos = textCursor.position(); return findPositivePos; } } return -1; }
/* indent when there has nothing before the char in the block charPos is positive position */ void Wt_TextEdit::wt_indentChar(int charPos, int toCharPos) { printf("wt_indentChar \n"); QTextCursor textCursor = this->textCursor(); textCursor.setPosition(toCharPos, QTextCursor::MoveAnchor); QString toLine = textCursor.block().text(); textCursor.setPosition(charPos, QTextCursor::MoveAnchor); int charBlockPos = textCursor.positionInBlock(); QString line = textCursor.block().text(); QChar mchar = line[charBlockPos]; // printf("mchar : %c | line : %s | charBlockPos: %d\n", mchar.cell(), line.toStdString().c_str(), charBlockPos); if(line.trimmed()[0] != mchar) { printf("mchar return : %c\n", mchar.cell()); return; } /* textCursor.setPosition(charPos, QTextCursor::KeepAnchor); pos between Anchor will be selected , delete will clear all selection */ for(int i = 0; i < charBlockPos ; i++) { printf("deleteChar\n"); textCursor.deletePreviousChar(); } for(int i = 0 ; i < toLine.length() ; i++) { if(toLine[i] == ' ' || toLine[i] == '\t') { textCursor.insertText(QString(toLine[i])); } else { break; } } }
CompletionContextFinder::CompletionContextFinder(const QTextCursor &cursor) : m_cursor(cursor) , m_colonCount(-1) , m_behaviorBinding(false) , m_inStringLiteral(false) , m_inImport(false) { QTextBlock lastBlock = cursor.block(); if (lastBlock.next().isValid()) lastBlock = lastBlock.next(); initialize(cursor.document()->begin(), lastBlock); m_startTokenIndex = yyLinizerState.tokens.size() - 1; // Initialize calls readLine - which skips empty lines. We should only adjust // the start token index if the linizer still is in the same block as the cursor. const int cursorPos = cursor.positionInBlock(); if (yyLinizerState.iter == cursor.block()) { for (; m_startTokenIndex >= 0; --m_startTokenIndex) { const Token &token = yyLinizerState.tokens.at(m_startTokenIndex); if (token.end() <= cursorPos) break; if (token.begin() < cursorPos && token.is(Token::String)) m_inStringLiteral = true; } if (m_startTokenIndex == yyLinizerState.tokens.size() - 1 && yyLinizerState.insertedSemicolon) --m_startTokenIndex; } getQmlObjectTypeName(m_startTokenIndex); checkBinding(); checkImport(); }
bool GlslCompleter::contextAllowsElectricCharacters(const QTextCursor &cursor) const { const Token tk = SimpleLexer::tokenAt(cursor.block().text(), cursor.positionInBlock(), BackwardsScanner::previousBlockState(cursor.block()), LanguageFeatures::defaultFeatures()); // XXX Duplicated from CppEditor::isInComment to avoid tokenizing twice if (tk.isComment()) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (pos == tk.utf16charsEnd()) { if (tk.is(T_CPP_COMMENT) || tk.is(T_CPP_DOXY_COMMENT)) return false; const int state = cursor.block().userState() & 0xFF; if (state > 0) return false; } if (pos < tk.utf16charsEnd()) return false; } else if (tk.isStringLiteral() || tk.isCharLiteral()) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (pos <= tk.utf16charsEnd()) return false; } return true; }
bool CppAutoCompleter::contextAllowsElectricCharacters(const QTextCursor &cursor) const { const Token tk = SimpleLexer::tokenAt(cursor.block().text(), cursor.positionInBlock(), BackwardsScanner::previousBlockState(cursor.block())); // XXX Duplicated from CPPEditor::isInComment to avoid tokenizing twice if (tk.isComment()) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (pos == tk.end()) { if (tk.is(T_CPP_COMMENT) || tk.is(T_CPP_DOXY_COMMENT)) return false; const int state = cursor.block().userState() & 0xFF; if (state > 0) return false; } if (pos < tk.end()) return false; } else if (tk.is(T_STRING_LITERAL) || tk.is(T_WIDE_STRING_LITERAL) || tk.is(T_CHAR_LITERAL) || tk.is(T_WIDE_CHAR_LITERAL)) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (pos <= tk.end()) return false; } return true; }
void GenericCodeEditor::handleKeyBackspace(QKeyEvent * event, QTextCursor & textCursor, bool & updateCursor) { if (event->modifiers() & Qt::META) { textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor); textCursor.removeSelectedText(); } else { if ( !overwriteMode() || (textCursor.positionInBlock() == 0) || textCursor.hasSelection() ) { QPlainTextEdit::keyPressEvent(event); } else { // in overwrite mode, backspace should insert a space textCursor.beginEditBlock(); textCursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); QString selectedText = textCursor.selectedText(); if (selectedText == QStringLiteral(" ") || selectedText == QStringLiteral("\t") ) { textCursor.clearSelection(); } else { textCursor.insertText(QString(QChar(' '))); textCursor.movePosition(QTextCursor::PreviousCharacter); } textCursor.endEditBlock(); } updateCursor = true; } }
void Wt_TextEdit::wt_pressEnter() { printf("wt_pressEnter \n"); QTextCursor textCursor = this->textCursor(); int curPos = textCursor.positionInBlock(); QString curString = textCursor.block().text(); QChar curChar = curString[curPos]; textCursor.insertText("\n"); if(curString != NULL && curString.length() > 0) { for(int i = 0 ;i < curString.length() && curString[i]=='\t' ; i++) { textCursor.insertText("\t"); } curString = curString.trimmed(); if(curString != NULL && curString.length() > 0 && curString[curString.length()-1] == '{') { textCursor.insertText("\t"); } //if(curString != NULL && curString.length() > 0 && curString[curString.length()-1] == '}') { // wt_indentCurrentSymbol('{'); //} if(curChar == '}') { wt_indentCurrentSymbol('{'); } } //wt_indentSymbol('{', '}'); }
void RefactoringEngine::startLocalRenaming(const CppTools::CursorInEditor &data, CppTools::ProjectPart *projectPart, RenameCallback &&renameSymbolsCallback) { using CppTools::CompilerOptionsBuilder; setRefactoringEngineAvailable(false); m_client.setLocalRenamingCallback(std::move(renameSymbolsCallback)); QString filePath = data.filePath().toString(); QTextCursor textCursor = data.cursor(); CompilerOptionsBuilder optionsBuilder{*projectPart, CLANG_VERSION, CLANG_RESOURCE_DIR}; Utils::SmallStringVector commandLine{optionsBuilder.build( fileKindInProjectPart(projectPart, filePath), CppTools::getPchUsage())}; commandLine.push_back(filePath); RequestSourceLocationsForRenamingMessage message(ClangBackEnd::FilePath(filePath), uint(textCursor.blockNumber() + 1), uint(textCursor.positionInBlock() + 1), textCursor.document()->toPlainText(), std::move(commandLine), textCursor.document()->revision()); m_server.requestSourceLocationsForRenamingMessage(std::move(message)); }
void DoxygenGenerator::assignCommentOffset(QTextCursor cursor) { if (cursor.hasSelection()) { if (cursor.anchor() < cursor.position()) cursor.setPosition(cursor.anchor()); } m_commentOffset = cursor.positionInBlock(); }
QString MatchingText::insertParagraphSeparator(const QTextCursor &tc) const { BackwardsScanner tk(tc, MAX_NUM_LINES); int index = tk.startToken(); if (tk[index - 1].isNot(T_LBRACE)) return QString(); // nothing to do. const QString textBlock = tc.block().text().mid(tc.positionInBlock()).trimmed(); if (! textBlock.isEmpty()) return QString(); --index; // consume the `{' const Token &token = tk[index - 1]; if (token.is(T_STRING_LITERAL) && tk[index - 2].is(T_EXTERN)) { // recognized extern "C" return QLatin1String("}"); } else if (token.is(T_IDENTIFIER)) { int i = index - 1; forever { const Token ¤t = tk[i - 1]; if (current.is(T_EOF_SYMBOL)) break; else if (current.is(T_CLASS) || current.is(T_STRUCT) || current.is(T_UNION) || current.is(T_ENUM)) { // found a class key. QString str = QLatin1String("};"); if (shouldInsertNewline(tc)) str += QLatin1Char('\n'); return str; } else if (current.is(T_NAMESPACE)) return QLatin1String("}"); // found a namespace declaration else if (current.is(T_SEMICOLON)) break; // found the `;' sync token else if (current.is(T_LBRACE) || current.is(T_RBRACE)) break; // braces are considered sync tokens else if (current.is(T_LPAREN) || current.is(T_RPAREN)) break; // sync token else if (current.is(T_LBRACKET) || current.is(T_RBRACKET)) break; // sync token --i; } }
QTextCursor ScCodeEditor::blockAroundCursor( const QTextCursor & cursor ) { TokenIterator left_bracket = previousOpeningBracket( TokenIterator::leftOf(cursor.block(), cursor.positionInBlock()) ); if (!left_bracket.isValid()) return QTextCursor(); TokenIterator right_bracket = nextClosingBracket( TokenIterator::rightOf(cursor.block(), cursor.positionInBlock()) ); if (!right_bracket.isValid()) return QTextCursor(); QTextCursor block_cursor = cursor; block_cursor.setPosition( left_bracket.position() ); block_cursor.setPosition( right_bracket.position() + 1, QTextCursor::KeepAnchor ); return block_cursor; }
QString GenericCodeEditor::symbolUnderCursor() { const QTextCursor cursor = textCursor(); if (cursor.hasSelection()) return cursor.selectedText(); const QString blockString = cursor.block().text(); const int position = cursor.positionInBlock(); return tokenInStringAt( position, blockString ); }
void ScCodeEditor::gotoNextBlock() { QTextCursor cursor = textCursor(); TokenIterator tokenIt = TokenIterator::rightOf( cursor.block(), cursor.positionInBlock() ); if (tokenIt.type() == Token::OpeningBracket && tokenIt.block() == cursor.block() && tokenIt->positionInBlock == cursor.positionInBlock()) ++tokenIt; tokenIt = nextClosingBracket( tokenIt ); if (tokenIt.isValid()) setTextCursor( cursorAt(tokenIt, 1) ); else { cursor.movePosition( QTextCursor::End ); setTextCursor( cursor ); } }
void ScCodeEditor::gotoPreviousBlock() { QTextCursor cursor = textCursor(); TokenIterator tokenIt = TokenIterator::leftOf(cursor.block(), cursor.positionInBlock()); if (tokenIt.type() == Token::ClosingBracket && tokenIt.block() == cursor.block() && tokenIt->positionInBlock == cursor.positionInBlock() - 1) --tokenIt; tokenIt = previousOpeningBracket( tokenIt ); if (tokenIt.isValid()) setTextCursor( cursorAt(tokenIt) ); else { cursor.movePosition( QTextCursor::Start ); setTextCursor( cursor ); } }
int AutoCompleter::paragraphSeparatorAboutToBeInserted(QTextCursor &cursor, const TabSettings &tabSettings) { if (!m_autoParenthesesEnabled) return 0; QTextDocument *doc = cursor.document(); if (doc->characterAt(cursor.position() - 1) != QLatin1Char('{')) return 0; if (!contextAllowsAutoParentheses(cursor)) return 0; // verify that we indeed do have an extra opening brace in the document QTextBlock block = cursor.block(); const QString textFromCusror = block.text().mid(cursor.positionInBlock()).trimmed(); int braceDepth = TextDocumentLayout::braceDepth(doc->lastBlock()); if (braceDepth <= 0 && (textFromCusror.isEmpty() || textFromCusror.at(0) != QLatin1Char('}'))) return 0; // braces are all balanced or worse, no need to do anything and separator inserted not between '{' and '}' // 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; */ int indentation = tabSettings.indentationColumn(block.text()); if (block.next().isValid()) { // not the last block block = block.next(); //skip all empty blocks while (block.isValid() && tabSettings.onlySpace(block.text())) block = block.next(); if (block.isValid() && tabSettings.indentationColumn(block.text()) > indentation) return 0; } const QString &textToInsert = insertParagraphSeparator(cursor); int pos = cursor.position(); cursor.insertBlock(); cursor.insertText(textToInsert); cursor.setPosition(pos); // if we actually insert a separator, allow it to be overwritten if // user types it if (!textToInsert.isEmpty()) m_allowSkippingOfBlockEnd = true; return 1; }
void ScCodeEditor::insertSpaceToNextTabStop( QTextCursor &cursor ) { if ( mSpaceIndent ) { const int indentWidth = mDoc->indentWidth(); if (indentWidth < 1) return; const int spaces = indentWidth - (cursor.positionInBlock() % indentWidth); QString spaceString (spaces, QChar(' ')); cursor.insertText( spaceString ); } else { cursor.insertText("\t"); } }
QString PostWindow::symbolUnderCursor() { QTextCursor cursor = textCursor(); if (cursor.hasSelection()) return cursor.selectedText(); else { QString blockString = cursor.block().text(); int position = cursor.positionInBlock(); return wordInStringAt( position, blockString ); } }
bool TypingSettings::tabShouldIndent(const QTextDocument *document, QTextCursor cursor, int *suggestedPosition) const { if (m_tabKeyBehavior == TabNeverIndents) return false; QTextCursor tc = cursor; if (suggestedPosition) *suggestedPosition = tc.position(); // At least suggest original position tc.movePosition(QTextCursor::StartOfLine); if (tc.atBlockEnd()) // cursor was on a blank line return true; if (document->characterAt(tc.position()).isSpace()) { tc.movePosition(QTextCursor::WordRight); if (tc.positionInBlock() >= cursor.positionInBlock()) { if (suggestedPosition) *suggestedPosition = tc.position(); // Suggest position after whitespace if (m_tabKeyBehavior == TabLeadingWhitespaceIndents) return true; } } return (m_tabKeyBehavior == TabAlwaysIndents); }
int AutoCompleter::paragraphSeparatorAboutToBeInserted(QTextCursor &cursor) { QTextBlock block = cursor.block(); const QString text = block.text().trimmed(); if (text == "end" || text == "else" || text.startsWith("elsif") || text.startsWith("rescue") || text == "ensure") { Indenter indenter(const_cast<QTextDocument*>(block.document())); indenter.indentBlock(block, QChar(), tabSettings()); } return 0; // This implementation is buggy #if 0 const QString textFromCursor = text.mid(cursor.positionInBlock()).trimmed(); if (!textFromCursor.isEmpty()) return 0; if (Language::symbolDefinition.indexIn(text) == -1 && Language::startOfBlock.indexIn(text) == -1) { return 0; } int spaces = 0; for (const QChar c : text) { if (!c.isSpace()) break; spaces++; } QString indent = text.left(spaces); QString line; QTextBlock nextBlock = block.next(); while (nextBlock.isValid()) { line = nextBlock.text(); if (Language::endKeyword.indexIn(line) != -1 && line.startsWith(indent)) return 0; if (!line.trimmed().isEmpty()) break; nextBlock = nextBlock.next(); } int pos = cursor.position(); cursor.insertBlock(); cursor.insertText("end"); cursor.setPosition(pos); return 1; #endif }
QTextCursor ScCodeEditor::currentRegion() { QTextCursor cursor = textCursor(); QTextBlock block = cursor.block(); int positionInBlock = cursor.positionInBlock(); if (TokenIterator(block, positionInBlock - 1).type() == Token::ClosingBracket) cursor.movePosition( QTextCursor::PreviousCharacter ); else if (TokenIterator(block, positionInBlock).type() == Token::OpeningBracket) cursor.movePosition( QTextCursor::NextCharacter ); return regionAroundCursor( cursor ); }
QString LiteWordCompleter::textUnderCursor(QTextCursor tc) const { QString text = tc.block().text().left(tc.positionInBlock()); if (text.isEmpty()) { return QString(); } static QRegExp reg("[a-zA-Z_]+[a-zA-Z0-9_\\.@]*$"); int index = reg.indexIn(text); if (index < 0) { return QString(); } return text.right(reg.matchedLength()); }
QString LiteEditorWidget::importUnderCursor(QTextCursor tc) const { QString text = tc.block().text().left(tc.positionInBlock()); if (text.isEmpty()) { return QString(); } static QRegExp reg("[\"`][a-zA-Z0-9_\\-\\.\\/]*$"); int index = reg.indexIn(text); if (index < 0) { return QString(); } return text.right(reg.matchedLength()-1); }
bool DEditorWidget::handleStringSplitting(QKeyEvent *e) const { if (!TextEditorSettings::completionSettings().m_autoSplitStrings) return false; if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) { QTextCursor cursor = textCursor(); if (autoCompleter()->isInString(cursor)) { cursor.beginEditBlock(); if (cursor.positionInBlock() > 0 && cursor.block().text().at(cursor.positionInBlock() - 1) == QLatin1Char('\\')) { // Already escaped: simply go back to line, but do not indent. cursor.insertText(QLatin1String("\n")); } else if (e->modifiers() & Qt::ShiftModifier) { // With 'shift' modifier, escape the end of line character // and start at beginning of next line. cursor.insertText(QLatin1String("\\\n")); } else { // End the current string, and start a new one on the line, properly indented. cursor.insertText(QLatin1String("\"\n\"")); textDocument()->autoIndent(cursor); } cursor.endEditBlock(); e->accept(); return true; } } return false; }
void UnifiedDiffEditorWidget::jumpToOriginalFile(const QTextCursor &cursor) { if (m_fileInfo.isEmpty()) return; const int blockNumber = cursor.blockNumber(); const int fileIndex = fileIndexForBlockNumber(blockNumber); if (fileIndex < 0) return; const FileData fileData = m_contextFileData.at(fileIndex); const QString leftFileName = fileData.leftFileInfo.fileName; const QString rightFileName = fileData.rightFileInfo.fileName; const int columnNumber = cursor.positionInBlock() - 1; // -1 for the first character in line const int rightLineNumber = m_rightLineNumbers.value(blockNumber, -1); if (rightLineNumber >= 0) { jumpToOriginalFile(rightFileName, rightLineNumber, columnNumber); return; } const int leftLineNumber = m_leftLineNumbers.value(blockNumber, -1); if (leftLineNumber >= 0) { if (leftFileName == rightFileName) { for (int i = 0; i < fileData.chunks.count(); i++) { const ChunkData chunkData = fileData.chunks.at(i); int newLeftLineNumber = chunkData.leftStartingLineNumber; int newRightLineNumber = chunkData.rightStartingLineNumber; for (int j = 0; j < chunkData.rows.count(); j++) { const RowData rowData = chunkData.rows.at(j); if (rowData.leftLine.textLineType == TextLineData::TextLine) newLeftLineNumber++; if (rowData.rightLine.textLineType == TextLineData::TextLine) newRightLineNumber++; if (newLeftLineNumber == leftLineNumber) { jumpToOriginalFile(leftFileName, newRightLineNumber, 0); return; } } } } else { jumpToOriginalFile(leftFileName, leftLineNumber, columnNumber); } return; } }
void FakeVimProxy::requestSetBlockSelection(const QTextCursor &tc) { QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(m_widget); if (!ed) return; QPalette pal = ed->parentWidget() != NULL ? ed->parentWidget()->palette() : QApplication::palette(); m_blockSelection.clear(); m_clearSelection.clear(); QTextCursor cur = tc; QTextEdit::ExtraSelection selection; selection.format.setBackground( pal.color(QPalette::Base) ); selection.format.setForeground( pal.color(QPalette::Text) ); selection.cursor = cur; m_clearSelection.append(selection); selection.format.setBackground( pal.color(QPalette::Highlight) ); selection.format.setForeground( pal.color(QPalette::HighlightedText) ); int from = cur.positionInBlock(); int to = cur.anchor() - cur.document()->findBlock(cur.anchor()).position(); const int min = qMin(cur.position(), cur.anchor()); const int max = qMax(cur.position(), cur.anchor()); for ( QTextBlock block = cur.document()->findBlock(min); block.isValid() && block.position() < max; block = block.next() ) { cur.setPosition( block.position() + qMin(from, block.length()) ); cur.setPosition( block.position() + qMin(to, block.length()), QTextCursor::KeepAnchor ); selection.cursor = cur; m_blockSelection.append(selection); } disconnect( ed, &QPlainTextEdit::selectionChanged, this, &FakeVimProxy::updateBlockSelection ); ed->setTextCursor(tc); connect( ed, &QPlainTextEdit::selectionChanged, this, &FakeVimProxy::updateBlockSelection ); QPalette pal2 = ed->palette(); pal2.setColor(QPalette::Highlight, Qt::transparent); pal2.setColor(QPalette::HighlightedText, Qt::transparent); ed->setPalette(pal2); updateExtraSelections(); }
void LiteEditorWidget::insertFromMimeData(const QMimeData *source) { if (isReadOnly()) return; if (source->hasFormat(QLatin1String(kVerticalTextBlockMimeType))) { QString text = QString::fromUtf8(source->data(QLatin1String(kVerticalTextBlockMimeType))); if (text.isEmpty()) return; QStringList lines = text.split(QLatin1Char('\n')); QTextCursor cursor = textCursor(); cursor.beginEditBlock(); const TextEditor::TabSettings &ts = this->tabSettings(); int initialCursorPosition = cursor.position(); int column = ts.columnAt(cursor.block().text(), cursor.positionInBlock()); cursor.insertText(lines.first()); for (int i = 1; i < lines.count(); ++i) { QTextBlock next = cursor.block().next(); if (next.isValid()) { cursor.setPosition(next.position()); } else { cursor.movePosition(QTextCursor::EndOfBlock); cursor.insertBlock(); } int offset = 0; int position = ts.positionAtColumn(cursor.block().text(), column, &offset); cursor.setPosition(cursor.block().position() + position); if (offset < 0) { cursor.deleteChar(); cursor.insertText(QString(-offset, QLatin1Char(' '))); } else { cursor.insertText(QString(offset, QLatin1Char(' '))); } cursor.insertText(lines.at(i)); } cursor.setPosition(initialCursorPosition); cursor.endEditBlock(); setTextCursor(cursor); ensureCursorVisible(); return; } QPlainTextEdit::insertFromMimeData(source); }
QString LiteEditorWidget::textUnderCursor(QTextCursor tc) const { QString text = tc.block().text().left(tc.positionInBlock()); if (text.isEmpty()) { return QString(); } //int index = text.lastIndexOf(QRegExp("\\b[a-zA-Z_][a-zA-Z0-9_\.]+")); static QRegExp reg("[a-zA-Z_\\.]+[a-zA-Z0-9_\\.]*$"); int index = reg.indexIn(text); if (index < 0) { return QString(); } return text.right(reg.matchedLength()); //int index = text.lastIndexOf(QRegExp("[\w]+$")); // qDebug() << ">" << text << index; // int left = text.lastIndexOf(QRegExp("[ |\t|\"|\(|\)|\'|<|>]")); // text = text.right(text.length()-left+1); return ""; }
// Return the Cpp expression, and, if desired, the function QString cppExpressionAt(TextEditor::ITextEditor *editor, int pos, int *line, int *column, QString *function /* = 0 */) { using namespace CppTools; using namespace CPlusPlus; *line = *column = 0; if (function) function->clear(); const QPlainTextEdit *plaintext = qobject_cast<QPlainTextEdit*>(editor->widget()); if (!plaintext) return QByteArray(); QString expr = plaintext->textCursor().selectedText(); CppModelManagerInterface *modelManager = CppModelManagerInterface::instance(); if (expr.isEmpty() && modelManager) { QTextCursor tc(plaintext->document()); tc.setPosition(pos); const QChar ch = editor->characterAt(pos); if (ch.isLetterOrNumber() || ch == QLatin1Char('_')) tc.movePosition(QTextCursor::EndOfWord); // Fetch the expression's code. CPlusPlus::ExpressionUnderCursor expressionUnderCursor; expr = expressionUnderCursor(tc); *column = tc.positionInBlock(); *line = tc.blockNumber(); } else { const QTextCursor tc = plaintext->textCursor(); *column = tc.positionInBlock(); *line = tc.blockNumber(); } if (function && !expr.isEmpty()) if (const Core::IFile *file = editor->file()) if (modelManager) *function = AbstractEditorSupport::functionAt(modelManager, file->fileName(), *line, *column); return expr.toUtf8(); }
void GmacsPreprocessor::codeCompletion(const QTextCursor &cursor) { int line = cursor.blockNumber(); int column = cursor.columnNumber(); //const char *name = filename->toLocal8Bit().data(); const char *name = clang_getCString(clang_getTranslationUnitSpelling(unit)); //qDebug() << cursor.document()->toPlainText(); //qDebug() << cursor.document()->toPlainText().size(); QString document = cursor.document()->toPlainText(); QString text = cursor.block().text(); QRegExp exp("\t"); int tab_count = text.count(exp); fprintf(stderr, "column = [%d]\n", cursor.positionInBlock()); //unsaved_file->Filename = name; //unsaved_file->Contents = document.toLocal8Bit().data(); //unsaved_file->Length = document.size(); if (!unit) return; CLANG_REPARSE(unit, NULL);//unsaved_file); fprintf(stderr, "line = [%d], column = [%d]\n", line+1, column + tab_count); fprintf(stderr, "name = [%s]\n", name); CXCodeCompleteResults *res = CLANG_CODE_COMPLETION(unit, name, line+1, column + tab_count); if (!res) fprintf(stderr, "ERROR: could not complete\n"); for (size_t i = 0; i < clang_codeCompleteGetNumDiagnostics(res); i++) { const CXDiagnostic &diag = clang_codeCompleteGetDiagnostic(res, i); const CXString &s = clang_getDiagnosticSpelling(diag); fprintf(stderr, "%s\n", clang_getCString(s)); } unsigned num_results = res->NumResults; fprintf(stderr, "num_results = [%d]\n"); for (unsigned i = 0; i < num_results; i++) { const CXCompletionString& str = res->Results[i].CompletionString; unsigned chunks = clang_getNumCompletionChunks(str); for (unsigned j = 0; j < chunks; j++) { const CXString& out = clang_getCompletionChunkText(str, j); //std::cout << clang_getCString(out) << " "; if (clang_getCompletionChunkKind(str, j) != CXCompletionChunk_TypedText) continue; } //std::cout << std::endl; } clang_disposeCodeCompleteResults(res); }
void History::on_plainTextEdit_cursorPositionChanged() { if(!plainTextEdit->toPlainText().isEmpty()) { QList<QTextEdit::ExtraSelection> extraSelections; QTextEdit::ExtraSelection selection; QColor lineColor = QColor(0,0,170).lighter(160); selection.format.setBackground(lineColor); selection.format.setProperty(QTextFormat::FullWidthSelection, true); selection.cursor =plainTextEdit->textCursor(); selection.cursor.clearSelection(); extraSelections.append(selection); //暂时标记指定的文档中的一部分,用指定的颜色 plainTextEdit->setExtraSelections(extraSelections); usePushButton->setEnabled(true); deletePushButton->setEnabled(true); copyPushButton->setEnabled(true); clearPushButton->setEnabled(true); //获取光标所在行数 QTextCursor tc = plainTextEdit->textCursor(); QTextLayout* lo = tc.block().layout(); int pos = tc.positionInBlock(); int rowIndex = lo->lineForTextPosition(pos).lineNumber() + tc.block().firstLineNumber(); lineEdit->setText(plainTextEdit->document()->findBlockByLineNumber(rowIndex).text()); //plainTextEdit->document()->findBlockByLineNumber(rowIndex).text() 获取指定行的内容 } else { usePushButton->setEnabled(false); deletePushButton->setEnabled(false); copyPushButton->setEnabled(false); clearPushButton->setEnabled(false); lineEdit->clear(); } }