예제 #1
0
        // Helper for GetPositionAtWordBoundary.
        // Returns true when passed TextPointer is next to a wordBreak in requested direction.
        private static bool IsPositionNextToWordBreak(TextPointer position, LogicalDirection wordBreakDirection)
        {
            bool isAtWordBoundary = false;

            // Skip over any formatting.
            if (position.GetPointerContext(wordBreakDirection) != TextPointerContext.Text)
            {
                position = position.GetInsertionPosition(wordBreakDirection);
            }

            if (position.GetPointerContext(wordBreakDirection) == TextPointerContext.Text)
            {
                LogicalDirection oppositeDirection = (wordBreakDirection == LogicalDirection.Forward) ?
                                                     LogicalDirection.Backward : LogicalDirection.Forward;

                char[] runBuffer         = new char[1];
                char[] oppositeRunBuffer = new char[1];

                position.GetTextInRun(wordBreakDirection, runBuffer, /*startIndex*/ 0, /*count*/ 1);
                position.GetTextInRun(oppositeDirection, oppositeRunBuffer, /*startIndex*/ 0, /*count*/ 1);

                if (runBuffer[0] == ' ' && !(oppositeRunBuffer[0] == ' '))
                {
                    isAtWordBoundary = true;
                }
            }
            else
            {
                // If we're not adjacent to text then we always want to consider this position a "word break".
                // In practice, we're most likely next to an embedded object or a block boundary.
                isAtWordBoundary = true;
            }

            return(isAtWordBoundary);
        }
예제 #2
0
        internal static int GetTextWithLimit(TextPointer thisPointer, LogicalDirection direction, char[] textBuffer, int startIndex, int count, TextPointer limit)
        {
            int num2;

            if (limit == null)
            {
                return(thisPointer.GetTextInRun(direction, textBuffer, startIndex, count));
            }

            if ((direction == LogicalDirection.Forward) && (limit.CompareTo(thisPointer) <= 0))
            {
                return(0);
            }

            if ((direction == LogicalDirection.Backward) && (limit.CompareTo(thisPointer) >= 0))
            {
                return(0);
            }

            if (direction == LogicalDirection.Forward)
            {
                num2 = Math.Min(count, thisPointer.GetOffsetToPosition(limit));
            }
            else
            {
                num2 = Math.Min(count, limit.GetOffsetToPosition(thisPointer));
            }

            num2 = Math.Min(count, num2);

            return(thisPointer.GetTextInRun(direction, textBuffer, startIndex, num2));
        }
예제 #3
0
        private TextPointer FindNextString(TextPointer tp)
        {
            //Skip over anything that isn't text
            while (tp.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text)
            {
                tp = tp.GetPositionAtOffset(1, LogicalDirection.Forward);

                if (tp == null)
                {
                    return(tp);
                }
            }

            //Skip over any whitespace we meet
            char[] buffer = new char[1];
            tp.GetTextInRun(LogicalDirection.Forward, buffer, 0, 1);

            while (IsWhiteSpace(buffer))
            {
                tp = tp.GetPositionAtOffset(1, LogicalDirection.Forward);

                if (tp == null)
                {
                    break;
                }

                tp.GetTextInRun(LogicalDirection.Forward, buffer, 0, 1);
            }

            return(tp);
        }
        private static bool IsPositionNextToWordBreak(TextPointer position, LogicalDirection wordBreakDirection)
        {
            // Skip over any formatting.
            if (position.GetPointerContext(wordBreakDirection) != TextPointerContext.Text)
            {
                position = position.GetInsertionPosition(wordBreakDirection);
            }

            if (position.GetPointerContext(wordBreakDirection) == TextPointerContext.Text)
            {
                var oppositeDirection = wordBreakDirection == LogicalDirection.Forward ? LogicalDirection.Backward : LogicalDirection.Forward;

                var runBuffer         = new char[1];
                var oppositeRunBuffer = new char[1];

                position.GetTextInRun(wordBreakDirection, runBuffer, 0, 1);
                position.GetTextInRun(oppositeDirection, oppositeRunBuffer, 0, 1);

                if ((runBuffer[0] == ' ' || runBuffer[0] == '\t') && oppositeRunBuffer[0] != ' ' && oppositeRunBuffer[0] != '\t')
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            // We are next to an embedded object or a block boundary
            // -> consider as word break
            return(true);
        }
 // Modified from: http://stackoverflow.com/a/26689916/3938401
 private string GetCurrentWord()
 {
     TextPointer start = CaretPosition;  // this is the variable we will advance to the left until a non-letter character is found
     TextPointer end = CaretPosition;    // this is the variable we will advance to the right until a non-letter character is found
     string stringBeforeCaret = start.GetTextInRun(LogicalDirection.Backward);   // extract the text in the current run from the caret to the left
     string stringAfterCaret = start.GetTextInRun(LogicalDirection.Forward);     // extract the text in the current run from the caret to the left
     int countToMoveLeft = 0;  // we record how many positions we move to the left until a non-letter character is found
     int countToMoveRight = 0; // we record how many positions we move to the right until a non-letter character is found
     for (int i = stringBeforeCaret.Length - 1; i >= 0; --i)
     {
         // if the character at the location CaretPosition-LeftOffset is a letter, we move more to the left
         if (!char.IsWhiteSpace(stringBeforeCaret[i]))
             ++countToMoveLeft;
         else break; // otherwise we have found the beginning of the word
     }
     for (int i = 0; i < stringAfterCaret.Length; ++i)
     {
         // if the character at the location CaretPosition+RightOffset is a letter, we move more to the right
         if (!char.IsWhiteSpace(stringAfterCaret[i]))
             ++countToMoveRight;
         else break; // otherwise we have found the end of the word
     }
     start = start.GetPositionAtOffset(-countToMoveLeft);    // modify the start pointer by the offset we have calculated
     end = end.GetPositionAtOffset(countToMoveRight);        // modify the end pointer by the offset we have calculated
     // extract the text between those two pointers
     TextRange r = new TextRange(start, end);
     string text = r.Text;
     // check the result
     return text;
 }
        //Разукрашивает комментарии. Должно находится внутри PaintEditor
        // Чувак, мне срочно нужен RGB код вот такого цвета
        private void PaintMultiLaneComments()
        {
            TextPointer position    = editor.Document.ContentStart;
            TextPointer endPosition = null;

            while (position != null)
            {
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    string textRun = position.GetTextInRun(LogicalDirection.Forward);

                    // Find the starting index of any substring that matches "word".
                    int indexInRun = textRun.IndexOf("/*");
                    if (indexInRun >= 0)
                    {
                        position = position.GetPositionAtOffset(indexInRun);
                        if (position.GetTextInRun(LogicalDirection.Forward).Contains("*/")) //частный случай
                        {
                            int       index = position.GetTextInRun(LogicalDirection.Forward).IndexOf("*/");
                            TextRange tr    = new TextRange(position, position.GetPositionAtOffset(index + 2));
                            tr.ApplyPropertyValue(TextElement.ForegroundProperty,
                                                  (SolidColorBrush)(br.ConvertFrom("#00FF00")));
                            position = position.GetNextContextPosition(LogicalDirection.Forward);
                            continue;
                        }
                        endPosition = position.GetPositionAtOffset(3);
                        while (endPosition != null) //
                        {
                            if (endPosition.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                            {
                                if (endPosition.GetTextInRun(LogicalDirection.Forward).Contains("*/"))
                                {
                                    int       index = position.GetTextInRun(LogicalDirection.Forward).IndexOf("*/");
                                    TextRange tr    = new TextRange(position, endPosition.GetPositionAtOffset(index + 3));
                                    tr.ApplyPropertyValue(TextElement.ForegroundProperty,
                                                          (SolidColorBrush)(br.ConvertFrom("#C0C0C0")));

                                    position = endPosition.GetPositionAtOffset(index);
                                    break;
                                }
                                else
                                {
                                    endPosition = endPosition.GetNextContextPosition(LogicalDirection.Forward);
                                }
                            }
                            else
                            {
                                endPosition = endPosition.GetNextContextPosition(LogicalDirection.Forward);
                            }
                        }
                    }
                    position = position.GetNextContextPosition(LogicalDirection.Forward);
                }
                else
                {
                    position = position.GetNextContextPosition(LogicalDirection.Forward);
                }
            }
        }
예제 #7
0
        public static string GetRunText(this TextPointer TextPointer)
        {
            string afterText  = TextPointer.GetTextInRun(LogicalDirection.Forward);
            string beforeText = TextPointer.GetTextInRun(LogicalDirection.Backward);
            string fullText   = beforeText + afterText;

            return(fullText);
        }
예제 #8
0
        public void curRun_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (!(e.LeftButton == MouseButtonState.Pressed && e.ClickCount == 2))
            {
                return;
            }

            Point mousePosition = Mouse.GetPosition(mFlowViewer);

            TextMediaBindableRun senderRun = (TextMediaBindableRun)sender;

            InlineCollection inlines = null;

            if (senderRun.Parent is Span)
            {
                Span o = senderRun.Parent as Span;
                inlines = o.Inlines;
            }
            else
            if (senderRun.Parent is Paragraph)
            {
                Paragraph o = senderRun.Parent as Paragraph;
                inlines = o.Inlines;
            }
            else if (senderRun.Parent is TextBlock)
            {
                TextBlock o = senderRun.Parent as TextBlock;
                inlines = o.Inlines;
            }
            else
            {
                Debug.Print("Should never happen");
            }

            if (inlines != null)
            {
                DoMouseDownStuff(senderRun, inlines);
            }

            TextPointer ptr = UrakawaHtmlFlowDocument.GetPositionFromPoint(senderRun, mousePosition);

            if (ptr != null)
            {
                string textAfterCursor = ptr.GetTextInRun(LogicalDirection.Forward);

                string textBeforeCursor = ptr.GetTextInRun(LogicalDirection.Backward);



                string[] textsAfterCursor = textAfterCursor.Split('.', ' ');

                string[] textsBeforeCursor = textBeforeCursor.Split('.', ' ');



                string currentWord = textsBeforeCursor[textsBeforeCursor.Length - 1] + textsAfterCursor[0];
            }
        }
예제 #9
0
        /// <summary>
        /// Computes the <see cref="Content"/> of a <see cref="Word"/>.
        /// </summary>
        /// <param name="textPointer">
        /// A <see cref="TextPointer"/>, pointing at a <see cref="char"/>. Text will be computed from this point to white spaces in both <see cref="LogicalDirection"/>s.
        /// </param>
        /// <returns>The <see cref="Content"/> of a <see cref="Word"/> to which the <see cref="TextPointer"/> points.</returns>
        private static string GetContentOfWord(TextPointer textPointer)
        {
            string backwards = textPointer.GetTextInRun(LogicalDirection.Backward);
            var    wordCharactersBeforePointer = new string(backwards.Reverse().TakeWhile(c => !char.IsWhiteSpace(c)).Reverse().ToArray());

            string fowards = textPointer.GetTextInRun(LogicalDirection.Forward);
            var    wordCharactersAfterPointer = new string(fowards.TakeWhile(c => !char.IsWhiteSpace(c)).ToArray());

            return(string.Join(string.Empty, wordCharactersBeforePointer, wordCharactersAfterPointer));
        }
예제 #10
0
        private void RichBoxDiscp_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            TextPointer textPointer = richBoxDiscp.CaretPosition;
            string      before;
            string      after;

            before = textPointer.GetTextInRun(LogicalDirection.Backward);
            after  = textPointer.GetTextInRun(LogicalDirection.Forward);

            full = after + before;
        }
예제 #11
0
 private string FindBreak(TextPointer pointer)
 {
     Rect rectAtStart = pointer.GetCharacterRect(LogicalDirection.Forward);
     pointer = pointer.GetNextInsertionPosition(LogicalDirection.Forward);
     Rect currentRect = pointer.GetCharacterRect(LogicalDirection.Forward);
     while (currentRect.Bottom == rectAtStart.Bottom)
     {
         pointer = pointer.GetNextInsertionPosition(LogicalDirection.Forward);
         currentRect = pointer.GetCharacterRect(LogicalDirection.Forward);
     }
     string textBeforeBreak = pointer.GetTextInRun(LogicalDirection.Backward);
     string textAfterBreak = pointer.GetTextInRun(LogicalDirection.Forward);
     return textAfterBreak;
 }
예제 #12
0
    protected override void OnMouseUp(MouseButtonEventArgs e)
    {
        TextPointer cursorPosition   = CaretPosition;
        string      strBeforeCursor  = cursorPosition.GetTextInRun(LogicalDirection.Backward);
        string      strAfterCursor   = cursorPosition.GetTextInRun(LogicalDirection.Forward);
        string      wordBeforeCursor = strBeforeCursor.Split().Last();
        string      wordAfterCursor  = strAfterCursor.Split().First();
        string      text             = wordBeforeCursor + wordAfterCursor;

        SelectedWord = string.Join("", text
                                   .Where(c => char.IsLetter(c))
                                   .ToArray());
        base.OnMouseUp(e);
    }
예제 #13
0
        public static TextRange FindWordFromPosition(TextPointer position, string word)
        {
            while (position != null)
            {
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    string textRun = position.GetTextInRun(LogicalDirection.Forward);
                    textRun = textRun.ToLower();

                    // Find the starting index of any substring that matches "word".
                    int indexInRun = textRun.IndexOf(word);
                    if (indexInRun >= 0)
                    {
                        TextPointer start = position.GetPositionAtOffset(indexInRun);
                        TextPointer end   = start.GetPositionAtOffset(word.Length);
                        return(new TextRange(start, end));
                    }
                }

                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }

            // position will be null if "word" is not found.
            return(null);
        }
        public static void HighlightKeywords(TextPointer startPointer, TextPointer endPointer, HashSet <string> keywords, Brush foreground)
        {
            if (startPointer == null)
            {
                throw new ArgumentNullException(nameof(startPointer));
            }
            if (endPointer == null)
            {
                throw new ArgumentNullException(nameof(endPointer));
            }

            TextRange   text     = new TextRange(startPointer, endPointer);
            TextPointer position = text.Start.GetInsertionPosition(LogicalDirection.Forward);

            while (position != null)
            {
                string textInRun = position.GetTextInRun(LogicalDirection.Forward);

                if (string.IsNullOrWhiteSpace(textInRun))
                {
                    position = position.GetNextContextPosition(LogicalDirection.Forward);
                    continue;
                }

                ChangeTextColor(keywords, foreground, text, position, textInRun);
                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }
        }
예제 #15
0
        public static void EnableHyperlinks(this Paragraph p)
        {
            string paragraphText = new TextRange(p.ContentStart, p.ContentEnd).Text;

            foreach (string word in paragraphText.Split(' ', '\n', '\t').ToList())
            {
                if (word.IndexOf("//") != -1 && Uri.IsWellFormedUriString(word, UriKind.Absolute))
                {
                    Uri uri = new Uri(word, UriKind.RelativeOrAbsolute);
                    if (!uri.IsAbsoluteUri)
                    {
                        uri = new Uri(@"http://" + word, UriKind.Absolute);
                    }
                    for (TextPointer position = p.ContentStart;
                         position != null;
                         position = position.GetNextContextPosition(LogicalDirection.Forward))
                    {
                        if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                        {
                            string textRun    = position.GetTextInRun(LogicalDirection.Forward);
                            int    indexInRun = textRun.IndexOf(word);
                            if (indexInRun >= 0)
                            {
                                TextPointer start = position.GetPositionAtOffset(indexInRun);
                                TextPointer end   = start.GetPositionAtOffset(word.Length);
                                var         link  = new Hyperlink(start, end);
                                link.NavigateUri      = uri;
                                link.RequestNavigate += (sender, args) => Process.Start(args.Uri.ToString());
                                break;
                            }
                        }
                    }
                }
            }
        }
예제 #16
0
        public static IEnumerable <TextRange> GetAllWordRanges(FlowDocument document)
        {
            //string pattern = @"[^\W\d](\w|[-']{1,2}(?=\w))*";
            TextPointer pointer = document.ContentStart;

            while (pointer != null)
            {
                if (pointer.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    string textRun = pointer.GetTextInRun(LogicalDirection.Forward);
                    yield return(new TextRange(pointer.GetPositionAtOffset(0),
                                               pointer.GetPositionAtOffset(textRun.Length)));
                    //MatchCollection matches = Regex.Matches(textRun, pattern);
                    //foreach (Match match in matches)
                    //{
                    //    int startIndex = match.Index;
                    //    int length = match.Length;
                    //    TextPointer start = pointer.GetPositionAtOffset(startIndex);
                    //    TextPointer end = start.GetPositionAtOffset(length);
                    //    yield return new TextRange(start, end);
                    //}
                }

                pointer = pointer.GetNextContextPosition(LogicalDirection.Forward);
            }
        }
예제 #17
0
        private void UserInputArea_TextChanged_ParseText(object sender, TextChangedEventArgs e)
        {
            // obj's and locals
            String      pattern   = @"(@|#| )\w+";
            Regex       reg       = new Regex(pattern);
            TextPointer navigator = UserInputArea.Document.ContentStart;
            // create list to hold ranges
            List <TextRange> ranges = new List <TextRange>();

            while (navigator.CompareTo(UserInputArea.Document.ContentEnd) < 0)
            {
                var run = new Run(navigator.Parent.ToString());

                if (run != null)
                {
                    string runText = navigator.GetTextInRun(LogicalDirection.Forward);
                    var    matches = reg.Matches(runText);

                    foreach (Match match in matches)
                    {
                        TextPointer start = navigator.GetPositionAtOffset(match.Index);
                        TextPointer end   = start.GetPositionAtOffset(match.Length);

                        TextRange textrange = new TextRange(start, end);
                        textrange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);

                        ranges.Add(textrange);
                    }
                }

                navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
            }
        }
예제 #18
0
        public void replaceLine(string oldLine, string newLine)
        {
            TextRange   text    = new TextRange(outputBoxNight.Document.ContentStart, outputBoxNight.Document.ContentEnd); //select all text
            TextPointer current = text.Start.GetInsertionPosition(LogicalDirection.Forward);

            while (current != null)                                                                    //cursor through like sql
            {
                string textInRun = current.GetTextInRun(LogicalDirection.Forward);
                if (!string.IsNullOrWhiteSpace(textInRun))
                {
                    int index = textInRun.IndexOf(oldLine);
                    if (index != -1)
                    {
                        TextPointer selectionStart = current.GetPositionAtOffset(index, LogicalDirection.Forward);
                        TextPointer selectionEnd   = selectionStart.GetPositionAtOffset(oldLine.Length, LogicalDirection.Forward);
                        TextRange   selection      = new TextRange(selectionStart, selectionEnd);
                        selection.Text = newLine;
                        selection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                        outputBoxNight.Selection.Select(selection.Start, selection.End);                      // this is used to update
                        //outputBoxNight.Focus();   not needed really i think
                    }
                }
                current = current.GetNextContextPosition(LogicalDirection.Forward);
            }
        }
예제 #19
0
        private List <TextRange> FindWordFromPosition(TextPointer position, string word)
        {
            List <TextRange> outVar = new List <TextRange>();

            //return outVar;
            while (position != null)
            {
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    string textRun = position.GetTextInRun(LogicalDirection.Forward);

                    // Find the starting index of any substring that matches "word".
                    //int indexInRun = textRun.IndexOf(word);
                    MatchCollection matches = Regex.Matches(textRun, word);
                    foreach (Match match in matches)
                    {
                        if (match.Index >= 0)
                        {
                            TextPointer start = position.GetPositionAtOffset(match.Index);
                            TextPointer end   = start.GetPositionAtOffset(word.Length);
                            outVar.Add(new TextRange(start, end));
                            //return new TextRange(start, end);
                        }
                    }
                }

                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }

            // position will be null if "word" is not found.
            return(outVar);
        }
        private void FillHashValue()
        {
            TextPointer position    = editor.Document.ContentStart;
            TextPointer endPosition = null;

            while (position != null)
            {
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    string textRun = position.GetTextInRun(LogicalDirection.Forward);

                    // Find the starting index of any substring that matches "word".
                    int indexInRun = textRun.IndexOf("#");

                    if (indexInRun >= 0 && hashValue.IsMatch(textRun))
                    {
                        position    = position.GetPositionAtOffset(indexInRun);
                        endPosition = position.GetPositionAtOffset(hashValue.Match(textRun).Length);
                        TextRange colouringText = new TextRange(position, endPosition);
                        colouringText.ApplyPropertyValue(TextElement.ForegroundProperty,
                                                         (SolidColorBrush)(br.ConvertFrom("#FC0FC0")));
                        return;
                    }
                    position = position.GetNextContextPosition(LogicalDirection.Forward);
                }
                else
                {
                    position = position.GetNextContextPosition(LogicalDirection.Forward);
                }
            }
        }
예제 #21
0
        private void btnReplace_Click(object sender, RoutedEventArgs e)
        {
            string      keyword   = txbFind.Text;
            string      newString = txbReplace.Text;
            TextRange   text      = new TextRange(rtbMainText.Document.ContentStart, rtbMainText.Document.ContentEnd);
            TextPointer current   = text.Start.GetInsertionPosition(LogicalDirection.Forward);

            while (current != null)
            {
                string textInRun = current.GetTextInRun(LogicalDirection.Forward);
                if (!string.IsNullOrWhiteSpace(textInRun))
                {
                    int index = textInRun.IndexOf(keyword);
                    if (index != -1)
                    {
                        TextPointer selectionStart = current.GetPositionAtOffset(index, LogicalDirection.Forward);
                        TextPointer selectionEnd   = selectionStart.GetPositionAtOffset(keyword.Length, LogicalDirection.Forward);
                        TextRange   selection      = new TextRange(selectionStart, selectionEnd);
                        selection.Text = newString;
                        rtbMainText.Selection.Select(selection.Start, selection.End);
                        rtbMainText.Focus();
                    }
                }
                current = current.GetNextContextPosition(LogicalDirection.Forward);
            }
        }
예제 #22
0
        public void Test(string value)
        {
            Regex            reg      = new Regex(value, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            TextPointer      position = Document.ContentStart;
            List <TextRange> ranges   = new List <TextRange>();

            while (position != null)
            {
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    string text   = position.GetTextInRun(LogicalDirection.Forward);
                    var    matchs = reg.Matches(text);

                    foreach (Match match in matchs)
                    {
                        TextPointer start = position.GetPositionAtOffset(match.Index);
                        TextPointer end   = start.GetPositionAtOffset(value.Trim().Length);

                        TextRange textrange = new TextRange(start, end);
                        ranges.Add(textrange);
                    }
                }
                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }


            foreach (TextRange range in ranges)
            {
                range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
                range.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
            }
        }
        private void HighlihtText(string searchTerm)
        {
            for (TextPointer position = unaTesis.flowDoc.ContentStart;
                 position != null && position.CompareTo(unaTesis.flowDoc.ContentEnd) <= 0;
                 position = position.GetNextContextPosition(LogicalDirection.Forward))
            {
                //if (position.CompareTo(unaTesis.flowDoc.ContentEnd) == 0)
                //{
                //    return unaTesis.flowDoc;
                //}

                String           textRun          = position.GetTextInRun(LogicalDirection.Forward);
                StringComparison stringComparison = StringComparison.CurrentCulture;
                Int32            indexInRun       = textRun.IndexOf(searchTerm, stringComparison);
                if (indexInRun >= 0)
                {
                    position = position.GetPositionAtOffset(indexInRun);
                    if (position != null)
                    {
                        TextPointer nextPointer = position.GetPositionAtOffset(searchTerm.Length);
                        TextRange   textRange   = new TextRange(position, nextPointer);
                        textRange.ApplyPropertyValue(TextElement.BackgroundProperty,
                                                     new SolidColorBrush(Colors.Yellow));
                    }
                }
            }
        }
예제 #24
0
        public Task <int> AddRange(RichTextBox RichT)
        {
            return(Task.Run(() =>
            {
                string pattern = @_pattern;
                TextPointer pointer = RichT.Document.ContentStart;
                try
                {
                    while (pointer != null)
                    {
                        if (pointer.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                        {
                            string textRun = pointer.GetTextInRun(LogicalDirection.Forward);
                            MatchCollection matches = Regex.Matches(textRun, pattern);
                            foreach (Match match in matches)
                            {
                                synx.Tags tag = new synx.Tags();
                                int startIndex = match.Index;
                                int length = match.Length;
                                TextPointer start = pointer.GetPositionAtOffset(startIndex);
                                TextPointer end = start.GetPositionAtOffset(length);
                                tag.Startindex = start;
                                tag.Endindex = end;
                                synx.Ranges.Add(tag);
                            }
                        }

                        pointer = pointer.GetNextContextPosition(LogicalDirection.Forward);
                    }
                    return 1;
                }
                catch { return 0; }
            }));
        }
예제 #25
0
        /// <summary>
        /// Computes a <see cref="Word"/> from a <see cref="TextPointer"/>, pointing at its <see cref="Content"/>.
        /// </summary>
        /// <param name="textPointer">
        /// The <see cref="TextPointer"/> pointing at any character in the <see cref="RichTextBox"/>.
        /// </param>
        /// <param name="programmingLanguage">
        /// The <see cref="programmingLanguage"/> used to recognize the <see cref="Word"/>.
        /// </param>
        /// <param name="allWords">
        /// An <see cref="IEnumerable{Word}"/> containing all <see cref="Word"/>s in the code.
        /// </param>
        /// <returns>
        /// A <see cref="Word"/>, to which the given <see cref="TextPointer"/> refers to.
        /// </returns>
        private static Word GetWordAtPointer(TextPointer textPointer, ProgrammingLanguage programmingLanguage, List <Word> allWords)
        {
            string backwards = textPointer.GetTextInRun(LogicalDirection.Backward);
            var    wordCharactersBeforePointer = new string(backwards.Reverse().TakeWhile(c => !char.IsWhiteSpace(c)).Reverse().ToArray());
            string forwards = textPointer.GetTextInRun(LogicalDirection.Forward);
            var    wordCharactersAfterPointer = new string(forwards.TakeWhile(c => !char.IsWhiteSpace(c)).ToArray());

            var    startPos = textPointer.DocumentStart;
            var    endPos   = textPointer.DocumentEnd;
            string content  = wordCharactersBeforePointer + wordCharactersAfterPointer;

            startPos = startPos.GetPositionAtOffset(startPos.GetOffsetToPosition(textPointer) - wordCharactersBeforePointer.Length, LogicalDirection.Forward);
            endPos   = endPos.GetPositionAtOffset(endPos.GetOffsetToPosition(textPointer) + wordCharactersAfterPointer.Length, LogicalDirection.Backward);

            return(new Word(startPos, endPos, content, programmingLanguage, allWords));
        }
예제 #26
0
        private static bool HighlightPlainTextDiff(FlowDocument document, char[] s, RichTextBox rtb)
        {
            //Console.WriteLine("-----------------------");
            int         s_i         = 0;
            TextPointer pointer     = document.ContentStart;
            bool        IsBlankLine = false;

            while (pointer != null)
            {
                //Console.WriteLine(pointer.GetPointerContext(LogicalDirection.Forward));
                TextPointerContext context = pointer.GetPointerContext(LogicalDirection.Forward);
                if (context == TextPointerContext.Text)
                {
                    IsBlankLine = false;
                    char[] textRun = pointer.GetTextInRun(LogicalDirection.Forward).ToCharArray();
                    int    i       = 0;
                    for (; i < textRun.Length && s_i < s.Length; ++i, ++s_i)
                    {
                        if (textRun[i] != s[s_i])
                        {
                            int unmatching_word = SearchUnmatchingWord(textRun, i);
                            rtb.Selection.Select(pointer.GetPositionAtOffset(i),
                                                 pointer.GetPositionAtOffset(unmatching_word));
                            rtb.Focus();
                            return(true);
                        }
                    }
                }
                else if (context == TextPointerContext.ElementStart)
                {
                    IsBlankLine = true;
                }
                else if (context == TextPointerContext.ElementEnd && IsBlankLine)
                {
                    pointer.InsertTextInRun("     ");
                    HighlightRange = new TextRange(pointer.Paragraph.ElementStart,
                                                   pointer.Paragraph.ElementEnd);
                    HighlightRange.ApplyPropertyValue(TextElement.BackgroundProperty,
                                                      Brushes.Gray); //new SolidColorBrush(SysColor));
                    //rtb.Selection.Select(HighlightRange.Start, HighlightRange.End);
                    //rtb.Focus();
                    return(true);
                }

                pointer = pointer.GetNextContextPosition(LogicalDirection.Forward);
            }

            if (s_i < s.Length)
            {
                HighlightRange = new TextRange(document.ContentEnd,
                                               document.ContentEnd);
                HighlightRange.Text = "     ";
                HighlightRange.ApplyPropertyValue(TextElement.BackgroundProperty,
                                                  Brushes.Gray);//new SolidColorBrush(SysColor));
                //rtb.Selection.Select(HighlightRange.Start, HighlightRange.End);
                //rtb.Focus();
                return(true);
            }
            return(false);
        }
        List <TextRange> FindWordFromPosition(TextPointer position, string word)
        {
            List <TextRange> matchingText = new List <TextRange>();

            while (position != null)
            {
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    //带有内容的文本
                    string textRun = position.GetTextInRun(LogicalDirection.Forward);
                    //查找关键字在这文本中的位置
                    int indexInRun   = textRun.IndexOf(word);
                    int indexHistory = 0;
                    while (indexInRun >= 0)
                    {
                        TextPointer start = position.GetPositionAtOffset(indexInRun + indexHistory);
                        TextPointer end   = start.GetPositionAtOffset(word.Length);
                        matchingText.Add(new TextRange(start, end));

                        indexHistory = indexHistory + indexInRun + word.Length;
                        textRun      = textRun.Substring(indexInRun + word.Length); //去掉已经采集过的内容
                        indexInRun   = textRun.IndexOf(word);                       //重新判断新的字符串是否还有关键字
                    }
                }
                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }
            return(matchingText);
        }
        public static void XiaHuaXian(RichTextBox richBox, string keyword)
        {
            //设置文字指针为Document初始位置
            //richBox.Document.FlowDirection
            TextPointer position = richBox.Document.ContentStart;

            while (position != null)
            {
                //向前搜索,需要内容为Text
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    //拿出Run的Text
                    string text = position.GetTextInRun(LogicalDirection.Forward);
                    //可能包含多个keyword,做遍历查找
                    int index = 0;
                    index = text.IndexOf(keyword, 0);
                    if (index != -1)
                    {
                        TextPointer start = position.GetPositionAtOffset(index);
                        TextPointer end   = start.GetPositionAtOffset(keyword.Length);
                        position = selecta2(richBox, keyword.Length, start, end);
                    }
                }
                //文字指针向前偏移
                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }
        }
예제 #29
0
        private void Find_Button_Click(object sender, RoutedEventArgs e)
        {
            string      searchedText = findTextBox.Text;
            string      keyword      = searchedText;
            string      newString    = searchedText;
            TextRange   text         = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
            TextPointer current      = text.Start.GetInsertionPosition(LogicalDirection.Forward);

            while (current != null)
            {
                string textInRun = current.GetTextInRun(LogicalDirection.Forward);
                if (!string.IsNullOrWhiteSpace(textInRun))
                {
                    int index = textInRun.IndexOf(keyword);
                    if (index != -1)
                    {
                        TextPointer selectionStart = current.GetPositionAtOffset(index, LogicalDirection.Forward);
                        TextPointer selectionEnd   = selectionStart.GetPositionAtOffset(keyword.Length, LogicalDirection.Forward);
                        TextRange   selection      = new TextRange(selectionStart, selectionEnd);
                        selection.Text = newString;
                        // selection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                        richTextBox.Selection.Select(selection.Start, selection.End);
                        richTextBox.Focus();
                    }
                }
                current = current.GetNextContextPosition(LogicalDirection.Forward);
            }
        }
예제 #30
0
        private void Highlite(string phrase)
        {
            phrase = phrase.ToUpperInvariant();

            for (TextPointer position = base.Document.ContentStart;
                 position != null && position.CompareTo(base.Document.ContentEnd) <= 0;
                 position = position.GetNextContextPosition(LogicalDirection.Forward))
            {
                if (position.CompareTo(base.Document.ContentEnd) == 0)
                {
                    break;
                }

                String textRun = position.GetTextInRun(LogicalDirection.Forward);

                StringComparison stringComparison = StringComparison.CurrentCulture;

                Int32 indexInRun = textRun.ToUpperInvariant().IndexOf(phrase, stringComparison);

                if (indexInRun >= 0)
                {
                    position = position.GetPositionAtOffset(indexInRun);

                    if (position != null)
                    {
                        TextPointer nextPointer = position.GetPositionAtOffset(phrase.Length);

                        TextRange textRange = new TextRange(position, nextPointer);

                        textRange.ApplyPropertyValue(TextElement.BackgroundProperty, this.HighlightColour);
                    }
                }
            }
        }