void MdiChild::removeSpacesAsTab(QTextCursor &cursor) { QRegExp regex(" +"); int spaces = cursor.columnNumber() % 4; if( spaces == 0 ) spaces = 4; if( cursor.columnNumber() < 4 ) spaces = cursor.columnNumber(); cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, spaces); if( regex.exactMatch(cursor.selectedText()) ) { cursor.removeSelectedText(); setTextCursor(cursor); } }
void MdiChild::insertSpacesAsTab(QTextCursor &cursor) { int spaces = 4 - cursor.columnNumber() % 4; for(;spaces>0;spaces--) cursor.insertText(" "); setTextCursor(cursor); }
void TextEditViewImpl::cursorPositionChanged() { QTextCursor cur = textEdit.textCursor(); std::stringstream s; s << cur.blockNumber()+1 << " : " << cur.columnNumber()+1 << " "; lineLabel.setText(QString(s.str().c_str())); }
/* 光标改变时设置光标的们位置 */ void TextEditer::doCursorChanged() { int row, col, tmp; QTextCursor cursor; QString str = ""; cursor = textEdit->textCursor(); /* 获取文本中的输入光标 */ col = cursor.columnNumber(); /* 获取列号 */ row = textEdit->document()->blockCount(); if (col == 0) { str = '0' + str; } while (col) { tmp = col % 10; col /= 10; str = (tmp + '0') + str; } str = ',' + str; if (row == 0) { str = '0' + str; } while (row) { tmp = row % 10; row /= 10; str = (tmp + '0') + str; } statusLabelOne->setText(str); }
void MainWindow::do_cursorChanged() { int rowNum = ui->textEdit->document()->blockCount(); const QTextCursor cursor =ui->textEdit->textCursor(); int colNum = cursor.columnNumber(); first_statusLabel->setText(tr("%1 行 %2 列").arg(rowNum).arg(colNum)); }
void KCDocumentRecorder::appendRecord(KCCodeEditor *editor, bool untitled) { UnclosedFileStatus currentStatus; QTextCursor cursor; currentStatus.untitled=untitled; if(untitled) { //This will treat as a untitled file. QString cacheFilePath=QString(unclosedUntitledFileDir + QString::number(cacheCount++)); //Save the file as a cache file editor->writeCacheFile(cacheFilePath); cursor=editor->getTextCursor(); currentStatus.filePath=cacheFilePath; } else { cursor=editor->getTextCursor(); currentStatus.filePath=editor->getFilePath(); } currentStatus.horizontalCursorPosition=cursor.blockNumber(); currentStatus.verticalCursorPosition=cursor.columnNumber(); currentStatus.horizontalScrollPosition=editor->getHScrollValue(); currentStatus.verticalScrollPosition=editor->getVScrollValue(); unclosedFileInfos.prepend(currentStatus); }
void TextView::updatePositionStatus() { QTextCursor cursor = textEdit()->textCursor(); int line = cursor.blockNumber() + 1; int column = cursor.columnNumber() + 1; Q_EMIT status(tr("Line %1, Column %2").arg(line).arg(column)); }
void window::update_cursor_position() { QTextCursor cursor = ui.text_edit->textCursor(); cursor_position->setText(tr("Line: %1 Column: %2") .arg(ui.text_edit->toPlainText().left(cursor.position()).count("\n") + 1) .arg(cursor.columnNumber() + 1)); }
bool ExpressionQueryWidget::eventFilter(QObject *obj, QEvent *event) { if (obj == m_textEdit) { switch (event->type()) { case QEvent::KeyPress: { QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); int key = keyEvent->key(); if (key == Qt::Key_Return || key == Qt::Key_Enter) { executeExpression(); return true; } else if (key == Qt::Key_Backspace) { // ensure m_expr doesn't contain backspace characters QTextCursor cursor = m_textEdit->textCursor(); bool atLastLine = !(cursor.block().next().isValid()); if (!atLastLine) return true; if (cursor.columnNumber() <= m_prompt.count()) return true; cursor.deletePreviousChar(); m_expr = cursor.block().text().mid(m_prompt.count()); return true; } else { m_textEdit->moveCursor(QTextCursor::End); m_expr += keyEvent->text(); } break; } case QEvent::FocusIn: checkCurrentContext(); m_textEdit->moveCursor(QTextCursor::End); break; default: break; } } else if (obj == m_lineEdit) { switch (event->type()) { case QEvent::KeyPress: { QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); int key = keyEvent->key(); if (key == Qt::Key_Up && m_lineEdit->text() != m_lastExpr) { m_expr = m_lineEdit->text(); if (!m_lastExpr.isEmpty()) m_lineEdit->setText(m_lastExpr); } else if (key == Qt::Key_Down) { m_lineEdit->setText(m_expr); } break; } case QEvent::FocusIn: checkCurrentContext(); break; default: break; } } return QWidget::eventFilter(obj, event); }
void QueryPanel::executeQuery() { QTextCursor c = editor->textCursor(); QString stmt = getActiveStatement(c.blockNumber(), c.columnNumber()); error->hide(); status->hide(); model->setQuery(stmt); model->select(); }
/* * 函数名称:捕获鼠标改变 * 函数功能:当光标的位置改变时,更新状态栏页、列信息 */ void QJDTextBrowser::doCursorChanged() { int pageNum=ui->textEdit->document()->pageCount();//页计数 const QTextCursor cursor=ui->textEdit->textCursor();//获取当前的可见光标 int colNum=cursor.columnNumber();//列计数 int rowNum=ui->textEdit->document()->blockCount();// 行计数 ui->label_1->setText(tr("Page:%1 Line:%2 Col:%3").arg(pageNum).arg(rowNum).arg(colNum)); }
void CMainWindow::doCursorChanged() { int pageNum = textEdit->document()->pageCount(); const QTextCursor cursor = textEdit->textCursor(); int colNum = cursor.columnNumber(); int rowNum = textEdit->document()->blockCount(); label1->setText(tr("%1 页 %3 列").arg(pageNum).arg(colNum)); }
/*! * \brief TextDoc::slotCursorPosChanged update status bar with line:column */ void TextDoc::slotCursorPosChanged() { QTextCursor pos = textCursor(); int x = pos.blockNumber(); int y = pos.columnNumber(); emit signalCursorPosChanged(x+1, y+1); tmpPosX = x; tmpPosY = y; }
/*! * \brief TextDoc::slotCursorPosChanged update status bar with line:column */ void TextDoc::slotCursorPosChanged() { QTextCursor pos = textCursor(); int x = pos.blockNumber(); int y = pos.columnNumber(); App->printCursorPosition(x+1, y+1); tmpPosX = x; tmpPosY = y; }
QString MatchingText::insertParagraphSeparator(const QTextCursor &tc) const { BackwardsScanner tk(tc, QString(), 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.columnNumber()).trimmed(); if (! textBlock.isEmpty()) return QString(); --index; // consume the `{' const SimpleToken &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 SimpleToken ¤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; } }
void XTextEdit::sIgnoreWord() { QTextCursor cursor = cursorForPosition(_lastPos); QString textBlock = cursor.block().text(); int pos = cursor.columnNumber(); int end = textBlock.indexOf(QRegExp("\\W+"),pos); int begin = textBlock.left(pos).lastIndexOf(QRegExp("\\W+"),pos); textBlock = textBlock.mid(begin+1,end-begin-1); _guiClientInterface->hunspell_ignore(textBlock); _highlighter->rehighlight(); }
void MdiChild::cursorPositionChanged() { QTextCursor cursor = this->textCursor(); // Current line text //QString cur_line_text = cursor.block().text().trimmed(); std::ostringstream oss; oss <<"Line:"<< cursor.blockNumber()+1 <<" Colum:"<<cursor.columnNumber(); statusBar->showMessage( QString::fromStdString(oss.str())); }
bool TabSettings::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.columnNumber() >= cursor.columnNumber()) { if (suggestedPosition) *suggestedPosition = tc.position(); // Suggest position after whitespace if (m_tabKeyBehavior == TabLeadingWhitespaceIndents) return true; } } return (m_tabKeyBehavior == TabAlwaysIndents); }
QString HaiQTextEdit::tab_text(QTextCursor cursor) { if (num_tab_spaces==0) return "\t"; else { QString ret=""; // ensure that we only add the missing chars up to the next tab stop int num = num_tab_spaces - (cursor.columnNumber() % num_tab_spaces); for (int j=0; j < num; j++) ret+=" "; return ret; } }
QPoint Editor::keyPopPoint(QTextCursor cursor) { int ht = fontMetrics().height(); int wd = fontMetrics().width(QLatin1Char('9')); int col = cursor.columnNumber(); int row = cursor.blockNumber()+2; // show just below line QTextBlock block = firstVisibleBlock(); int top = block.firstLineNumber(); QPoint pt = QPoint(lineNumberAreaWidth()+col*wd,(row-top)*ht); return pt; }
void FunctionDeclDefLinkFinder::startFindLinkAt( QTextCursor cursor, const Document::Ptr &doc, const Snapshot &snapshot) { // check if cursor is on function decl/def DeclarationAST *parent = 0; FunctionDeclaratorAST *funcDecl = 0; DeclaratorAST *declarator = 0; if (!findDeclOrDef(doc, cursor.blockNumber() + 1, cursor.columnNumber() + 1, &parent, &declarator, &funcDecl)) return; // find the start/end offsets CppRefactoringChanges refactoringChanges(snapshot); CppRefactoringFilePtr sourceFile = refactoringChanges.file(doc->fileName()); sourceFile->setCppDocument(doc); int start, end; declDefLinkStartEnd(sourceFile, parent, funcDecl, &start, &end); // if already scanning, don't scan again if (!m_scannedSelection.isNull() && m_scannedSelection.selectionStart() == start && m_scannedSelection.selectionEnd() == end) { return; } // build the selection for the currently scanned area m_scannedSelection = cursor; m_scannedSelection.setPosition(end); m_scannedSelection.setPosition(start, QTextCursor::KeepAnchor); m_scannedSelection.setKeepPositionOnInsert(true); // build selection for the name DeclaratorIdAST *declId = getDeclaratorId(declarator); m_nameSelection = cursor; m_nameSelection.setPosition(sourceFile->endOf(declId)); m_nameSelection.setPosition(sourceFile->startOf(declId), QTextCursor::KeepAnchor); m_nameSelection.setKeepPositionOnInsert(true); // set up a base result QSharedPointer<FunctionDeclDefLink> result(new FunctionDeclDefLink); result->nameInitial = m_nameSelection.selectedText(); result->sourceDocument = doc; result->sourceFunction = funcDecl->symbol; result->sourceDeclaration = parent; result->sourceFunctionDeclarator = funcDecl; // handle the rest in a thread m_watcher.reset(new QFutureWatcher<QSharedPointer<FunctionDeclDefLink> >()); connect(m_watcher.data(), SIGNAL(finished()), this, SLOT(onFutureDone())); m_watcher->setFuture(QtConcurrent::run(&findLinkHelper, result, refactoringChanges)); }
void TextEditWidget::onTextCursorMoved() { // write the line we're in QTextCursor cursor = m_editor->textCursor(); int lineNumber = cursor.blockNumber() + 1; char tmpStr[256]; sprintf( tmpStr, "Row: %d, Col: %d", lineNumber, cursor.columnNumber() ); m_statusBar->setText( tmpStr ); // highlight the line we're currently editing highlightCurrentLine(); }
int Editor::autoIndent() { QTextCursor cur = this->textCursor(); if(cur.selectedText().length() > 0) { return 0; } int col = cur.columnNumber(); cur.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor); cur.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor,col); QString text = cur.selectedText(); cur.clearSelection(); int stop = -1; int indent = -1; int slcm = text.indexOf("'"); if(slcm > -1) { stop = slcm; } cur.beginEditBlock(); cur.insertBlock(); for(int n = 0; n <= stop || isspace(text[n].toLatin1()); n++) { if(n == slcm) { if(text.indexOf("''") > -1) cur.insertText("''"); else cur.insertText("'"); } else { cur.insertText(" "); } } if(indent > 0) { for(int n = 0; n < indent; n++) { cur.insertText(" "); } } this->setTextCursor(cur); cur.endEditBlock(); return 1; }
// --------------------------------------------------- void TextDoc::slotCursorPosChanged() { QTextCursor pos = textCursor(); int x = pos.blockNumber(); int y = pos.columnNumber(); // TODO This seems to be difficult; maybe http://pepper.troll.no/s60prereleases/doc/widgets-codeeditor.html //if(tmpPosX > x) //TODO clearParagraphBackground(tmpPosX); //else //for(int z=tmpPosX; z<x; z++) //TODO clearParagraphBackground(z); //if(tmpPosX != x) //TODO setParagraphBackgroundColor(x, QColor(240, 240, 255)); App->printCursorPosition(x+1, y+1); tmpPosX = x; tmpPosY = y; }
void XTextEdit::contextMenuEvent(QContextMenuEvent *event) { QMenu *menu = createStandardContextMenu(); bool enableSpellPref = false; if(_x_preferences) enableSpellPref = (_x_preferences->value("SpellCheck")=="t"); if(_guiClientInterface && _guiClientInterface->hunspell_ready() && enableSpellPref && _spellStatus && this->isEnabled() && !this->isReadOnly()) { _lastPos=event->pos(); QTextCursor cursor = cursorForPosition(_lastPos); QString textBlock = cursor.block().text(); int pos = cursor.columnNumber(); int end = textBlock.indexOf(QRegExp("\\W+"),pos); int begin = textBlock.left(pos).lastIndexOf(QRegExp("\\W+"),pos); textBlock = textBlock.mid(begin+1,end-begin-1).trimmed(); QStringList wordList = _guiClientInterface->hunspell_suggest(textBlock); if (_guiClientInterface->hunspell_check(textBlock) < 1) { menu->addSeparator(); QAction *act; act = menu->addAction(tr("Add Word"), this, SLOT(sAddWord())); act = menu->addAction(tr("Ignore Word"), this, SLOT(sIgnoreWord())); if(!wordList.isEmpty()) { menu->addSeparator(); for (int menuActionCount = 0;menuActionCount < qMin(int(_MaxWords),wordList.size()); ++menuActionCount) { act = menu->addAction(wordList.at(menuActionCount).trimmed(), this, SLOT(sCorrectWord())); } } menu->addSeparator(); } } menu->exec(event->globalPos()); delete menu; }
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); }
/** * @brief Inserts tabulation(s) at the cursor position. */ void TextEditorWidget::insert_tab () { QTextCursor cursor = textCursor(); // Get tabulation character(s). QString tab = "\t"; if (replace_tab_by_spaces) { int length = tab_length; if (!cursor.hasSelection()) { length -= (cursor.columnNumber() % tab_length); } tab = QString(" ").repeated(length); } cursor.beginEditBlock(); // Insert tab for all selected lines. if (cursor.hasSelection()) { // Get the end block number dans set position to start. int start_pos = cursor.selectionStart(); cursor.setPosition(cursor.selectionEnd()); int block_number = cursor.blockNumber(); cursor.setPosition(start_pos); // Loop on each blocks. while (cursor.blockNumber() <= block_number) { cursor.movePosition(QTextCursor::StartOfLine); cursor.insertText(tab); cursor.movePosition(QTextCursor::NextBlock); } } // Insert tab before the cursor. else { cursor.insertText(tab); } cursor.endEditBlock(); }
void FindEditor::findHelper(FindOption *opt) { bool bFocus = m_findEdit->hasFocus(); LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); QTextCursor find; if (textEditor) { QPlainTextEdit *ed = LiteApi::getPlainTextEdit(editor); if (ed) { find = findEditor(ed->document(),ed->textCursor(),opt); if (!find.isNull()) { ed->setTextCursor(find); } } } else { QTextBrowser *ed = LiteApi::findExtensionObject<QTextBrowser*>(editor,"LiteApi.QTextBrowser"); if (ed) { find = findEditor(ed->document(),ed->textCursor(),opt); if (!find.isNull()) { ed->setTextCursor(find); } } } if (find.isNull()) { m_status->setText(tr("Not find")); } else { m_status->setText(QString("Ln:%1 Col:%2"). arg(find.blockNumber()+1). arg(find.columnNumber()+1)); } if (bFocus) { m_findEdit->setFocus(); } else if (textEditor) { textEditor->onActive(); } }
void PythonConsoleViewImpl::tabComplete() { python::gil_scoped_acquire lock; orgStdout = sys.attr("stdout"); orgStderr = sys.attr("stderr"); orgStdin = sys.attr("stdin"); sys.attr("stdout") = consoleOut; sys.attr("stderr") = consoleOut; sys.attr("stdin") = consoleIn; QTextCursor cursor = textCursor(); string beforeCursorString = getInputString().toStdString(); beforeCursorString = beforeCursorString.substr(0,cursor.columnNumber()-inputColumnOffset); QString afterCursorString = getInputString(); afterCursorString.remove(0, cursor.columnNumber()-inputColumnOffset); size_t maxSplitIdx = 0; for(std::vector<string>::iterator it = splitStringVec.begin(); it != splitStringVec.end(); ++it){ size_t splitIdx = beforeCursorString.find_last_of(*it); maxSplitIdx = std::max(splitIdx == string::npos ? 0 : splitIdx + 1, maxSplitIdx); } string lastWord = beforeCursorString.substr(maxSplitIdx); beforeCursorString = beforeCursorString.substr(0,maxSplitIdx); std::vector<string> dottedStrings; boost::split(dottedStrings, lastWord, boost::is_any_of(".")); string lastDottedString = dottedStrings.back();// word after last dot std::vector<string> moduleNames = dottedStrings;// words before last dot moduleNames.pop_back(); python::object targetMemberObject = getMemberObject(moduleNames, mainModule); //member object before last dot std::vector<string> memberNames = getMemberNames(targetMemberObject); // builtin function and syntax completions if(dottedStrings.size() == 1){ python::object builtinsObject = mainModule.attr("__builtins__"); std::vector<string> builtinMethods = getMemberNames(builtinsObject); memberNames.insert(memberNames.end(), builtinMethods.begin(), builtinMethods.end()); memberNames.insert(memberNames.end(), keywords.begin(), keywords.end()); } std::vector<string> completions; unsigned long int maxLength = std::numeric_limits<long>::max(); for(size_t i=0; i < memberNames.size(); ++i){ if(memberNames[i].substr(0,lastDottedString.size()) == lastDottedString){ completions.push_back(memberNames[i]); maxLength = std::min((unsigned long int)memberNames[i].size(),maxLength); } } if(PyErr_Occurred()){ PyErr_Print(); } sys.attr("stdout") = orgStdout; sys.attr("stderr") = orgStderr; sys.attr("stdin") = orgStdin; if(completions.size() != 0){ // max common string among completions std::string maxCommonStr = lastDottedString; for(size_t i=maxCommonStr.size(); i < maxLength; ++i){ bool commomFlg = true; for(size_t j=1; j < completions.size(); ++j){ if(completions[0].at(i) != completions[j].at(i)){ commomFlg = false; break; } } if( commomFlg ){ maxCommonStr.push_back(completions[0].at(i)); } else { break; } } string beforeLastDotStr = ""; for(std::vector<string>::iterator it = dottedStrings.begin(); it != dottedStrings.end()-1; ++it){ beforeLastDotStr.append(*it); beforeLastDotStr.append("."); } if(lastDottedString == maxCommonStr){ put("\n"); // This must be done after getInputString(). string str = ""; for(size_t i=0; i < completions.size(); ++i){ str.append(beforeLastDotStr); str.append(completions[i]); str.append(" "); } putln(QString(str.c_str())); putPrompt(); } string str = ""; str.append(beforeCursorString); str.append(beforeLastDotStr); str.append(maxCommonStr); str.append(afterCursorString.toStdString()); setInputString(QString(str.c_str())); for(size_t i=0; i < afterCursorString.toStdString().size(); ++i){ moveCursor(QTextCursor::Left); } } }
/* ======================== positionChanged ======================== */ void CMdiEditWindow::positionChanged( void ) { QTextCursor cursor = m_editors[tabToShader(m_tabs->currentIndex())]->textCursor(); int ln = cursor.blockNumber() + 1; int col = cursor.columnNumber() + 1; m_lineNumber->setText( "Ln: " + QString::number(ln) + " | Col: " + QString::number(col) ); }