示例#1
0
///The first definition that belongs to a context that surrounds the current cursor
Declaration* cursorContextDeclaration() {
  KTextEditor::View* view = ICore::self()->documentController()->activeTextDocumentView();
  if(!view)
    return nullptr;

  KDevelop::DUChainReadLocker lock( DUChain::lock() );

  TopDUContext* ctx = DUChainUtils::standardContextForUrl(view->document()->url());
  if(!ctx)
    return nullptr;

  KTextEditor::Cursor cursor(view->cursorPosition());

  DUContext* subCtx = ctx->findContext(ctx->transformToLocalRevision(cursor));

  while(subCtx && !subCtx->owner())
    subCtx = subCtx->parentContext();

  Declaration* definition = nullptr;

  if(!subCtx || !subCtx->owner())
    definition = DUChainUtils::declarationInLine(cursor, ctx);
  else
    definition = subCtx->owner();

  if(!definition)
    return nullptr;

  return definition;
}
KTextEditor::View* HtmlEditor::createView( QWidget* parent )
{
    KTextEditor::Document *document = mEditor->createDocument( parent );
    bool result = document->setHighlightingMode( "html" );
    if ( result ) {
        kDebug() << "Syntax highlighting enabled";
    }
    KTextEditor::View *view = document->createView( parent );
    QMenu *menu = view->defaultContextMenu();

    KTextEditor::ConfigInterface *interface = qobject_cast< KTextEditor::ConfigInterface* >( view );

    if ( interface ) {
        KAction *actWordWrap = new KAction( i18n( "Dynamic Word Wrap" ), view );
        actWordWrap->setCheckable( true );
        connect( actWordWrap, SIGNAL(triggered(bool)), this, SLOT(toggleWordWrap()) );

        KAction *actLineNumber = new KAction( i18n("Show line numbers"), view );
        actLineNumber->setCheckable( true );
        connect( actLineNumber, SIGNAL(triggered(bool)), this, SLOT(toggleLineNumber()) );

        QMenu *options = new QMenu( i18n( "Options" ), qobject_cast< QWidget* >( view ) );
        options->addAction( actWordWrap );
        options->addAction( actLineNumber );

        menu->addSeparator();
        menu->addMenu( options );
        
        interface->setConfigValue( "dynamic-word-wrap", true );
        actWordWrap->setChecked( true );
    }
    view->setContextMenu( menu );
    return view;
}
示例#3
0
	void Konsole::sync()
	{
		if(!KileConfig::syncConsoleDirWithTabs()) {
			return;
		}

		KTextEditor::Document *doc = m_ki->activeTextDocument();
		KTextEditor::View *view = Q_NULLPTR;

		if(doc) {
			view = doc->views().first();
		}

		if(view) {
			QString finame;
			QUrl url = view->document()->url();

			if(url.path().isEmpty()) {
				return;
			}

			QFileInfo fic(url.adjusted(QUrl::RemoveFilename|QUrl::StripTrailingSlash).path());
			if(fic.isReadable()) {
				setDirectory(url.adjusted(QUrl::RemoveFilename|QUrl::StripTrailingSlash).path());
			}
		}
	}
示例#4
0
bool KateViewManager::createView ( KTextEditor::Document *doc )
{
  if (m_blockViewCreationAndActivation) return false;

  // create doc
  if (!doc)
    doc = KateDocManager::self()->createDoc ();

  // create view, registers its XML gui itself
  KTextEditor::View *view = (KTextEditor::View *) doc->createView (activeViewSpace()->stack);

  m_viewList.append (view);
  m_activeStates[view] = false;

  // disable settings dialog action
  delete view->actionCollection()->action( "set_confdlg" );
  delete view->actionCollection()->action( "editor_options" );

  //view->setContextMenu(view->defaultContextMenu());

  connect(view, SIGNAL(dropEventPass(QDropEvent *)), mainWindow(), SLOT(slotDropEvent(QDropEvent *)));
  connect(view, SIGNAL(focusIn(KTextEditor::View *)), this, SLOT(activateSpace(KTextEditor::View *)));

  activeViewSpace()->addView( view );

  viewCreated(view);

  activateView( view );

  return true;
}
示例#5
0
Declaration* cursorDeclaration() {

  KTextEditor::View* view = ICore::self()->documentController()->activeTextDocumentView();
  if(!view)
    return nullptr;

  KDevelop::DUChainReadLocker lock( DUChain::lock() );

  return DUChainUtils::declarationForDefinition( DUChainUtils::itemUnderCursor( view->document()->url(), KTextEditor::Cursor(view->cursorPosition()) ).declaration );
}
TextEditor::TextEditor(KTextEditor::Document *editorPart, PackageModel *model, QWidget *parent)
        : QWidget(parent)
{
    QHBoxLayout *l = new QHBoxLayout(this);

    QWidget *centralWidget = editorPart->widget();
    KTextEditor::View *view = qobject_cast<KTextEditor::View*>(centralWidget);
    if (view) {
        view->setContextMenu(view->defaultContextMenu());

        //modify the toolbar
        modifyToolBar(view);

        KTextEditor::ConfigInterface *config = qobject_cast<KTextEditor::ConfigInterface*>(view);
        if (config) {
            config->setConfigValue("line-numbers", true);
            config->setConfigValue("dynamic-word-wrap", true);
        }

        config = dynamic_cast<KTextEditor::ConfigInterface*>(editorPart);
        if (config) {
            config->setConfigValue("backup-on-save-prefix", ".");
        }

        // set nice defaults for katepart
        KTextEditor::CommandInterface *command = dynamic_cast<KTextEditor::CommandInterface *>(editorPart->editor());
        QString ret;
        if (command) { //generic
            command->queryCommand("set-indent-mode")->exec(view, "set-indent-mode normal", ret); // more friendly
            command->queryCommand("set-replace-tabs")->exec(view, "set-replace-tabs 1", ret);// replaces tabs with spaces????
            command->queryCommand("set-indent-width")->exec(view, "set-indent-width 4", ret);//4 spaces, Plasma's general coding style
        }

        //we should be setting the specific editing indentation, highlighting based on the type of document
        if (model->implementationApi() == "declarativeappletscript" || model->implementationApi() == "javascript") {
            editorPart->setHighlightingMode("JavaScript");
        } else if (model->implementationApi() == "ruby-script") {
            editorPart->setHighlightingMode("ruby");
            if (command) {
                command->queryCommand("set-indent-width")->exec(view, "set-indent-width 2", ret);// 2 spaces recommended for ruby
            }
        }
        //there is no need for one more control. But we keep the code because it is easier to understand.
        //so keep the generic format.
        /*} else if (editorPart->setHighlightingMode() == "python") {
            continue;
            // Q: why we don't change the spaces?
            // A: 4 spaces are recommended for python
        }*/

    }

    l->addWidget(centralWidget);
}
示例#7
0
QUrl KateBuildView::docUrl()
{
    KTextEditor::View *kv = m_win->activeView();
    if (!kv) {
        qDebug() << "no KTextEditor::View" << endl;
        return QUrl();
    }

    if (kv->document()->isModified()) kv->document()->save();
    return kv->document()->url();
}
示例#8
0
文件: documentinfo.cpp 项目: KDE/kile
KTextEditor::View* TextInfo::createView(QWidget *parent, const char* /* name */)
{
	if(!m_doc) {
		return Q_NULLPTR;
	}
	KTextEditor::View *view = m_doc->createView(parent);
	installEventFilters(view);
	installSignalConnections(view);
	registerCodeCompletionModels(view);
	view->setStatusBarEnabled(false);
	connect(view, SIGNAL(destroyed(QObject*)), this, SLOT(slotViewDestroyed(QObject*)));
	return view;
}
示例#9
0
void KateBuildView::displayBuildResult(const QString &msg, KTextEditor::Message::MessageType level)
{
    KTextEditor::View *kv = m_win->activeView();
    if (!kv) return;

    delete m_infoMessage;
    m_infoMessage = new KTextEditor::Message(xi18nc("@info", "<title>Make Results:</title><nl/>%1", msg), level);
    m_infoMessage->setWordWrap(true);
    m_infoMessage->setPosition(KTextEditor::Message::BottomInView);
    m_infoMessage->setAutoHide(5000);
    m_infoMessage->setAutoHideMode(KTextEditor::Message::Immediate);
    m_infoMessage->setView(kv);
    kv->document()->postMessage(m_infoMessage);
}
示例#10
0
void KatePluginSymbolViewerView::slotDocChanged()
{
 slotRefreshSymbol();

 KTextEditor::View *view = m_mainWindow->activeView();
 //qDebug()<<"Document changed !!!!" << view;
 if (view) {
   connect(view, SIGNAL(cursorPositionChanged(KTextEditor::View*,KTextEditor::Cursor)),
           this, SLOT(cursorPositionChanged()), Qt::UniqueConnection);

   if (view->document()) {
     connect(view->document(), SIGNAL(textChanged(KTextEditor::Document*)),
             this, SLOT(slotDocEdited()), Qt::UniqueConnection);
   }
 }
void KDevelop::DocumentationController::doShowDocumentation()
{
    IDocument* doc = ICore::self()->documentController()->activeDocument();
    if(!doc)
      return;
    
    KTextEditor::Document* textDoc = doc->textDocument();
    if(!textDoc)
      return;
    
    KTextEditor::View* view = textDoc->activeView();
    if(!view)
      return;
    
    KDevelop::DUChainReadLocker lock( DUChain::lock() );
    
    Declaration *dec = DUChainUtils::declarationForDefinition( DUChainUtils::itemUnderCursor( doc->url(), SimpleCursor(view->cursorPosition()) ) );
    
    if(dec) {
        KSharedPtr< IDocumentation > documentation = documentationForDeclaration(dec);
        if(documentation) {
            showDocumentation(documentation);
        }
    }
}
示例#12
0
void MainWindow::slotEditKeys()
{
  KKeyDialog dlg;
  dlg.insert(actionCollection());

  if(m_tabEditor->count() != 0)
  {
    KTextEditor::View* view  = m_tabEditor->currentView();
    if(view)
    {
      dlg.insert(view->actionCollection());
    }
  }

  dlg.configure();
}
示例#13
0
bool KateViewSpace::showView(KTextEditor::Document *document)
{
    const int index = m_lruDocList.lastIndexOf(document);

    if (index < 0) {
        return false;
    }

    if (! m_docToView.contains(document)) {
        return false;
    }

    KTextEditor::View *kv = m_docToView[document];

    // move view to end of list
    m_lruDocList.removeAt(index);
    m_lruDocList.append(document);
    stack->setCurrentWidget(kv);
    kv->show();

    // in case a tab does not exist, add one
    if (! m_docToTabId.contains(document)) {
        // if space is available, add button
        if (m_tabBar->count() < m_tabBar->maxTabCount()) {
            // just insert
            insertTab(m_tabBar->count(), document);
        } else {
            // remove "oldest" button and replace with new one
            Q_ASSERT(m_lruDocList.size() > m_tabBar->count());

            // we need to subtract by 1 more, as we just added ourself to the end of the lru list!
            KTextEditor::Document * docToHide = m_lruDocList[m_lruDocList.size() - m_tabBar->maxTabCount() - 1];
            Q_ASSERT(m_docToTabId.contains(docToHide));
            const int insertIndex = removeTab(docToHide, false);

            // add new one at removed position
            insertTab(insertIndex, document);
        }
    }

    // follow current view
    Q_ASSERT(m_docToTabId.contains(document));
    m_tabBar->setCurrentTab(m_docToTabId.value(document, -1));

    return true;
}
示例#14
0
// /home/follinge/projects/kscope-kde4/src/editorpage4.h:61:7: error: candidate is: bool kscope4::EditorPage::getCursorPos(uint&, uint&)
bool EditorPage::getCursorPos(int& nLine, int& nCol)
{
    KTextEditor::View* pCursorIf;

    // Acquire the view cursor
    pCursorIf = dynamic_cast<KTextEditor::View*>(m_pView);
    if (pCursorIf == NULL)
        return false;

    // Get the cursor position (adjusted to 1-based counting)
    //pCursorIf->cursorPosition(&nLine, &nCol);
    pCursorIf->cursorPosition().position(nLine, nCol);
    nLine++;
    nCol++;

    return true;
}
示例#15
0
void PluginKateXMLCheckView::slotClicked(QTreeWidgetItem *item, int column)
{
	Q_UNUSED(column);
	qDebug() << "slotClicked";
	if( item ) {
		bool ok = true;
		uint line = item->text(1).toUInt(&ok);
		bool ok2 = true;
		uint column = item->text(2).toUInt(&ok);
		if( ok && ok2 ) {
			KTextEditor::View *kv = m_mainWindow->activeView();
			if( ! kv )
				return;

			kv->setCursorPosition(KTextEditor::Cursor (line-1, column));
		}
	}
}
示例#16
0
static void slipInFilter(KProcess & proc, KTextEditor::View & view, QString command)
{
  QString inputText;

  if (view.selection()) {
    inputText = view.selectionText();
  }

  proc.clearProgram ();
  proc.setShellCommand(command);

  proc.start();
  QByteArray encoded = inputText.toLocal8Bit();
  proc.write(encoded);
  proc.closeWriteChannel();
  //  TODO: Put up a modal dialog to defend the text from further
  //  keystrokes while the command is out. With a cancel button...
}
示例#17
0
void View::run()
{
  KTextEditor::View *view = mw->activeView();

  if (!view) {
    return;
  }
  if (m_global.saveBeforeRun) {
    view->document()->save();
  }

  KTextEditor::Document *doc = view->document();
  QString filename = doc->url().path();
  QString directory = doc->url().directory();

  kDebug() << filename << "-" << directory;
  QString cmd = txtCommand->text();
  cmd = cmd.replace("%filename", filename).replace("%directory", directory);
  execute(cmd);
}
示例#18
0
KTextEditor::View *KateViewSpace::createView(KTextEditor::Document *doc)
{
    // should only be called if a view does not yet exist
    Q_ASSERT(! m_docToView.contains(doc));

    /**
     * Create a fresh view
     */
    KTextEditor::View *v = doc->createView(stack, m_viewManager->mainWindow()->wrapper());

    // set status bar to right state
    v->setStatusBarEnabled(m_viewManager->mainWindow()->showStatusBar());

    // restore the config of this view if possible
    if (!m_group.isEmpty()) {
        QString fn = v->document()->url().toString();
        if (! fn.isEmpty()) {
            QString vgroup = QString::fromLatin1("%1 %2").arg(m_group).arg(fn);

            KateSession::Ptr as = KateApp::self()->sessionManager()->activeSession();
            if (as->config() && as->config()->hasGroup(vgroup)) {
                KConfigGroup cg(as->config(), vgroup);
                v->readSessionConfig(cg);
            }
        }
    }

    // register document, it is shown below through showView() then
    if (! m_lruDocList.contains(doc)) {
        registerDocument(doc);
        Q_ASSERT(m_lruDocList.contains(doc));
    }

    // insert View into stack
    stack->addWidget(v);
    m_docToView[doc] = v;
    showView(v);

    return v;
}
示例#19
0
void KateViewManager::slotDocumentOpen ()
{
  KTextEditor::View *cv = activeView();

  if (cv)
  {
    KEncodingFileDialog::Result r = KEncodingFileDialog::getOpenUrlsAndEncoding(
                                      KateDocManager::self()->editor()->defaultEncoding(),
                                      cv->document()->url().url(),
                                      QString(), m_mainWindow, i18n("Open File"));

    KateDocumentInfo docInfo;
    docInfo.openedByUser = true;

    KTextEditor::Document *lastID = 0;
    for (KUrl::List::Iterator i = r.URLs.begin(); i != r.URLs.end(); ++i)
      lastID = openUrl( *i, r.encoding, false, false, docInfo);

    if (lastID)
      activateView (lastID);
  }
}
示例#20
0
QWidget* QuickOpenPlugin::specialObjectNavigationWidget() const
{
  KTextEditor::View* view = ICore::self()->documentController()->activeTextDocumentView();
  if( !view )
    return nullptr;

  QUrl url = ICore::self()->documentController()->activeDocument()->url();

  const auto languages = ICore::self()->languageController()->languagesForUrl(url);
  foreach (const auto language, languages) {
    QWidget* w = language->specialLanguageObjectNavigationWidget(url, KTextEditor::Cursor(view->cursorPosition()) );
    if(w)
      return w;
  }
示例#21
0
void View::infoSelected(QTreeWidgetItem* item, int column)
{
  Q_UNUSED(column);

  QString path = item->data(0, Qt::ToolTipRole).toString();
  uint line = item->data(1, Qt::ToolTipRole).toUInt();
  uint col = item->data(2, Qt::ToolTipRole).toUInt();

  if(!path.isEmpty() && QFile::exists(path)) {
    KUrl url(path);
    KTextEditor::View* kv = mw->openUrl(url);
    if(line > 0) {
      kv->setCursorPosition(KTextEditor::Cursor(line - 1, col - 1));
    } else {
      // Line = 0 is used to show information about a file.
      // Just go to the beginning.
      kv->setCursorPosition(KTextEditor::Cursor(0, 0));
    }
    kv->setFocus();
    kDebug() << "Opened file: " << path;
  } else {
    setStatus(i18n("File not found: %1", path));
  }
}
示例#22
0
QString KateCTagsView::currentWord( )
{
    KTextEditor::View *kv = mainWindow()->activeView();
    if (!kv) {
        kDebug() << "no KTextEditor::View" << endl;
        return QString();
    }

    if (kv->selection()) {
        return kv->selectionText();
    }

    if (!kv->cursorPosition().isValid()) {
        kDebug() << "cursor not valid!" << endl;
        return QString();
    }

    int line = kv->cursorPosition().line();
    int col = kv->cursorPosition().column();
    bool includeColon = m_ctagsUi.cmdEdit->text().contains("--extra=+q");

    QString linestr = kv->document()->line(line);

    int startPos = qMax(qMin(col, linestr.length()-1), 0);
    int endPos = startPos;
    while (startPos >= 0 && (linestr[startPos].isLetterOrNumber() ||
        (linestr[startPos] == ':' && includeColon) ||
        linestr[startPos] == '_' ||
        linestr[startPos] == '~'))
    {
        startPos--;
    }
    while (endPos < (int)linestr.length() && (linestr[endPos].isLetterOrNumber() ||
        (linestr[endPos] == ':' && includeColon) ||
        linestr[endPos] == '_')) {
        endPos++;
    }
    if  (startPos == endPos) {
        kDebug() << "no word found!" << endl;
        return QString();
    }

    //kDebug() << linestr.mid(startPos+1, endPos-startPos-1);
    return linestr.mid(startPos+1, endPos-startPos-1);
}
示例#23
0
bool PluginKateXMLCheckView::slotValidate()
{
	qDebug() << "slotValidate()";

	m_mainWindow->showToolView (dock);
	m_validating = false;
	m_dtdname = "";

	KTextEditor::View *kv = m_mainWindow->activeView();
	if( ! kv )
	  return false;
	delete m_tmp_file;
	m_tmp_file = new QTemporaryFile();
	if( !m_tmp_file->open() ) {
		qDebug() << "Error (slotValidate()): could not create '" << m_tmp_file->fileName() << "': " << m_tmp_file->errorString();
		KMessageBox::error(0, i18n("<b>Error:</b> Could not create "
			"temporary file '%1'.", m_tmp_file->fileName()));
		delete m_tmp_file;
		m_tmp_file=0L;
		return false;
	}

	QTextStream s ( m_tmp_file );
	s << kv->document()->text();
	s.flush();

    QString exe = QStandardPaths::findExecutable("xmllint");
	if( exe.isEmpty() ) {
		exe = QStandardPaths::locate(QStandardPaths::ApplicationsLocation, "xmllint");
	}
    //qDebug() << "exe=" <<exe;
// 	// use catalogs for KDE docbook:
// 	if( ! getenv("XML_CATALOG_FILES") ) {
// 		KComponentData ins("katexmlcheckplugin");
// 		QString catalogs;
// 		catalogs += ins.dirs()->findResource("data", "ksgmltools2/customization/catalog.xml");
// 		qDebug() << "catalogs: " << catalogs;
// 		setenv("XML_CATALOG_FILES", QFile::encodeName( catalogs ).data(), 1);
// 	}
	//qDebug() << "**catalogs: " << getenv("XML_CATALOG_FILES");
        QStringList args;
        args << "--noout";

	// tell xmllint the working path of the document's file, if possible.
	// otherweise it will not find relative DTDs

        // I should give path to location of file, but remove filename
        // I can make QUrl.adjusted(rm filename).path()
        // or QUrl.toString(rm filename|rm schema)
        // Result is the same. Which variant should I choose?
        //QString path = kv->document()->url().adjusted(QUrl::RemoveFilename).path();
        // xmllint uses space- or colon-separated path option, so spaces should be encoded to %20. It is done with EncodeSpaces.

        // Now what about colons in file names or paths?
        // This way xmllint works normally:
        // xmllint --noout --path "/home/user/my/with:colon/" --valid "/home/user/my/with:colon/demo-1.xml"
        // but because this plugin makes temp file path to file is another and this way xmllint refuses to find dtd:
        // xmllint --noout --path "/home/user/my/with:colon/" --valid "/tmp/kate.X23725"
        // As workaround we can encode ':' with %3A
        QString path = kv->document()->url().toString(QUrl::RemoveFilename|QUrl::PreferLocalFile|QUrl::EncodeSpaces);
        path.replace(":","%3A");
        // because of such inconvinience with xmllint and pathes, maybe switch to xmlstarlet?

        qDebug() << "path=" << path;

	if (!path.isEmpty()) {
                args << "--path" << path;

	}

	// heuristic: assume that the doctype is in the first 10,000 bytes:
	QString text_start = kv->document()->text().left(10000);
	// remove comments before looking for doctype (as a doctype might be commented out
	// and needs to be ignored then):
	QRegExp re("<!--.*-->");
	re.setMinimal(true);
	text_start.remove(re);
	QRegExp re_doctype("<!DOCTYPE\\s+(.*)\\s+(?:PUBLIC\\s+[\"'].*[\"']\\s+[\"'](.*)[\"']|SYSTEM\\s+[\"'](.*)[\"'])", Qt::CaseInsensitive);
	re_doctype.setMinimal(true);

	if( re_doctype.indexIn(text_start) != -1 ) {
		QString dtdname;
		if( ! re_doctype.cap(2).isEmpty() ) {
			dtdname = re_doctype.cap(2);
		} else {
			dtdname = re_doctype.cap(3);
		}
		if( !dtdname.startsWith("http:") ) {		// todo: u_dtd.isLocalFile() doesn't work :-(
			// a local DTD is used
			m_validating = true;
                        args << "--valid";
		} else {
			m_validating = true;
                        args << "--valid";
		}
	} else if( text_start.indexOf("<!DOCTYPE") != -1 ) {
		// DTD is inside the XML file
		m_validating = true;
                args << "--valid";
	}
        args << m_tmp_file->fileName();
        qDebug() << "m_tmp_file->fileName()=" << m_tmp_file->fileName();

        m_proc.start(exe,args);
        qDebug() << "m_proc.program():" << m_proc.program(); // I want to see parmeters
        qDebug() << "args=" << args;
        qDebug() << "exit code:"<< m_proc.exitCode();
        if( ! m_proc.waitForStarted(-1) ) {
		KMessageBox::error(0, i18n("<b>Error:</b> Failed to execute xmllint. Please make "
			"sure that xmllint is installed. It is part of libxml2."));
		return false;
	}
	QApplication::setOverrideCursor(Qt::WaitCursor);
	return true;
}
示例#24
0
void DataOutputWidget::slotExport()
{
  if (m_model->rowCount() <= 0)
    return;

  while (m_model->canFetchMore())
    m_model->fetchMore();

  if (!m_view->selectionModel()->hasSelection())
    m_view->selectAll();

  ExportWizard wizard(this);

  if (wizard.exec() != QDialog::Accepted)
    return;

  bool outputInDocument = wizard.field("outDocument").toBool();
  bool outputInClipboard = wizard.field("outClipboard").toBool();
  bool outputInFile = wizard.field("outFile").toBool();

  bool exportColumnNames = wizard.field("exportColumnNames").toBool();
  bool exportLineNumbers = wizard.field("exportLineNumbers").toBool();

  Options opt = NoOptions;

  if (exportColumnNames)
    opt |= ExportColumnNames;
  if (exportLineNumbers)
    opt |= ExportLineNumbers;

  bool quoteStrings = wizard.field("checkQuoteStrings").toBool();
  bool quoteNumbers = wizard.field("checkQuoteNumbers").toBool();

  QChar stringsQuoteChar = (quoteStrings) ? wizard.field("quoteStringsChar").toString().at(0) : '\0';
  QChar numbersQuoteChar = (quoteNumbers) ? wizard.field("quoteNumbersChar").toString().at(0) : '\0';

  QString fieldDelimiter = wizard.field("fieldDelimiter").toString();

  if (outputInDocument)
  {
    Kate::MainWindow *mw = Kate::application()->activeMainWindow();
    KTextEditor::View *kv = mw->activeView();

    if (!kv)
      return;

    QString text;
    QTextStream stream(&text);

    exportData(stream, stringsQuoteChar, numbersQuoteChar, fieldDelimiter, opt);

    kv->insertText(text);
    kv->setFocus();
  }
  else if (outputInClipboard)
  {
    QString text;
    QTextStream stream(&text);

    exportData(stream, stringsQuoteChar, numbersQuoteChar, fieldDelimiter, opt);

    kapp->clipboard()->setText(text);
  }
  else if (outputInFile)
  {
    QString url = wizard.field("outFileUrl").toString();
    QFile data(url);
    if (data.open(QFile::WriteOnly | QFile::Truncate))
    {
      QTextStream stream(&data);

      exportData(stream, stringsQuoteChar, numbersQuoteChar, fieldDelimiter, opt);

      stream.flush();
    }
    else
    {
      KMessageBox::error(this, i18nc("@info", "Unable to open file <filename>%1</filename>").arg(url));
    }
  }
}
示例#25
0
bool SwapFile::recover(QDataStream& stream, bool checkDigest)
{
  if (!isValidSwapFile(stream, checkDigest)) {
    return false;
  }

  // disconnect current signals
  setTrackingEnabled(false);

  // needed to set undo/redo cursors in a sane way
  bool firstEditInGroup = false;
  KTextEditor::Cursor undoCursor = KTextEditor::Cursor::invalid();
  KTextEditor::Cursor redoCursor = KTextEditor::Cursor::invalid();

  // replay swapfile
  bool editRunning = false;
  bool brokenSwapFile = false;
  while (!stream.atEnd()) {
    if (brokenSwapFile)
      break;

    qint8 type;
    stream >> type;
    switch (type) {
      case EA_StartEditing: {
        m_document->editStart();
        editRunning = true;
        firstEditInGroup = true;
        undoCursor = KTextEditor::Cursor::invalid();
        redoCursor = KTextEditor::Cursor::invalid();
        break;
      }
      case EA_FinishEditing: {
        m_document->editEnd();
        
        // empty editStart() / editEnd() groups exist: only set cursor if required
        if (!firstEditInGroup) {
          // set undo/redo cursor of last KateUndoGroup of the undo manager
          m_document->undoManager()->setUndoRedoCursorsOfLastGroup(undoCursor, redoCursor);
          m_document->undoManager()->undoSafePoint();
        }
        firstEditInGroup = false;
        editRunning = false;
        break;
      }
      case EA_WrapLine: {
        if (!editRunning) {
          brokenSwapFile = true;
          break;
        }

        int line = 0, column = 0;
        stream >> line >> column;
        
        // emulate buffer unwrapLine with document
        m_document->editWrapLine(line, column, true);

        // track undo/redo cursor
        if (firstEditInGroup) {
          firstEditInGroup = false;
          undoCursor = KTextEditor::Cursor(line, column);
        }
        redoCursor = KTextEditor::Cursor(line + 1, 0);

        break;
      }
      case EA_UnwrapLine: {
        if (!editRunning) {
          brokenSwapFile = true;
          break;
        }

        int line = 0;
        stream >> line;
        
        // assert valid line
        Q_ASSERT (line > 0);

        const int undoColumn = m_document->lineLength(line - 1);

        // emulate buffer unwrapLine with document
        m_document->editUnWrapLine(line - 1, true, 0);

        // track undo/redo cursor
        if (firstEditInGroup) {
          firstEditInGroup = false;
          undoCursor = KTextEditor::Cursor(line, 0);
        }
        redoCursor = KTextEditor::Cursor(line - 1, undoColumn);

        break;
      }
      case EA_InsertText: {
        if (!editRunning) {
          brokenSwapFile = true;
          break;
        }

        int line, column;
        QByteArray text;
        stream >> line >> column >> text;
        m_document->insertText(KTextEditor::Cursor(line, column), QString::fromUtf8 (text.data (), text.size()));

        // track undo/redo cursor
        if (firstEditInGroup) {
          firstEditInGroup = false;
          undoCursor = KTextEditor::Cursor(line, column);
        }
        redoCursor = KTextEditor::Cursor(line, column + text.size());

        break;
      }
      case EA_RemoveText: {
        if (!editRunning) {
          brokenSwapFile = true;
          break;
        }

        int line, startColumn, endColumn;
        stream >> line >> startColumn >> endColumn;
        m_document->removeText (KTextEditor::Range(KTextEditor::Cursor(line, startColumn), KTextEditor::Cursor(line, endColumn)));

        // track undo/redo cursor
        if (firstEditInGroup) {
          firstEditInGroup = false;
          undoCursor = KTextEditor::Cursor(line, endColumn);
        }
        redoCursor = KTextEditor::Cursor(line, startColumn);

        break;
      }
      default: {
        kWarning( 13020 ) << "Unknown type:" << type;
      }
    }
  }

  // balanced editStart and editEnd?
  if (editRunning) {
    brokenSwapFile = true;
    m_document->editEnd();
  }

  // warn the user if the swap file is not complete
  if (brokenSwapFile) {
    kWarning ( 13020 ) << "Some data might be lost";
  } else {
    // set sane final cursor, if possible
    KTextEditor::View * view = m_document->activeView();
    redoCursor = m_document->undoManager()->lastRedoCursor();
    if (view && redoCursor.isValid()) {
      view->setCursorPosition(redoCursor);
    }
  }

  // reconnect the signals
  setTrackingEnabled(true);

  return true;
}
InteractiveConsole::InteractiveConsole(QWidget *parent)
    : QDialog(parent),
      m_splitter(new QSplitter(Qt::Vertical, this)),
      m_editorPart(0),
      m_editor(0),
      m_output(0),
      m_loadAction(KStandardAction::open(this, SLOT(openScriptFile()), this)),
      m_saveAction(KStandardAction::saveAs(this, SLOT(saveScript()), this)),
      m_clearAction(KStandardAction::clear(this, SLOT(clearEditor()), this)),
      m_executeAction(new QAction(QIcon::fromTheme(QStringLiteral("system-run")), i18n("&Execute"), this)),
      m_plasmaAction(new QAction(QIcon::fromTheme(QStringLiteral("plasma")), i18nc("Toolbar Button to switch to Plasma Scripting Mode", "Plasma"), this)),
      m_kwinAction(new QAction(QIcon::fromTheme(QStringLiteral("kwin")), i18nc("Toolbar Button to switch to KWin Scripting Mode", "KWin"), this)),
      m_snippetsMenu(new QMenu(i18n("Templates"), this)),
      m_fileDialog(0),
      m_closeWhenCompleted(false),
      m_mode(PlasmaConsole)
{
    addAction(KStandardAction::close(this, SLOT(close()), this));
    addAction(m_saveAction);
    addAction(m_clearAction);

    setWindowTitle(i18n("Desktop Shell Scripting Console"));
    setAttribute(Qt::WA_DeleteOnClose);
    //setButtons(QDialog::None);

    QWidget *widget = new QWidget(m_splitter);
    QVBoxLayout *editorLayout = new QVBoxLayout(widget);

    QLabel *label = new QLabel(i18n("Editor"), widget);
    QFont f = label->font();
    f.setBold(true);
    label->setFont(f);
    editorLayout->addWidget(label);

    connect(m_snippetsMenu, &QMenu::aboutToShow, this, &InteractiveConsole::populateTemplatesMenu);

    QToolButton *loadTemplateButton = new QToolButton(this);
    loadTemplateButton->setPopupMode(QToolButton::InstantPopup);
    loadTemplateButton->setMenu(m_snippetsMenu);
    loadTemplateButton->setText(i18n("Load"));
    connect(loadTemplateButton, &QToolButton::triggered, this, &InteractiveConsole::loadTemplate);

    QToolButton *useTemplateButton = new QToolButton(this);
    useTemplateButton->setPopupMode(QToolButton::InstantPopup);
    useTemplateButton->setMenu(m_snippetsMenu);
    useTemplateButton->setText(i18n("Use"));
    connect(useTemplateButton, &QToolButton::triggered, this, &InteractiveConsole::useTemplate);

    QActionGroup *modeGroup = new QActionGroup(this);
    modeGroup->addAction(m_plasmaAction);
    modeGroup->addAction(m_kwinAction);
    m_plasmaAction->setCheckable(true);
    m_kwinAction->setCheckable(true);
    m_plasmaAction->setChecked(true);
    connect(modeGroup, &QActionGroup::triggered, this, &InteractiveConsole::modeSelectionChanged);

    KToolBar *toolBar = new KToolBar(this, true, false);
    toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    toolBar->addAction(m_loadAction);
    toolBar->addAction(m_saveAction);
    toolBar->addAction(m_clearAction);
    toolBar->addAction(m_executeAction);
    toolBar->addAction(m_plasmaAction);
    toolBar->addAction(m_kwinAction);
    toolBar->addWidget(loadTemplateButton);
    toolBar->addWidget(useTemplateButton);

    editorLayout->addWidget(toolBar);

    KService::List offers = KServiceTypeTrader::self()->query(QStringLiteral("KTextEditor/Document"));
    foreach (const KService::Ptr service, offers) {
        m_editorPart = service->createInstance<KTextEditor::Document>(widget);
        if (m_editorPart) {
            m_editorPart->setHighlightingMode(QStringLiteral("JavaScript/PlasmaDesktop"));

            KTextEditor::View * view = m_editorPart->createView(widget);
            view->setContextMenu(view->defaultContextMenu());

            KTextEditor::ConfigInterface *config = qobject_cast<KTextEditor::ConfigInterface*>(view);
            if (config) {
                config->setConfigValue(QStringLiteral("line-numbers"), true);
                config->setConfigValue(QStringLiteral("dynamic-word-wrap"), true);
            }

            editorLayout->addWidget(view);
            connect(m_editorPart, &KTextEditor::Document::textChanged,
                    this, &InteractiveConsole::scriptTextChanged);
            break;
        }
    }
void EditorTabWidget::createDocument(KURL url/*, const QString& text*/)
{
  /*
    KTextEditor::PopupMenuInterface* popupIf = dynamic_cast<KTextEditor::PopupMenuInterface*>(w->view());
    if (popupIf)
       popupIf->installPopup((QPopupMenu *)quantaApp->factory()->container("popup_editor", quantaApp));
  */

  KTextEditor::View *view;
  if((view = openKDocument(url)) == NULL) return;


  KTextEditor::MarkInterfaceExtension* imarkex =
    dynamic_cast<KTextEditor::MarkInterfaceExtension*>(view->document());

  if(imarkex) {
    KIconLoader *loader = KGlobal::iconLoader();

    #if (KDE_VERSION_MAJOR >= 3) &&  (KDE_VERSION_MINOR >= 3)
    imarkex->setPixmap(KTextEditor::MarkInterface::Execution, loader->loadIcon(
                         "executionpoint", KIcon::Small));
    #else
    imarkex->setPixmap(KTextEditor::MarkInterface::markType05, loader->loadIcon(
                         "executionpoint", KIcon::Small));
    #endif

    imarkex->setPixmap(KTextEditor::MarkInterface::markType08, loader->loadIcon(
                         "preexecutionpoint", KIcon::Small));

    #if (KDE_VERSION_MAJOR >= 3) &&  (KDE_VERSION_MINOR >= 3)
    imarkex->setPixmap(KTextEditor::MarkInterface::BreakpointActive, loader->loadIcon(
                         "activebreakpoint",KIcon::Small));
    #else
    imarkex->setPixmap(KTextEditor::MarkInterface::markType02, loader->loadIcon(
                         "activebreakpoint", KIcon::Small));
    #endif

    #if (KDE_VERSION_MAJOR >= 3) &&  (KDE_VERSION_MINOR >= 3)
    imarkex->setPixmap(KTextEditor::MarkInterface::BreakpointDisabled, loader->loadIcon(
                         "disabledbreakpoint",KIcon::Small));
    #else
    imarkex->setPixmap(KTextEditor::MarkInterface::markType04, loader->loadIcon(
                         "disabledbreakpoint", KIcon::Small));
    #endif

    #if (KDE_VERSION_MAJOR >= 3) &&  (KDE_VERSION_MINOR >= 3)
    imarkex->setDescription(KTextEditor::MarkInterface::BreakpointActive, "Breakpoint");
    #else
    imarkex->setDescription(KTextEditor::MarkInterface::markType02, "Breakpoint");
    #endif

    #if (KDE_VERSION_MAJOR >= 3) &&  (KDE_VERSION_MINOR >= 3)
    imarkex->setMarksUserChangable(KTextEditor::MarkInterface::Bookmark + KTextEditor::MarkInterface::BreakpointActive);
    #else
    imarkex->setMarksUserChangable(KTextEditor::MarkInterface::markType01 + KTextEditor::MarkInterface::markType02);
    #endif

  }

  connect(view->document(), SIGNAL(marksChanged()), this, SLOT(slotMarkChanged()));

  connect(view->document(), SIGNAL(undoChanged()), this, SLOT(slotUndoChanged()));

  Document_t d;
  d.path = url.path();
  d.view = view;
  d.hasUndo = false;
  d.hasRedo = false;

  //d.marks = imark->marks();
  m_docList.append(d);
  disableUndoAction();
  disableRedoAction();
}
示例#28
0
void KDataToolPluginView::aboutToShow()
{
	kdDebug()<<"KTextEditor::KDataToolPluginView::aboutToShow"<<endl;
	QString word;
	m_singleWord = false;
	m_wordUnderCursor = QString::null;

	// unplug old actions, if any:
	KAction *ac;
	for ( ac = m_actionList.first(); ac; ac = m_actionList.next() ) {
		m_menu->remove(ac);
	}
	if (m_notAvailable) {
		m_menu->remove(m_notAvailable);
		delete m_notAvailable;
		m_notAvailable=0;
	}
	if ( selectionInterface(m_view->document())->hasSelection() )
	{
		word = selectionInterface(m_view->document())->selection();
		if ( word.find(' ') == -1 && word.find('\t') == -1 && word.find('\n') == -1 )
			m_singleWord = true;
		else
			m_singleWord = false;
	} else {
		// No selection -> use word under cursor
		KTextEditor::EditInterface *ei;
		KTextEditor::ViewCursorInterface *ci;
		KTextEditor::View *v = (KTextEditor::View*)m_view; 
		ei = KTextEditor::editInterface(v->document());
		ci = KTextEditor::viewCursorInterface(v);
		uint line, col;
		ci->cursorPositionReal(&line, &col);
		QString tmp_line = ei->textLine(line);
		m_wordUnderCursor = "";
		// find begin of word:
		m_singleWord_start = 0;
		for(int i = col; i >= 0; i--) {
			QChar ch = tmp_line.at(i);
			if( ! (ch.isLetter() || ch == '-' || ch == '\'') )
			{
				m_singleWord_start = i+1;
				break;
			}
			m_wordUnderCursor = ch + m_wordUnderCursor;
		}
		// find end of word:
		m_singleWord_end = tmp_line.length();
		for(uint i = col+1; i < tmp_line.length(); i++) {
			QChar ch = tmp_line.at(i);
			if( ! (ch.isLetter() || ch == '-' || ch == '\'') )
			{
				m_singleWord_end = i;
				break;
			}
			m_wordUnderCursor += ch;
		}
		if( ! m_wordUnderCursor.isEmpty() )
		{
			m_singleWord = true;
			m_singleWord_line = line;
		} else {
			m_notAvailable = new KAction(i18n("(not available)"), QString::null, 0, this, 
					SLOT(slotNotAvailable()), actionCollection(),"dt_n_av");
			m_menu->insert(m_notAvailable);
			return;
		}
	}

	KInstance *inst=instance();

	QValueList<KDataToolInfo> tools;
	tools += KDataToolInfo::query( "QString", "text/plain", inst );
	if( m_singleWord )
		tools += KDataToolInfo::query( "QString", "application/x-singleword", inst );

	m_actionList = KDataToolAction::dataToolActionList( tools, this,
		SLOT( slotToolActivated( const KDataToolInfo &, const QString & ) ) );

	for ( ac = m_actionList.first(); ac; ac = m_actionList.next() ) {
		m_menu->insert(ac);
	}

	if( m_actionList.isEmpty() ) {
		m_notAvailable = new KAction(i18n("(not available)"), QString::null, 0, this,
			SLOT(slotNotAvailable()), actionCollection(),"dt_n_av");
		m_menu->insert(m_notAvailable);
	}
}
示例#29
0
void
FileManager::showInEditor(const KURL& url)
{
    for (std::list<ManagedFileInfo*>::iterator mfi = files.begin();
         mfi != files.end(); ++mfi)
        if ((*mfi)->getFileURL() == url)
        {
            if (!(*mfi)->getEditor())
            {
                // The file has not yet been loaded, so we create an editor for
                // it.
                KTextEditor::Document* document;
                if (!(document = KTextEditor::EditorChooser::createDocument
                      (viewStack, "KTextEditor::Document", "Editor")))
                {
                    KMessageBox::error
                        (viewStack,
                         i18n("A KDE text-editor component could not "
                              "be found; please check your KDE "
                              "installation."));
                    return;
                }
                if (!editorConfigured)
                {
                    if (!KTextEditor::configInterface(document))
                    {
                        KMessageBox::error
                            (viewStack,
                             i18n("You have selected a KDE Editor component "
                                  "that is not powerful enough for "
                                  "TaskJuggler. "
                                  "Please select the 'Embedded Advanced Text "
                                  "Editor' component in the KDE Control "
                                  "Panel."));
                        return;
                    }
                    KTextEditor::configInterface(document)->readConfig(config);
                    editorConfigured = true;
                }

                KTextEditor::View* editor =
                    document->createView(viewStack);
                viewStack->addWidget(editor);
                (*mfi)->setEditor(editor);
                editor->setMinimumSize(400, 200);
                editor->setSizePolicy(QSizePolicy(QSizePolicy::Maximum,
                                                  QSizePolicy::Maximum, 0, 85,
                                                  editor->sizePolicy()
                                                  .hasHeightForWidth()));
                document->openURL(url);
                document->setReadWrite(true);
                document->setModified(false);

                // Signal to update the file-modified status
                connect(document, SIGNAL(textChanged()),
                        *mfi, SLOT(setModified()));

                connect(document,
                        SIGNAL(modifiedOnDisc(Kate::Document*, bool,
                                              unsigned char)),
                        *mfi,
                        SLOT(setModifiedOnDisc(Kate::Document*, bool,
                                               unsigned char)));

                /* Remove some actions of the editor that we don't want to
                 * show in the menu/toolbars */
                KActionCollection* ac = editor->actionCollection();
                if (ac->action("file_print"))
                    ac->remove(ac->action("file_print"));
                if (ac->action("view_folding_markers"))
                    ac->action("view_folding_markers")->
                        setShortcut(KShortcut());
                if (ac->action("view_border"))
                    ac->action("view_border")->setShortcut(KShortcut());
                if (ac->action("view_line_numbers"))
                    ac->action("view_line_numbers")->setShortcut(KShortcut());
                if (ac->action("view_dynamic_word_wrap"))
                    ac->action("view_dynamic_word_wrap")->
                        setShortcut(KShortcut());

/*                KActionPtrList actionList =
                    editor->actionCollection()->actions();
                for (KActionPtrList::iterator it = actionList.begin();
                     it != actionList.end(); ++it)
                {
                    printf("** Action found: %s\n", (*it)->name());
                }*/
            }
            viewStack->raiseWidget((*mfi)->getEditor());

            browser->clearSelection();
            QListViewItem* lvi = (*mfi)->getBrowserEntry();
            if (lvi)
            {
                browser->setCurrentItem(lvi);
                lvi->setSelected(true);
            }

            break;
        }