private void Find(string pattern, FindNextDirection direction)
{
string originalPattern = pattern;
Place start = new Place(0,0);
Place endOfDocument = new Place(tb.GetLineLength(tb.LinesCount - 1), tb.LinesCount - 1);
try
{
// create Regex
RegexOptions opt = cbMatchCase.Checked ? RegexOptions.None : RegexOptions.IgnoreCase;
if (!cbRegex.Checked)
pattern = Regex.Escape(pattern);
if (cbWholeWord.Checked)
pattern = "\\b" + pattern + "\\b";
// the current position
Range range = tb.Selection.Clone();
range.Normalize();
// remember the start position
start = new Place(range.Start.iChar, range.Start.iLine);
if (direction == FindNextDirection.Next)
{
// search till the end of the document
if (this.hasPreviousFindResult)
{
// increase range.Start with one position (if we don't do this will keep finding the same string)
range.Start = NextPlace(start);
}
else
{
range.Start = start;
}
range.End = endOfDocument; // search until end of document
}
else // find previous
{
// search backwards till start of document
range.Start = new Place(0, 0);
range.End = start;
}
Place foundMatchPlace;
bool foundMatch = TryFindNext(pattern, opt, direction, range, out foundMatchPlace);
if (foundMatch)
{
this.hasPreviousFindResult = true;
return;
}
// Searching forwarded and started at (0,0) => we have found nothing...
if (direction == FindNextDirection.Next && start == new Place(0, 0))
{
// Only show message when we don't have a previous find.
if (!this.hasPreviousFindResult) MessageBox.Show(String.Format("Pattern {0} not found.", originalPattern));
this.hasPreviousFindResult = false;
return;
}
// Searching backward and started at end of document => we have found nothing
if (direction == FindNextDirection.Previous && start == endOfDocument)
{
// Only show message when we don't have a previous find.
if (!this.hasPreviousFindResult) MessageBox.Show(String.Format("Pattern {0} not found.", originalPattern));
this.hasPreviousFindResult = false;
return;
}
// we haven't searched the entire document
// Change the search range depending on whether we are searching for the next or previous
if (direction == FindNextDirection.Next)
{
// search from (0,0) to the line-end of start
range.Start = new Place(0, 0);
range.End = EndOfLine(start);
}
else // find previous
{
// search from document-end to line-start of start
range.Start = StartOfLine(start);
range.End = endOfDocument; // search until end of document
}
Place foundMatchPlace2;
bool foundMatch2 = TryFindNext(pattern, opt, direction, range, out foundMatchPlace2);
if (foundMatch2)
{
this.hasPreviousFindResult = true;
return;
}
// Found nothing
// Only show message when we don't have a previous find.
if (!this.hasPreviousFindResult) MessageBox.Show(String.Format("Pattern {0} not found.", originalPattern));
this.hasPreviousFindResult = false;
}
catch (Exception e)
{
MessageBox.Show(this, e.Message, "Exception while searching");
}
}