private static int FindNextWhitespaceBackward(RichTextBox edit) { TextPointer pointer = edit.CaretPosition; WordParser parser = new WordParser("", LogicalDirection.Backward); int resOffset = -1; while (pointer != null) { string textInRun = pointer.GetTextInRun(LogicalDirection.Backward); if (textInRun != "") { parser.Text = textInRun; int res = parser.FindNextWhitespace(); if (res != -1) { resOffset = edit.Document.ContentStart.GetOffsetToPosition(pointer) - res + 1; break; } } pointer = pointer.GetNextContextPosition(LogicalDirection.Backward); } if (pointer == null) { resOffset = 0; } return(resOffset); }
private TextRange SelectCurrentWord(RichTextBox edit) { TextPointer pointer = edit.CaretPosition; TextPointer wordEnd = edit.CaretPosition; TextPointer wordStart = edit.CaretPosition; // Ищем вперед pointer = wordEnd; bool wSpaceFound = false; while (pointer != null) { string nextText = pointer.GetTextInRun(LogicalDirection.Forward); if (nextText != "") { for (int i = 0; i < nextText.Length; i++) { if (WordParser.IsAlphanumeric(nextText[i]) || WordParser.IsWhitespace(nextText[i])) { wordEnd = pointer.GetPositionAtOffset(i, LogicalDirection.Forward); wSpaceFound = true; break; } } if (wSpaceFound) { break; } else { wordEnd = pointer.GetPositionAtOffset(nextText.Length); } } pointer = pointer.GetNextContextPosition(LogicalDirection.Forward); } // ищем назад pointer = wordStart; wSpaceFound = false; while (pointer != null) { string prevText = pointer.GetTextInRun(LogicalDirection.Backward); if (prevText != "") { for (int i = prevText.Length - 1; i >= 0; i--) { if (WordParser.IsAlphanumeric(prevText[i]) || WordParser.IsWhitespace(prevText[i])) { wordStart = pointer.GetPositionAtOffset(-(prevText.Length - i) + 1); wSpaceFound = true; break; } } if (wSpaceFound) { break; } } TextPointer lastPointer = pointer; pointer = pointer.GetNextContextPosition(LogicalDirection.Backward); if (pointer == null) { wordStart = lastPointer; } } return(new TextRange(wordStart, wordEnd)); }
private static int FindNextWhitespaceForward(RichTextBox edit) { TextPointer pointer = edit.CaretPosition; WordParser parser = null; int resOffset = -1; while (pointer != null) { string textInRun = pointer.GetTextInRun(LogicalDirection.Forward); if (textInRun != "") { if (parser == null) parser = new WordParser(textInRun, LogicalDirection.Forward); else parser.Text = textInRun; int res = parser.FindNextWhitespace(); if (res != -1) { resOffset = edit.Document.ContentStart.GetOffsetToPosition(pointer) + res; break; } } pointer = pointer.GetNextContextPosition(LogicalDirection.Forward); } if (pointer == null) resOffset = edit.Document.ContentStart.GetOffsetToPosition(edit.Document.ContentEnd); return resOffset; }