Beispiel #1
0
        public virtual void ReplaceText(string searchValue,
                                        string newValue,
                                        bool trackChanges          = false,
                                        RegexOptions options       = RegexOptions.None,
                                        Formatting newFormatting   = null,
                                        Formatting matchFormatting = null,
                                        MatchFormattingOptions fo  = MatchFormattingOptions.SubsetMatch,
                                        bool escapeRegEx           = true,
                                        bool useRegExSubstitutions = false,
                                        bool removeEmptyParagraph  = true)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                throw new ArgumentException("searchValue cannot be null or empty.", "searchValue");
            }
            if (newValue == null)
            {
                throw new ArgumentException("newValue cannot be null.", "newValue");
            }

            foreach (var p in this.Paragraphs)
            {
                p.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo, escapeRegEx, useRegExSubstitutions, removeEmptyParagraph);
            }
        }
Beispiel #2
0
        public virtual void ReplaceText(string searchValue,
                                        string newValue,
                                        bool trackChanges          = false,
                                        RegexOptions options       = RegexOptions.None,
                                        Formatting newFormatting   = null,
                                        Formatting matchFormatting = null,
                                        MatchFormattingOptions fo  = MatchFormattingOptions.SubsetMatch,
                                        bool escapeRegEx           = true,
                                        bool useRegExSubstitutions = false,
                                        bool removeEmptyParagraph  = true)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                throw new ArgumentException("searchValue cannot be null or empty.", "searchValue");
            }
            if (newValue == null)
            {
                throw new ArgumentException("newValue cannot be null.", "newValue");
            }

            // ReplaceText in Headers of the document.
            var headerList = new List <Header>()
            {
                this.Document.Headers.First, this.Document.Headers.Even, this.Document.Headers.Odd
            };

            foreach (Header h in headerList)
            {
                if (h != null)
                {
                    foreach (Paragraph p in h.Paragraphs)
                    {
                        p.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo, escapeRegEx, useRegExSubstitutions, removeEmptyParagraph);
                    }
                }
            }

            // ReplaceText int main body of document.
            foreach (Paragraph p in this.Paragraphs)
            {
                p.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo, escapeRegEx, useRegExSubstitutions, removeEmptyParagraph);
            }

            // ReplaceText in Footers of the document.
            var footerList = new List <Footer> {
                this.Document.Footers.First, this.Document.Footers.Even, this.Document.Footers.Odd
            };

            foreach (Footer f in footerList)
            {
                if (f != null)
                {
                    foreach (Paragraph p in f.Paragraphs)
                    {
                        p.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo, escapeRegEx, useRegExSubstitutions, removeEmptyParagraph);
                    }
                }
            }
        }
Beispiel #3
0
    public int RemoveTextInGivenFormat( Formatting formattingToMatch, MatchFormattingOptions formattingOptions = MatchFormattingOptions.SubsetMatch )
    {
      var count = 0;
      foreach( var element in Xml.Elements() )
        count += RecursiveRemoveText( element, formattingToMatch, formattingOptions );

      return count;
    }  
Beispiel #4
0
        public int RemoveTextInGivenFormat(Formatting matchFormatting, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
        {
            int num = 0;

            foreach (XElement item in base.Xml.Elements())
            {
                num += RemoveTextWithFormatRecursive(item, matchFormatting, fo);
            }
            return(num);
        }
Beispiel #5
0
        /// <summary>
        /// Removes all items with required formatting
        /// </summary>
        /// <returns>Numer of texts removed</returns>
        public int RemoveTextInGivenFormat(Formatting matchFormatting, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
        {
            var deletedCount = 0;

            foreach (var x in Xml.Elements())
            {
                deletedCount += RemoveTextWithFormatRecursive(x, matchFormatting, fo);
            }

            return(deletedCount);
        }
Beispiel #6
0
        /// <summary>
        /// Checks whether 'toCheck' has all children that 'desired' has and values of 'val' attributes are the same
        /// </summary>
        /// <param name="desired"></param>
        /// <param name="toCheck"></param>
        /// <param name="fo">Matching options whether check if desired attributes are inder a, or a has exactly and only these attributes as b has.</param>
        /// <returns></returns>
        internal static bool ContainsEveryChildOf(XElement desired, XElement toCheck, MatchFormattingOptions fo)
        {
            foreach (XElement e in desired.Elements())
            {
                // If a formatting property has the same name and 'val' attribute's value, its considered to be equivalent.
                if (!toCheck.Elements(e.Name).Where(bElement => bElement.GetAttribute(XName.Get("val", DocX.w.NamespaceName)) == e.GetAttribute(XName.Get("val", DocX.w.NamespaceName))).Any())
                    return false;
            }

            // If the formatting has to be exact, no additionaly formatting must exist.
            if (fo == MatchFormattingOptions.ExactMatch)
                return desired.Elements().Count() == toCheck.Elements().Count();

            return true;
        }
Beispiel #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="searchValue">The value to find.</param>
        /// <param name="regexMatchHandler">A Func who accepts the matching regex search group value and passes it to this to return the replacement string.</param>
        /// <param name="trackChanges">Enable or disable the track changes.</param>
        /// <param name="options">The Regex options.</param>
        /// <param name="newFormatting"></param>
        /// <param name="matchFormatting"></param>
        /// <param name="fo"></param>
        /// <param name="removeEmptyParagraph">Remove empty paragraph</param>
        public virtual void ReplaceText(string searchValue,
                                        Func <string, string> regexMatchHandler,
                                        bool trackChanges          = false,
                                        RegexOptions options       = RegexOptions.None,
                                        Formatting newFormatting   = null,
                                        Formatting matchFormatting = null,
                                        MatchFormattingOptions fo  = MatchFormattingOptions.SubsetMatch,
                                        bool removeEmptyParagraph  = true)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                throw new ArgumentException("searchValue cannot be null or empty.", "searchValue");
            }
            if (regexMatchHandler == null)
            {
                throw new ArgumentException("regexMatchHandler cannot be null", "regexMatchHandler");
            }

            // Replace text in headers and footers of the Document.
            foreach (var section in this.Document.Sections)
            {
                var headersFootersList = new List <IParagraphContainer>()
                {
                    section.Headers.First,
                    section.Headers.Even,
                    section.Headers.Odd,
                    section.Footers.First,
                    section.Footers.Even,
                    section.Footers.Odd,
                };

                foreach (var hf in headersFootersList)
                {
                    if (hf != null)
                    {
                        foreach (var p in hf.Paragraphs)
                        {
                            p.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, fo, removeEmptyParagraph);
                        }
                    }
                }
            }

            foreach (var p in this.Paragraphs)
            {
                p.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, fo, removeEmptyParagraph);
            }
        }
Beispiel #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="searchValue">The value to find.</param>
        /// <param name="regexMatchHandler">A Func who accepts the matching regex search group value and passes it to this to return the replacement string.</param>
        /// <param name="trackChanges">Enable or disable the track changes.</param>
        /// <param name="options">The Regex options.</param>
        /// <param name="newFormatting"></param>
        /// <param name="matchFormatting"></param>
        /// <param name="fo"></param>
        /// <param name="removeEmptyParagraph">Remove empty paragraph</param>
        public virtual void ReplaceText(string searchValue,
                                        Func <string, string> regexMatchHandler,
                                        bool trackChanges          = false,
                                        RegexOptions options       = RegexOptions.None,
                                        Formatting newFormatting   = null,
                                        Formatting matchFormatting = null,
                                        MatchFormattingOptions fo  = MatchFormattingOptions.SubsetMatch,
                                        bool removeEmptyParagraph  = true)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                throw new ArgumentException("searchValue cannot be null or empty.", "searchValue");
            }
            if (regexMatchHandler == null)
            {
                throw new ArgumentException("regexMatchHandler cannot be null", "regexMatchHandler");
            }

            foreach (var p in this.Paragraphs)
            {
                p.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, fo, removeEmptyParagraph);
            }
        }
Beispiel #9
0
        public virtual void ReplaceTextWithObject(string searchValue,
                                                  DocumentElement objectToAdd,
                                                  bool trackChanges          = false,
                                                  RegexOptions options       = RegexOptions.None,
                                                  Formatting matchFormatting = null,
                                                  MatchFormattingOptions fo  = MatchFormattingOptions.SubsetMatch,
                                                  bool escapeRegEx           = true,
                                                  bool removeEmptyParagraph  = true)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                throw new ArgumentException("searchValue cannot be null or empty.", "searchValue");
            }
            if (objectToAdd == null)
            {
                throw new ArgumentException("objectToAdd cannot be null.", "objectToAdd");
            }

            // ReplaceText in the container
            foreach (Paragraph p in this.Paragraphs)
            {
                p.ReplaceTextWithObject(searchValue, objectToAdd, trackChanges, options, matchFormatting, fo, escapeRegEx, removeEmptyParagraph);
            }
        }
Beispiel #10
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchValue">Value to find</param>
        /// <param name="regexMatchHandler">A Func that accepts the matching regex search group value and passes it to this to return the replacement string</param>
        /// <param name="trackChanges">Enable trackchanges</param>
        /// <param name="options">Regex options</param>
        /// <param name="newFormatting"></param>
        /// <param name="matchFormatting"></param>
        /// <param name="formattingOptions"></param>
        public virtual void ReplaceText(string searchValue, Func<string,string> regexMatchHandler, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions formattingOptions = MatchFormattingOptions.SubsetMatch)
        {
            if (string.IsNullOrEmpty(searchValue))
                throw new ArgumentException("oldValue cannot be null or empty", "searchValue");

            if (regexMatchHandler == null)
                throw new ArgumentException("regexMatchHandler cannot be null", "regexMatchHandler");

            // ReplaceText in Headers/Footers of the document.
            var containerList = new List<IParagraphContainer> {
                Document.Headers.first, Document.Headers.even, Document.Headers.odd,
                Document.Footers.first, Document.Footers.even, Document.Footers.odd };
            foreach (var container in containerList)
                if (container != null)
                    foreach (var paragraph in container.Paragraphs)
                        paragraph.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions);

            // ReplaceText int main body of document.
            foreach (var paragraph in Paragraphs)
                paragraph.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions);
        }
Beispiel #11
0
        public virtual void ReplaceText(string searchValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions formattingOptions = MatchFormattingOptions.SubsetMatch, bool escapeRegEx = true, bool useRegExSubstitutions = false)
        {
            if (string.IsNullOrEmpty(searchValue))
                throw new ArgumentException("oldValue cannot be null or empty", "searchValue");

            if (newValue == null)
                throw new ArgumentException("newValue cannot be null or empty", "newValue");
            // ReplaceText in Headers of the document.
            var headerList = new List<Header> { Document.Headers.first, Document.Headers.even, Document.Headers.odd };
            foreach (var header in headerList)
                if (header != null)
                    foreach (var paragraph in header.Paragraphs)
                        paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);

            // ReplaceText int main body of document.
            foreach (var paragraph in Paragraphs)
                paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);

            // ReplaceText in Footers of the document.
            var footerList = new List<Footer> { Document.Footers.first, Document.Footers.even, Document.Footers.odd };
            foreach (var footer in footerList)
                if (footer != null)
                    foreach (var paragraph in footer.Paragraphs)
                        paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
        }
Beispiel #12
0
        /// <summary>
        /// Removes all items with required formatting
        /// </summary>
        /// <returns>Numer of texts removed</returns>
        public int RemoveTextInGivenFormat(Formatting matchFormatting, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
        {
            var deletedCount = 0;
            foreach (var x in Xml.Elements())
            {
                deletedCount += RemoveTextWithFormatRecursive(x, matchFormatting, fo);
            }

            return deletedCount;
        }
Beispiel #13
0
        internal static bool ContainsEveryChildOf(XElement elementWanted, XElement elementToValidate, MatchFormattingOptions formattingOptions)
        {
            foreach (XElement subElement in elementWanted.Elements())
            {
                if (!elementToValidate.Elements(subElement.Name).Where(bElement => bElement.GetAttribute(XName.Get("val", DocX.w.NamespaceName)) == subElement.GetAttribute(XName.Get("val", DocX.w.NamespaceName))).Any())
                {
                    return(false);
                }
            }

            if (formattingOptions == MatchFormattingOptions.ExactMatch)
            {
                return(elementWanted.Elements().Count() == elementToValidate.Elements().Count());
            }

            return(true);
        }
Beispiel #14
0
        internal bool ContainsEveryChildOf(XElement a, XElement b, MatchFormattingOptions fo)
        {
            foreach (XElement e in a.Elements())
            {
                // If a formatting property has the same name and value, its considered to be equivalent.
                if (!b.Elements(e.Name).Where(bElement => bElement.Value == e.Value).Any())
                    return false;
            }

            // If the formatting has to be exact, no additionaly formatting must exist.
            if (fo == MatchFormattingOptions.ExactMatch)
                return a.Elements().Count() == b.Elements().Count();

            return true;
        }
Beispiel #15
0
        /// <summary>
        /// Replaces all occurrences of a specified System.String in this instance, with another specified System.String.
        /// </summary>
        /// <example>
        /// <code>
        /// // Load a document using a relative filename.
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // The formatting to match.
        ///     Formatting matchFormatting = new Formatting();
        ///     matchFormatting.Size = 10;
        ///     matchFormatting.Italic = true;
        ///     matchFormatting.FontFamily = new FontFamily("Times New Roman");
        ///
        ///     // The formatting to apply to the inserted text.
        ///     Formatting newFormatting = new Formatting();
        ///     newFormatting.Size = 22;
        ///     newFormatting.UnderlineStyle = UnderlineStyle.dotted;
        ///     newFormatting.Bold = true;
        ///
        ///     // Iterate through the paragraphs in this document.
        ///     foreach (Paragraph p in document.Paragraphs)
        ///     {
        ///         /* 
        ///          * Replace all instances of the string "wrong" with the string "right" and ignore case.
        ///          * Each inserted instance of "wrong" should use the Formatting newFormatting.
        ///          * Only replace an instance of "wrong" if it is Size 10, Italic and Times New Roman.
        ///          * SubsetMatch means that the formatting must contain all elements of the match formatting,
        ///          * but it can also contain additional formatting for example Color, UnderlineStyle, etc.
        ///          * ExactMatch means it must not contain additional formatting.
        ///          */
        ///         p.ReplaceText("wrong", "right", false, RegexOptions.IgnoreCase, newFormatting, matchFormatting, MatchFormattingOptions.SubsetMatch);
        ///     }
        ///
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        /// <seealso cref="Paragraph.RemoveText(int, int, bool)"/>
        /// <seealso cref="Paragraph.RemoveText(int, bool)"/>
        /// <seealso cref="Paragraph.InsertText(string, bool)"/>
        /// <seealso cref="Paragraph.InsertText(int, string, bool)"/>
        /// <seealso cref="Paragraph.InsertText(int, string, bool, Formatting)"/>
        /// <seealso cref="Paragraph.InsertText(string, bool, Formatting)"/>
        /// <param name="newValue">A System.String to replace all occurances of oldValue.</param>
        /// <param name="oldValue">A System.String to be replaced.</param>
        /// <param name="options">A bitwise OR combination of RegexOption enumeration options.</param>
        /// <param name="trackChanges">Track changes</param>
        /// <param name="newFormatting">The formatting to apply to the text being inserted.</param>
        /// <param name="matchFormatting">The formatting that the text must match in order to be replaced.</param>
        /// <param name="fo">How should formatting be matched?</param>
        public void ReplaceText(string oldValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
        {
            MatchCollection mc = Regex.Matches(this.Text, Regex.Escape(oldValue), options);

            // Loop through the matches in reverse order
            foreach (Match m in mc.Cast<Match>().Reverse())
            {
                // Assume the formatting matches until proven otherwise.
                bool formattingMatch = true;

                // Does the user want to match formatting?
                if (matchFormatting != null)
                {
                    // The number of characters processed so far
                    int processed = 0;

                    do
                    {
                        // Get the next run effected
                        Run run = GetFirstRunEffectedByEdit(m.Index + processed);

                        // Get this runs properties
                        XElement rPr = run.Xml.Element(XName.Get("rPr", DocX.w.NamespaceName));

                        if (rPr == null)
                            rPr = new Formatting().Xml;

                        /* 
                         * Make sure that every formatting element in f.xml is also in this run,
                         * if this is not true, then their formatting does not match.
                         */
                        if (!ContainsEveryChildOf(matchFormatting.Xml, rPr, fo))
                        {
                            formattingMatch = false;
                            break;
                        }

                        // We have processed some characters, so update the counter.
                        processed += run.Value.Length;

                    } while (processed < m.Length);
                }

                // If the formatting matches, do the replace.
                if (formattingMatch)
                {
                    InsertText(m.Index + oldValue.Length, newValue, trackChanges, newFormatting);
                    RemoveText(m.Index, m.Length, trackChanges);
                }
            }
        }
Beispiel #16
0
        /// <summary>
        /// Checks whether 'toCheck' has all children that 'desired' has and values of 'val' attributes are the same
        /// </summary>
        /// <param name="desired"></param>
        /// <param name="toCheck"></param>
        /// <param name="fo">Matching options whether check if desired attributes are inder a, or a has exactly and only these attributes as b has.</param>
        /// <returns></returns>
        internal static bool ContainsEveryChildOf(XElement desired, XElement toCheck, MatchFormattingOptions fo)
        {
            foreach (XElement e in desired.Elements())
            {
                // If a formatting property has the same name and 'val' attribute's value, its considered to be equivalent.
                if (!toCheck.Elements(e.Name).Where(bElement => bElement.GetAttribute(XName.Get("val", DocX.w.NamespaceName)) == e.GetAttribute(XName.Get("val", DocX.w.NamespaceName))).Any())
                {
                    return(false);
                }
            }

            // If the formatting has to be exact, no additionaly formatting must exist.
            if (fo == MatchFormattingOptions.ExactMatch)
            {
                return(desired.Elements().Count() == toCheck.Elements().Count());
            }

            return(true);
        }
Beispiel #17
0
        public virtual void ReplaceText(string searchValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions formattingOptions = MatchFormattingOptions.SubsetMatch, bool escapeRegEx = true, bool useRegExSubstitutions = false)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                throw new ArgumentException("oldValue cannot be null or empty", "searchValue");
            }

            if (newValue == null)
            {
                throw new ArgumentException("newValue cannot be null or empty", "newValue");
            }
            // ReplaceText in Headers of the document.
            var headerList = new List <Header> {
                Document.Headers.first, Document.Headers.even, Document.Headers.odd
            };

            foreach (var header in headerList)
            {
                if (header != null)
                {
                    foreach (var paragraph in header.Paragraphs)
                    {
                        paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
                    }
                }
            }

            // ReplaceText int main body of document.
            foreach (var paragraph in Paragraphs)
            {
                paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
            }

            // ReplaceText in Footers of the document.
            var footerList = new List <Footer> {
                Document.Footers.first, Document.Footers.even, Document.Footers.odd
            };

            foreach (var footer in footerList)
            {
                if (footer != null)
                {
                    foreach (var paragraph in footer.Paragraphs)
                    {
                        paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
                    }
                }
            }
        }
Beispiel #18
0
 internal static bool ContainsEveryChildOf(XElement desired, XElement toCheck, MatchFormattingOptions fo)
 {
     foreach (XElement item in desired.Elements())
     {
         if (!(from bElement in toCheck.Elements(item.Name)
               where bElement.GetAttribute(XName.Get("val", DocX.w.NamespaceName)) == item.GetAttribute(XName.Get("val", DocX.w.NamespaceName))
               select bElement).Any())
         {
             return(false);
         }
     }
     if (fo == MatchFormattingOptions.ExactMatch)
     {
         return(desired.Elements().Count() == toCheck.Elements().Count());
     }
     return(true);
 }
Beispiel #19
0
        public virtual void ReplaceText(string searchValue, Func <string, string> regexMatchHandler, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions formattingOptions = MatchFormattingOptions.SubsetMatch)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                throw new ArgumentException("oldValue cannot be null or empty", "searchValue");
            }
            if (regexMatchHandler == null)
            {
                throw new ArgumentException("regexMatchHandler cannot be null", "regexMatchHandler");
            }
            List <IParagraphContainer> list = new List <IParagraphContainer>
            {
                base.Document.Headers.first,
                base.Document.Headers.even,
                base.Document.Headers.odd,
                base.Document.Footers.first,
                base.Document.Footers.even,
                base.Document.Footers.odd
            };

            foreach (IParagraphContainer item in list)
            {
                if (item != null)
                {
                    foreach (Paragraph paragraph in item.Paragraphs)
                    {
                        paragraph.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions);
                    }
                }
            }
            foreach (Paragraph paragraph2 in Paragraphs)
            {
                paragraph2.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions);
            }
        }
Beispiel #20
0
        public virtual void ReplaceText(string searchValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions formattingOptions = MatchFormattingOptions.SubsetMatch, bool escapeRegEx = true, bool useRegExSubstitutions = false)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                throw new ArgumentException("oldValue cannot be null or empty", "searchValue");
            }
            if (newValue == null)
            {
                throw new ArgumentException("newValue cannot be null or empty", "newValue");
            }
            List <Header> list = new List <Header>
            {
                base.Document.Headers.first,
                base.Document.Headers.even,
                base.Document.Headers.odd
            };

            foreach (Header item in list)
            {
                if (item != null)
                {
                    foreach (Paragraph paragraph in item.Paragraphs)
                    {
                        paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
                    }
                }
            }
            foreach (Paragraph paragraph2 in Paragraphs)
            {
                paragraph2.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
            }
            List <Footer> list2 = new List <Footer>
            {
                base.Document.Footers.first,
                base.Document.Footers.even,
                base.Document.Footers.odd
            };

            foreach (Footer item2 in list2)
            {
                if (item2 != null)
                {
                    foreach (Paragraph paragraph3 in item2.Paragraphs)
                    {
                        paragraph3.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
                    }
                }
            }
        }
Beispiel #21
0
        /// <summary>
        /// Replaces all occurrences of a specified System.String in this instance, with another specified System.String.
        /// </summary>
        /// <example>
        /// <code>
        /// // Load a document using a relative filename.
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // The formatting to match.
        ///     Formatting matchFormatting = new Formatting();
        ///     matchFormatting.Size = 10;
        ///     matchFormatting.Italic = true;
        ///     matchFormatting.FontFamily = new FontFamily("Times New Roman");
        ///
        ///     // The formatting to apply to the inserted text.
        ///     Formatting newFormatting = new Formatting();
        ///     newFormatting.Size = 22;
        ///     newFormatting.UnderlineStyle = UnderlineStyle.dotted;
        ///     newFormatting.Bold = true;
        ///
        ///     // Iterate through the paragraphs in this document.
        ///     foreach (Paragraph p in document.Paragraphs)
        ///     {
        ///         /* 
        ///          * Replace all instances of the string "wrong" with the string "right" and ignore case.
        ///          * Each inserted instance of "wrong" should use the Formatting newFormatting.
        ///          * Only replace an instance of "wrong" if it is Size 10, Italic and Times New Roman.
        ///          * SubsetMatch means that the formatting must contain all elements of the match formatting,
        ///          * but it can also contain additional formatting for example Color, UnderlineStyle, etc.
        ///          * ExactMatch means it must not contain additional formatting.
        ///          */
        ///         p.ReplaceText("wrong", "right", false, RegexOptions.IgnoreCase, newFormatting, matchFormatting, MatchFormattingOptions.SubsetMatch);
        ///     }
        ///
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        /// <seealso cref="Paragraph.RemoveText(int, int, bool)"/>
        /// <seealso cref="Paragraph.RemoveText(int, bool)"/>
        /// <seealso cref="Paragraph.InsertText(int, string, bool, Formatting)"/>
        /// <seealso cref="Paragraph.InsertText(string, bool, Formatting)"/>
        /// <param name="newValue">A System.String to replace all occurrences of oldValue.</param>
        /// <param name="oldValue">A System.String to be replaced.</param>
        /// <param name="options">A bitwise OR combination of RegexOption enumeration options.</param>
        /// <param name="trackChanges">Track changes</param>
        /// <param name="newFormatting">The formatting to apply to the text being inserted.</param>
        /// <param name="matchFormatting">The formatting that the text must match in order to be replaced.</param>
        /// <param name="fo">How should formatting be matched?</param>
        /// <param name="escapeRegEx">True if the oldValue needs to be escaped, otherwise false. If it represents a valid RegEx pattern this should be false.</param>
        /// <param name="useRegExSubstitutions">True if RegEx-like replace should be performed, i.e. if newValue contains RegEx substitutions. Does not perform named-group substitutions (only numbered groups).</param>
        public void ReplaceText(string oldValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch, bool escapeRegEx = true, bool useRegExSubstitutions = false)
        {
            string tText = Text;
            MatchCollection mc = Regex.Matches(tText, escapeRegEx ? Regex.Escape(oldValue) : oldValue, options);

            // Loop through the matches in reverse order
            foreach (Match m in mc.Cast<Match>().Reverse())
            {
                // Assume the formatting matches until proven otherwise.
                bool formattingMatch = true;

                // Does the user want to match formatting?
                if (matchFormatting != null)
                {
                    // The number of characters processed so far
                    int processed = 0;

                    do
                    {
                        // Get the next run effected
                        Run run = GetFirstRunEffectedByEdit(m.Index + processed);

                        // Get this runs properties
                        XElement rPr = run.Xml.Element(XName.Get("rPr", DocX.w.NamespaceName));

                        if (rPr == null)
                            rPr = new Formatting().Xml;

                        /*
                         * Make sure that every formatting element in f.xml is also in this run,
                         * if this is not true, then their formatting does not match.
                         */
                        if (!HelperFunctions.ContainsEveryChildOf(matchFormatting.Xml, rPr, fo))
                        {
                            formattingMatch = false;
                            break;
                        }

                        // We have processed some characters, so update the counter.
                        processed += run.Value.Length;

                    } while (processed < m.Length);
                }

                // If the formatting matches, do the replace.
                if (formattingMatch)
                {
                    string repl = newValue;
                    //perform RegEx substitutions. Only named groups are not supported. Everything else is supported. However character escapes are not covered.
                    if (useRegExSubstitutions && !String.IsNullOrEmpty(repl))
                    {
                        repl = repl.Replace("$&", m.Value);
                        if (m.Groups.Count > 0)
                        {
                            int lastcap = 0;
                            for (int k = 0; k < m.Groups.Count; k++)
                            {
                                var g = m.Groups[k];
                                if ((g == null) || (g.Value == ""))
                                    continue;
                                repl = repl.Replace("$" + k.ToString(), g.Value);
                                lastcap = k;
                                //cannot get named groups ATM
                            }
                            repl = repl.Replace("$+", m.Groups[lastcap].Value);
                        }
                        if (m.Index > 0)
                        {
                            repl = repl.Replace("$`", tText.Substring(0, m.Index));
                        }
                        if ((m.Index + m.Length) < tText.Length)
                        {
                            repl = repl.Replace("$'", tText.Substring(m.Index + m.Length));
                        }
                        repl = repl.Replace("$_", tText);
                        repl = repl.Replace("$$", "$");
                    }
                    if (!String.IsNullOrEmpty(repl))
                        InsertText(m.Index + m.Length, repl, trackChanges, newFormatting);
                    if (m.Length > 0)
                        RemoveText(m.Index, m.Length, trackChanges);
                }
            }
        }
Beispiel #22
0
        public virtual void ReplaceText(string oldValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
        {
            // ReplaceText in Headers of the document.
            Headers       headers    = Document.Headers;
            List <Header> headerList = new List <Header> {
                headers.first, headers.even, headers.odd
            };

            foreach (Header h in headerList)
            {
                if (h != null)
                {
                    foreach (Paragraph p in h.Paragraphs)
                    {
                        p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
                    }
                }
            }

            // ReplaceText int main body of document.
            foreach (Paragraph p in Paragraphs)
            {
                p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
            }

            // ReplaceText in Footers of the document.
            Footers       footers    = Document.Footers;
            List <Footer> footerList = new List <Footer> {
                footers.first, footers.even, footers.odd
            };

            foreach (Footer f in footerList)
            {
                if (f != null)
                {
                    foreach (Paragraph p in f.Paragraphs)
                    {
                        p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
                    }
                }
            }
        }
Beispiel #23
0
        internal int RemoveTextWithFormatRecursive(XElement element, Formatting matchFormatting, MatchFormattingOptions fo)
        {
            var deletedCount = 0;
            foreach (var x in element.Elements())
            {
                if ("rPr".Equals(x.Name.LocalName))
                {
                    if (HelperFunctions.ContainsEveryChildOf(matchFormatting.Xml, x, fo))
                    {
                        x.Parent.Remove();
                        ++deletedCount;
                    }
                }

                deletedCount += RemoveTextWithFormatRecursive(x, matchFormatting, fo);
            }

            return deletedCount;
        }
Beispiel #24
0
        internal int RecursiveRemoveText(XElement element, Formatting formattingToMatch, MatchFormattingOptions formattingOptions)
        {
            var count = 0;

            foreach (var subElement in element.Elements())
            {
                if ("rPr".Equals(subElement.Name.LocalName))
                {
                    if (HelperFunctions.ContainsEveryChildOf(formattingToMatch.Xml, subElement, formattingOptions))
                    {
                        subElement.Parent.Remove();
                        ++count;
                    }
                }

                count += RecursiveRemoveText(subElement, formattingToMatch, formattingOptions);
            }

            return(count);
        }
Beispiel #25
0
        public virtual void ReplaceText(string oldValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
        {
            // PATCH BY HeDo - Arguments check!
            if (oldValue == null || oldValue.Length == 0)
            {
                throw new ArgumentException("oldValue cannot be null or empty", "oldValue");
            }

            if (newValue == null || newValue.Length == 0)
            {
                throw new ArgumentException("newValue cannot be null or empty", "newValue");
            }
            // ReplaceText in Headers of the document.
            Headers       headers    = Document.Headers;
            List <Header> headerList = new List <Header> {
                headers.first, headers.even, headers.odd
            };

            foreach (Header h in headerList)
            {
                if (h != null)
                {
                    foreach (Paragraph p in h.Paragraphs)
                    {
                        p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
                    }
                }
            }

            // ReplaceText int main body of document.
            foreach (Paragraph p in Paragraphs)
            {
                p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
            }

            // ReplaceText in Footers of the document.
            Footers       footers    = Document.Footers;
            List <Footer> footerList = new List <Footer> {
                footers.first, footers.even, footers.odd
            };

            foreach (Footer f in footerList)
            {
                if (f != null)
                {
                    foreach (Paragraph p in f.Paragraphs)
                    {
                        p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
                    }
                }
            }
        }
Beispiel #26
0
        public virtual void ReplaceTextWithObject(string searchValue,
                                                  DocumentElement objectToAdd,
                                                  bool trackChanges          = false,
                                                  RegexOptions options       = RegexOptions.None,
                                                  Formatting matchFormatting = null,
                                                  MatchFormattingOptions fo  = MatchFormattingOptions.SubsetMatch,
                                                  bool escapeRegEx           = true,
                                                  bool removeEmptyParagraph  = true)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                throw new ArgumentException("searchValue cannot be null or empty.", "searchValue");
            }
            if (objectToAdd == null)
            {
                throw new ArgumentException("objectToAdd cannot be null.", "objectToAdd");
            }

            // ReplaceText in Headers of the document.
            foreach (var section in this.Document.Sections)
            {
                var headerList = new List <Header>()
                {
                    section.Headers.First, section.Headers.Even, section.Headers.Odd
                };
                foreach (var h in headerList)
                {
                    if (h != null)
                    {
                        foreach (var p in h.Paragraphs)
                        {
                            p.ReplaceTextWithObject(searchValue, objectToAdd, trackChanges, options, matchFormatting, fo, escapeRegEx, removeEmptyParagraph);
                        }
                    }
                }
            }

            // ReplaceText int main body of document.
            foreach (Paragraph p in this.Paragraphs)
            {
                p.ReplaceTextWithObject(searchValue, objectToAdd, trackChanges, options, matchFormatting, fo, escapeRegEx, removeEmptyParagraph);
            }

            // ReplaceText in Footers of the document.
            foreach (var section in this.Document.Sections)
            {
                var footerList = new List <Footer> {
                    section.Footers.First, section.Footers.Even, section.Footers.Odd
                };
                foreach (var f in footerList)
                {
                    if (f != null)
                    {
                        foreach (var p in f.Paragraphs)
                        {
                            p.ReplaceTextWithObject(searchValue, objectToAdd, trackChanges, options, matchFormatting, fo, escapeRegEx, removeEmptyParagraph);
                        }
                    }
                }
            }
        }
Beispiel #27
0
        public virtual void ReplaceText(string oldValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
        {
            // PATCH BY HeDo - Arguments check!
            if (oldValue == null || oldValue.Length == 0)
                throw new ArgumentException("oldValue cannot be null or empty", "oldValue");

            if (newValue == null || newValue.Length == 0)
                throw new ArgumentException("newValue cannot be null or empty", "newValue");
            // ReplaceText in Headers of the document.
            Headers headers = Document.Headers;
            List<Header> headerList = new List<Header> { headers.first, headers.even, headers.odd };
            foreach (Header h in headerList)
                if (h != null)
                    foreach (Paragraph p in h.Paragraphs)
                        p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);

            // ReplaceText int main body of document.
            foreach (Paragraph p in Paragraphs)
                p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);

            // ReplaceText in Footers of the document.
            Footers footers = Document.Footers;
            List<Footer> footerList = new List<Footer> { footers.first, footers.even, footers.odd };
            foreach (Footer f in footerList)
                if (f != null)
                    foreach (Paragraph p in f.Paragraphs)
                        p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
        }
Beispiel #28
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="searchValue">Value to find</param>
        /// <param name="regexMatchHandler">A Func that accepts the matching regex search group value and passes it to this to return the replacement string</param>
        /// <param name="trackChanges">Enable trackchanges</param>
        /// <param name="options">Regex options</param>
        /// <param name="newFormatting"></param>
        /// <param name="matchFormatting"></param>
        /// <param name="formattingOptions"></param>
        public virtual void ReplaceText(string searchValue, Func <string, string> regexMatchHandler, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions formattingOptions = MatchFormattingOptions.SubsetMatch)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                throw new ArgumentException("oldValue cannot be null or empty", "searchValue");
            }

            if (regexMatchHandler == null)
            {
                throw new ArgumentException("regexMatchHandler cannot be null", "regexMatchHandler");
            }

            // ReplaceText in Headers/Footers of the document.
            var containerList = new List <IParagraphContainer> {
                Document.Headers.first, Document.Headers.even, Document.Headers.odd,
                Document.Footers.first, Document.Footers.even, Document.Footers.odd
            };

            foreach (var container in containerList)
            {
                if (container != null)
                {
                    foreach (var paragraph in container.Paragraphs)
                    {
                        paragraph.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions);
                    }
                }
            }

            // ReplaceText int main body of document.
            foreach (var paragraph in Paragraphs)
            {
                paragraph.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions);
            }
        }
Beispiel #29
0
        public virtual void ReplaceText(string oldValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
        {
            // ReplaceText in Headers of the document.
            Headers headers = Document.Headers;
            List<Header> headerList = new List<Header> { headers.first, headers.even, headers.odd };
            foreach (Header h in headerList)
                if (h != null)
                    foreach (Paragraph p in h.Paragraphs)
                        p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);

            // ReplaceText int main body of document.
            foreach (Paragraph p in Paragraphs)
                p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);

            // ReplaceText in Footers of the document.
            Footers footers = Document.Footers;
            List<Footer> footerList = new List<Footer> { footers.first, footers.even, footers.odd };
            foreach (Footer f in footerList)
                if (f != null)
                    foreach (Paragraph p in f.Paragraphs)
                        p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
        }
Beispiel #30
0
        internal int RemoveTextWithFormatRecursive(XElement element, Formatting matchFormatting, MatchFormattingOptions fo)
        {
            var deletedCount = 0;

            foreach (var x in element.Elements())
            {
                if ("rPr".Equals(x.Name.LocalName))
                {
                    if (HelperFunctions.ContainsEveryChildOf(matchFormatting.Xml, x, fo))
                    {
                        x.Parent.Remove();
                        ++deletedCount;
                    }
                }

                deletedCount += RemoveTextWithFormatRecursive(x, matchFormatting, fo);
            }

            return(deletedCount);
        }
Beispiel #31
0
        internal int RemoveTextWithFormatRecursive(XElement element, Formatting matchFormatting, MatchFormattingOptions fo)
        {
            int num = 0;

            foreach (XElement item in element.Elements())
            {
                if ("rPr".Equals(item.Name.LocalName) && HelperFunctions.ContainsEveryChildOf(matchFormatting.Xml, item, fo))
                {
                    item.Parent.Remove();
                    num++;
                }
                num += RemoveTextWithFormatRecursive(item, matchFormatting, fo);
            }
            return(num);
        }