private void txtCommand_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox txt = (TextBox)sender;

            txt.Foreground = getBrush(Colors.Black);

            TabItem item = this.tc.SelectedItem as TabItem;

            if (item == null)
            {
                return;
            }
            else if (item == this.tiHTML_DOM)
            {
                if (_document == null)
                {
                    return;
                }

                #region tiHTML_DOM
                try
                {
                    if (this.previous_DOM_mapKeys != null)
                    {
                        foreach (HtmlNode node in this.previous_DOM_mapKeys)
                        {
                            if (this._DOM_map.ContainsKey(node))
                            {
                                this._DOM_map[node].Background = getBrush(Colors.Transparent);
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(txt.Text))
                    {
                        return;
                    }

                    HtmlNodeCollection nodes = _document.DocumentNode.SelectNodes(txt.Text);

                    foreach (HtmlNode node in nodes)
                    {
                        if (this._DOM_map.ContainsKey(node))
                        {
                            this._DOM_map[node].Background = getBrush(0xFF, 0x7F, 0xFF);
                        }
                    }
                    this.previous_DOM_mapKeys = nodes;
                }
                catch (Exception)
                {
                    txt.Foreground = getBrush(Colors.Red);
                }
                #endregion
            }
            else if (item == this.tiHTML_SORTED)
            {
                #region tiHTML_SOURTED
                try
                {
                    foreach (TextRange range in previous_SORTED_textRanges)
                    {
                        range.ApplyPropertyValue(TextElement.BackgroundProperty, getBrush(Colors.Transparent));
                    }

                    if (string.IsNullOrEmpty(txt.Text))
                    {
                        return;
                    }

                    TextRange       contentRange = new TextRange(this.fdsvHTML_SORTED.Document.ContentStart, this.fdsvHTML_SORTED.Document.ContentEnd);
                    string          source       = contentRange.Text;
                    MatchCollection matches      = Regex.Matches(source, txt.Text);

                    foreach (Match match in matches)
                    {
                        int         index    = 0;
                        TextPointer position = this.fdsvHTML_SORTED.Document.ContentStart;
                        TextPointer start    = null;
                        TextPointer end      = null;
                        while (position != null)
                        {
                            if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                            {
                                string text = position.GetTextInRun(LogicalDirection.Forward);
                                if (index <= match.Index && (index + text.Length) > match.Index)
                                {
                                    start = position.GetPositionAtOffset(match.Index - index);
                                }
                                if (index <= (match.Index + match.Length) && (index + text.Length) > (match.Index + match.Length))
                                {
                                    end = position.GetPositionAtOffset(match.Index + match.Length - index);
                                }
                                index += text.Length;
                            }

                            if (start != null && end != null)
                            {
                                break;
                            }

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

                        if (start != null && end != null)
                        {
                            TextRange range = new TextRange(start, end);
                            range.ApplyPropertyValue(TextElement.BackgroundProperty, getBrush(0xFF, 0x7F, 0xFF));
                            this.previous_SORTED_textRanges.Add(range);
                        }
                    }
                }
                catch (Exception)
                {
                    txt.Foreground = getBrush(Colors.Red);
                }
                #endregion
            }
            else if (item == this.tiHTML_SOURCE)
            {
                if (this._source == null)
                {
                    return;
                }

                #region tiHTML_SOURCE
                try
                {
                    foreach (TextRange range in previous_SOURCE_textRanges)
                    {
                        range.ApplyPropertyValue(TextElement.BackgroundProperty, getBrush(Colors.Transparent));
                    }

                    if (string.IsNullOrEmpty(txt.Text))
                    {
                        return;
                    }

                    MatchCollection matches = Regex.Matches(_source.Replace(Environment.NewLine, string.Empty), txt.Text);
                    foreach (Match match in matches)
                    {
                        int         index    = 0;
                        TextPointer position = this.rtbHTML_SOURCE.Document.ContentStart;
                        TextPointer start    = null;
                        TextPointer end      = null;
                        while (position != null)
                        {
                            if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                            {
                                string text = position.GetTextInRun(LogicalDirection.Forward);
                                if (index <= match.Index && (index + text.Length) > match.Index)
                                {
                                    start = position.GetPositionAtOffset(match.Index - index);
                                }
                                if (index <= (match.Index + match.Length) && (index + text.Length) > (match.Index + match.Length))
                                {
                                    end = position.GetPositionAtOffset(match.Index + match.Length - index);
                                }
                                index += text.Length;
                            }

                            if (start != null && end != null)
                            {
                                break;
                            }

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

                        if (start != null && end != null)
                        {
                            TextRange range = new TextRange(start, end);
                            range.ApplyPropertyValue(TextElement.BackgroundProperty, getBrush(0xFF, 0x7F, 0xFF));
                            this.previous_SOURCE_textRanges.Add(range);
                        }
                    }
                }
                catch (Exception)
                {
                    txt.Foreground = getBrush(Colors.Red);
                }

                #endregion
            }
            else if (item == this.tiHTML_DocumentViewer)
            {
                ;                                          // Do nothing.
            }
            else
            {
                throw new NotSupportedException();
            }
        }
Example #2
0
        public static void ChangeColor(string l, RichTextBox richBox, string keyword)
        {
            //设置文字指针为Document初始位置
            // richBox.Document.FlowDirection
            TextPointer position = richBox.Document.ContentStart, old = richBox.Selection.Start;

            while (position != null)
            {
                //向前搜索,需要内容为Text
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    //拿出Run的Text
                    string text = position.GetTextInRun(LogicalDirection.Forward);
                    //可能包含多个keyword,做遍历查找
                    int index = 0;
                    while (index < text.Length)
                    {
                        index = text.IndexOf(keyword, index);
                        if (index == -1)
                        {
                            break;
                        }
                        else
                        {
                            if (index - 1 >= 0)
                            {
                                foreach (var c in RichTextEditor.HighLightEdit.ignore)
                                {
                                    if (c == text[index - 1])
                                    {
                                        goto keywordend;
                                    }
                                }
                                break;
                            }
keywordend:
                            if (index + keyword.Length < text.Length)
                            {
                                foreach (var c in RichTextEditor.HighLightEdit.ignore)
                                {
                                    if (c == text[index + keyword.Length])
                                    {
                                        goto addrange;
                                    }
                                }
                                break;
                            }
addrange:
                            //添加为新的Range
                            TextPointer start = position.GetPositionAtOffset(index);
                            TextPointer end  = start.GetPositionAtOffset(keyword.Length);
                            TextPointer end1 = start.GetPositionAtOffset(index + keyword.Length);
                            selecta(l, richBox, keyword.Length, start, end);

                            index += keyword.Length;
                        }
                    }
                }
                //文字指针向前偏移
                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }
            richBox.Selection.Select(old, old);
        }
Example #3
0
        /// <summary>
        /// Replace Emoji characters with EmojiInline objects inside the document.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnTextChanged(TextChangedEventArgs e)
        {
            if (m_pending_change)
            {
                return;
            }

            m_pending_change = true;

            base.OnTextChanged(e);

            // Prevent our operation from polluting the undo buffer
            BeginChange();

            TextPointer cur = Document.ContentStart;

            while (cur.CompareTo(Document.ContentEnd) < 0)
            {
                TextPointer next = cur.GetNextInsertionPosition(LogicalDirection.Forward);
                if (next == null)
                {
                    break;
                }

                var emoji_range = new TextRange(cur, next);
                if (EmojiData.MatchOne.IsMatch(emoji_range.Text))
                {
                    // Preserve caret position
                    bool caret_was_next = (0 == next.CompareTo(CaretPosition));

                    // We found an emoji, but it’s possible that GetNextInsertionPosition
                    // did not pick enough characters and the emoji sequence is actually
                    // longer. To avoid this, we look up to 50 characters ahead and retry
                    // the match.
                    var lookup = next.GetNextContextPosition(LogicalDirection.Forward);
                    if (cur.GetOffsetToPosition(lookup) > 50)
                    {
                        lookup = cur.GetPositionAtOffset(50, LogicalDirection.Forward);
                    }
                    var full_text = new TextRange(cur, lookup).Text;
                    var match     = EmojiData.MatchOne.Match(new TextRange(cur, lookup).Text);
                    while (match.Length > emoji_range.Text.Length)
                    {
                        next = next.GetNextInsertionPosition(LogicalDirection.Forward);
                        if (next == null)
                        {
                            break;
                        }
                        emoji_range = new TextRange(cur, next);
                    }

                    var font_size  = emoji_range.GetPropertyValue(TextElement.FontSizeProperty);
                    var foreground = emoji_range.GetPropertyValue(TextElement.ForegroundProperty);

                    // Delete the Unicode characters and insert our emoji inline instead.
                    emoji_range.Text = "";
                    Inline inline = new EmojiInline(cur)
                    {
                        FontSize   = (double)(font_size ?? FontSize),
                        Foreground = (Brush)(foreground ?? Foreground),
                        Text       = match.Value,
                    };

                    next = inline.ContentEnd;
                    if (caret_was_next)
                    {
                        CaretPosition = next;
                    }
                }

                cur = next;
            }

            EndChange();

            // FIXME: make this call lazy inside Text.get()
            SetValue(TextProperty, new TextSelection(Document.ContentStart, Document.ContentEnd).Text);

            m_pending_change = false;
#if DEBUG
            try
            {
                var xaml = XamlWriter.Save(Document);
                xaml = Regex.Replace(xaml, "<FlowDocument[^>]*>", "<FlowDocument>");
                SetValue(XamlTextProperty, xaml);
            }
            catch { }
#endif
        }
Example #4
0
        /// <summary>
        /// Finds the corresponding<see cref="TextRange"/> instance
        /// representing the input string given a specified text pointer position.
        /// </summary>
        /// <param name="position">the current text position</param>
        /// <param name="textToFind">input text</param>
        /// <param name="findOptions">the search option</param>
        /// <returns>
        /// An<see cref="TextRange"/> instance represeneting the matching
        /// string withing the text container.
        /// </returns>
        public TextRange GetTextRangeFromPosition(ref TextPointer position,
                                                  String input,
                                                  FindOptions findOptions)
        {
            Boolean matchCase      = (findOptions & FindOptions.MatchCase) == FindOptions.MatchCase;
            Boolean matchWholeWord = (findOptions & FindOptions.MatchWholeWord)
                                     == FindOptions.MatchWholeWord;

            TextRange textRange = null;

            while (position != null)
            {
                if (position.CompareTo(inputDocument.ContentEnd) == 0)
                {
                    break;
                }

                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    String           textRun          = position.GetTextInRun(LogicalDirection.Forward);
                    StringComparison stringComparison = matchCase ?
                                                        StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
                    Int32 indexInRun = textRun.IndexOf(input, stringComparison);

                    if (indexInRun >= 0)
                    {
                        position = position.GetPositionAtOffset(indexInRun);
                        TextPointer nextPointer = position.GetPositionAtOffset(input.Length);
                        textRange = new TextRange(position, nextPointer);

                        if (matchWholeWord)
                        {
                            if (IsWholeWord(textRange)) // Test if the "textRange" represents a word.
                            {
                                // If a WholeWord match is found, directly terminate the loop.
                                position = position.GetPositionAtOffset(input.Length);
                                break;
                            }
                            else
                            {
                                // If a WholeWord match is not found, go to next recursion to find it.
                                position = position.GetPositionAtOffset(input.Length);
                                return(GetTextRangeFromPosition(ref position, input, findOptions));
                            }
                        }
                        else
                        {
                            // If a none-WholeWord match is found, directly terminate the loop.
                            position = position.GetPositionAtOffset(input.Length);
                            break;
                        }
                    }
                    else
                    {
                        // If a match is not found, go over to the next context position after the "textRun".
                        position = position.GetPositionAtOffset(textRun.Length);
                    }
                }
                else
                {
                    //If the current position doesn't represent a text context position, go to the next context position.
                    // This can effectively ignore the formatting or embed element symbols.
                    position = position.GetNextContextPosition(LogicalDirection.Forward);
                }
            }

            if (textRange != null)
            {
                return(new TextRange(textRange.Start, textRange.Start.GetPositionAtOffset(input.Length)));
            }
            return(null);
        }
Example #5
0
        private bool BoldTextFromPosition(TextPointer position, string word, bool red, bool green)
        {
            TextRange   range;
            Object      obj;
            int         indexInRun;
            string      textRun;
            FontWeight  fontWeight;
            TextPointer start, end;
            TextRange   selection;
            string      pattern = @"[a-zA-Zа-яА-Я0-9]";
            bool        fl;

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

                    indexInRun = textRun.IndexOf(word, StringComparison.CurrentCultureIgnoreCase);
                    while (indexInRun != -1)
                    {
                        //проверка окаймляющих символов - должны быть nonword
                        fl = false; // -  не найдены word символы
                        // символ перед словом
                        start = position.GetPositionAtOffset(indexInRun - 1);
                        range = new TextRange(start, start.GetPositionAtOffset(1));
                        if (Regex.IsMatch(range.Text, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase))
                        {
                            fl = true;
                        }

                        // символ после слова
                        start = position.GetPositionAtOffset(indexInRun + word.Length);
                        range = new TextRange(start, start.GetPositionAtOffset(1));
                        if (Regex.IsMatch(range.Text, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase))
                        {
                            fl = true;
                        }

                        //конец проверка окаймляющих символов - должны быть nonword

                        if (!fl)
                        {
                            start      = position.GetPositionAtOffset(indexInRun);
                            range      = new TextRange(start, start.GetPositionAtOffset(1));
                            obj        = range.GetPropertyValue(TextElement.FontWeightProperty);
                            fontWeight = (FontWeight)obj;
                            if (fontWeight == FontWeights.Normal)
                            {
                                end       = start.GetPositionAtOffset(word.Length);
                                selection = new TextRange(start, end);
                                selection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                                if (red)
                                {
                                    selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
                                }
                                if (green)
                                {
                                    selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Aqua);
                                }

                                return(true);
                            }
                        }

                        indexInRun = textRun.IndexOf(word, indexInRun + 1, StringComparison.CurrentCultureIgnoreCase);
                    }
                    position = position.GetPositionAtOffset(textRun.Length);
                }
                else
                {
                    position = position.GetNextContextPosition(LogicalDirection.Forward);
                }
            }
            return(false);
        }
Example #6
0
        private void DelNote_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var im = sender as System.Windows.Controls.Image;

            if (im == null)
            {
                return;
            }
            var key = im.Tag.ToString();

            if (key == null)
            {
                return;
            }
            byte[] flag = getJPGFromImageControl(Properties.Resources.noteFlag);
            Notes[key].Range.ApplyPropertyValue(TextElement.BackgroundProperty, null);
            for (TextPointer position = Notes[key].Range.Start; position != null && position.CompareTo(Notes[key].Range.End) != 1; position = position.GetNextContextPosition(LogicalDirection.Forward))
            {
                InlineUIContainer element = position.Parent as InlineUIContainer;
                if (element != null && element.Child is System.Windows.Controls.Image)
                {
                    var image = element.Child as System.Windows.Controls.Image;
                    if (image == null)
                    {
                        continue;
                    }
                    var imageSourse = image.Source as System.Windows.Media.ImageSource;
                    if (imageSourse == null)
                    {
                        continue;
                    }
                    byte[] byt = getJPGFromImageControl(imageSourse);
                    //сравнивает картинки
                    if (byt.Length == flag.Length)
                    {
                        bool isflag = true;
                        for (int t = 0; t < byt.Length; t++)
                        {
                            if (byt[t] != flag[t])
                            {
                                isflag = false; break;
                            }
                        }
                        if (!isflag)
                        {
                            continue;
                        }
                        element.SiblingInlines.Remove(element);
                        //new TextRange(element.ContentStart, element.ContentEnd).Text = string.Empty;
                    }
                }
            }
            Notes.Remove(im.Tag.ToString());
            OnSave(() => { }, ParentControl.BrowseProject.LoadedFile);
            MainControl.Items.Refresh();
        }
        /// <summary>
        /// Find the corresponding <see cref="TextRange"/> instance
        /// representing the input string given a specified text pointer position.
        /// </summary>
        /// <param name="position">the current text position</param>
        /// <param name="textToFind">input text</param>
        /// <param name="findOptions">the search option</param>
        /// <returns>An <see cref="TextRange"/> instance represeneting the matching string withing the text container.</returns>
        public TextRange GetTextRangeFromPosition(ref TextPointer position, String input, FindOptions findOptions)
        {
            Boolean matchCase      = findOptions.MatchCase;
            Boolean matchWholeWord = findOptions.MatchWholeWord;

            TextRange textRange = null;

            while (position != null)
            {
                if (position.CompareTo(inputDocument.ContentEnd) == 0) //到了文档结尾
                {
                    break;
                }
                //是文本元素
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    String           textRun          = position.GetTextInRun(LogicalDirection.Forward); //读取文本
                    StringComparison stringComparison = matchCase ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
                    //进行查找
                    Int32 indexInRun = textRun.IndexOf(input, stringComparison);

                    if (indexInRun >= 0)                                                      //找到了
                    {
                        position = position.GetPositionAtOffset(indexInRun);                  //移动文字指针到开头
                        TextPointer nextPointer = position.GetPositionAtOffset(input.Length); //设定匹配项尾文字指针
                        textRange = new TextRange(position, nextPointer);

                        if (matchWholeWord)             //是全字匹配的话
                        {
                            if (IsWholeWord(textRange)) // 测试匹配项是否是一个单词
                            {
                                // 是一个完整的单词
                                break;
                            }
                            else
                            {
                                // 找到的不是一个完整的单词,继续在本Run元素中查找
                                position = position.GetPositionAtOffset(input.Length);
                                return(GetTextRangeFromPosition(ref position, input, findOptions));
                            }
                        }
                        else
                        {
                            //不要求全字匹配
                            position = position.GetPositionAtOffset(input.Length);
                            break;
                        }
                    }
                    else
                    {
                        // 没找到匹配项,移到当前的Run元素之后 "textRun".
                        position = position.GetPositionAtOffset(textRun.Length);
                    }
                }
                else
                {
                    //如果当前位置不是文本类型的元素,继续"前进",跳过这些非文本元素.
                    position = position.GetNextContextPosition(LogicalDirection.Forward);
                }
            }

            return(textRange);
        }
Example #8
0
        private void TextChangedEventHandler(object sender, TextChangedEventArgs e)
        {
            if (rtbEditor.Document == null)
            {
                return;
            }

            printLineNumbers();

            foreach (TextChange C in e.Changes)
            {
                TextPointer P = rtbEditor.Document.ContentStart.GetPositionAtOffset(C.Offset);
                if (P.Paragraph != null)
                {
                    P.Paragraph.Tag = null;                      //It needs reformatting
                }
            }

            if (rtbEditor.Document.Blocks.Count > 0)
            {
                Block B = rtbEditor.Document.Blocks.FirstBlock;
                while (B != null)
                {
                    if (B is Paragraph)
                    {
                        Paragraph P = B as Paragraph;
                        if (P.Tag == null)
                        {
                            TextRange documentRange = new TextRange(P.ContentStart, P.ContentEnd);
                            documentRange.ClearAllProperties();

                            TextPointer navigator = P.ContentStart;
                            while (navigator.CompareTo(P.ContentEnd) < 0)
                            {
                                TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward);
                                if (context == TextPointerContext.ElementStart && navigator.Parent is Run)
                                {
                                    CheckWordsInRun((Run)navigator.Parent);
                                }
                                navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
                            }

                            P.Tag = true; //It has been highlighted
                        }
                    }
                    else
                    {
                        throw new Exception("Unknown block type " + B.ToString());
                    }
                    B = B.NextBlock;
                }
            }



/*
 *          TextRange documentRange = new TextRange(rtbEditor.Document.ContentStart, rtbEditor.Document.ContentEnd);
 *          documentRange.ClearAllProperties();
 *
 *          TextPointer navigator = rtbEditor.Document.ContentStart;
 *          while (navigator.CompareTo(rtbEditor.Document.ContentEnd) < 0)
 *          {
 *              TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward);
 *              if (context == TextPointerContext.ElementStart && navigator.Parent is Run)
 *              {
 *                  CheckWordsInRun((Run)navigator.Parent);
 *
 *              }
 *              navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
 *          }
 */
            Format();
        }
Example #9
0
        private Tuple <List <TextRange>, List <double[]> > get_range(Point p, double w, double h) // 上下k行
        {
            List <TextRange> select = new List <TextRange>();

            var pos = richTextBox.GetPositionFromPoint(p, true);

            if (pos == null)
            {
                return(new Tuple <List <TextRange>, List <double[]> >(select, new List <double[]>()));
            }
            TextPointer begin = pos.GetLineStartPosition(-1);

            //  TextPointer lastEnd = poz.DocumentEnd.GetLineStartPosition(-3);
            if (begin == null)
            {
                begin = pos.DocumentStart;
            }
            if (begin.CompareTo(pos.DocumentEnd) < -1)
            {
                begin = pos.DocumentStart;
            }

            /*if (begin != null && lastEnd != null && begin.CompareTo(lastEnd) > 0)
             * {
             *  begin = lastEnd;
             * }*/
            TextPointer end = pos.GetLineStartPosition(1);

            begin = begin.GetPositionAtOffset(2);  //?? Magic 2
            Rect            beginR    = begin.GetCharacterRect(LogicalDirection.Forward);
            List <double[]> arrayPos  = new List <double[]>();
            TextPointer     lineBegin = begin;

            //Console.WriteLine("========================");
            while (begin != null)
            {
                if (end != null && begin.CompareTo(end) > -1)
                {
                    break;
                }
                if (begin.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    string   text       = begin.GetTextInRun(LogicalDirection.Forward);
                    string[] words      = text.Split(' ');
                    int      startIndex = 0;

                    foreach (var word in words)
                    {
                        if (word.Length > 0)
                        {
                            // Console.WriteLine("startIndes:{0}, word.length:{1}", startIndex, word.Length);
                            TextPointer headP = lineBegin.GetPositionAtOffset(startIndex, LogicalDirection.Forward);
                            TextPointer tailP = lineBegin.GetPositionAtOffset(startIndex + word.Length, LogicalDirection.Forward);
                            // Console.WriteLine(new TextRange(headP, tailP).Text + "|");
                            //Console.WriteLine(new TextRange(headP, lineBegin.GetPositionAtOffset(startIndex+word.Length+1, LogicalDirection.Forward)).Text + "|");
                            //Console.WriteLine(new TextRange(headP, lineBegin.GetPositionAtOffset(startIndex + word.Length + 2, LogicalDirection.Forward)).Text + "|");
                            bool dealed = false;
                            // Console.WriteLine("{0}", headP.GetLineStartPosition(0).CompareTo(lineBegin.GetLineStartPosition(0)));
                            if (headP.GetLineStartPosition(0).CompareTo(lineBegin.GetLineStartPosition(0)) != 0 /*||
                                                                                                                 * (headP.GetLineStartPosition(0).CompareTo(lineBegin.GetLineStartPosition(0)) == 0 &&
                                                                                                                 * beginR.X + (startIndex + word.Length) * Config.fontWidth > richTextBox.ActualWidth)*/)
                            {
                                dealed = true;
                                //beginR = headP.GetCharacterRect(LogicalDirection.Forward);
                                beginR.Y  += beginR.Height;
                                beginR.X   = 0;
                                lineBegin  = headP;
                                startIndex = 0;
                            }

                            //Rect head = headP.GetCharacterRect(LogicalDirection.Forward);
                            //Rect tail = tailP.GetCharacterRect(LogicalDirection.Backward);
                            Rect head = new Rect();
                            Rect tail = new Rect();
                            head.X      = beginR.X + startIndex * Config.fontWidth;
                            head.Y      = beginR.Y;
                            head.Height = beginR.Height;
                            tail.X      = beginR.X + (startIndex + word.Length) * Config.fontWidth;
                            tail.Y      = beginR.Y;
                            tail.Height = beginR.Height;
                            if (tailP.GetLineStartPosition(0).CompareTo(headP.GetLineStartPosition(0)) != 0 && !dealed) //如果换行
                            {
                                //Rect tp = tailP.GetCharacterRect(LogicalDirection.Backward);
                                //tail = tp;
                                head.X     = 0;
                                head.Y    += head.Height;
                                tail.X     = (word.Length * Config.fontWidth);
                                tail.Y    += head.Height;
                                lineBegin  = tailP;
                                beginR.Y  += head.Height;
                                beginR.X   = tail.X;
                                startIndex = -(word.Length);
                                //if (tp.X > 0)
                                //{
                                //    head.Y = tp.Y;
                                //    head.X = 0;
                                //    head.Height = tp.Height;
                                //}
                            }
                            //Console.WriteLine("{0},{1},{2}, {3}", word, head.X, tail.X, tailP.GetLineStartPosition(0).CompareTo(headP.GetLineStartPosition(0)));
                            if (!(head.X > (p.X + w) || tail.X < (p.X - w)) && !(head.Y > (p.Y + h + head.Height + 5) || head.Y - head.Height < (p.Y - h - head.Height - 5)))
                            {
                                if ((arrayPos.Count == 0) || Math.Abs(arrayPos.Last()[0] - head.Y) > Double.Epsilon)
                                {
                                    arrayPos.Add(new double[3]);
                                    arrayPos.Last()[0] = head.Y;
                                    arrayPos.Last()[1] = head.X;
                                    arrayPos.Last()[2] = tail.X;
                                }
                                else
                                {
                                    arrayPos.Last()[1] = Math.Min(arrayPos.Last()[1], head.X);
                                    arrayPos.Last()[2] = Math.Max(arrayPos.Last()[2], tail.X);
                                }
                                select.Add(new TextRange(headP, tailP));
                                //Console.WriteLine("in:" + textRange.Text);
                            }
                        }
                        startIndex += (word.Length + 1);
                    }
                }
                begin = begin.GetNextContextPosition(LogicalDirection.Forward);
            }



            /*if (end != null)
             * {
             *  end = poz.DocumentEnd;
             * }*/
            //List<TextRange> allTextRanges = GetAllWordRanges(begin, end).ToList();

            // Console.WriteLine(arrayPos);
            return(new Tuple <List <TextRange>, List <double[]> >(select, arrayPos));
        }
        private void commandEnterPressed(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                TextRange range1 = new TextRange(rtbEditor.Document.ContentStart, rtbEditor.Document.ContentEnd);

                range1.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Black));

                string key = commandLine.Text;

                string[] k = key.Split(null);

                lblAction.Text = k[0];

                if (k[0].ToLower() == "save")
                {
                    if (k[1] != null)
                    {
                        if (k[1].ToLower() == "as")
                        {
                            FileStream fileStream = new FileStream(k[2], FileMode.Create);

                            TextRange range = new TextRange(rtbEditor.Document.ContentStart, rtbEditor.Document.ContentEnd);

                            range.Save(fileStream, DataFormats.Rtf);
                        }
                    }

                    else
                    {
                        Save_Executed(sender, null);
                    }

                    commandLine.Text = "";
                }

                else if (k[0].ToLower() == "open")
                {
                    if (k[1] != null)
                    {
                        FileStream fileStream = new FileStream(k[1], FileMode.Open);

                        TextRange range = new TextRange(rtbEditor.Document.ContentStart, rtbEditor.Document.ContentEnd);

                        range.Load(fileStream, DataFormats.Rtf);
                    }

                    commandLine.Text = "";
                }

                else if (k[0].ToLower() == "find")
                {
                    int n = 0;

                    try
                    {
                        int h = Int32.Parse(k[2]);

                        if (h > 0)
                        {
                            n = h;
                        }
                    }

                    catch (Exception a) { }

                    var str = k[1].Split('/');

                    int num = 0;

                    rtbEditor.SelectAll();

                    TextPointer start = rtbEditor.Selection.Start.GetLineStartPosition(currentLine - 1 + n);

                    TextPointer end = rtbEditor.Selection.Start.GetLineStartPosition(currentLine + num - 1);

                    TextRange range = new TextRange(start, end);

                    Regex reg = new Regex(str[1], RegexOptions.Compiled | RegexOptions.IgnoreCase);

                    while (start != null && start.CompareTo(end) < 0)
                    {
                        if (start.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                        {
                            var match = reg.Match(start.GetTextInRun(LogicalDirection.Forward));

                            var textrange = new TextRange(start.GetPositionAtOffset(match.Index, LogicalDirection.Forward), start.GetPositionAtOffset(match.Index + match.Length, LogicalDirection.Backward));

                            textrange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));

                            start = textrange.End;
                        }

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

                    commandLine.Text = "Press enter to turn text back to black";
                }

                else if (k[0].ToLower() == "up")
                {
                    int num = 1;

                    if (k[1] != null)
                    {
                        bool isNumeric = int.TryParse(k[1], out num);

                        if (!isNumeric)
                        {
                            num = 1;
                        }
                    }

                    for (int i = 0; i < num; i++)
                    {
                        UpButton_Click(sender, null);
                    }

                    commandLine.Text = "";
                }

                else if (k[0].ToLower() == "down")
                {
                    int num = 1;

                    if (k[1] != null)
                    {
                        bool isNumeric = int.TryParse(k[1], out num);

                        if (!isNumeric)
                        {
                            num = 1;
                        }
                    }

                    for (int i = 0; i < num; i++)
                    {
                        DownButton_Click(sender, null);
                    }

                    commandLine.Text = "";
                }
                else if (k[0].ToLower() == "i")
                {
                    int num = 1;
                    if (k[1] != null)
                    {
                        bool isNumeric = int.TryParse(k[1], out num);
                        if (!isNumeric)
                        {
                            num = 1;
                        }
                    }
                    for (int i = 0; i < num; i++)
                    {
                        // File.AppendText("\n");
                        //Lines();
                    }

                    commandLine.Text = "";
                }
                else if (k[0].ToLower() == "forward")
                {
                    for (int i = 0; i < Lines(); i++)
                    {
                        forwardButton_Click(sender, null);
                    }
                    commandLine.Text = "";
                }

                else if (k[0].ToLower() == "backward")
                {
                    for (int i = 0; i < Lines(); i++)
                    {
                        backButton_Click(sender, null);
                    }
                    commandLine.Text = "";
                }

                else if (k[0].ToLower() == "left")
                {
                    int num = 1;

                    if (k[1] != null)
                    {
                        bool isNumeric = int.TryParse(k[1], out num);

                        if (!isNumeric)
                        {
                            num = 1;
                        }
                    }

                    for (int i = 0; i < num; i++)
                    {
                        LeftButton_Click(sender, null);
                    }

                    commandLine.Text = "";
                }

                else if (k[0].ToLower() == "right")
                {
                    int num = 1;

                    if (k[1] != null)
                    {
                        bool isNumeric = int.TryParse(k[1], out num);

                        if (!isNumeric)
                        {
                            num = 1;
                        }
                    }

                    for (int i = 0; i < num; i++)
                    {
                        RightButton_Click(sender, null);
                    }

                    commandLine.Text = "";
                }

                else if (k[0].ToLower() == "change")
                {
                    var str = k[1].Split('/');

                    int num = 0;

                    bool isNumeric = int.TryParse(str[3], out num);

                    int n = 0;

                    int h = Int32.Parse(str[3]);

                    if (h > 0)
                    {
                        n = h;
                    }

                    rtbEditor.SelectAll();

                    TextPointer start = rtbEditor.Selection.Start.GetLineStartPosition(currentLine - 1 + n);

                    TextPointer end = rtbEditor.Selection.Start.GetLineStartPosition(currentLine + num - 1 + n);

                    TextRange range = new TextRange(start, end);

                    String txt = new TextRange(start, end).Text;

                    txt = txt.Replace(str[1], str[2]);

                    if (txt != new TextRange(start, end).Text)
                    {
                        new TextRange(start, end).Text = txt; // Change the current text to _Text
                    }
                }

                else if (k[0].ToLower() == "setcl")
                {
                    int num = 1;
                    if (k[1] != null)
                    {
                        bool isNumeric = int.TryParse(k[1], out num);
                        //  int deneme = Convert.ToInt16(k[1]);//str[0];

                        //  num = int.Parse(k[1]);
                        if (!isNumeric)
                        {
                            num = 1;
                        }
                        //  currentLine = num;
                    }
                    //  Console.WriteLine(deneme);

                    /*
                     *
                     * TextPointer start = rtbEditor.Selection.Start.GetLineStartPosition(currentLine - 1);
                     *
                     *  TextPointer end = rtbEditor.Selection.Start.GetLineStartPosition(currentLine + num - 1);
                     * int someBigNumber = int.MaxValue;
                     *
                     * int lineMoved, currentLineNumber;
                     *
                     * suffix.Selection.Start.GetLineStartPosition(-someBigNumber, out lineMoved);
                     *
                     * currentLineNumber = -lineMoved;
                     *
                     *
                     */
                    var textToSync = (sender == rtbEditor) ? suffix : rtbEditor;

                    textToSync.ScrollToVerticalOffset(num);

                    textToSync.ScrollToHorizontalOffset(num);

                    //   TextPointer start = rtbEditor.Selection.Start.GetLineStartPosition(num);

                    // TextPointer end = rtbEditor.Selection.Start.GetLineStartPosition(num);
                    //currentLine = num;
                    commandLine.Text = "";
                }

                else if (k[0].ToLower() == "help")
                {
                    Help_Click(e, null);
                }

                else
                {
                    int num;

                    bool isNumeric = int.TryParse(k[0], out num);

                    if (isNumeric)
                    {
                        rtbEditor.ScrollToHome();

                        for (int i = 0; i < num - 1; i++)
                        {
                            DownButton_Click(sender, null);
                        }

                        rtbEditor.SelectAll();

                        TextPointer start = rtbEditor.Selection.Start.GetLineStartPosition(num - 1);

                        TextPointer end = rtbEditor.Selection.Start.GetLineStartPosition(num);

                        var textrange = new TextRange(start, end);

                        textrange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
                    }

                    else
                    {
                        commandLine.Text = "Type help for options";
                    }
                }
            }
        }
Example #11
0
        /// <summary>
        /// <para>Gets a TextPointer to a text character offset in the FlowDocument.</para>
        /// <para>Notes:</para>
        /// <para>This method searches for next character-offset TextPointer in a forward direction.</para>
        /// <para>Search iterates through text blocks and determines if character offset is within current
        /// text block (instead of searching every character.)</para>
        /// <para>If CharOffset is beyond FlowDocument, an end-of-document TextPointer is returned.</para>
        /// <para>Tabs in a Paragraph's Margin Left or TextIndent property are not counted
        /// as tab characters.</para>
        /// <para>Assumes newlines are "\r\n" characters.</para>
        /// <para>Multiple calls can be made without reseting text position fields to speed up
        /// finding Textpointers.</para>
        /// <para>If one is operating in a forward order, one can use the obtained TextPointers to create
        /// TextRanges and call ApplyPropertyValue method without needing to reset text positions to start.</para>
        /// </summary>
        /// <param name="CharOffset">The text character offset in the FlowDocument.</param>
        /// <param name="ResetToStart">Whether or not to reset text positions to start of FlowDocument before
        /// next search.</param>
        /// <returns>The TextPointer if found, or an end-of-document TextPointer.</returns>
        public TextPointer GetTextPointer(int CharOffset, bool ResetToStart)
        {
            #region Strategy
            // The goal is to count Text run lengths until CharOffset is within a Text run.
            // Characters also need to be added to the count for end of Paragraph and Linebreak
            // (which in the text string is signified as "\r\n" characters)
            //
            // The CharOffset is considered to be inside the run if the caret (textpointer) is positioned
            // before the first character of the run, or after the last character of the run (to
            // keep the textpointer within the run.)
            //
            // i_start: character index of start of current run
            // i_end: character index of end of current run
            #endregion

            if (ResetToStart)
            {
                this.ResetToStart();
            }

            // loop until end of doc
            while (this.navigator.CompareTo(this.endOfDoc) < 0)
            {
                // switch pointer context
                switch (this.navigator.GetPointerContext(LogicalDirection.Forward))
                {
                case TextPointerContext.ElementEnd:
                {
                    DependencyObject d = this.navigator.GetAdjacentElement(LogicalDirection.Forward);
                    if (d is Paragraph || d is LineBreak)
                    {
                        // Add 2 for linebreak: "\r\n"
                        // Note: Text in a TextRange between to TextPointers inserts "\r\n" at
                        // end of a Paragraph and end of LinkBreak
                        this.i_start += 2;
                    }
                    break;
                }

                case TextPointerContext.Text:
                {
                    // 0 1 2 3 4 5 6
                    // a b c d e X

                    // calc character index of end of current run
                    int i_end = this.i_start + this.navigator.GetTextRunLength(LogicalDirection.Forward);

                    // case: character offset is within current run
                    if (CharOffset <= i_end)
                    {
                        // calc offset within current run
                        int offset = CharOffset - this.i_start;

                        // return text pointer to character offset
                        return(this.navigator.GetPositionAtOffset(offset, LogicalDirection.Forward));
                    }

                    // calc character index to next text run (if it exists)
                    this.i_start = i_end;
                    break;
                }
                }
                // Advance the naviagtor to the next context position.
                this.navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
            }

            // case: counter index went past CharOffset and last paragraph and there is no more
            // text runs to check for CharOffset: therefore, return end-of-doc text pointer
            if (this.i_start != 0 && CharOffset <= this.i_start)
            {
                return(this.endOfDoc.GetNextInsertionPosition(LogicalDirection.Backward));
            }

            // default: not found
            return(this.endOfDoc);
        }
        private void tb_class_text_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (this.tb_class_text.Document == null)
            {
                return;
            }

            // this prevents infinite loops
            this.tb_class_text.TextChanged -= tb_class_text_TextChanged;

            this.keywords.Clear();
            this.specialwords.Clear();

            //clear all formats
            TextRange documentRange = new TextRange(this.tb_class_text.Document.ContentStart, this.tb_class_text.Document.ContentEnd);

            documentRange.ClearAllProperties();

            // save caret position
            TextPointer caretPos = this.tb_class_text.CaretPosition;
            int         offset   = caretPos.GetOffsetToPosition(this.tb_class_text.Document.ContentStart);

            // combine runs (user input is placed in a new run...)
            Dictionary <Paragraph, string> current_content = new Dictionary <Paragraph, string>();
            var rtb_blocks = this.tb_class_text.Document.Blocks;

            foreach (var block in rtb_blocks)
            {
                Paragraph p = block as Paragraph;
                if (p != null)
                {
                    // combine runs in the paragraph
                    var    inlines   = p.Inlines;
                    string p_content = "";
                    foreach (var inline in inlines)
                    {
                        Run r = inline as Run;
                        if (r != null)
                        {
                            p_content += r.Text;
                        }
                    }
                    current_content.Add(p, p_content);
                }
            }
            foreach (var entry in current_content)
            {
                entry.Key.Inlines.Clear();
                entry.Key.Inlines.Add(new Run(entry.Value));
            }

            // restore caret position
            this.tb_class_text.CaretPosition = this.tb_class_text.Document.ContentStart.GetPositionAtOffset(-offset + this.caret_offset_add, caretPos.LogicalDirection);

            // find all keywords
            TextPointer navigator = this.tb_class_text.Document.ContentStart;

            while (navigator.CompareTo(this.tb_class_text.Document.ContentEnd) < 0)
            {
                TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward);
                if (context == TextPointerContext.ElementStart && navigator.Parent is Run)
                {
                    string text_snippet = ((Run)navigator.Parent).Text;
                    if (text_snippet != "")
                    {
                        LookForKeyordsInRun((Run)navigator.Parent, text_snippet);
                    }
                }
                navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
            }

            //only after all keywords are found, then we highlight them
            for (int i = 0; i < this.keywords.Count; i++)
            {
                try
                {
                    TextRange range = new TextRange(this.keywords[i].start_pos, this.keywords[i].end_pos);
                    range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));
                    range.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                }
                catch { }
            }
            for (int i = 0; i < this.specialwords.Count; i++)
            {
                try
                {
                    TextRange range = new TextRange(this.specialwords[i].start_pos, this.specialwords[i].end_pos);
                    range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ff008ab7")));
                }
                catch { }
            }

            // this prevents infinite loops
            this.tb_class_text.TextChanged += tb_class_text_TextChanged;
        }
Example #13
0
        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));
        }
Example #14
0
        void advanceColor_Click(object sender, RoutedEventArgs e)
        {
            DialogWindowBrushColor dialoWindow = new DialogWindowBrushColor();

            dialoWindow.Owner = Application.Current.MainWindow;

            Lovatts.ColorEditor.BrushEditor brushEditor = (Lovatts.ColorEditor.BrushEditor)dialoWindow.Content;
            brushEditor.ParentWindow = dialoWindow;

            if (dialoWindow.ShowDialog() == true)
            {
                Brush newBrush = brushEditor.BrushEditorViewModel.Brush;

                MainWindow mainWindow = (MainWindow)Application.Current.MainWindow;

                ColorButton colorButton = new ColorButton(CustomRichTextBox, Grid, newBrush, stackPanelRecentColor, DropButton, RectangleColor);

                if (mainWindow.RecentColorCollection.Count < 7)
                {
                    stackPanelRecentColor.Children.Add(colorButton);

                    mainWindow.RecentColorCollection.Add(colorButton);
                }
                else
                {
                    mainWindow.RecentColorCollection.RemoveAt(0);
                    mainWindow.RecentColorCollection.Add(colorButton);

                    stackPanelRecentColor.Children.RemoveAt(0);
                    stackPanelRecentColor.Children.Add(colorButton);
                }

                RectangleColor.Fill = newBrush;

                TextPointer textPoint = CustomRichTextBox.CaretPosition;
                CustomRichTextBox.startTextPointer = null;
                CustomRichTextBox.endTextPointer   = null;

                if (CustomRichTextBox.Selection.IsEmpty)
                {
                    TextElement textElement = null;

                    if (CustomRichTextBox.CaretPosition.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.None)
                    {
                        CustomRichTextBox.IsCreateRunNull = true;

                        CustomRichTextBox.CreateRunTextPointer = CustomRichTextBox.CaretPosition;

                        e.Handled = true;

                        return;
                    }
                    else if (CustomRichTextBox.CaretPosition.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.ElementStart)
                    {
                        textElement = (TextElement)CustomRichTextBox.CaretPosition.GetAdjacentElement(LogicalDirection.Backward);

                        if (textElement is Paragraph)
                        {
                            CustomRichTextBox.IsCreateRunNull = true;

                            CustomRichTextBox.CreateRunTextPointer = CustomRichTextBox.CaretPosition;

                            e.Handled = true;

                            return;
                        }
                        else if (textElement is ListItem)
                        {
                            CustomRichTextBox.IsCreateRunNull = true;

                            CustomRichTextBox.CreateRunTextPointer = CustomRichTextBox.CaretPosition;

                            e.Handled = true;

                            return;
                        }
                    }
                    else if (CustomRichTextBox.CaretPosition.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.ElementEnd)
                    {
                        textElement = (TextElement)CustomRichTextBox.CaretPosition.GetAdjacentElement(LogicalDirection.Backward);

                        if (textElement is LineBreak)
                        {
                            CustomRichTextBox.IsCreateRunNull = true;

                            CustomRichTextBox.CreateRunTextPointer = CustomRichTextBox.CaretPosition;

                            e.Handled = true;

                            return;
                        }
                    }

                    if (textPoint.GetTextRunLength(LogicalDirection.Backward) > 0) // Если позади каретки в текстовом элементе есть текст
                    {
                        TextPointer textPointer = textPoint.GetNextContextPosition(LogicalDirection.Backward);

                        Run run = (Run)textPointer.GetAdjacentElement(LogicalDirection.Backward);

                        TextElement nextBackTextElement = (TextElement)run.ElementStart.GetAdjacentElement(LogicalDirection.Backward);

                        int i = CustomRichTextBox.CaretPosition.GetTextRunLength(LogicalDirection.Backward);

                        TextRange textRange = new TextRange(textPointer, CustomRichTextBox.CaretPosition);

                        int index = textRange.Text.LastIndexOfAny(new char[] { ' ', ',', '.', '?', '!', ':', ';' });

                        if (index != -1)
                        {
                            if (textRange.Text[i - 1] != ' ' && textRange.Text[i - 1] != ',' && textRange.Text[i - 1] != '.' && textRange.Text[i - 1] != '?' && textRange.Text[i - 1] != '!' && textRange.Text[i - 1] != ':' && textRange.Text[i - 1] != ';')
                            {
                                CustomRichTextBox.startTextPointer = CustomRichTextBox.CaretPosition.GetPositionAtOffset(index + 1 - i);
                            }
                            else
                            {
                                CustomRichTextBox.startTextPointer = null;
                            }
                        }
                        else
                        {
                            CustomRichTextBox.IsText = true;

                            CustomRichTextBox.StartTextPointer(nextBackTextElement);
                        }
                    }
                    else
                    {
                        CustomRichTextBox.IsTextNull = true;

                        TextElement nextBackTextElement = (TextElement)CustomRichTextBox.CaretPosition.GetAdjacentElement(LogicalDirection.Backward);

                        if (nextBackTextElement is Run)
                        {
                            nextBackTextElement = (TextElement)nextBackTextElement.ElementStart.GetAdjacentElement(LogicalDirection.Backward);
                        }

                        CustomRichTextBox.StartTextPointer(nextBackTextElement);
                    }

                    CustomRichTextBox.IsTextNull = false;

                    CustomRichTextBox.IsText = false;

                    if (textPoint.GetTextRunLength(LogicalDirection.Forward) > 0) // Если в текстовом элементе впереди каретки есть текст
                    {
                        TextPointer textPointer = textPoint.GetNextContextPosition(LogicalDirection.Forward);

                        Run run = (Run)textPointer.GetAdjacentElement(LogicalDirection.Forward);

                        TextElement nextForwardTextElement = (TextElement)run.ElementEnd.GetAdjacentElement(LogicalDirection.Forward);

                        int i = CustomRichTextBox.CaretPosition.GetTextRunLength(LogicalDirection.Forward);

                        TextRange textRange = new TextRange(CustomRichTextBox.CaretPosition, textPointer);

                        int index = textRange.Text.IndexOfAny(new char[] { ' ', ',', '.', '?', '!', ':', ';' });

                        if (index != -1)
                        {
                            if (textRange.Text[0] != ' ' && textRange.Text[0] != ',' && textRange.Text[0] != '.' && textRange.Text[0] != '?' && textRange.Text[0] != '!' && textRange.Text[0] != ':' && textRange.Text[0] != ';')
                            {
                                CustomRichTextBox.endTextPointer = CustomRichTextBox.CaretPosition.GetPositionAtOffset(index);
                            }
                            else
                            {
                                CustomRichTextBox.endTextPointer = null;
                            }
                        }
                        else
                        {
                            CustomRichTextBox.IsText = true;

                            CustomRichTextBox.EndTextPointer(nextForwardTextElement);
                        }
                    }
                    else
                    {
                        CustomRichTextBox.IsTextNull = true;

                        TextElement nextForwardTextElement = (TextElement)CustomRichTextBox.CaretPosition.GetAdjacentElement(LogicalDirection.Forward);

                        if (nextForwardTextElement is Run)
                        {
                            nextForwardTextElement = (TextElement)nextForwardTextElement.ElementEnd.GetAdjacentElement(LogicalDirection.Forward);
                        }

                        CustomRichTextBox.EndTextPointer(nextForwardTextElement);
                    }

                    CustomRichTextBox.IsText = false;

                    CustomRichTextBox.IsTextNull = false;

                    if (CustomRichTextBox.startTextPointer != null && CustomRichTextBox.endTextPointer != null)
                    {
                        TextRange textRange = new TextRange(CustomRichTextBox.startTextPointer, CustomRichTextBox.endTextPointer);

                        textRange.ApplyPropertyValue(TextElement.ForegroundProperty, newBrush);
                    }
                    else
                    {
                        if (CustomRichTextBox.Run.Foreground is SolidColorBrush && newBrush is SolidColorBrush)
                        {
                            SolidColorBrush runBrush           = CustomRichTextBox.Run.Foreground as SolidColorBrush;
                            SolidColorBrush newSolidColorBrush = newBrush as SolidColorBrush;

                            if (runBrush.Color.A != newSolidColorBrush.Color.A || runBrush.Color.B != newSolidColorBrush.Color.B || runBrush.Color.G != newSolidColorBrush.Color.G || runBrush.Color.R != newSolidColorBrush.Color.R || runBrush.Color.ScA != newSolidColorBrush.Color.ScA || runBrush.Color.ScB != newSolidColorBrush.Color.ScB || runBrush.Color.ScG != newSolidColorBrush.Color.ScG || runBrush.Color.ScR != newSolidColorBrush.Color.ScR || runBrush.Opacity != newSolidColorBrush.Opacity)
                            {
                                CustomRichTextBox.IsCreateRunColor = true;

                                CustomRichTextBox.CreateRunTextPointer = CustomRichTextBox.CaretPosition;
                            }
                            else
                            {
                                CustomRichTextBox.IsCreateRunColor = false;
                            }
                        }
                        else if (CustomRichTextBox.Run.Foreground is LinearGradientBrush && newBrush is LinearGradientBrush)
                        {
                            LinearGradientBrush runBrush = CustomRichTextBox.Run.Foreground as LinearGradientBrush;
                            LinearGradientBrush newLinearGradientBrush = newBrush as LinearGradientBrush;

                            int count = 0;

                            if (runBrush.ColorInterpolationMode != newLinearGradientBrush.ColorInterpolationMode || runBrush.EndPoint != newLinearGradientBrush.EndPoint || runBrush.Opacity != newLinearGradientBrush.Opacity || runBrush.MappingMode != newLinearGradientBrush.MappingMode || runBrush.SpreadMethod != newLinearGradientBrush.SpreadMethod || runBrush.StartPoint != newLinearGradientBrush.StartPoint || runBrush.GradientStops.Count != newLinearGradientBrush.GradientStops.Count)
                            {
                                CustomRichTextBox.IsCreateRunColor = true;

                                CustomRichTextBox.CreateRunTextPointer = CustomRichTextBox.CaretPosition;
                            }
                            else
                            {
                                GradientStop newGradientStop;

                                foreach (GradientStop runGradientStop in runBrush.GradientStops)
                                {
                                    newGradientStop = newLinearGradientBrush.GradientStops[count];

                                    if (runGradientStop.Color.A != newGradientStop.Color.A || runGradientStop.Color.B != newGradientStop.Color.B || runGradientStop.Color.G != newGradientStop.Color.G || runGradientStop.Color.R != newGradientStop.Color.R || runGradientStop.Color.ScA != newGradientStop.Color.ScA || runGradientStop.Color.ScB != newGradientStop.Color.ScB || runGradientStop.Color.ScG != newGradientStop.Color.ScG || runGradientStop.Color.ScR != newGradientStop.Color.ScR)
                                    {
                                        CustomRichTextBox.IsCreateRunColor = true;

                                        CustomRichTextBox.CreateRunTextPointer = CustomRichTextBox.CaretPosition;

                                        e.Handled = true;

                                        return;
                                    }
                                    else
                                    {
                                        CustomRichTextBox.IsCreateRunColor = false;
                                    }

                                    count++;
                                }
                            }
                        }
                        else if (CustomRichTextBox.Run.Foreground is RadialGradientBrush && newBrush is RadialGradientBrush)
                        {
                            RadialGradientBrush runBrush = CustomRichTextBox.Run.Foreground as RadialGradientBrush;
                            RadialGradientBrush newRadialGradientBrush = newBrush as RadialGradientBrush;

                            int count = 0;

                            if (runBrush.Center != newRadialGradientBrush.Center || runBrush.ColorInterpolationMode != newRadialGradientBrush.ColorInterpolationMode || runBrush.GradientOrigin != newRadialGradientBrush.GradientOrigin || runBrush.MappingMode != newRadialGradientBrush.MappingMode || runBrush.Opacity != newRadialGradientBrush.Opacity || runBrush.RadiusX != newRadialGradientBrush.RadiusX || runBrush.RadiusY != newRadialGradientBrush.RadiusY || runBrush.SpreadMethod != newRadialGradientBrush.SpreadMethod || runBrush.GradientStops.Count != newRadialGradientBrush.GradientStops.Count)
                            {
                                CustomRichTextBox.IsCreateRunColor = true;

                                CustomRichTextBox.CreateRunTextPointer = CustomRichTextBox.CaretPosition;
                            }
                            else
                            {
                                GradientStop newGradientStop;

                                foreach (GradientStop runGradientStop in runBrush.GradientStops)
                                {
                                    newGradientStop = newRadialGradientBrush.GradientStops[count];

                                    if (runGradientStop.Color.A != newGradientStop.Color.A || runGradientStop.Color.B != newGradientStop.Color.B || runGradientStop.Color.G != newGradientStop.Color.G || runGradientStop.Color.R != newGradientStop.Color.R || runGradientStop.Color.ScA != newGradientStop.Color.ScA || runGradientStop.Color.ScB != newGradientStop.Color.ScB || runGradientStop.Color.ScG != newGradientStop.Color.ScG || runGradientStop.Color.ScR != newGradientStop.Color.ScR)
                                    {
                                        CustomRichTextBox.IsCreateRunColor = true;

                                        CustomRichTextBox.CreateRunTextPointer = CustomRichTextBox.CaretPosition;

                                        e.Handled = true;

                                        return;
                                    }
                                    else
                                    {
                                        CustomRichTextBox.IsCreateRunColor = false;
                                    }

                                    count++;
                                }
                            }
                        }
                        else
                        {
                            CustomRichTextBox.IsCreateRunColor = true;

                            CustomRichTextBox.CreateRunTextPointer = CustomRichTextBox.CaretPosition;
                        }
                    }
                }
                else
                {
                    CustomRichTextBox.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, newBrush);
                }
            }

            e.Handled = true;
        }
        public void LoadText(Dictionary <string, string> fields, string source)
        {
            try
            {
                this.source = source;
                FileStream fileStream = new FileStream(source, FileMode.Open);
                TextRange  range      = new TextRange(rtbEditor.Document.ContentStart, rtbEditor.Document.ContentEnd);
                range.Load(fileStream, DataFormats.Rtf);
                fileStream.Close();

                ComputeFields();


                for (int i = 0; i < ModelsField.Count; i++)
                {
                    string      keyword   = '#' + ModelsField[i] + '#';
                    string      newString = fields[ModelsField[i]];
                    TextRange   trange    = new TextRange(rtbEditor.Document.ContentStart, rtbEditor.Document.ContentEnd);
                    TextPointer current   = trange.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 start      = current.GetPositionAtOffset(index, LogicalDirection.Forward);
                                TextPointer end        = start.GetPositionAtOffset(keyword.Length, LogicalDirection.Forward);
                                TextRange   selection  = new TextRange(start, end);
                                bool        underlined = false;

                                object fontWeight = selection.GetPropertyValue(Inline.FontWeightProperty);
                                object fontStyle  = selection.GetPropertyValue(Inline.FontStyleProperty);

                                object fontUnderline = selection.GetPropertyValue(Inline.TextDecorationsProperty);
                                if (fontUnderline.Equals(TextDecorations.Underline))
                                {
                                    underlined = true;
                                }


                                object fontFamily = selection.GetPropertyValue(Inline.FontFamilyProperty);
                                object fontSize   = selection.GetPropertyValue(Inline.FontSizeProperty);

                                selection.Text = newString;

                                selection.ApplyPropertyValue(TextElement.FontWeightProperty, fontWeight);
                                selection.ApplyPropertyValue(TextElement.FontStyleProperty, fontStyle);

                                if (underlined)
                                {
                                    selection.ApplyPropertyValue(Inline.TextDecorationsProperty, TextDecorations.Underline);
                                }

                                selection.ApplyPropertyValue(TextElement.FontFamilyProperty, fontFamily);
                                selection.ApplyPropertyValue(TextElement.FontSizeProperty, fontSize);
                            }
                        }
                        current = current.GetNextContextPosition(LogicalDirection.Forward);
                    }
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
Example #16
0
        //private SearchResult Find(string therm, string file)
        //{
        //    var document = LoadFile(file);
        //    TextPointer current = document.ContentStart;
        //    int index;
        //    int count = 0;
        //    foreach (var block in document.Blocks)
        //    {
        //        string textInRun = new TextRange(block.ContentStart, block.ContentEnd).Text;
        //        if (!string.IsNullOrWhiteSpace(textInRun))
        //        {
        //            index = textInRun.IndexOf(therm);
        //            if (index != -1)
        //            {
        //                return new SearchResult { Position = index + count, Path = file, Text = therm };// new TextRange(document.ContentStart.GetPositionAtOffset(index), document.ContentStart.GetPositionAtOffset(index + therm.Length)).Text });
        //            }
        //            count += textInRun.Length;
        //        }
        //    }
        //    //    while (current != null)
        //    //{
        //    //    int index;
        //    //    string textInRun = current.GetTextInRun(LogicalDirection.Forward);
        //    //    if (!string.IsNullOrWhiteSpace(textInRun))
        //    //    {
        //    //        index = textInRun.IndexOf(therm);
        //    //        if (index != -1)
        //    //        {
        //    //            return new KeyValuePair<int, SearchResult>(index, new SearchResult { Path = file, Text = new TextRange(document.ContentStart.GetPositionAtOffset(index), document.ContentStart.GetPositionAtOffset(index + therm.Length)).Text });
        //    //        }
        //    //    }
        //    //    current = current.GetNextContextPosition(LogicalDirection.Forward);
        //    //}
        //    return null;
        //}

        //private void SelectSearchWord(string file, List<SearchResult> items)
        //{
        //    foreach (var item in items)
        //    {
        //        if (item.Path == file)
        //        {
        //            new TextRange
        //                (TextBox.MainControl.GetTextPointAt(TextBox.MainControl.Document.ContentStart, item.Position),
        //                TextBox.MainControl.GetTextPointAt(TextBox.MainControl.Document.ContentStart, item.Position + item.Text.Length))
        //                .ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Yellow);
        //        }
        //    }
        //}


        //private void Founds(string textInRun, string threm, string file, int paragraphPosition, ref List<SearchResult> items)
        //{
        //    if (!string.IsNullOrWhiteSpace(textInRun))
        //    {
        //        int count = 0;
        //        while (count != -1)
        //        {
        //            count = textInRun.IndexOf(threm, count);
        //            if (count > -1)
        //            {
        //                items.Add(new SearchResult { Position = paragraphPosition+count, Path = file, Text = threm});
        //                count += threm.Length;
        //            }
        //        }
        //    }
        //}

        private List <SearchResult> FindAll(string therm, string file)
        {
            var list     = new List <SearchResult>();
            var document = TextBox.MainControl;//LoadFile(file);

            document.SelectAll();
            document.Selection
            //   new TextRange
            //             (document.ContentStart, document.ContentEnd)
            .ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.White);
            Regex            reg      = new Regex(therm, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            TextPointer      position = document.Document.ContentStart;
            List <TextRange> ranges   = new List <TextRange>();
            int count = 0;

            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(therm.Trim().Length);
                        TextRange   textrange = new TextRange(start, end);
                        //  ranges.Add(textrange);
                        //       var range = new TextRange(start, end);// document.ContentStart.(position)+document.ContentStart.GetPositionAtOffset(match.Index), document.ContentStart.GetPositionAtOffset(therm.Trim().Length));
                        list.Add(new SearchResult {
                            Path = file, Text = textrange.Text, Range = textrange                       /*Start = document.ContentStart.GetOffsetToPosition(start), End = document.ContentStart.GetOffsetToPosition(end)*/
                        });
                        //range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
                    }
                }
                else
                {
                    count++;
                }
                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }
            foreach (var range in list)
            {
                range.Range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Red));
                //   range.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
            }

            //foreach (var item in list)
            //{
            //    new TextRange(document.ContentStart.GetPositionAtOffset(list.LastOrDefault().Start), document.ContentStart.GetPositionAtOffset(list.LastOrDefault().End)).
            //     ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Yellow);
            //}
            //TextPointer p = TextBox.MainControl.Document.ContentStart;
            //while (true)
            //{
            //    var range = FindWordFromPosition(p, therm);
            //    if(range == null) { break; }
            //    list.Add(new SearchResult { Path = file, Position = TextBox.MainControl.Document.ContentStart.GetOffsetToPosition(range.Start.DocumentStart), Text = range.Text });
            //    p = range.End;
            //}


            return(list);
        }
        private void bnt_Search_Click(object sender, RoutedEventArgs e)
        {
            TextRange textRange = new TextRange(rich.Document.ContentStart, rich.Document.ContentEnd);

            //clear up highlighted text before starting a new search
            textRange.ClearAllProperties();
            lbl_Status.Content = "";

            //get the richtextbox text
            string textBoxText = textRange.Text;

            //get search text
            string searchText = searchTextBox.Text;

            if (string.IsNullOrWhiteSpace(textBoxText) || string.IsNullOrWhiteSpace(searchText))
            {
                lbl_Status.Content = "Please provide search text or source text to search from";
            }

            else
            {
                //using regex to get the search count
                //this will include search word even it is part of another word
                //say we are searching "hi" in "hi, how are you Mahi?" --> match count will be 2 (hi in 'Mahi' also)

                Regex regex            = new Regex(searchText);
                int   count_MatchFound = Regex.Matches(textBoxText, regex.ToString()).Count;

                for (TextPointer startPointer = rich.Document.ContentStart;
                     startPointer.CompareTo(rich.Document.ContentEnd) <= 0;
                     startPointer = startPointer.GetNextContextPosition(LogicalDirection.Forward))
                {
                    //check if end of text
                    if (startPointer.CompareTo(rich.Document.ContentEnd) == 0)
                    {
                        break;
                    }

                    //get the adjacent string
                    string parsedString = startPointer.GetTextInRun(LogicalDirection.Forward);

                    //check if the search string present here
                    int indexOfParseString = parsedString.IndexOf(searchText);

                    if (indexOfParseString >= 0) //present
                    {
                        //setting up the pointer here at this matched index
                        startPointer = startPointer.GetPositionAtOffset(indexOfParseString);

                        if (startPointer != null)
                        {
                            //next pointer will be the length of the search string
                            TextPointer nextPointer = startPointer.GetPositionAtOffset(searchText.Length);

                            //create the text range
                            TextRange searchedTextRange = new TextRange(startPointer, nextPointer);

                            //color up
                            searchedTextRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));

                            //add other setting property
                        }
                    }
                }

                //update the label text with count
                if (count_MatchFound > 0)
                {
                    lbl_Status.Content = "Total Match Found : " + count_MatchFound;
                }
                else
                {
                    lbl_Status.Content = "No Match Found !";
                }
            }
        }
Example #18
0
        public static void highlightText(FlowDocument document, string keyword0, bool isRegex0, bool isCasesensitive0)
        {
            string keyword1;

            if (isRegex0)
            {
                keyword1 = keyword0;
            }
            else
            {
                StringBuilder sb1 = new StringBuilder();
                foreach (var item in Regex.Split(keyword0, "\\s+"))
                {
                    if (0 < sb1.Length)
                    {
                        sb1.Append("|");
                    }
                    sb1.Append("(" + Regex.Escape(item) + ")");
                }
                keyword1 = sb1.ToString();
            }
            // 半角・全角を区別しない
            {
                Regex         rgx_Wide1   = new Regex("[0-9A-Za-z:- ]+");
                Regex         rgx_Narrow1 = new Regex("[0-9A-Za-z\\:\\- ]+");
                StringBuilder sb1         = new StringBuilder();
                bool          isEscaped1  = false;
                for (int i1 = 0; i1 < keyword1.Length; i1++)
                {
                    string s2 = keyword1[i1].ToString();
                    if (isRegex0 && keyword1[i1] == '\\')
                    {
                        sb1.Append(s2);
                        isEscaped1 = true;
                    }
                    else if (isEscaped1)
                    {
                        sb1.Append(s2);
                        isEscaped1 = false;
                    }
                    else
                    {
                        Match m_W2 = rgx_Wide1.Match(s2);
                        Match m_N2 = rgx_Narrow1.Match(s2);
                        if (m_W2.Success)
                        {
                            string s3 = Strings.StrConv(m_W2.Value, VbStrConv.Narrow, 0);
                            sb1.Append("(" + s2 + "|" + s3 + ")");
                        }
                        else if (m_N2.Success)
                        {
                            string s3 = Strings.StrConv(m_N2.Value, VbStrConv.Wide, 0);
                            sb1.Append("(" + s2 + "|" + s3 + ")");
                        }
                        else
                        {
                            sb1.Append(s2);
                        }
                    }
                }
                keyword1 = sb1.ToString();
            }
            //
            RegexOptions regexOptions1 = RegexOptions.Compiled;

            if (!isCasesensitive0)
            {
                regexOptions1 |= RegexOptions.IgnoreCase;
            }
            Regex       rgx1    = new Regex(keyword1, regexOptions1);
            TextPointer pointer = document.ContentStart;

            while (pointer != null)
            {
                if (pointer.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    string           textRun     = pointer.GetTextInRun(LogicalDirection.Forward);
                    List <TextRange> textRanges1 = new List <TextRange>();
                    foreach (Match match1 in rgx1.Matches(textRun))
                    {
                        TextPointer start      = pointer.GetPositionAtOffset(match1.Index);
                        TextPointer end        = start.GetPositionAtOffset(match1.Length);
                        TextRange   textRange1 = new TextRange(start, end);
                        textRanges1.Add(textRange1);
                    }
                    foreach (var textRange1 in textRanges1)
                    {
                        textRange1.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Yellow);
                    }
                }

                pointer = pointer.GetNextContextPosition(LogicalDirection.Forward);
            }
        }
Example #19
0
        private void updageTagOnFlag(Note note)
        {
            byte[] flag = NotesBrowser.getJPGFromImageControl(Properties.Resources.noteFlag);
            for (TextPointer position = note.Range.Start; position != null && position.CompareTo(note.Range.End) != 1; position = position.GetNextContextPosition(LogicalDirection.Forward))
            {
                InlineUIContainer element = position.Parent as InlineUIContainer;
                if (element != null && element.Child is System.Windows.Controls.Image)
                {
                    var image = element.Child as System.Windows.Controls.Image;
                    if (image == null)
                    {
                        continue;
                    }
                    var imageSourse = image.Source as System.Windows.Media.ImageSource;
                    if (imageSourse == null)
                    {
                        continue;
                    }
                    byte[] byt = NotesBrowser.getJPGFromImageControl(imageSourse);
                    //сравнивает картинки
                    if (byt.Length == flag.Length)
                    {
                        bool isflag = true;
                        for (int t = 0; t < byt.Length; t++)
                        {
                            if (byt[t] != flag[t])
                            {
                                isflag = false; break;
                            }
                        }
                        if (!isflag)
                        {
                            continue;
                        }

                        image.Tag = note.Name;
                    }
                }
            }
        }
        public void HighlightText()
        {
            // Clear out the old highlights within the correct block.
            highlights.RemoveAll(i => HighlightStart.CompareTo(i.Range.Start) >= 0 && HighlightEnd.CompareTo(i.Range.Start) < 0);

            // Create a pointer to the start - which we will increment.
            CurrentPointer = HighlightStart;

            // Initilize the parser.
            TextHighlighter.Init();

            // Set the textbox within the parser to this textbox.
            TextHighlighter.TextBox = this;

            // Reset text for parser instead of setting, b/c we'll dynamically set it as we come across each run,
            // so that the whitespace detection (which allows anything at the end) will allow tokens at the end of a run!
            //TextHighlighter.Text = ABParse.ABParser.ToCharArray(TextNoLineBreaks);
            TextHighlighter.Text = new char[TextNoLineBreaks.Length];

            // Move forward through all the symbols, and act where all the text is...
            while (CurrentPointer.CompareTo(HighlightEnd) < 0)
            {
                // We're going to use ABParser, which is another ABSoftware product capable of parsing a test JSON string (55 characters) within 0.0232ms!
                // However, we can't use it the way it's intended (with a string) because this RichTextBox has a BUNCH of other symbols added.
                // So, instead... We're going to manually call to method that processes each character... When we're actually at a piece of text!

                // Get the current context - this is essentially what this symbol means.
                var context = CurrentPointer.GetPointerContext(LogicalDirection.Backward);

                // If this is a run - that's where the text is so we can process it!
                if (context == TextPointerContext.ElementStart && CurrentPointer.Parent is Run run)
                {
                    // Just in case the "Highlight" methods execute too late, we'll store this run in a variable.
                    lastRun = run;

                    // Add this run as text to the parser - the parser works with character arrays so we need to make sure we convert it.
                    ABParse.ABParser.ToCharArray(run.Text).CopyTo(TextHighlighter.Text, TextHighlighter.CurrentLocation);

                    // Go through all the text in this run - this is where the heart of the highlighter is.
                    for (currentPos = 0; currentPos < run.Text.Length; currentPos++)
                    {
                        // Process this character.
                        var result = TextHighlighter.ProcessChar(true);

                        // Also, we passed false to the process character method because we wanted the events to execute AFTER getting
                        // the start of the token, so, NOW we'll check the events - if we should.
                        //if (!result)
                        //TextHighlighter.ProcessBuiltUpTokens(false);

                        // Make sure we move on the next character in the parser - if this isn't the last one.
                        if (TextHighlighter.CurrentLocation + 1 < TextHighlighter.Text.Length)
                        {
                            TextHighlighter.MoveForward();
                        }
                    }

                    // We need to store the end of this run - so that the whitespace detection can allow tokens at start/ends of runs.
                    TextHighlighter.RunStart = TextHighlighter.CurrentLocation;

                    // Now that we've finished with this run - which represent lines in our case, make sure we aren't highlighting the line anymore.
                    TextHighlighter.LineHighlighted = false;

                    // The currentPos is now one character too far ahead - so, if this is the end of the string, shift it back one.
                    //if (TextHighlighter.CurrentLocation + 1 == TextHighlighter.Text.Length)
                    //    currentPos--;
                }

                // Go to the next insertion point if it isn't at a valid one.
                CurrentPointer = CurrentPointer.GetNextContextPosition(LogicalDirection.Forward);
            }

            // Now that we're completely finished, we haven't chosen a start/emd yet.
            chosenStartEnd = false;

            // Make sure we clean it up afterwards
            TextHighlighter.ProcessBuiltUpTokens(false);

            // We also want to reset all the variables ready for the next go.
            TextHighlighter.Stop();

            // Now, apply all the highlights that were created - they had to be put into an array, because,
            // otherwise, the runs start to change while we're highlighting... which isn't what we want.
            ApplyHighlights();

            //// Create a navigator to go through the text.
            //var navigator = txtCode.Document.ContentStart;

            //// Go through all the text.
            //while (navigator.CompareTo(txtCode.Document.ContentEnd) < 0)
            //{
            //    // Get a context of where the navigator is.
            //    var context = navigator.GetPointerContext(LogicalDirection.Backward);

            //    // If we're at the start of a run, start highlighting.
            //    if (context == TextPointerContext.ElementStart && navigator.Parent is Run)
            //        HighlightRun(navigator.Parent as Run);

            //    // Go to the next character.
            //    navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
            //}
        }
Example #21
0
        /// <summary>
        /// Writes the container into the specified XmlWriter.
        /// </summary>
        private void WriteContainer(TextPointer start, TextPointer end, XmlWriter writer)
        {
            TextElement textElement;

            System.Diagnostics.Debug.Assert(start != null);
            System.Diagnostics.Debug.Assert(end != null);
            System.Diagnostics.Debug.Assert(writer != null);

            _writer = writer;

            WriteWordXmlHead();

            _cursor = start;
            while (_cursor.CompareTo(end) < 0)
            {
                switch (_cursor.GetPointerContext(_dir))
                {
                case TextPointerContext.None:
                    System.Diagnostics.Debug.Assert(false,
                                                    "Next symbol should never be None if cursor < End.");
                    break;

                case TextPointerContext.Text:
                    RequireOpenRange();
                    _writer.WriteStartElement(WordXmlSerializer.WordTextTag);
                    _writer.WriteString(_cursor.GetTextInRun(_dir));
                    _writer.WriteEndElement();
                    break;

                case TextPointerContext.EmbeddedElement:
                    DependencyObject obj = _cursor.GetAdjacentElement(LogicalDirection.Forward);
                    if (obj is LineBreak)
                    {
                        RequireOpenRange();
                        _writer.WriteStartElement(WordXmlSerializer.WordBreakTag);
                        _writer.WriteEndElement();
                    }
                    // TODO: try to convert some known embedded objects.
                    break;

                case TextPointerContext.ElementStart:
                    TextPointer position;
                    position    = _cursor;
                    position    = position.GetNextContextPosition(LogicalDirection.Forward);
                    textElement = position.Parent as TextElement;

                    if (textElement is Paragraph)
                    {
                        RequireClosedRange();
                        RequireOpenParagraph();
                    }
                    else if (textElement is Inline)
                    {
                        RequireClosedRange();
                        RequireOpenParagraph();
                        RequireOpenRange();
                    }
                    break;

                case TextPointerContext.ElementEnd:
                    textElement = _cursor.Parent as TextElement;

                    if (textElement is Inline)
                    {
                        RequireClosedRange();
                    }
                    else if (textElement is Paragraph)
                    {
                        RequireClosedParagraph();
                    }
                    break;
                }
                _cursor = _cursor.GetNextContextPosition(_dir);
            }

            RequireClosedRange();
            WriteWordXmlTail();
        }
Example #22
0
        private void btnTab1Ok_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                txtTab3Search.Text = txtTab4Search.Text = txtTab1Search.Text;
                var myFile = (File.ReadAllText(myOpenedFile)).Split();
                labNumberHits.Text = myFile.Where(u => u.Contains(txtTab1Search.Text)).Count().ToString();

                int        i           = 0;
                List <int> indexOfFind = new List <int>();
                foreach (var q in myFile)
                {
                    if (q.Contains(txtTab1Search.Text))
                    {
                        indexOfFind.Add(i);
                    }

                    i++;
                }
                txtRichText1.Document.Blocks.Clear();
                foreach (var t in indexOfFind)
                {
                    string S = "";
                    if (t >= 7)
                    {
                        for (int u = 7; u >= 0; u--)
                        {
                            S += " " + myFile[t - u];
                        }
                    }
                    else
                    {
                        for (int u = t % 7; u >= 0; u--)
                        {
                            S += " " + myFile[t - u];
                        }
                    }

                    if (t + 7 <= myFile.Count())
                    {
                        for (int u = 1; u <= 7; u++)
                        {
                            S += " " + myFile[t + u];
                        }
                    }
                    else
                    {
                        for (int u = 1; u <= u - myFile.Count(); u++)
                        {
                            S += " " + myFile[t + u];
                        }
                    }
                    txtRichText1.Document.Blocks.Add(new Paragraph(new Run(S)));
                }

                txtRichText1.SelectAll();
                txtRichText1.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Black));
                txtRichText1.Selection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Normal);


                Regex            reg      = new Regex(txtTab1Search.Text.Trim(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                TextPointer      position = txtRichText1.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(txtTab1Search.Text.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.Blue));
                    range.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("File not selected!");
            }
        }
Example #23
0
        private void TextInput_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextInput.TextChanged -= TextInput_TextChanged;
            string tokens = "(auto|double|int|struct|break|else|long|switch|case|" +
                            "enum|register|typedef|char|extern|return|union|const|" +
                            "float|short|unsigned|continue|for|signed|void |default|" +
                            "goto|sizeof|volatile|do|if|static|while|using)";
            Regex rex = new Regex(tokens);


            if (TextInput.Document == null)
            {
                return;
            }

            TextRange documentRange = new TextRange(TextInput.Document.ContentStart, TextInput.Document.ContentEnd);

            documentRange.ClearAllProperties();

            //Console.WriteLine(documentRange.Text);

            TextPointer position = TextInput.Document.ContentStart;

            while (position != null)
            {
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    break;
                }
                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }

            MatchCollection mc = rex.Matches(documentRange.Text);

            foreach (Match m in mc)
            {
                //Console.Write("{0}({1}-{2}), ", m.Value, m.Index, m.Index + m.Length);
                TextPointer t1 = GetTextPointAt(position, m.Index);
                TextRange   tr = new TextRange(t1, GetTextPointAt(t1, m.Length));
                tr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
            }
            TextInput.TextChanged += TextInput_TextChanged;
            return;

            /*
             * int line = 0;
             * int b = 0;
             * while (position != null)
             * {
             *  if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
             *  {
             *      string textRun = position.GetTextInRun(LogicalDirection.Forward);
             *      MatchCollection mc = rex.Matches(textRun);
             *      foreach (Match m in mc)
             *      {
             *          //Console.Write("{0}({1}-{2}), ", m.Value, m.Index, m.Index+m.Length);
             *          TextPointer t1 = GetTextPointAt(position, m.Index);
             *          TextRange tr = new TextRange(t1, GetTextPointAt(t1, m.Length));
             *
             *          if ((b % 3) == 0)
             *          {
             *              tr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
             *          }
             *          else if ((b % 3) == 1)
             *          {
             *              tr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.LightBlue));
             *          }
             *          else
             *          {
             *              tr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Yellow));
             *          }
             ++b;
             *
             *      }
             *      // Find the starting index of any substring that matches "word".
             *      /*int indexInRun = textRun.IndexOf("void");
             *      if (indexInRun >= 0)
             *      {
             *          Console.WriteLine("Found: {0}, text:\"{1}\" ", indexInRun, textRun);
             *          //position = position.GetPositionAtOffset(indexInRun);
             *          //break;
             *      }
             *      position = position.GetLineStartPosition(1);
             *      continue;
             *  }
             *  position = position.GetNextContextPosition(LogicalDirection.Forward);
             * }
             */

            /*if (tp1 == null)
             *  return;
             * while (tp1.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text)
             * {
             *  tp1 = tp1.GetNextContextPosition(LogicalDirection.Forward);
             * }
             * //Console.WriteLine("");
             *
             * foreach (Match m in mc)
             * {
             *  Console.WriteLine("Match: {0} [{1},{2}]", m.Value, m.Index, m.Length);
             *  //int startIdx = m.Index;
             *  //int stopIdx = m.Length;
             *  //documentRange.Select(TextInput.Document.ContentStart, TextInput.Document.ContentStart.GetPositionAtOffset(m.Index + m.Length, LogicalDirection.Forward));
             *  TextPointer tp2 = tp1.GetPositionAtOffset(m.Index, LogicalDirection.Forward);
             *
             *  Console.WriteLine(tp2.GetOffsetToPosition(tp2.GetPositionAtOffset(m.Length, LogicalDirection.Forward)));
             *
             *  TextRange tr = new TextRange(tp2, tp2.GetPositionAtOffset(m.Length, LogicalDirection.Forward));
             *
             *  tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
             * }*/


            TextInput.TextChanged += TextInput_TextChanged;
            //TextInput.TextChanged += TextInput_TextChanged;



            /*documentRange.ClearAllProperties();
             *
             * Console.WriteLine(documentRange.Text);
             *
             * TextPointer navigator = TextInput.Document.ContentStart;
             *
             * while (navigator.CompareTo(TextInput.Document.ContentEnd) < 0)
             * {
             *  TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward);
             *  if (context == TextPointerContext.ElementStart && navigator.Parent is Run)
             *  {
             *      Console.WriteLine(navigator.GetTextRunLength(LogicalDirection.Forward));
             *  }
             *
             *  navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
             * }
             *
             * Format();
             * */
        }
Example #24
0
        /// <summary>
        /// When input text is changed, change colors of text based on syntax
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InputTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            string text = "";

            //Input is empty, no need to color anything
            if (inputTextBox.Document == null || inputTextBox.Document.Blocks.Count == 0)
            {
                return;
            }
            //Remove event handler to prevent infinite loop.
            inputTextBox.TextChanged -= InputTextBox_TextChanged;

            words.Clear();

            TextRange documentRange = new TextRange(inputTextBox.Document.ContentStart, inputTextBox.Document.ContentEnd);

            documentRange.ClearAllProperties();

            TextPointer navigator = inputTextBox.Document.ContentStart;

            //Go through the document
            while (navigator.CompareTo(inputTextBox.Document.ContentEnd) < 0)
            {
                TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward);
                if (context == TextPointerContext.ElementStart && navigator.Parent is Run)
                {
                    text = ((Run)navigator.Parent).Text;
                    if (text != "" && text.Length != 0)
                    {
                        Run parentRun = (Run)navigator.Parent;
                        CheckWords(parentRun, text);
                    }
                }

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

            RedrawInput();

            if (words.Count() > 0)
            {
                if (GetItemIndex(-1, words) != -1)
                {
                    //There was an error in the input, equation can not be solved
                }
                else
                {
                    string result = Solve(WordToNodeList(words));

                    if (result == "" || (result.Length >= 3 && result.Substring(0, 3) == "err"))
                    {
                        textBlockResult.Text = "Neplatny vyraz";
                    }
                    else
                    {
                        textBlockResult.Text = result;
                    }
                    textBlockMemory.Text = "";
                    for (int i = 0; i < memory.Count(); i++)
                    {
                        if (i % 3 == 2)
                        {
                            textBlockMemory.Text += memory[i].Letter + "=" + Convert.ToString(memory[i].Number) + "\n";
                        }
                        else
                        {
                            textBlockMemory.Text += memory[i].Letter + "=" + Convert.ToString(memory[i].Number) + "\t";
                        }
                    }
                }
            }



            //Add back event handler
            inputTextBox.TextChanged += InputTextBox_TextChanged;
        }
Example #25
0
        private void txtStatus_TextChanged(object sender, TextChangedEventArgs e)
        {
            string desktopPath  = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string settingsPath = desktopPath + "\\CodeVoidProject\\CodeVoid\\CodeVoidWPF\\bin\\Debug\\Data\\DarkModeFix.txt";

            using (StreamReader sr = new StreamReader(settingsPath))
            {
                string line;
                line = sr.ReadLine();
                if (line.Contains("DarkMode:True"))
                {
                    txtStatus.Background = Brushes.DarkGray;
                }
                else
                {
                    //do something..
                }
            }

            if (txtStatus.Document == null)
            {
                return;
            }
            txtStatus.TextChanged -= txtStatus_TextChanged;

            m_blueTags.Clear();
            gr_Tags.Clear();
            yellow_Tags.Clear();

            Console.WriteLine();
            TextPointer navigator       = txtStatus.Document.ContentStart;
            TextPointer grnavigator     = txtStatus.Document.ContentStart;
            TextPointer yellownavigator = txtStatus.Document.ContentStart;

            while (navigator.CompareTo(txtStatus.Document.ContentEnd) < 0)
            {
                TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward);
                if (context == TextPointerContext.ElementStart && navigator.Parent is Run)
                {
                    text = ((Run)navigator.Parent).Text; //fix 2
                    if (text != "")
                    {
                        CheckWordsInRun((Run)navigator.Parent);
                    }
                }
                navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
            }
            while (grnavigator.CompareTo(txtStatus.Document.ContentEnd) < 0)
            {
                TextPointerContext grcontext = grnavigator.GetPointerContext(LogicalDirection.Backward);
                if (grcontext == TextPointerContext.ElementStart && grnavigator.Parent is Run)
                {
                    grtext = ((Run)grnavigator.Parent).Text; //fix 2
                    if (grtext != "")
                    {
                        grCheckWordsInRun((Run)grnavigator.Parent);
                    }
                }
                grnavigator = grnavigator.GetNextContextPosition(LogicalDirection.Forward);
            }
            while (yellownavigator.CompareTo(txtStatus.Document.ContentEnd) < 0)
            {
                TextPointerContext yellowcontext = yellownavigator.GetPointerContext(LogicalDirection.Backward);
                if (yellowcontext == TextPointerContext.ElementStart && yellownavigator.Parent is Run)
                {
                    yellowtext = ((Run)yellownavigator.Parent).Text; //fix 2
                    if (yellowtext != "")
                    {
                        yellowCheckWordsInRun((Run)yellownavigator.Parent);
                    }
                }
                yellownavigator = yellownavigator.GetNextContextPosition(LogicalDirection.Forward);
            }
            for (int i = 0; i < m_blueTags.Count; i++)
            {
                try
                {
                    TextRange range = new TextRange(m_blueTags[i].StartPosition, m_blueTags[i].EndPosition);
                    range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));
                    range.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Normal);
                }
                catch { }
            }
            for (int i = 0; i < gr_Tags.Count; i++)
            {
                try
                {
                    Console.WriteLine();
                    TextRange grrange = new TextRange(gr_Tags[i].grStartPosition, gr_Tags[i].grEndPosition);
                    grrange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Green));
                    grrange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Normal);
                }
                catch { }
            }
            for (int i = 0; i < yellow_Tags.Count; i++)
            {
                try
                {
                    Console.WriteLine();
                    TextRange yellowrange = new TextRange(yellow_Tags[i].yellowStartPosition, yellow_Tags[i].yellowEndPosition);
                    yellowrange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.GreenYellow));
                    yellowrange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Normal);
                }
                catch { }
            }
            txtStatus.TextChanged += txtStatus_TextChanged;
        }
Example #26
0
        void WriteOpenXML(TextPointer contentstart, TextPointer contentend, XmlWriter xmlwriter, XmlWriter numberingwriter)
        {
            TextElement textElement;

            _openxmlwriter   = xmlwriter;
            _numberingwriter = numberingwriter;
            WriteOpenXmlHeader();
            WriteNumberingHeader();
            WriteNumberingBody();

            _textpointer = contentstart;
            while (_textpointer.CompareTo(contentend) < 0)
            {
                TextPointerContext tpc = _textpointer.GetPointerContext(LogicalDirection.Forward);
                if (tpc == TextPointerContext.ElementStart)
                {
                    TextPointer position;
                    position    = _textpointer;
                    position    = position.GetNextContextPosition(LogicalDirection.Forward);
                    textElement = position.Parent as TextElement;

                    if (textElement is Paragraph)
                    {
                        CloseTextRunTag();
                        CreateParagraphTag();
                    }
                    else if (textElement is Inline)
                    {
                        CloseTextRunTag();
                        EnsureWithinParagraphTag();
                        CreateTextRunTag();
                    }
                    else if (textElement is List)
                    {
                        //keep track of list levels (add)

                        List            lx  = (List)textElement;
                        TextMarkerStyle mst = (TextMarkerStyle)lx.GetValue(List.MarkerStyleProperty);
                        listMarkerStyle[listLevel] = mst;
                        listLevel++;


                        if (listLevel > 29)
                        {
                            listLevel = 29;
                        }
                    }
                    else if (textElement is ListItem)
                    {
                        listContext = 1;
                    }
                }
                else if (tpc == TextPointerContext.ElementEnd)
                {
                    textElement = _textpointer.Parent as TextElement;
                    if (textElement is Inline)
                    {
                        CloseTextRunTag();
                    }
                    else if (textElement is Paragraph)
                    {
                        CloseParagraphTag();
                    }
                    else if (textElement is List)
                    {
                        //keep track of list levels (subtract)


                        listLevel--;
                        if (listLevel < 0)
                        {
                            listLevel = 0;
                        }
                    }
                    else if (textElement is ListItem)
                    {
                    }
                }
                else if (tpc == TextPointerContext.Text)
                {
                    CreateTextRunTag();
                    _openxmlwriter.WriteStartElement("w:t");
                    _openxmlwriter.WriteString(_textpointer.GetTextInRun(LogicalDirection.Forward));
                    _openxmlwriter.WriteEndElement();
                }
                else if (tpc == TextPointerContext.EmbeddedElement)
                {
                    DependencyObject obj = _textpointer.GetAdjacentElement(LogicalDirection.Forward);
                    if (obj is LineBreak)
                    {
                        CreateTextRunTag();
                        _openxmlwriter.WriteStartElement("w:br");
                        _openxmlwriter.WriteEndElement();
                    }
                    // other embedded objects here
                }

                _textpointer = _textpointer.GetNextContextPosition(LogicalDirection.Forward);
            }//end while


            CloseTextRunTag();
            WriteNumberingFooter();
            WriteOpenXmlFooter();
        }
Example #27
0
        internal string GetTextInternal(TextPointer startPosition, TextPointer endPosition, ref char[] charArray)
        {
            StringBuilder textBuffer      = new StringBuilder();
            Stack <int>   listItemCounter = null;
            TextPointer   navigator       = startPosition;

            Debug.Assert(startPosition.CompareTo(endPosition) <= 0, "expecting: startPosition <= endPosition");

            while (navigator.CompareTo(endPosition) < 0)
            {
                Type        elementType;
                int         start = textBuffer.Length;
                TextPointer begin = navigator;

                switch (navigator.GetPointerContext(LogicalDirection.Forward))
                {
                case TextPointerContext.Text:
                {
                    PlainConvertTextRun(textBuffer, ref navigator, endPosition, ref charArray);
                    Add(begin, navigator, start, textBuffer.Length);
                    continue;
                }

                case TextPointerContext.EmbeddedElement:
                {
                    textBuffer.Append(' ');
                    navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
                    Add(begin, navigator, start, textBuffer.Length);
                    continue;
                }

                case TextPointerContext.ElementStart:
                {
                    elementType = navigator.GetAdjacentElement(LogicalDirection.Forward).GetType();

                    if (!typeof(AnchoredBlock).IsAssignableFrom(elementType))
                    {
                        if (typeof(List).IsAssignableFrom(elementType) && (navigator is TextPointer))
                        {
                            PlainConvertListStart(navigator, ref listItemCounter);
                        }
                        else if (typeof(ListItem).IsAssignableFrom(elementType))
                        {
                            PlainConvertListItemStart(textBuffer, navigator, ref listItemCounter);
                        }
                        else
                        {
                            PlainConvertAccessKey(textBuffer, navigator);
                        }
                    }

                    //textBuffer.Append(Environment.NewLine);
                    navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
                    Add(begin, navigator, start, textBuffer.Length);
                    continue;
                }

                case TextPointerContext.ElementEnd:
                {
                    elementType = navigator.Parent.GetType();

                    if (!typeof(Paragraph).IsAssignableFrom(elementType) &&
                        !typeof(BlockUIContainer).IsAssignableFrom(elementType))
                    {
                        break;
                    }

                    PlainConvertParagraphEnd(textBuffer, ref navigator);
                    Add(begin, navigator, start, textBuffer.Length);
                    continue;
                }

                default:
                    Debug.Assert(false, "Unexpected value for TextPointerContext");
                    continue;
                }

                if (typeof(LineBreak).IsAssignableFrom(elementType))
                {
                    navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
                    textBuffer.Append(Environment.NewLine);
                    Add(begin, navigator, start, textBuffer.Length);
                }
                else if (typeof(List).IsAssignableFrom(elementType))
                {
                    PlainConvertListEnd(ref navigator, ref listItemCounter);
                    Add(begin, navigator, start, textBuffer.Length);
                }
                else
                {
                    navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
                }

                continue;
            }

            return(textBuffer.ToString());
        }
Example #28
0
        /*
         *  ---------------- / HELPER FUNCTIONS --------------
         */


        /*
         *  ---------------- TEXT EDITOR STYLE HANDLERS ----------------
         */

        private void Editor_TextChanged(object sender, TextChangedEventArgs e)
        {
            /* Don't do anything if the document is not set up yet */
            if (Editor.Document == null)
            {
                return;
            }

            /* Temporarily disable TextChanged event handler */
            Editor.TextChanged -= Editor_TextChanged;

            /* Clear the buffer that holds the words to be styled */
            keywordBuffer.Clear();

            /* Remove all current formatting properties */
            TextRange docRange = new TextRange(Editor.Document.ContentStart, Editor.Document.ContentEnd);

            docRange.ClearAllProperties();

            /* Find keywords in program by checking each run */
            TextPointer nav = Editor.Document.ContentStart;

            while (nav.CompareTo(Editor.Document.ContentEnd) < 0)
            {
                TextPointerContext ctxt = nav.GetPointerContext(LogicalDirection.Backward);
                if (ctxt == TextPointerContext.ElementStart && nav.Parent is Run)
                {
                    currentText = ((Run)nav.Parent).Text;

                    /* Only check words if the Run is not empty */
                    if (currentText != "")
                    {
                        CheckWordsInRun((Run)nav.Parent);
                    }
                }
                nav = nav.GetNextContextPosition(LogicalDirection.Forward);
            }
            /* / Find keywords in program */

            /* Highlight keywords in program */
            for (int i = 0; i < keywordBuffer.Count; ++i)
            {
                try
                {
                    /* Find the desired keyword in the text box using the current word's location data */
                    TextRange range = new TextRange(keywordBuffer[i].Start, keywordBuffer[i].End);

                    /* Apply every style property from the Style data */
                    foreach (KeyValuePair <DependencyProperty, object> style in keywordBuffer[i].Style.GetDict())
                    {
                        range.ApplyPropertyValue(style.Key, style.Value);
                    }
                }

                /* This shouldn't ever happen */
                catch
                {
                    MessageBox.Show("There was a problem with the editor's color highlighting feature\nSorry for the inconvenience....");
                    System.Environment.Exit(1);
                }
            }
            /* / Highlight keywords in program */

            Editor.TextChanged += Editor_TextChanged; /* Re-enable TextChanged event handler */
        }