Ejemplo n.º 1
0
void AStylePart::beautifySource()
{
  KTextEditor::EditInterface *iface
      = dynamic_cast<KTextEditor::EditInterface*>(partController()->activePart());
  if (!iface)
    return;

    bool has_selection = false;

  KTextEditor::SelectionInterface *sel_iface
      = dynamic_cast<KTextEditor::SelectionInterface*>(partController()->activePart());
  if (sel_iface && sel_iface->hasSelection())
    has_selection = true;

  //if there is a selection, we only format it.
  ASStringIterator is(has_selection ? sel_iface->selection() : iface->text());
  KDevFormatter formatter(m_project);

  formatter.init(&is);

  QString output;
  QTextStream os(&output, IO_WriteOnly);

  // put the selection back to the same indent level.
  // taking note of the config options.
  unsigned int indentCount=0;
  QString indentWith("");
  if ( has_selection){
  	QString original = sel_iface->selection();
	for (;indentCount<original.length();indentCount++){
		QChar ch = original[indentCount];
		if ( ch.isSpace()){
			if ( ch == QChar('\n') || ch == QChar('\r')){
				indentWith="";
			}
			else{
				indentWith+=original[indentCount];
			}
	  	}
		else{
			break;
		}
	}

	int wsCount = m_project["FillCount"].toInt();
	if (m_project["Fill"].toString() == "Tabs")
	{
		// tabs and wsCount spaces to be a tab
		QString replace;
		for (int i =0;i<wsCount;i++)
			replace+=' ';

		indentWith=indentWith.replace(replace, QChar('\t'));
		indentWith=indentWith.remove(' ');
	} else
	{
		if ( m_project["FillForce"].toBool()){
			//convert tabs to spaces
			QString replace;
			for (int i =0;i<wsCount;i++)
				replace+=' ';

			indentWith=indentWith.replace(QChar('\t'),replace);
		}
	}
  }

  while (formatter.hasMoreLines()){
	  if ( has_selection ){
		  os << indentWith;
	  }
	  os << QString::fromUtf8(formatter.nextLine().c_str()) << endl;
  }

  uint col = 0;
  uint line = 0;

  if(has_selection) //there was a selection, so only change the part of the text related to it
  {
    //remove the final newline character, unless it should be there
    if ( !sel_iface->selection().endsWith( "\n" ) )
      output.setLength(output.length()-1);

    sel_iface->removeSelectedText();
    cursorPos( partController()->activePart(), &col, &line );
    iface->insertText( col, line, output);

    return;
  }

  cursorPos( partController()->activePart(), &col, &line );

  iface->setText( output );

  setCursorPos( partController()->activePart(), col, line );
}