Detailed Description

Represents a contiguous area in a document.

The document is represented by a tree of nodes and the nodes provide operations to work with the tree, but some operations are easier to perform if the document is treated as a contiguous sequence of text.

Range is a "facade" interface that provide methods that treat the document or portions of the document as "flat" text regardless of the fact that the document nodes are stored in a tree-like object model.

Range does not contain any text or nodes, it is merely a view or "window" over a fragment of a document.

Examples

Shows how to get the text contents of all the nodes that a range covers.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Write(u"Hello world!");
ASSERT_EQ(u"Hello world!", doc->get_Range()->get_Text().Trim());

#include <Aspose.Words.Cpp/Range.h>

+ Inheritance diagram for Aspose::Words::Range:

Public Member Functions

void Delete ()
 Deletes all characters of the range. More...
 
SharedPtr< BookmarkCollectionget_Bookmarks ()
 Returns a Bookmarks collection that represents all bookmarks in the range. More...
 
SharedPtr< FieldCollectionget_Fields ()
 Returns a Fields collection that represents all fields in the range. More...
 
SharedPtr< FormFieldCollectionget_FormFields ()
 Returns a FormFields collection that represents all form fields in the range. More...
 
String get_Text ()
 Gets the text of the range. More...
 
virtual const TypeInfoGetType () const override
 
virtual bool Is (const TypeInfo &target) const override
 
void NormalizeFieldTypes ()
 Changes field type values FieldType of FieldStart, FieldSeparator, FieldEnd in this range so that they correspond to the field types contained in the field codes. More...
 
int32_t Replace (SharedPtr< Regex > pattern, String replacement)
 Replaces all occurrences of a character pattern specified by a regular expression with another string. More...
 
int32_t Replace (SharedPtr< Regex > pattern, String replacement, SharedPtr< FindReplaceOptions > options)
 Replaces all occurrences of a character pattern specified by a regular expression with another string. More...
 
int32_t Replace (String pattern, String replacement)
 Replaces all occurrences of a specified character string pattern with a replacement string. More...
 
int32_t Replace (String pattern, String replacement, SharedPtr< FindReplaceOptions > options)
 Replaces all occurrences of a specified character string pattern with a replacement string. More...
 
SharedPtr< DocumentToDocument ()
 Constructs a new fully formed document that contains the range. More...
 
void UnlinkFields ()
 Unlinks fields in this range. More...
 
void UpdateFields ()
 Updates the values of document fields in this range. More...
 

Static Public Member Functions

static const TypeInfoType ()
 

Member Function Documentation

◆ Delete()

void Aspose::Words::Range::Delete ( )

Deletes all characters of the range.

Examples

Shows how to delete all the nodes from a range.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Add text to the first section in the document, and then add another section.
builder->Write(u"Section 1. ");
builder->InsertBreak(BreakType::SectionBreakContinuous);
builder->Write(u"Section 2.");
ASSERT_EQ(u"Section 1. \fSection 2.", doc->GetText().Trim());
// Remove the first section entirely by removing all the nodes
// within its range, including the section itself.
doc->get_Sections()->idx_get(0)->get_Range()->Delete();
ASSERT_EQ(1, doc->get_Sections()->get_Count());
ASSERT_EQ(u"Section 2.", doc->GetText().Trim());

◆ get_Bookmarks()

System::SharedPtr<Aspose::Words::BookmarkCollection> Aspose::Words::Range::get_Bookmarks ( )

Returns a Bookmarks collection that represents all bookmarks in the range.

Examples

Shows how to add bookmarks and update their contents.

void CreateUpdateAndPrintBookmarks()
{
// Create a document with three bookmarks, then use a custom document visitor implementation to print their contents.
SharedPtr<Document> doc = CreateDocumentWithBookmarks(3);
SharedPtr<BookmarkCollection> bookmarks = doc->get_Range()->get_Bookmarks();
PrintAllBookmarkInfo(bookmarks);
// Bookmarks can be accessed in the bookmark collection by index or name, and their names can be updated.
bookmarks->idx_get(0)->set_Name(String::Format(u"{0}_NewName", bookmarks->idx_get(0)->get_Name()));
bookmarks->idx_get(u"MyBookmark_2")->set_Text(String::Format(u"Updated text contents of {0}", bookmarks->idx_get(1)->get_Name()));
// Print all bookmarks again to see updated values.
PrintAllBookmarkInfo(bookmarks);
}
static SharedPtr<Document> CreateDocumentWithBookmarks(int numberOfBookmarks)
{
auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
for (int i = 1; i <= numberOfBookmarks; i++)
{
String bookmarkName = String(u"MyBookmark_") + i;
builder->Write(u"Text before bookmark.");
builder->StartBookmark(bookmarkName);
builder->Write(String::Format(u"Text inside {0}.", bookmarkName));
builder->EndBookmark(bookmarkName);
builder->Writeln(u"Text after bookmark.");
}
return doc;
}
static void PrintAllBookmarkInfo(SharedPtr<BookmarkCollection> bookmarks)
{
auto bookmarkVisitor = MakeObject<ExBookmarks::BookmarkInfoPrinter>();
// Get each bookmark in the collection to accept a visitor that will print its contents.
{
SharedPtr<System::Collections::Generic::IEnumerator<SharedPtr<Bookmark>>> enumerator = bookmarks->GetEnumerator();
while (enumerator->MoveNext())
{
SharedPtr<Bookmark> currentBookmark = enumerator->get_Current();
if (currentBookmark != nullptr)
{
currentBookmark->get_BookmarkStart()->Accept(bookmarkVisitor);
currentBookmark->get_BookmarkEnd()->Accept(bookmarkVisitor);
std::cout << currentBookmark->get_BookmarkStart()->GetText() << std::endl;
}
}
}
}
class BookmarkInfoPrinter : public DocumentVisitor
{
public:
VisitorAction VisitBookmarkStart(SharedPtr<BookmarkStart> bookmarkStart) override
{
std::cout << "BookmarkStart name: \"" << bookmarkStart->get_Name() << "\", Contents: \"" << bookmarkStart->get_Bookmark()->get_Text() << "\""
<< std::endl;
}
VisitorAction VisitBookmarkEnd(SharedPtr<BookmarkEnd> bookmarkEnd) override
{
std::cout << "BookmarkEnd name: \"" << bookmarkEnd->get_Name() << "\"" << std::endl;
}
};

◆ get_Fields()

System::SharedPtr<Aspose::Words::Fields::FieldCollection> Aspose::Words::Range::get_Fields ( )

Returns a Fields collection that represents all fields in the range.

◆ get_FormFields()

System::SharedPtr<Aspose::Words::Fields::FormFieldCollection> Aspose::Words::Range::get_FormFields ( )

Returns a FormFields collection that represents all form fields in the range.

Examples

Shows how insert different kinds of form fields into a document, and process them with using a document visitor implementation.

void Visitor()
{
auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Use a document builder to insert a combo box.
builder->Write(u"Choose a value from this combo box: ");
SharedPtr<FormField> comboBox = builder->InsertComboBox(u"MyComboBox", MakeArray<String>({u"One", u"Two", u"Three"}), 0);
comboBox->set_CalculateOnExit(true);
ASSERT_EQ(3, comboBox->get_DropDownItems()->get_Count());
ASSERT_EQ(0, comboBox->get_DropDownSelectedIndex());
ASSERT_TRUE(comboBox->get_Enabled());
builder->InsertBreak(BreakType::ParagraphBreak);
// Use a document builder to insert a check box.
builder->Write(u"Click this check box to tick/untick it: ");
SharedPtr<FormField> checkBox = builder->InsertCheckBox(u"MyCheckBox", false, 50);
checkBox->set_IsCheckBoxExactSize(true);
checkBox->set_HelpText(u"Right click to check this box");
checkBox->set_OwnHelp(true);
checkBox->set_StatusText(u"Checkbox status text");
checkBox->set_OwnStatus(true);
ASPOSE_ASSERT_EQ(50.0, checkBox->get_CheckBoxSize());
ASSERT_FALSE(checkBox->get_Checked());
ASSERT_FALSE(checkBox->get_Default());
builder->InsertBreak(BreakType::ParagraphBreak);
// Use a document builder to insert text input form field.
builder->Write(u"Enter text here: ");
SharedPtr<FormField> textInput = builder->InsertTextInput(u"MyTextInput", TextFormFieldType::Regular, u"", u"Placeholder text", 50);
textInput->set_EntryMacro(u"EntryMacro");
textInput->set_ExitMacro(u"ExitMacro");
textInput->set_TextInputDefault(u"Regular");
textInput->set_TextInputFormat(u"FIRST CAPITAL");
textInput->SetTextInputValue(System::ObjectExt::Box<String>(u"New placeholder text"));
ASSERT_EQ(TextFormFieldType::Regular, textInput->get_TextInputType());
ASSERT_EQ(50, textInput->get_MaxLength());
// This collection contains all our form fields.
SharedPtr<FormFieldCollection> formFields = doc->get_Range()->get_FormFields();
ASSERT_EQ(3, formFields->get_Count());
// Fields display our form fields. We can see their field codes by opening this document
// in Microsoft and pressing Alt + F9. These fields have no switches,
// and members of the FormField object fully govern their form fields' content.
ASSERT_EQ(3, doc->get_Range()->get_Fields()->get_Count());
ASSERT_EQ(u" FORMDROPDOWN \u0001", doc->get_Range()->get_Fields()->idx_get(0)->GetFieldCode());
ASSERT_EQ(u" FORMCHECKBOX \u0001", doc->get_Range()->get_Fields()->idx_get(1)->GetFieldCode());
ASSERT_EQ(u" FORMTEXT \u0001", doc->get_Range()->get_Fields()->idx_get(2)->GetFieldCode());
// Allow each form field to accept a document visitor.
auto formFieldVisitor = MakeObject<ExFormFields::FormFieldVisitor>();
{
SharedPtr<System::Collections::Generic::IEnumerator<SharedPtr<FormField>>> fieldEnumerator = formFields->GetEnumerator();
while (fieldEnumerator->MoveNext())
{
fieldEnumerator->get_Current()->Accept(formFieldVisitor);
}
}
std::cout << formFieldVisitor->GetText() << std::endl;
doc->UpdateFields();
doc->Save(ArtifactsDir + u"FormFields.Visitor.html");
}
class FormFieldVisitor : public DocumentVisitor
{
public:
FormFieldVisitor()
{
mBuilder = MakeObject<System::Text::StringBuilder>();
}
VisitorAction VisitFormField(SharedPtr<FormField> formField) override
{
AppendLine(System::ObjectExt::ToString(formField->get_Type()) + u": \"" + formField->get_Name() + u"\"");
AppendLine(String(u"\tStatus: ") + (formField->get_Enabled() ? String(u"Enabled") : String(u"Disabled")));
AppendLine(String(u"\tHelp Text: ") + formField->get_HelpText());
AppendLine(String(u"\tEntry macro name: ") + formField->get_EntryMacro());
AppendLine(String(u"\tExit macro name: ") + formField->get_ExitMacro());
switch (formField->get_Type())
{
case FieldType::FieldFormDropDown:
AppendLine(String(u"\tDrop-down items count: ") + formField->get_DropDownItems()->get_Count() + u", default selected item index: " +
formField->get_DropDownSelectedIndex());
AppendLine(String(u"\tDrop-down items: ") + String::Join(u", ", formField->get_DropDownItems()->LINQ_ToArray()));
break;
case FieldType::FieldFormCheckBox:
AppendLine(String(u"\tCheckbox size: ") + formField->get_CheckBoxSize());
AppendLine(String(u"\t") + u"Checkbox is currently: " + (formField->get_Checked() ? String(u"checked, ") : String(u"unchecked, ")) +
u"by default: " + (formField->get_Default() ? String(u"checked") : String(u"unchecked")));
break;
case FieldType::FieldFormTextInput:
AppendLine(String(u"\tInput format: ") + formField->get_TextInputFormat());
AppendLine(String(u"\tCurrent contents: ") + formField->get_Result());
break;
default:
break;
}
// Let the visitor continue visiting other nodes.
}
String GetText()
{
return mBuilder->ToString();
}
private:
SharedPtr<System::Text::StringBuilder> mBuilder;
void AppendLine(String text)
{
mBuilder->Append(text + u'\n');
}
};

◆ get_Text()

System::String Aspose::Words::Range::get_Text ( )

Gets the text of the range.

The returned string includes all control and special characters as described in ControlChar.

Examples

Shows how to get the text contents of all the nodes that a range covers.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Write(u"Hello world!");
ASSERT_EQ(u"Hello world!", doc->get_Range()->get_Text().Trim());

◆ GetType()

virtual const System::TypeInfo& Aspose::Words::Range::GetType ( ) const
overridevirtual

Reimplemented from System::Object.

◆ Is()

virtual bool Aspose::Words::Range::Is ( const System::TypeInfo target) const
overridevirtual

Reimplemented from System::Object.

◆ NormalizeFieldTypes()

void Aspose::Words::Range::NormalizeFieldTypes ( )

Changes field type values FieldType of FieldStart, FieldSeparator, FieldEnd in this range so that they correspond to the field types contained in the field codes.

Use this method after document changes that affect field types.

To change field type values in the whole document use NormalizeFieldTypes.

◆ Replace() [1/4]

int32_t Aspose::Words::Range::Replace ( System::SharedPtr< System::Text::RegularExpressions::Regex pattern,
System::String  replacement 
)

Replaces all occurrences of a character pattern specified by a regular expression with another string.

Replaces the whole match captured by the regular expression.

Method is able to process breaks in both pattern and replacement strings.

You should use special meta-characters if you need to work with breaks:

  • %&p - paragraph break
  • %&b - section break
  • %&m - page break
  • %&l - manual line break
Parameters
patternA regular expression pattern used to find matches.
replacementA string to replace all occurrences of pattern.
Returns
The number of replacements made.
Examples

Shows how to replace all occurrences of a regular expression pattern with other text.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"I decided to get the curtains in gray, ideal for the grey-accented room.");
doc->get_Range()->Replace(MakeObject<System::Text::RegularExpressions::Regex>(u"gr(a|e)y"), u"lavender");
ASSERT_EQ(u"I decided to get the curtains in lavender, ideal for the lavender-accented room.", doc->GetText().Trim());

◆ Replace() [2/4]

int32_t Aspose::Words::Range::Replace ( System::SharedPtr< System::Text::RegularExpressions::Regex pattern,
System::String  replacement,
System::SharedPtr< Aspose::Words::Replacing::FindReplaceOptions options 
)

Replaces all occurrences of a character pattern specified by a regular expression with another string.

Replaces the whole match captured by the regular expression.

Method is able to process breaks in both pattern and replacement strings.

You should use special meta-characters if you need to work with breaks:

  • %&p - paragraph break
  • %&b - section break
  • %&m - page break
  • %&l - manual line break
  • %&& - & character
Parameters
patternA regular expression pattern used to find matches.
replacementA string to replace all occurrences of pattern.
optionsFindReplaceOptions object to specify additional options.
Returns
The number of replacements made.
Examples

Shows how to replace all occurrences of a regular expression pattern with another string, while tracking all such replacements.

void ReplaceWithCallback()
{
auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(String(u"Our new location in New York City is opening tomorrow. ") + u"Hope to see all our NYC-based customers at the opening!");
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
auto options = MakeObject<FindReplaceOptions>();
// Set a callback that tracks any replacements that the "Replace" method will make.
auto logger = MakeObject<ExRange::TextFindAndReplacementLogger>();
options->set_ReplacingCallback(logger);
doc->get_Range()->Replace(MakeObject<System::Text::RegularExpressions::Regex>(u"New York City|NYC"), u"Washington", options);
ASSERT_EQ(String(u"Our new location in (Old value:\"New York City\") Washington is opening tomorrow. ") +
u"Hope to see all our (Old value:\"NYC\") Washington-based customers at the opening!",
doc->GetText().Trim());
ASSERT_EQ(String(u"\"New York City\" converted to \"Washington\" 20 characters into a Run node.\r\n") +
u"\"NYC\" converted to \"Washington\" 42 characters into a Run node.",
logger->GetLog().Trim());
}
class TextFindAndReplacementLogger : public IReplacingCallback
{
public:
ReplaceAction Replacing(SharedPtr<ReplacingArgs> args) override
{
mLog->AppendLine(String::Format(u"\"{0}\" converted to \"{1}\" ", args->get_Match()->get_Value(), args->get_Replacement()) +
String::Format(u"{0} characters into a {1} node.", args->get_MatchOffset(), args->get_MatchNode()->get_NodeType()));
args->set_Replacement(String::Format(u"(Old value:\"{0}\") {1}", args->get_Match()->get_Value(), args->get_Replacement()));
return ReplaceAction::Replace;
}
String GetLog()
{
return mLog->ToString();
}
TextFindAndReplacementLogger() : mLog(MakeObject<System::Text::StringBuilder>())
{
}
private:
SharedPtr<System::Text::StringBuilder> mLog;
};

Shows how to insert an entire document's contents as a replacement of a match in a find-and-replace operation.

void InsertDocumentAtReplace()
{
auto mainDoc = MakeObject<Document>(MyDir + u"Document insertion destination.docx");
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
auto options = MakeObject<FindReplaceOptions>();
options->set_ReplacingCallback(MakeObject<ExRange::InsertDocumentAtReplaceHandler>());
mainDoc->get_Range()->Replace(MakeObject<System::Text::RegularExpressions::Regex>(u"\\[MY_DOCUMENT\\]"), u"", options);
mainDoc->Save(ArtifactsDir + u"InsertDocument.InsertDocumentAtReplace.docx");
}
class InsertDocumentAtReplaceHandler : public IReplacingCallback
{
public:
ReplaceAction Replacing(SharedPtr<ReplacingArgs> args) override
{
auto subDoc = MakeObject<Document>(MyDir + u"Document.docx");
// Insert a document after the paragraph containing the matched text.
auto para = System::DynamicCast<Paragraph>(args->get_MatchNode()->get_ParentNode());
InsertDocument(para, subDoc);
// Remove the paragraph with the matched text.
para->Remove();
return ReplaceAction::Skip;
}
};
static void InsertDocument(SharedPtr<Node> insertionDestination, SharedPtr<Document> docToInsert)
{
if (insertionDestination->get_NodeType() == NodeType::Paragraph || insertionDestination->get_NodeType() == NodeType::Table)
{
SharedPtr<CompositeNode> dstStory = insertionDestination->get_ParentNode();
auto importer = MakeObject<NodeImporter>(docToInsert, insertionDestination->get_Document(), ImportFormatMode::KeepSourceFormatting);
for (auto srcSection : System::IterateOver(docToInsert->get_Sections()->LINQ_OfType<SharedPtr<Section>>()))
{
for (auto srcNode : System::IterateOver(srcSection->get_Body()))
{
// Skip the node if it is the last empty paragraph in a section.
if (srcNode->get_NodeType() == NodeType::Paragraph)
{
auto para = System::DynamicCast<Paragraph>(srcNode);
if (para->get_IsEndOfSection() && !para->get_HasChildNodes())
{
continue;
}
}
SharedPtr<Node> newNode = importer->ImportNode(srcNode, true);
dstStory->InsertAfter(newNode, insertionDestination);
insertionDestination = newNode;
}
}
}
else
{
throw System::ArgumentException(u"The destination node must be either a paragraph or table.");
}
}

◆ Replace() [3/4]

int32_t Aspose::Words::Range::Replace ( System::String  pattern,
System::String  replacement 
)

Replaces all occurrences of a specified character string pattern with a replacement string.

The pattern will not be used as regular expression. Please use Replace() if you need regular expressions.

Used case-insensitive comparison.

Method is able to process breaks in both pattern and replacement strings.

You should use special meta-characters if you need to work with breaks:

  • %&p - paragraph break
  • %&b - section break
  • %&m - page break
  • %&l - manual line break
Parameters
patternA string to be replaced.
replacementA string to replace all occurrences of pattern.
Returns
The number of replacements made.
Examples

Shows how to perform a find-and-replace text operation on the contents of a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Greetings, _FullName_!");
// Perform a find-and-replace operation on our document's contents and verify the number of replacements that took place.
int replacementCount = doc->get_Range()->Replace(u"_FullName_", u"John Doe");
ASSERT_EQ(1, replacementCount);
ASSERT_EQ(u"Greetings, John Doe!", doc->GetText().Trim());

Shows how to add formatting to paragraphs in which a find-and-replace operation has found matches.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Every paragraph that ends with a full stop like this one will be right aligned.");
builder->Writeln(u"This one will not!");
builder->Write(u"This one also will.");
SharedPtr<ParagraphCollection> paragraphs = doc->get_FirstSection()->get_Body()->get_Paragraphs();
ASSERT_EQ(ParagraphAlignment::Left, paragraphs->idx_get(0)->get_ParagraphFormat()->get_Alignment());
ASSERT_EQ(ParagraphAlignment::Left, paragraphs->idx_get(1)->get_ParagraphFormat()->get_Alignment());
ASSERT_EQ(ParagraphAlignment::Left, paragraphs->idx_get(2)->get_ParagraphFormat()->get_Alignment());
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
auto options = MakeObject<FindReplaceOptions>();
// Set the "Alignment" property to "ParagraphAlignment.Right" to right-align every paragraph
// that contains a match that the find-and-replace operation finds.
options->get_ApplyParagraphFormat()->set_Alignment(ParagraphAlignment::Right);
// Replace every full stop that is right before a paragraph break with an exclamation point.
int count = doc->get_Range()->Replace(u".&p", u"!&p", options);
ASSERT_EQ(2, count);
ASSERT_EQ(ParagraphAlignment::Right, paragraphs->idx_get(0)->get_ParagraphFormat()->get_Alignment());
ASSERT_EQ(ParagraphAlignment::Left, paragraphs->idx_get(1)->get_ParagraphFormat()->get_Alignment());
ASSERT_EQ(ParagraphAlignment::Right, paragraphs->idx_get(2)->get_ParagraphFormat()->get_Alignment());
ASSERT_EQ(String(u"Every paragraph that ends with a full stop like this one will be right aligned!\r") + u"This one will not!\r" +
u"This one also will!",
doc->GetText().Trim());

◆ Replace() [4/4]

int32_t Aspose::Words::Range::Replace ( System::String  pattern,
System::String  replacement,
System::SharedPtr< Aspose::Words::Replacing::FindReplaceOptions options 
)

Replaces all occurrences of a specified character string pattern with a replacement string.

The pattern will not be used as regular expression. Please use Replace() if you need regular expressions.

Method is able to process breaks in both pattern and replacement strings.

You should use special meta-characters if you need to work with breaks:

  • %&p - paragraph break
  • %&b - section break
  • %&m - page break
  • %&l - manual line break
  • %&& - & character
Parameters
patternA string to be replaced.
replacementA string to replace all occurrences of pattern.
optionsFindReplaceOptions object to specify additional options.
Returns
The number of replacements made.
Examples

Shows how to replace text in a document's footer.

auto doc = MakeObject<Document>(MyDir + u"Footer.docx");
SharedPtr<HeaderFooterCollection> headersFooters = doc->get_FirstSection()->get_HeadersFooters();
SharedPtr<HeaderFooter> footer = headersFooters->idx_get(HeaderFooterType::FooterPrimary);
auto options = MakeObject<FindReplaceOptions>();
options->set_MatchCase(false);
options->set_FindWholeWordsOnly(false);
int currentYear = System::DateTime::get_Now().get_Year();
footer->get_Range()->Replace(u"(C) 2006 Aspose Pty Ltd.", String::Format(u"Copyright (C) {0} by Aspose Pty Ltd.", currentYear), options);
doc->Save(ArtifactsDir + u"HeaderFooter.ReplaceText.docx");

Shows how to toggle case sensitivity when performing a find-and-replace operation.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Ruby bought a ruby necklace.");
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
auto options = MakeObject<FindReplaceOptions>();
// Set the "MatchCase" flag to "true" to apply case sensitivity while finding strings to replace.
// Set the "MatchCase" flag to "false" to ignore character case while searching for text to replace.
options->set_MatchCase(matchCase);
doc->get_Range()->Replace(u"Ruby", u"Jade", options);
ASSERT_EQ(matchCase ? String(u"Jade bought a ruby necklace.") : String(u"Jade bought a Jade necklace."), doc->GetText().Trim());

Shows how to toggle standalone word-only find-and-replace operations.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Jackson will meet you in Jacksonville.");
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
auto options = MakeObject<FindReplaceOptions>();
// Set the "FindWholeWordsOnly" flag to "true" to replace the found text if it is not a part of another word.
// Set the "FindWholeWordsOnly" flag to "false" to replace all text regardless of its surroundings.
options->set_FindWholeWordsOnly(findWholeWordsOnly);
doc->get_Range()->Replace(u"Jackson", u"Louis", options);
ASSERT_EQ(findWholeWordsOnly ? String(u"Louis will meet you in Jacksonville.") : String(u"Louis will meet you in Louisville."), doc->GetText().Trim());

Shows how to replace all instances of String of text in a table and cell.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->Write(u"Carrots");
builder->InsertCell();
builder->Write(u"50");
builder->EndRow();
builder->InsertCell();
builder->Write(u"Potatoes");
builder->InsertCell();
builder->Write(u"50");
builder->EndTable();
auto options = MakeObject<FindReplaceOptions>();
options->set_MatchCase(true);
options->set_FindWholeWordsOnly(true);
// Perform a find-and-replace operation on an entire table.
table->get_Range()->Replace(u"Carrots", u"Eggs", options);
// Perform a find-and-replace operation on the last cell of the last row of the table.
table->get_LastRow()->get_LastCell()->get_Range()->Replace(u"50", u"20", options);
ASSERT_EQ(String(u"Eggs\a50\a\a") + u"Potatoes\a20\a\a", table->GetText().Trim());

◆ ToDocument()

System::SharedPtr<Aspose::Words::Document> Aspose::Words::Range::ToDocument ( )

Constructs a new fully formed document that contains the range.

◆ Type()

static const System::TypeInfo& Aspose::Words::Range::Type ( )
static

◆ UnlinkFields()

void Aspose::Words::Range::UnlinkFields ( )

Unlinks fields in this range.

Replaces all the fields in this range with their most recent results.

To unlink fields in the whole document use UnlinkFields.

Examples

Shows how to unlink all fields in a range.

auto doc = MakeObject<Document>(MyDir + u"Linked fields.docx");
auto newSection = System::DynamicCast<Section>(doc->get_Sections()->idx_get(0)->Clone(true));
doc->get_Sections()->Add(newSection);
doc->get_Sections()->idx_get(1)->get_Range()->UnlinkFields();

◆ UpdateFields()

void Aspose::Words::Range::UpdateFields ( )

Updates the values of document fields in this range.

When you open, modify and then save a document, Aspose.Words does not update fields automatically, it keeps them intact. Therefore, you would usually want to call this method before saving if you have modified the document programmatically and want to make sure the proper (calculated) field values appear in the saved document.

There is no need to update fields after executing a mail merge because mail merge is a kind of field update and automatically updates all fields in the document.

This method does not update all field types. For the detailed list of supported field types, see the Programmers Guide.

This method does not update fields that are related to the page layout algorithms (e.g. PAGE, PAGES, PAGEREF). The page layout-related fields are updated when you render a document or call UpdatePageLayout.

To update fields in the whole document use UpdateFields.

Examples

Shows how to update all the fields in a range.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->InsertField(u" DOCPROPERTY Category");
builder->InsertBreak(BreakType::SectionBreakEvenPage);
builder->InsertField(u" DOCPROPERTY Category");
// The above DOCPROPERTY fields will display the value of this built-in document property.
doc->get_BuiltInDocumentProperties()->set_Category(u"MyCategory");
// If we update the value of a document property, we will need to update all the DOCPROPERTY fields to display it.
ASSERT_EQ(String::Empty, doc->get_Range()->get_Fields()->idx_get(0)->get_Result());
ASSERT_EQ(String::Empty, doc->get_Range()->get_Fields()->idx_get(1)->get_Result());
// Update all the fields that are in the range of the first section.
doc->get_FirstSection()->get_Range()->UpdateFields();
ASSERT_EQ(u"MyCategory", doc->get_Range()->get_Fields()->idx_get(0)->get_Result());
ASSERT_EQ(String::Empty, doc->get_Range()->get_Fields()->idx_get(1)->get_Result());