Example #1
0
void NewWakuSettingsWindow::dropEvent(QDropEvent *event)
{
  const QRegExp broadIDrg("^.+lv(\\d+).*$");
  if (broadIDrg.indexIn(event->mimeData()->text()) != -1) {
    mwin->getNewWakuAPI(0, broadIDrg.cap(1));
    event->acceptProposedAction();
  } else {
    event->dropAction();
  }

}
Example #2
0
int  Icc_parser::bbNum(std::string &in)
{
	QRegExp regexp;
	QString str(in.c_str());

	regexp.setPattern( icc_patt_bb);
	if ( regexp.indexIn( str) != -1)
		return regexp.cap( 2).toInt();
	else
		return -1;
}
Example #3
0
// Determine type of line and return enumeration, cut out
// expression for '@if/@elsif'.
PreprocessorSection PreprocessContext::preprocessorLine(const QString &in,
                                                        QString *ifExpression) const
{
    if (m_ifPattern.exactMatch(in)) {
        *ifExpression = m_ifPattern.cap(2).trimmed();
        return IfSection;
    }
    if (m_elsifPattern.exactMatch(in)) {
        *ifExpression = m_elsifPattern.cap(2).trimmed();
        return ElsifSection;
    }

    ifExpression->clear();

    if (m_elsePattern.exactMatch(in))
        return ElseSection;
    if (m_endifPattern.exactMatch(in))
        return EndifSection;
    return OtherSection;
}
Example #4
0
void PageSelector::GotoPage()
{
	static QRegExp rx("^([0-9])+.*");
	int p = rx.cap(1).toInt();
	if (p < 1)
		p=1;
	if (p > LastPG)
		p = LastPG;
	GotoPg(p-1);
	emit GotoPage(p);
}
Example #5
0
string  Icc_parser::isFnName(std::string &in)
{
	QRegExp regexp;
	QString str(in.c_str());

	regexp.setPattern( icc_patt_fnname);
	if ( regexp.indexIn( str, 0) != -1)
		return regexp.cap( 1).toAscii().constData();
	else
		return "";
}
QString VariableParser::parseResource()
{
  //z:6:\"stream\":3;
  QRegExp rx;
  rx.setPattern("z:\\d*:[^:]*:(\\d*);");

  if(rx.search(m_raw, m_index) == -1) return "";
  m_index += rx.matchedLength();

  return rx.cap(1);
}
QString VariableParser::parseClassType()
{
  //O:6:"Classe":3:{s:6:...
  QRegExp rx;
  rx.setPattern("O:\\d*:\"([^\"]*)\":");

  if(rx.search(m_raw, m_index) == -1) return "";
  m_index += rx.matchedLength();

  return rx.cap(1);
}
static int parseVersion(const QString &text)
{
    // The version in Artistic Style is printed like "Artistic Style Version 2.04"
    const QRegExp rx("([2-9]{1})\\.([0-9]{2})(\\.[1-9]{1})?$");
    if (rx.indexIn(text) != -1) {
        const int major = rx.cap(1).toInt() * 100;
        const int minor = rx.cap(2).toInt();
        return major + minor;
    }
    return 0;
}
 QList<QUrl> GetURLsFromText(const QString &searchText)
 {
     QList<QUrl> retList;
     QRegExp searchRX = QRegExp("\\b(?:http|https)://(?:[a-z0-9]\\.)?(?:[\\-\\.a-z0-9]+)*[a-z0-9]{2,}(?::[0-9]{1,5})?(?:/\\S*(?:\\.\\S+))*/*", Qt::CaseInsensitive);
     int pos = 0;
     while ((pos = searchRX.indexIn(searchText, pos)) != -1) {
             retList.append(QUrl(searchRX.cap(0)));
             pos += searchRX.matchedLength();
     }
     return retList;
 }
QValidator::State KoUnitDoubleSpinBox::validate(QString &input, int &pos) const
{
#ifdef DEBUG_VALIDATOR
    kDebug(30004) <<"KoUnitDoubleSpinBox::validate :" << input <<" at" << pos;
#else
    Q_UNUSED(pos);
#endif

    QRegExp regexp ("([ a-zA-Z]+)$"); // Letters or spaces at end
    const int res = input.indexOf( regexp );

    if ( res == -1 )
    {
        // Nothing like an unit? The user is probably editing the unit
#ifdef DEBUG_VALIDATOR
        kDebug(30004) <<"Intermediate (no unit)";
#endif
        return QValidator::Intermediate;
    }

    // ### TODO: are all the QString::trimmed really necessary?
    const QString number ( input.left( res ).trimmed() );
    const QString unitName ( regexp.cap( 1 ).trimmed().toLower() );

#ifdef DEBUG_VALIDATOR
    kDebug(30004) <<"Split:" << number <<":" << unitName <<":";
#endif

    const double value = valueFromText( number );
    double newVal = 0.0;
    if (!isnan(value)) {
        bool ok;
        const KoUnit unit = KoUnit::fromSymbol(unitName, &ok);
        if ( ok )
            newVal = unit.fromUserValue( value );
        else
        {
            // Probably the user is trying to edit the unit
#ifdef DEBUG_VALIDATOR
            kDebug(30004) <<"Intermediate (unknown unit)";
#endif
            return QValidator::Intermediate;
        }
    }
    else
    {
        kWarning(30004) << "Not a number: " << number;
        return QValidator::Invalid;
    }
    newVal = KoUnit::ptToUnit( newVal, d->unit );
    //input = textFromValue( newVal ); // don't overwrite for now; the effect is not exactly what I expect...

    return QValidator::Acceptable;
}
Example #11
0
 /*!
     判断指定字符串中是否含有文件名
     预期输入为: ID_LENGTH=239.00
     输出为:239
              true
   \param 【IN】QString &line_data mplaer 输出的一行信息
   \param 【OUT】int &total_tme 做为输出时间,以秒为单位.
  */
 bool IBMediaControlCData::isTotalTime(const QString & line_data,int &total_tme)
 {
     int index = -1;
     index = m_rx_total_length.indexIn(line_data);
     if(index>-1)
     {
         total_tme = (int)m_rx_total_length.cap(1).toDouble();
         return true;
     }
     return false;
 }
QString VariableParser::parseInt()
{
  QRegExp rx;
  //rx.setPattern("i:(\\d*);"); //crash if the number is negative, ie. "i:-1". \\d doesn't reconize negatives
  rx.setPattern("i:([^;]*);");

  if(rx.search(m_raw, m_index) == -1) return "";
  m_index += rx.matchedLength();

  return rx.cap(1);
}
Example #13
0
void SpellHighlighter::highlightBlock(const QString &AText)
{
	if (FEnabled)
	{
		// Match words (minimally) excluding digits within a word
		static const QRegExp expression("\\b[^\\s\\d]+\\b");

		int index = 0;
		while ((index = expression.indexIn(AText, index)) != -1)
		{
			int length = expression.matchedLength();
			if (!isUserNickName(expression.cap()))
			{
				if (!SpellBackend::instance()->isCorrect(expression.cap()))
					setFormat(index, length, FCharFormat);
			}
			index += length;
		}
	}
}
Example #14
0
/**
 * The passed QRegExp is copied. Use the other findInFile function to access
 * the RegExp.
 *
 * Throws FileOpenError
 *
 * @param filename
 * @param regexp
 * @return
 */
QString findInFile (const QString &filename, const QRegExp &regexp, int group)
{
	// Make a copy because apparenly we cannot capture in a const QRegExp (but
	// we want to pass a const& so we can use an anonymous value in calls).
	QRegExp re (regexp);

	if (findInFile (filename, re))
		return re.cap (group);
	else
		return QString ();
}
Example #15
0
bool MetricAggregator::importRide(QDir path, RideFile *ride, QString fileName, unsigned long fingerprint, bool modify)
{
    SummaryMetrics *summaryMetric = new SummaryMetrics();
    QFile file(path.absolutePath() + "/" + fileName);

    QRegExp rx = RideFileFactory::instance().rideFileRegExp();
    if (!rx.exactMatch(fileName)) {
        return false; // not a ridefile!
    }
    summaryMetric->setFileName(fileName);
    assert(rx.numCaptures() == 7);
    QDate date(rx.cap(1).toInt(), rx.cap(2).toInt(),rx.cap(3).toInt());
    QTime time(rx.cap(4).toInt(), rx.cap(5).toInt(),rx.cap(6).toInt());
    QDateTime dateTime(date, time);

    summaryMetric->setRideDate(dateTime);
    summaryMetric->setId(ride->id());

    const RideMetricFactory &factory = RideMetricFactory::instance();
    QStringList metrics;

    for (int i = 0; i < factory.metricCount(); ++i)
        metrics << factory.metricName(i);

    // compute all the metrics
    QHash<QString, RideMetricPtr> computed = RideMetric::computeMetrics(main, ride, zones, hrzones, metrics);

    // get metrics into summaryMetric QMap
    for(int i = 0; i < factory.metricCount(); ++i) {
        // check for override
        summaryMetric->setForSymbol(factory.metricName(i), computed.value(factory.metricName(i))->value(true));
    }

    // what color will this ride be?
    QColor color = colorEngine->colorFor(ride->getTag("Calendar Text", ""));

    dbaccess->importRide(summaryMetric, ride, color, fingerprint, modify);
    delete summaryMetric;

    return true;
}
Example #16
0
QString languageName (int id, QString language)
{
  static const QString middle ("|ave|bam|ben|bih|bos|ces|che|chu|chv|div|epo|est|ewe|fao|fij|fry|glv|grn|hat|hmo|ido|iku|ile|ina|ind|ipk|jav|kal|kan|kas|khm|lao|lav|lin|lit|lug|mah|mal|mri|mar|mlg|mlt|mon|mri|nav|nob|orm|pli|pol|pus|run|sag|slk|sme|snd|sot|tat|tgl|tsn|tuk|tur|uig|zha|");
  static const QString right ("|aar|abk|afr|aka|amh|ara|asm|ava|aym|aze|bak|bel|bis|bod|bre|cat|cha|cos|cre|cym|dan|deu|dzo|ell|eng|eus|fas|fin|fra|fre|glg|guj|hau|heb|hin|hrv|hun|hye|iii|isl|ita|kat|kik|kor|kur|lat|lim|lub|mkd|mol|msa|mya|nau|nde|nep|nld|nno|nor|nya|oci|oji|ori|oss|pan|que|ron|rus|san|srp|sin|slv|smo|sna|som|sqi|srp|ssw|sun|swa|tam|tel|tgk|tha|tir|ton|tso|twi|ukr|urd|uzb|ven|vie|vol|wol|xho|yid|yor|zho|zul|");
  static const QString other ("|alb|sq|arg|an|arm|hy|baq|eu|bul|bg|bur|my|cze|cs|chi|zh|cor|kw|wel|cy|ger|de|dut|nl|gre|el|per|fa|ful|ff|geo|ka|gla|gd|gle|ga|her|hz|scr|hr|ibo|ig|ice|is|jpn|ja|kau|kr|kaz|kk|kin|rw|kir|ky|kom|kv|kon|kg|kua|kj|ltz|lb|mac|mk|mao|mi|may|ms|nbl|nr|ndo|ng|por|pt|roh|rm|rum|ro|scc|sr|slo|sk|spa|es|srd|sc|swe|sv|tah|ty|tib|bo|wln|wa");
  static QRegExp re_lang_code ("^([^\\[]+)\\[([^\\]]+)\\]");
  if ( language.length() < 2 )
    return i18n("Track %1", id);
  QString name;
  if ( re_lang_code.indexIn (language) >= 0 )
  {
    name = re_lang_code.cap(2).simplified();
    if ( ! name.isEmpty() )
      language = name;
    name = re_lang_code.cap(1).simplified();
  }
  if ( language.length() == 3 )
  {
    QString code ('|' + language + '|');
    if ( middle.indexOf (code, 0, Qt::CaseInsensitive) >= 0 )
      language.remove (1, 1);
    else if ( right.indexOf (code, 0, Qt::CaseInsensitive) >= 0 )
      language.remove (2, 1);
    else
    {
      int index = other.indexOf (code, 0, Qt::CaseInsensitive);
      if ( index >= 0 )
        language = other.mid (index + 5, 2);
    }
  }
  QString locname (KGlobal::locale() -> languageCodeToName (language));
  if ( locname.isEmpty() )
  {
    if ( language == "no" )
      language = I18N_NOOP("Norwegian");
    else if ( ! name.isEmpty() )
      language = name;
    return i18n(language.toUtf8());
  }
  return locname;
}
Example #17
0
ProbeABI ProbeABI::fromString(const QString &id)
{
    QStringList idParts = id.split('-');
    if (idParts.size() < 2)
        return ProbeABI();

    int index = 0;
    ProbeABI abi;

    // version
    static QRegExp versionRegExp("^qt(\\d+)\\_(\\d+)$");
    if (versionRegExp.indexIn(idParts.value(index++)) != 0)
        return ProbeABI();
    abi.setQtVersion(versionRegExp.cap(1).toInt(), versionRegExp.cap(2).toInt());

    // compiler
#ifdef Q_OS_WIN
    abi.setCompiler(idParts.value(index++));
    if (abi.isVersionRelevant())
        abi.setCompilerVersion(idParts.value(index++));
#endif

    if (idParts.size() != index + 1)
        return ProbeABI();

    // architecture / debug/release
    const QString postfix = QStringLiteral(GAMMARAY_DEBUG_POSTFIX);
    QString arch = idParts.value(index);

    if (!postfix.isEmpty()) {
        if (arch.endsWith(postfix, Qt::CaseInsensitive)) {
            arch.chop(postfix.length());

            if (abi.isDebugRelevant())
                abi.setIsDebug(true);
        }
    }

    abi.setArchitecture(arch);
    return abi;
}
Example #18
0
    void RunnerGUI::doubleClickedOnDetails(int para, int /*pos*/)
    {
        static QRegExp reFileAndLine("^(.*)\\[([0-9]+)\\]:");

        QString line = m_testerWidget->details()->text(para);
        m_testerWidget->details()->setSelection(para, 0, para, line.length()-1);

        if ( reFileAndLine.search(line) != -1 )
        {
            DCOPClient client;
            client.attach();
            QByteArray data;
            QDataStream arg(&data, QIODevice::WriteOnly);
            bool ok;
            arg << QString(reFileAndLine.cap(1)) << (reFileAndLine.cap(2).toInt(&ok) - 1);
            client.send("kdevelop-*", "KDevPartController", "editDocument(QString,int)", data);
            client.send("kdevelop-*", "MainWindow", "raise()", "");

            client.detach();
        }
    }
Example #19
0
int SearchOpenFiles::searchSingleLineRegExp(KTextEditor::Document *doc, const QRegExp &regExp, int startLine)
{
    int column;
    QTime time;

    time.start();
    for (int line = startLine; line < doc->lines(); line++) {
        if (time.elapsed() > 100) {
            kDebug() << "Search time exceeded" << time.elapsed() << line;
            return line;
        }
        column = regExp.indexIn(doc->line(line));
        while (column != -1) {
            if (regExp.cap().isEmpty()) break;
            emit matchFound(doc->url().pathOrUrl(), doc->documentName(), line, column,
                            doc->line(line), regExp.matchedLength());
            column = regExp.indexIn(doc->line(line), column + regExp.cap().size());
        }
    }
    return 0;
}
AstChanParts::AstChanParts(QString channel, QObject *parent)
  :QObject(parent)
{
  _isValid = false;
  _prefix=QString();
  _type=QString();
  _exten=QString();
  _extra=QString();
  _special=QString();
  QRegExp re ("^([^/]+/)?([^/]+)/([^-]+)([-])?([^<]+)?<?([^>]+)?>?$");
  if(re.exactMatch(channel) && re.captureCount() == 6)
  {
    this->setPrefix(re.cap(1));
    this->setType(re.cap(2));
    this->setExten(re.cap(3));
    this->setExtra(re.cap(5));
    this->setSpecial(re.cap(6));
    if(!_type.isNull() && !_type.isEmpty() && !_exten.isNull() && !_exten.isEmpty())
      _isValid = true;
  }
}
Example #21
0
void CVSLogPage::slotJobExited( bool normalExit, int exitStatus )
{
//    m_part->core()->running( m_part, false );
    if (!normalExit)
    {
        KMessageBox::sorry( this, i18n("Log failed with exitStatus == %1").arg( exitStatus), i18n("Log Failed") );
        return;
    }

    static QRegExp rx_sep( "\\-+" );
    static QRegExp rx_sep2( "=+" );
    static QRegExp rx_date( "date: .* author: .* state: .* lines: .*" );
    // "revision" followed by one or more decimals followed by a optional dot
    static QRegExp rx_rev( "revision ((\\d+\\.?)+)" );
    m_textBrowser->setTextFormat( QTextBrowser::PlainText );

    for (size_t i=0; i<m_diffStrings.count(); ++i) {
        QString s = m_diffStrings[i];
        kdDebug(9006) << "Examining line: " << s << endl;
        if ( rx_rev.exactMatch(s) )
        {
            QString ver = rx_rev.cap( 1 );
            QString dstr = "<b>" + s + "</b> ";
            int lastVer = ver.section( '.', -1 ).toInt() - 1;
            if ( lastVer > 0 ) {
                QString lv = ver.left( ver.findRev( "." ) + 1 ) + QString::number( lastVer );
                dstr += " [<a href=\"diff:/" + m_pathName + "/" + lv + "_" + ver + "\">diff to " + lv + "</a>]";
            }
            m_textBrowser->setTextFormat( QTextBrowser::RichText );
            m_textBrowser->append( dstr );
            m_textBrowser->setTextFormat( QTextBrowser::PlainText );
        }
        else if ( rx_date.exactMatch(s) )
        {
            m_textBrowser->setTextFormat( QTextBrowser::RichText );
            m_textBrowser->append( "<i>" + s + "</i>" );
            m_textBrowser->setTextFormat( QTextBrowser::PlainText );
        }
        else if ( rx_sep.exactMatch(s) || rx_sep2.exactMatch(s) )
        {
            m_textBrowser->append( "\n" );
            m_textBrowser->setTextFormat( QTextBrowser::RichText );
            m_textBrowser->append( "<hr>" );
            m_textBrowser->setTextFormat( QTextBrowser::PlainText );
        } else
        {
            m_textBrowser->append( s );
        }
    }
    m_logTextBackup = m_textBrowser->source();

//    emit jobFinished( normalExit, exitStatus );
}
Example #22
0
static QString extractFilter (const QString &aRawFilter)
{
    static const char qt_file_dialog_filter_reg_exp[] =
        "([a-zA-Z0-9 ]*)\\(([a-zA-Z0-9_.*? +;#\\[\\]]*)\\)$";

    QString result = aRawFilter;
    QRegExp r (QString::fromLatin1 (qt_file_dialog_filter_reg_exp));
    int index = r.indexIn (result);
    if (index >= 0)
        result = r.cap (2);
    return result.replace (QChar (' '), QChar (';'));
}
Example #23
0
QSqlQuery Application::execSql(const QString &query_str)
{
	QString qs = query_str;
	{
		static QRegExp rx_id_placeholders("\\{\\{([A-Za-z0-9\\.\\_\\/]+)\\}\\}");
		int pos = 0;
		while((pos = rx_id_placeholders.indexIn(query_str, pos)) != -1) {
			QString fld_name = rx_id_placeholders.cap(1);
			qs.replace(rx_id_placeholders.cap(0), appConfigValue(fld_name).toString());
			pos += rx_id_placeholders.matchedLength();
		}
	}
	QSqlDatabase db = sqlConnetion();
	QSqlQuery q(db);
	if(!q.exec(qs)) {
		QSqlError err = q.lastError();
        //qCritical() << ("SQL ERROR: "%err.text());
        //qCritical() << ("QUERY: "%q.lastQuery());
	}
	return q;
}
Example #24
0
QList<QDomNode> VideoExpander::matchToDomNodes(QDomDocument document, QRegExp regExp)
{
	QDomElement embedElement = document.createElement("embed");
	embedElement.setAttribute("src", QString("http://www.youtube.com/v/%1&autoplay=0").arg(regExp.cap(1)));
	embedElement.setAttribute("type", "application/x-shockwave-flash");
	embedElement.setAttribute("width", "640");
	embedElement.setAttribute("height", "390");

	QDomText textElement = document.createTextNode(regExp.cap());

	return QList<QDomNode>() << embedElement << document.createElement("br") << textElement;
}
Example #25
0
/** La completion n'est réalisée que si aucune sélection n'est actuellement définie */
bool RzxTextEdit::nickAutocompletion()
{
	QTextCursor cursor = textCursor();
	
	//Si y'a une sélection, on zappe
	if(cursor.hasSelection())
		return false;
	
	//On récupère la position du curseur et la paragraphe concerné
	int index = cursor.position();
	index -= cursor.block().position();
	if(!index) return false;
	
	static const QRegExp mask("[^-A-Za-z0-9]([-A-Za-z0-9]+)$");
	const QString textPara = cursor.block().text();
	
	//Juste pour se souvenir des pseudos possibles
	const QString localName = RzxComputer::localhost()->name();
	const QString remoteName = chat->computer()->name();
	const QString localLower = localName.toLower();
	const QString remoteLower = remoteName.toLower();
	
	for(int i = 1 ; i <= index && (localName.length() > i || remoteName.length() > i) ; i++)
	{
		//Chaine de caractère qui précède le curseur de taille i
		QString nick = textPara.mid(index-i, i).toLower();
		
		if(mask.indexIn(nick) != -1 || i == index)
		{
			if(mask.indexIn(nick) != -1) nick = mask.cap(1);
			if(!remoteLower.indexOf(nick, false) && localLower.indexOf(nick, false))
			{
				for(int i = 0; i< nick.length();i++)
				{
					cursor.deletePreviousChar ();
				}
				cursor.insertText(remoteName + " ");
				return true;
			}
			else if(remoteLower.indexOf(nick, false) && !localLower.indexOf(nick, false))
			{
				for(int i = 0; i< nick.length();i++)
				{
					cursor.deletePreviousChar ();
				}
				cursor.insertText(localName + " ");
				return true;
			}
			return false;
		}
	}
	return false;
}
Example #26
0
void AudioCdRecord::checkProgressLine( const QString & str )
{
    QRegExp reg;
    int pos;
    bool ok;

    reg.setPattern( "(\\d+)(?:\\s*)of\\s+\\d+\\s+(KB|MB|GB)" );
    pos = reg.indexIn( str );
    if( pos > -1 )
        p->written_size_int = reg.cap(1).toInt(&ok);

    reg.setPattern( "(\\d+)(?:\\s*)(KB|MB|GB)" );
    pos = reg.indexIn( str );
    if( pos > -1 )
        p->image_size_int = reg.cap(1).toInt(&ok);

    reg.setPattern( "fifo\\s+(\\d+)(?:\\s*)%" );
    pos = reg.indexIn( str );
    if( pos > -1 )
        p->ring_buffer_percent_int = reg.cap(1).toInt(&ok);

    reg.setPattern( "buf\\s+(\\d+)(?:\\s*)%" );
    pos = reg.indexIn( str );
    if( pos > -1 )
        p->buffer_percent_int = reg.cap(1).toInt(&ok);

    reg.setPattern( "(\\d+\\.\\d)(?:\\s*)x\\.$" );
    pos = reg.indexIn( str );
    if( pos > -1 )
        p->written_speed_int = reg.cap(1).toDouble(&ok);

    if( p->image_size_int > 0 )
        p->process_precent = 100 * p->written_size_int / p->image_size_int;

    emit ringBufferChanged( p->ring_buffer_percent_int );
    emit bufferChanged(     p->buffer_percent_int      );
    emit writeSizeChenged(  p->written_size_int        );
    emit writeSpeedChanged( p->written_speed_int       );
    emit percentChanged(    p->process_precent         );
}
Example #27
0
QString QgsStringUtils::insertLinks( const QString &string, bool *foundLinks )
{
  QString converted = string;

  // http://alanstorm.com/url_regex_explained
  // note - there's more robust implementations available, but we need one which works within the limitation of QRegExp
  static QRegExp urlRegEx( "(\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_`{|}~\\s]|/))))" );
  static QRegExp protoRegEx( "^(?:f|ht)tps?://" );
  static QRegExp emailRegEx( "([\\w._%+-]+@[\\w.-]+\\.[A-Za-z]+)" );

  int offset = 0;
  bool found = false;
  while ( urlRegEx.indexIn( converted, offset ) != -1 )
  {
    found = true;
    QString url = urlRegEx.cap( 1 );
    QString protoUrl = url;
    if ( protoRegEx.indexIn( protoUrl ) == -1 )
    {
      protoUrl.prepend( "http://" );
    }
    QString anchor = QStringLiteral( "<a href=\"%1\">%2</a>" ).arg( protoUrl.toHtmlEscaped(), url.toHtmlEscaped() );
    converted.replace( urlRegEx.pos( 1 ), url.length(), anchor );
    offset = urlRegEx.pos( 1 ) + anchor.length();
  }
  offset = 0;
  while ( emailRegEx.indexIn( converted, offset ) != -1 )
  {
    found = true;
    QString email = emailRegEx.cap( 1 );
    QString anchor = QStringLiteral( "<a href=\"mailto:%1\">%1</a>" ).arg( email.toHtmlEscaped(), email.toHtmlEscaped() );
    converted.replace( emailRegEx.pos( 1 ), email.length(), anchor );
    offset = emailRegEx.pos( 1 ) + anchor.length();
  }

  if ( foundLinks )
    *foundLinks = found;

  return converted;
}
/** @short Prepare a subject to be used in a reply message */
QString replySubject(const QString &subject)
{
    // These operations should *not* check for internationalized variants of "Re"; these are evil.

#define RE_PREFIX_RE "(?:(?:Re:\\s*)*)"
#define RE_PREFIX_ML "(?:(\\[[^\\]]+\\]\\s*)?)"

    static QRegExp rePrefixMatcher(QLatin1String("^"
                                                 RE_PREFIX_RE // a sequence of "Re: " prefixes
                                                 RE_PREFIX_ML // something like a mailing list prefix
                                                 RE_PREFIX_RE // a sequence of "Re: " prefixes
                                                 ), Qt::CaseInsensitive);
    rePrefixMatcher.setPatternSyntax(QRegExp::RegExp2);
    QLatin1String correctedPrefix("Re: ");

    if (rePrefixMatcher.indexIn(subject) == -1) {
        // Our regular expression has failed, so better play it safe and blindly prepend "Re: "
        return correctedPrefix + subject;
    } else {
        QStringList listPrefixes;
        int pos = 0;
        int oldPos = 0;
        while ((pos = rePrefixMatcher.indexIn(subject, pos, QRegExp::CaretAtOffset)) != -1) {
            if (rePrefixMatcher.matchedLength() == 0)
                break;
            pos += rePrefixMatcher.matchedLength();
            if (!listPrefixes.contains(rePrefixMatcher.cap(1)))
                listPrefixes << rePrefixMatcher.cap(1);
            oldPos = pos;
        }

        QString mlPrefix = listPrefixes.join(QString()).trimmed();
        QString baseSubject = subject.mid(oldPos + qMax(0, rePrefixMatcher.matchedLength()));

        if (!mlPrefix.isEmpty())
            mlPrefix += QLatin1Char(' ');

        return mlPrefix + correctedPrefix + baseSubject;
    }
}
Example #29
0
QValidator::State OffsetValidator::validate(QString &input, int &) const
{
    if (input.isEmpty())
        return QValidator::Intermediate;

    QRegExp offsetRegExp = OffsetGotoWidget::offsetRegexp;
    if (offsetRegExp.indexIn(input) != -1) {
        if (!offsetRegExp.cap(3).isEmpty()) {
            bool ok = false;
            if (offsetRegExp.cap(2) == "o") {
                offsetRegExp.cap(3).toULongLong(&ok, 8);
            } else if (offsetRegExp.cap(2) == "n") {
                offsetRegExp.cap(3).toULongLong(&ok, 10);
            } else {
                offsetRegExp.cap(3).toULongLong(&ok, 16);
            }

            if (ok) {
                return QValidator::Acceptable;
            } else {
                return QValidator::Invalid;
            }

        }
        return QValidator::Intermediate;
    }
    return QValidator::Invalid;
}
Example #30
0
        /**
         * Highlight all words in a line and mark the rest as failure.
         */
        bool highlightWords(const QString &text, const QRegExp &regex, const QTextCharFormat &format) {

            bool highlighted = false;
            int pos = 0;
            while ((pos = regex.indexIn(text, pos)) != -1) {

                if(!regex.cap(1).isEmpty() ) {
                    // highlight submatch only
                    int pos2 = regex.cap(0).indexOf(regex.cap(1));
                    if(pos2 >= -1) {
                        int pos2 = regex.cap(0).indexOf(regex.cap(1));
                        setFormat(pos + pos2, regex.cap(1).length(), format);
                        pos += regex.matchedLength();
                        highlighted = true;
                        continue;
                    }
                }

                // highlight match
                setFormat(pos, regex.matchedLength(), format);
                pos += regex.matchedLength();
                highlighted = true;
            }
            return highlighted;
        }