예제 #1
0
        List <TextRange> FindWordFromPosition(string keyword)
        {
            var regex    = new Regex(keyword);
            var result   = new List <TextRange>();
            var position = RichTextBoxLogs.Document.ContentStart;

            while (position != null)
            {
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    //拿出Run的Text
                    var text = position.GetTextInRun(LogicalDirection.Forward);
                    //可能包含多个keyword,做遍历查找
                    var all = regex.Matches(text);
                    foreach (Match match in all)
                    {
                        TextPointer start   = position.GetPositionAtOffset(match.Index);
                        TextPointer end     = start?.GetPositionAtOffset(match.Length);
                        var         current = new TextRange(start, end);
                        result.Add(current);
                        current.ApplyPropertyValue(TextElement.BackgroundProperty,
                                                   new SolidColorBrush(Colors.GreenYellow));
                    }
                }
                //文字指针向前偏移
                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }
            return(result);
        }
예제 #2
0
        public IEnumerable <TextRange> GetOccurrencesRanges(Regex regex, bool updatePreviousCall = false)
        {
            if (regex != null)
            {
                List <TextRange> result = new List <TextRange>();

                TextPointer pointer = null;

                #region initPointer
                {
                    if (updatePreviousCall)
                    {
                        if (_previousRanges != null)
                        {
                            pointer = _previousRanges
                                      .LastOrDefault()
                                      ?.Start
                                      .GetNextContextPosition(LogicalDirection.Forward);
                        }
                    }

                    if (pointer == null)
                    {
                        pointer = FlowDocument.ContentStart;
                    }
                }
                #endregion

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

                        MatchCollection matches = regex.Matches(textRun);

                        for (int i = 0; i < matches.Count; i++)
                        {
                            int startIndex = matches[i].Index;
                            int length     = matches[i].Length;

                            TextPointer start = pointer.GetPositionAtOffset(startIndex);
                            TextPointer end   = start?.GetPositionAtOffset(length);

                            TextRange textRange = new TextRange(start, end);

                            result.Add(textRange);
                        }
                    }

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

                return(_previousRanges = result);
            }

            return(null);
        }
예제 #3
0
        private static TextPointer LetterShift_Exact(TextPointer start, int numLetters)
        {
            if (numLetters == 0 || start == null)
            {
                return(start);
            }

            int         decrease     = (numLetters < 0 ? -1 : 1);
            TextPointer projectedEnd = start.GetPositionAtOffset(numLetters);

            if (projectedEnd == null)
            {
                while (projectedEnd == null)
                {
                    numLetters   = numLetters - decrease;
                    projectedEnd = start.GetPositionAtOffset(numLetters);
                    if (numLetters == 0)
                    {
                        return(start);
                    }
                }
                return(projectedEnd);
            }
            int mover = (numLetters > 0 ? 1 : -1);

            uint        letterCount = (uint)Math.Abs(numLetters);
            TextPointer ptrLastGood = projectedEnd;

            while (start.GetLetterOffset(projectedEnd) < letterCount)
            {
                projectedEnd = projectedEnd.GetPositionAtOffset(mover);
                if (projectedEnd == null)
                {
                    return(ptrLastGood);
                }
                ptrLastGood = projectedEnd;
            }
            return(projectedEnd);
        }
예제 #4
0
        public TextRange FindTextInRange(TextRange searchRange, string searchText)
        {
            // Search the text with IndexOf
            int offset = searchRange.Text.IndexOf(searchText, StringComparison.InvariantCultureIgnoreCase);

            if (offset < 0)
            {
                return(null); // Not found
            }
            // Try to select the text as a contiguous range
            for (TextPointer start = searchRange.Start.GetPositionAtOffset(offset);
                 start != searchRange.End && start != null;
                 start = start.GetPositionAtOffset(1))
            {
                var result = new TextRange(start, start.GetPositionAtOffset(searchText.Length));
                if (result.Text.ToLower() == searchText.ToLower())
                {
                    return(result);
                }
            }
            return(null);
        }
        /* ---------------------Helper Methods for StyleContent-------------------------------*/
        private static TextPointer GetTextPointAt(TextPointer from, int pos)
        {
            TextPointer ret = from;
            int         i   = 0;

            while ((i < pos) && (ret != null))
            {
                if ((ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.Text) || (ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.None))
                {
                    i++;
                }

                if (ret.GetPositionAtOffset(1, LogicalDirection.Forward) == null)
                {
                    return(ret);
                }

                ret = ret.GetPositionAtOffset(1, LogicalDirection.Forward);
            }

            return(ret);
        }
예제 #6
0
        private void ApplyFormatting()
        {
            // We want to start from the beginning of the document.
            TextPointer tp = rtbTextContent.Document.ContentStart;

            //Find the next block of text.
            tp = FindNextString(tp);

            while (tp != null)
            {
                TextPointer textRangeEnd = tp.GetPositionAtOffset(1,
                                                                  LogicalDirection.Forward);

                TextRange tokenTextRange = new TextRange(tp,
                                                         tp.GetPositionAtOffset(1, LogicalDirection.Forward));

                TokenType tokenType = ClassifyToken(tokenTextRange.Text);

                switch (tokenType)
                {
                case TokenType.Numerical:
                    tokenTextRange.ApplyPropertyValue(TextElement.ForegroundProperty,
                                                      Brushes.Blue);
                    break;

                case TokenType.Operator:
                    tokenTextRange.ApplyPropertyValue(TextElement.FontWeightProperty,
                                                      FontWeights.Bold);
                    break;

                case TokenType.Other:
                    tokenTextRange.ApplyPropertyValue(TextElement.FontSizeProperty, 20d);
                    break;
                }

                tp = FindNextString(textRangeEnd);
            }
        }
        private void Content_LostFocus(object sender, RoutedEventArgs e)
        {
            MainWindow.ColorSelect -= ColorSelect;
            MainWindow.Instance.HideColorBar();

            TextRange   document = new TextRange(Content.Document.ContentStart, Content.Document.ContentEnd);
            TextPointer start    = Content.Document.ContentStart;

            for (int n = 0; n < 10; n++)
            {
                TextRange color = new TextRange(start.GetPositionAtOffset(n), start.GetPositionAtOffset(n + 1));

                if (color.GetPropertyValue(TextElement.ForegroundProperty) is Brush)
                {
                    Brush brush = color.GetPropertyValue(TextElement.ForegroundProperty) as Brush;
                    Console.WriteLine(brush.ToString() + ": " + color.Text + " / " + n + " <> " + (n + 1));
                }
                else
                {
                    Console.WriteLine("nc");
                }
            }
        }
예제 #8
0
        /// <summary>
        /// 历史记录更新
        /// </summary>
        /// <param name="strInput">添加字符串</param>
        /// <param name="fontColor">字符串字体颜色</param>
        public void RichTextBoxUpdate(string strInput, Color fontColor)
        {
            TextPointer tpend = rtbHistory.Document.ContentEnd;

            rtbHistory.AppendText(strInput);
            //TextPointer tpstart = rtbHistory.Document.ContentEnd;
            int         p2      = strInput.Length + 4;
            TextPointer tpstart = tpend.GetPositionAtOffset(-1 * p2);
            TextRange   range   = rtbHistory.Selection;

            range.Select(tpstart, tpend);
            range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(fontColor));
            //rtbHistory.SelectionBrush = fontColor;
        }
예제 #9
0
        void PasteCommand(object sender, ExecutedRoutedEventArgs e)
        {
            if (Clipboard.ContainsText())
            {
                string      text = Clipboard.GetText();
                TextPointer p    = this.CaretPosition;
                p.InsertTextInRun(text);
                p             = this.CaretPosition;
                CaretPosition = p.GetPositionAtOffset(p.GetTextRunLength(LogicalDirection.Forward));

                LinksCheck(p);
                return;
            }
        }
예제 #10
0
        private void FindAndReplaceButton_OnClick(object sender, RoutedEventArgs e)
        {
            string findWord    = FindTextBox.Text;
            string replaceWord = ReplaceTextBox.Text;

            if (findWord.Equals(String.Empty) || replaceWord.Equals(String.Empty))
            {
                MessageBoxResult emptyInput = MessageBox.Show("You need to enter both 'Find' and 'Replace' arguments.",
                                                              "Find & Replace", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                TextRange   text    = new TextRange(rtbList[index].Document.ContentStart, rtbList[index].Document.ContentEnd);
                TextPointer current = text.Start.GetInsertionPosition(LogicalDirection.Forward);

                while (current != null)
                {
                    string textInRun = current.GetTextInRun(LogicalDirection.Forward);
                    if (!string.IsNullOrWhiteSpace(textInRun))
                    {
                        int idx = textInRun.IndexOf(findWord);
                        if (idx != -1)
                        {
                            TextPointer selectionStart = current.GetPositionAtOffset(idx, LogicalDirection.Forward);
                            TextPointer selectionEnd   = selectionStart.GetPositionAtOffset(findWord.Length, LogicalDirection.Forward);
                            TextRange   selection      = new TextRange(selectionStart, selectionEnd);

                            object o  = selection.GetPropertyValue(TextElement.FontFamilyProperty);                 // For some reason, it has to be like this
                            object o1 = selection.GetPropertyValue(TextElement.ForegroundProperty);
                            object o2 = selection.GetPropertyValue(Inline.TextDecorationsProperty);
                            object o3 = selection.GetPropertyValue(TextElement.FontWeightProperty);
                            object o4 = selection.GetPropertyValue(TextElement.FontStyleProperty);
                            object o5 = selection.GetPropertyValue(Inline.FontSizeProperty);

                            selection.Text = replaceWord;

                            selection.ApplyPropertyValue(TextElement.FontFamilyProperty, o);
                            selection.ApplyPropertyValue(TextElement.ForegroundProperty, o1);
                            selection.ApplyPropertyValue(Inline.TextDecorationsProperty, o2);
                            selection.ApplyPropertyValue(TextElement.FontWeightProperty, o3);
                            selection.ApplyPropertyValue(TextElement.FontStyleProperty, o4);
                            selection.ApplyPropertyValue(Inline.FontSizeProperty, o5);

                            rtbList[index].Focus();
                        }
                    }
                    current = current.GetNextContextPosition(LogicalDirection.Forward);
                }
            }
        }
        public void PaintSingleLineComments()
        {
            TextPointer position = editor.Document.ContentStart;
            TextPointer endPosition;

            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);
                        endPosition = position.GetLineStartPosition(1);
                        if (endPosition == null)
                        {
                            endPosition = position.GetPositionAtOffset(textRun.Length - 1);
                        }
                        TextRange tr = new TextRange(position, endPosition);
                        tr.ApplyPropertyValue(TextElement.ForegroundProperty,
                                              (SolidColorBrush)(br.ConvertFrom("#C0C0C0")));
                        position = position.GetNextContextPosition(LogicalDirection.Forward);
                    }
                    else
                    {
                        position = position.GetNextContextPosition(LogicalDirection.Forward);
                    }
                }
                else
                {
                    position = position.GetNextContextPosition(LogicalDirection.Forward);
                }
            }
        }
예제 #12
0
        private void Find_Click(object sender, RoutedEventArgs e)
        {
            TextRange        range   = new TextRange(textEditor.Document.ContentStart, textEditor.Document.ContentEnd);
            string           source  = range.Text;
            string           pattern = SearchQuery.Text;
            List <TextRange> list    = new List <TextRange>();

            range.ApplyPropertyValue(TextElement.BackgroundProperty, null);

            foreach (Paragraph paragraph in textEditor.Document.Blocks)
            {
                foreach (Inline inline in paragraph.Inlines)
                {
                    TextPointer start      = inline.ContentStart;
                    TextPointer end        = inline.ContentEnd;
                    TextRange   r          = new TextRange(start, end);
                    string      src        = r.Text;
                    int         startIndex = 0;
                    int         index      = src.IndexOf(pattern, startIndex);

                    while (index != -1 && !src.Equals("") && !pattern.Equals(""))
                    {
                        TextRange tmp = new TextRange(start.GetPositionAtOffset(index),
                                                      start.GetPositionAtOffset(index + pattern.Length));
                        startIndex = index + pattern.Length;
                        index      = src.IndexOf(pattern, startIndex);
                        list.Add(tmp);
                    }
                }
            }
            range.ApplyPropertyValue(TextElement.BackgroundProperty, null);

            foreach (TextRange textRange in list)
            {
                textRange.ApplyPropertyValue(TextElement.BackgroundProperty, "#66FFFF00");
            }
        }
예제 #13
0
        public void Search()
        {
            if (SearchTerm == _currentKeyword)
            {
                if (CanGoToLastSearchResult())
                {
                    GoToNextSearchResult();
                }
                return;
            }

            SearchResults.Clear();
            _currentKeyword = SearchTerm;

            TextRange   text    = new TextRange(Document.ContentStart, Document.ContentEnd);
            TextPointer current = text.Start.GetInsertionPosition(LogicalDirection.Backward);

            while (current != null)
            {
                string textInRun = current.GetTextInRun(LogicalDirection.Forward);
                if (!string.IsNullOrWhiteSpace(textInRun))
                {
                    int index = 0;
                    index = textInRun.IndexOf(SearchTerm, index);
                    while (index != -1)
                    {
                        TextPointer selectionStart = current.GetPositionAtOffset(index, LogicalDirection.Forward);
                        TextPointer selectionEnd   = selectionStart.GetPositionAtOffset(SearchTerm.Length, LogicalDirection.Forward);
                        TextRange   selection      = new TextRange(selectionStart, selectionEnd);
                        SearchResults.Add(selection);
                        index = textInRun.IndexOf(SearchTerm, index + 1);
                    }
                }

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

            if (SearchResults.Count == 0)
            {
                NoSearchResultsVisibility = Visibility.Visible;
                SearchResultsVisibility   = Visibility.Collapsed;
            }
            else
            {
                NoSearchResultsVisibility = Visibility.Collapsed;
                SearchResultsVisibility   = Visibility.Visible;
                SelectedSearchResult      = SearchResults.First();
            }
        }
예제 #14
0
        private void TextEntered(string text)
        {
            Debug.WriteLine(String.Format("Text entered: '{0}'", text));

            // Удалить то количество символов, которое указано в text из ввода.
            if (__ImeJustPrecessed)
            {
                TextPointer remove_start = Selection.Start;
                TextPointer remove_end   = remove_start.GetPositionAtOffset(-text.Length);
                TextRange   remove_range = new TextRange(remove_start, remove_end);
                remove_range.Text = "";
            }

            if (!Selection.IsEmpty)
            {
                PushUndoAction(new FormatUndo(Document, Selection, this), true);

                TextPointer insertPoint = Selection.Start;

                Selection.Start.InsertTextInRun(text);
                TextPointer newPointer = insertPoint.GetPositionAtOffset(text.Length);
                Selection.Select(newPointer, Selection.End);
                Selection.Text = "";
                CaretPosition  = newPointer;
                Selection.Select(CaretPosition, CaretPosition);
                return;
            }

            TextPointer beforeInsert = CaretPosition.GetPositionAtOffset(0, LogicalDirection.Backward);
            TextPointer insert       = CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);

            insert.InsertTextInRun(text);
            CaretPosition = insert.GetPositionAtOffset(0, LogicalDirection.Backward);

            TextRange range = new TextRange(beforeInsert, CaretPosition);

            range.ApplyPropertyValue(RichTextBox.FontWeightProperty, Selection.GetPropertyValue(RichTextBox.FontWeightProperty));
            range.ApplyPropertyValue(RichTextBox.FontFamilyProperty, Selection.GetPropertyValue(RichTextBox.FontFamilyProperty));
            range.ApplyPropertyValue(RichTextBox.FontSizeProperty, Selection.GetPropertyValue(RichTextBox.FontSizeProperty));
            range.ApplyPropertyValue(RichTextBox.FontStyleProperty, Selection.GetPropertyValue(RichTextBox.FontStyleProperty));
            range.ApplyPropertyValue(TextBlock.TextDecorationsProperty, Selection.GetPropertyValue(TextBlock.TextDecorationsProperty));
            PushUndoAction(new UndoTextEnter(this, range, text), true);

            TextPointer endPointer = CaretPosition.GetPositionAtOffset(0, LogicalDirection.Backward);

            Selection.Select(CaretPosition, endPointer);

            LinksCheck(CaretPosition);
        }
예제 #15
0
 public static TextRange GetRange(this RichTextBox rtb, TextPointer p, int len)
 {
     try
     {
         if (p == null)
         {
             return(null);
         }
         TextPointer positionAtCharOffset;
         if (len >= 0)
         {
             p = p.GetPositionAtOffset(0, LogicalDirection.Forward);
             positionAtCharOffset = p.GetPositionAtCharOffset(len, LogicalDirection.Backward);
             return(new TextRange(p, positionAtCharOffset));
         }
         p = p.GetPositionAtOffset(0, LogicalDirection.Backward);
         positionAtCharOffset = p.GetPositionAtCharOffset(len, LogicalDirection.Forward);
         return(new TextRange(positionAtCharOffset, p));
     }
     catch
     {
     }
     return(null);
 }
예제 #16
0
        void FindWordFromPosition(TextPointer position, string pattern)
        {
            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".

                    var r = new System.Text.RegularExpressions.Regex(pattern);
                    System.Text.RegularExpressions.Match m = r.Match(textRun);

                    TextPointer textPointerEnd = position;
                    {
                        var position_start = position.GetPositionAtOffset(m.Index);
                        textPointerEnd = position.GetPositionAtOffset(m.Index + m.Length);
                        TextRange tr = new TextRange(position_start, textPointerEnd);
                        tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
                    }
                }
                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }
        }
예제 #17
0
 private TextPointer GetTextPointerFromTextOffset(TextPointer start, int textCharacterOffset)
 {
     while (textCharacterOffset > 0)
     {
         int    charsInRun = start.GetTextRunLength(LogicalDirection.Forward);
         string run        = start.GetTextInRun(LogicalDirection.Forward);
         if (textCharacterOffset <= charsInRun)
         {
             return(start.GetPositionAtOffset(textCharacterOffset));
         }
         textCharacterOffset -= charsInRun;
         start = start.GetNextContextPosition(LogicalDirection.Forward);
     }
     return(start);
 }
        /// <summary>
        /// 获取RichTextBox中光标最近的一个字符(向后)
        /// </summary>
        /// <param name="rtf"></param>
        /// <param name="curLoc"></param>
        /// <returns></returns>
        public TextRange GetNextChar(TextPointer curLoc)
        {
            //文字指针向前移一个字符
            TextPointer nextLoc = curLoc.GetPositionAtOffset(1);

            if (nextLoc == null) //找不到对应位置
            {
                return(null);
            }

            //现在可获取插入光标最近一个字符
            TextRange nearestChar = new TextRange(curLoc, nextLoc);

            return(nearestChar);
        }
예제 #19
0
        /*private static TextPointer GetPointOld(TextPointer start, int x)
         * {
         *  var ret = start;
         *  var i = 0;
         *  while (i < x && ret != null)
         *  {
         *      if (ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.Text || ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.None)
         *          i++;
         *      if (ret.GetPositionAtOffset(1, LogicalDirection.Forward) == null)
         *          return ret;
         *      ret = ret.GetPositionAtOffset(1, LogicalDirection.Forward);
         *  }
         *  return ret;
         * }*/
        private static TextPointer GetPoint(TextPointer start, int x)
        {
            TextPointer ret = start.GetPositionAtOffset(x);

            while (new TextRange(start, ret).Text.Length < x)
            {
                if (ret.GetPositionAtOffset(1, LogicalDirection.Forward) == null)
                {
                    return(ret);
                }
                ret = ret.GetPositionAtOffset(1, LogicalDirection.Forward);
            }

            return(ret);
        }
예제 #20
0
        public ReadingWIndow(int fontSize, string path, int _TraversalSpeed, System.Windows.Media.Color color1)
        {
            try
            {
                this.path     = path;
                this.brush1   = new SolidColorBrush(color1);
                this.textSize = fontSize;

                InitializeComponent();

                traversallTimer.Elapsed += new ElapsedEventHandler(TraversalEvent);
                traversallTimer.Interval = 1000 / _TraversalSpeed;

                StreamReader reader = new StreamReader(@path, Encoding.Default, true);
                prompterText.AppendText(reader.ReadToEnd());
                prompterText.FontSize            = textSize;
                prompterText.HorizontalAlignment = HorizontalAlignment.Center;

                TextPointer text = prompterText.Document.ContentStart;
                while (text.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text)
                {
                    text = text.GetNextContextPosition(LogicalDirection.Forward);
                }
                TextPointer startPos = text.GetPositionAtOffset(index);
                TextPointer endPos   = text.GetPositionAtOffset(index + 30);
                prompterText.Selection.Select(startPos, endPos);
                prompterText.SelectionBrush = brush1;

                this.KeyDown += new KeyEventHandler(PrompterWindow_KeyDown_AsyncAndSync);
            }

            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
예제 #21
0
        public TextPointer GetTextPointer(int charOffset, bool reset = false)
        {
            if (reset)
            {
                ResetToStart();
            }

            while (CurrentPosition.CompareTo(EndOfDocument) < 0)
            {
                switch (CurrentPosition.GetPointerContext(LogicalDirection.Forward))
                {
                case TextPointerContext.ElementEnd: {
                    DependencyObject d = this.CurrentPosition.GetAdjacentElement(LogicalDirection.Forward);
                    if (d is Paragraph || d is LineBreak)
                    {
                        CurrentCharacterOffset += 2;
                    }
                    if (d is InlineUIContainer)
                    {
                        CurrentCharacterOffset += 1;
                    }
                    break;
                }

                case TextPointerContext.Text: {
                    int characterInCurrentRun = CurrentCharacterOffset + CurrentPosition.GetTextRunLength(LogicalDirection.Forward);

                    if (charOffset <= characterInCurrentRun)
                    {
                        int offset = charOffset - CurrentCharacterOffset;

                        return(CurrentPosition.GetPositionAtOffset(offset, LogicalDirection.Forward));
                    }

                    CurrentCharacterOffset = characterInCurrentRun;
                    break;
                }
                }
                CurrentPosition = CurrentPosition.GetNextContextPosition(LogicalDirection.Forward);
            }

            if (CurrentCharacterOffset != 0 && charOffset <= CurrentCharacterOffset)
            {
                return(EndOfDocument.GetNextInsertionPosition(LogicalDirection.Backward));
            }

            return(EndOfDocument);
        }
예제 #22
0
        TextRange FindWordFromPosition(TextPointer position, string word)
        {
            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);
                    if (indexInRun >= 0)
                    {
                        TextPointer start = position.GetPositionAtOffset(indexInRun);
                        TextPointer end   = start.GetPositionAtOffset(word.Length);

                        TextRange test = new TextRange(end, end.GetPositionAtOffset(1));

                        if (word == "for")
                        {
                            if (test.Text != "e")
                            {
                                return(new TextRange(start, end));
                            }
                            else
                            {
                                continue;
                            }
                        }
                        else
                        {
                            if (test.Text == " " || test.Text == "" || test.Text == "\n" || test.Text == "(")
                            {
                                return(new TextRange(start, end));
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                }

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

            // position will be null if "word" is not found.
            return(null);
        }
예제 #23
0
        private TextRange FindWordFromPosition(TextPointer position, string word, SearchDirection searchDirection)
        {
            string wordToFind;

            if (!CaseSensitive)
            {
                wordToFind = word.ToLower();
            }
            else
            {
                wordToFind = word;
            }

            LogicalDirection logicalDirection = SearchDirectionToLogicalDirection(searchDirection);

            while (position != null)
            {
                if (position.Parent is ConversationContentRun)
                {
                    string textRun = position.GetTextInRun(logicalDirection);

                    int indexInRun = FindWordInString(wordToFind, textRun, searchDirection);

                    if (indexInRun >= 0)
                    {
                        int startOffset;

                        if (searchDirection == SearchDirection.Down)
                        {
                            startOffset = indexInRun;
                        }
                        else
                        {
                            startOffset = -1 * (textRun.Length - indexInRun);
                        }

                        TextPointer start = position.GetPositionAtOffset(startOffset, logicalDirection);
                        TextPointer end   = start.GetPositionAtOffset(wordToFind.Length, logicalDirection);
                        return(new TextRange(start, end));
                    }
                }

                position = position.GetNextContextPosition(logicalDirection);
            }

            return(null);
        }
예제 #24
0
        protected String ConvertToFlowDocumentString(String sbDescString, String[] boldWords)
        {
            int          indexInRun;
            FlowDocument flowDocument = null;

            if (sbDescString[0] == '<')
            {
                flowDocument = XamlReader.Parse(sbDescString) as FlowDocument;
            }

            if (flowDocument == null)
            {
                flowDocument = new FlowDocument();
                flowDocument.Blocks.Clear();
                flowDocument.Blocks.Add(new Paragraph(new Run(sbDescString)));
            }

            if (boldWords != null)
            {
                TextPointer position = flowDocument.ContentStart;
                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".
                        foreach (String word in boldWords)
                        {
                            indexInRun = textRun.IndexOf(word);
                            if (indexInRun >= 0)
                            {
                                TextPointer start     = position.GetPositionAtOffset(indexInRun);
                                TextPointer end       = start.GetPositionAtOffset(word.Length);
                                TextRange   selection = new TextRange(start, end);
                                selection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                            }
                        }
                    }
                    position = position.GetNextContextPosition(LogicalDirection.Forward);
                }
            }

            sbDescString = XamlWriter.Save(flowDocument);
            return(sbDescString);
        }
예제 #25
0
 private TextPointer GetPointer(TextPointer docEnd, TextPointer startPointer, int offset)
 {
     try
     {
         int findEnd = offset, textLength = 0;
         while (startPointer != null && docEnd.CompareTo(startPointer) > -1)
         {
             while (startPointer != null && startPointer.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text)
             {
                 TextPointerContext context = startPointer.GetPointerContext(LogicalDirection.Forward);
                 if (context == TextPointerContext.ElementEnd)
                 {
                     var next = startPointer.GetNextContextPosition(LogicalDirection.Forward);
                     if (next != null && next.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.ElementEnd)
                     {
                         textLength  += 2;
                         offset      -= 2;
                         startPointer = next;
                     }
                 }
                 startPointer = startPointer.GetNextContextPosition(LogicalDirection.Forward);
             }
             if (startPointer == null)
             {
                 return(docEnd);
             }
             var len = startPointer.GetTextRunLength(LogicalDirection.Forward);
             if (textLength + len < findEnd)
             {
                 textLength  += len;
                 offset      -= len;
                 startPointer = startPointer.GetNextContextPosition(LogicalDirection.Forward);
             }
             else
             {
                 break;
             }
         }
         var tp = startPointer.GetPositionAtOffset(offset, LogicalDirection.Forward);
         return(tp);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
예제 #26
0
        private TextPointer _GetTextPositionAtOffset(TextPointer position, int characterCount)
        {
            // Console.WriteLine($"Character count {characterCount}");
            while (position != null)
            {
                var    type = position.GetPointerContext(LogicalDirection.Forward);
                string TypeName;
                //Console.WriteLine($"type:{type}");
                var AdjacentElementF = position.GetAdjacentElement(LogicalDirection.Forward);
                if (AdjacentElementF != null)
                {
                    TypeName = AdjacentElementF.GetType().Name;
                    //  Console.WriteLine($"element {TypeName}");
                }
                else
                {
                    TypeName = "";
                }

                if (type == TextPointerContext.Text)
                {
                    //Console.WriteLine("Text in run:" + position.GetTextInRun(LogicalDirection.Forward));
                    int count = position.GetTextRunLength(LogicalDirection.Forward);
                    if (characterCount <= count)
                    {
                        return(position.GetPositionAtOffset(characterCount));
                    }
                    characterCount -= count;
                }
                if (type == TextPointerContext.ElementEnd && (TypeName == "Paragraph" || TypeName == "LineBreak"))
                {
                    //Console.WriteLine("Enter Count -- ");
                    characterCount -= 2;
                }

                TextPointer nextContextPosition = position.GetNextContextPosition(LogicalDirection.Forward);
                if (nextContextPosition == null)
                {
                    return(position);
                }

                position = nextContextPosition;
            }

            return(position);
        }
    public static FormattingTag GetTag(TextPointer start, int startIndex, int length, DependencyProperty formattingProperty, object value)
    {
        while (start.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text)
        {
            start = start.GetNextContextPosition(LogicalDirection.Forward);
        }

        TextPointer   contentStart = start.GetPositionAtOffset(startIndex);
        TextPointer   contentEnd   = contentStart.GetPositionAtOffset(length);
        FormattingTag tag          = new FormattingTag(startIndex, length);

        tag.StartPosition      = contentStart;
        tag.EndPosition        = contentEnd;
        tag.FormattingProperty = formattingProperty;
        tag.Value = value;
        return(tag);
    }
예제 #28
0
        public static void FromTextPointer(TextPointer startPointer, TextPointer endPointer, string keyword, FontStyle fontStyle, FontWeight fontWeight, Brush foreground, Brush background, double fontSize, string newString)
        {
            if (startPointer == null)
            {
                throw new ArgumentNullException(nameof(startPointer));
            }
            if (endPointer == null)
            {
                throw new ArgumentNullException(nameof(endPointer));
            }
            if (string.IsNullOrEmpty(keyword))
            {
                throw new ArgumentNullException(keyword);
            }

            TextRange   text    = new TextRange(startPointer, endPointer);
            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);

                        if (!string.IsNullOrEmpty(newString))
                        {
                            selection.Text = newString;
                        }

                        selection.ApplyPropertyValue(TextElement.FontSizeProperty, fontSize);
                        selection.ApplyPropertyValue(TextElement.FontStyleProperty, fontStyle);
                        selection.ApplyPropertyValue(TextElement.FontWeightProperty, fontWeight);
                        selection.ApplyPropertyValue(TextElement.ForegroundProperty, foreground);
                        selection.ApplyPropertyValue(TextElement.BackgroundProperty, background);
                    }
                }
                current = current.GetNextContextPosition(LogicalDirection.Forward);
            }
        }
예제 #29
0
        private static TextPointer getTextPointerToWordStart(TextSelection position)
        {
            TextPointer selectionStart = position.Start;
            String      s = selectionStart.GetTextInRun(LogicalDirection.Backward);

            if (position.IsEmpty)
            {
                int lastInd     = s.LastIndexOf(' ');
                int offsetToPos = (lastInd == -1) ? 0 : -1;
                s = s.Substring((lastInd == -1) ? 0 : lastInd);
                TextPointer tp = selectionStart.GetPositionAtOffset(-(s.Length + offsetToPos));
                return(tp);
            }
            else
            {
                return(selectionStart);
            }
        }
예제 #30
0
        private bool InsertAssistWord()
        {
            bool isInserted = false;

            if (IntellisenseList.SelectedIndex != -1)
            {
                TextPointer pointer = this.CaretPosition;
                var         text    = pointer.GetTextInRun(LogicalDirection.Backward);
                var         offset  = LastWord.Length * -1;
                this.CaretPosition = pointer.GetPositionAtOffset(offset, LogicalDirection.Backward);
                var wordToInsert = IntellisenseList.SelectedItem.ToString();
                this.CaretPosition.DeleteTextInRun(LastWord.Length);
                this.InsertText(wordToInsert);
                isInserted = true;
            }
            IntellisenseList.Visibility = System.Windows.Visibility.Collapsed;
            return(isInserted);
        }