It seems that your implementation is returning a section even when the bookmark does not contain any section. This could be due to the logic in your TryGetSectionInBookmark function, which traverses the nodes in a pre-order manner and checks for the NodeType::Section.
To ensure that you only return a section if it is indeed part of the bookmark, you might want to adjust your logic. Here’s a revised version of your function that checks if the bookmark’s start and end nodes are within the same section:
SharedPtr<Section> TryGetSectionInBookmark(const SharedPtr<Document>& currentDocument, const SmartPtr<Bookmark>& bookmark)
{
SmartPtr bookmarkStart{ bookmark->get_BookmarkStart() };
SmartPtr bookmarkEnd{ bookmark->get_BookmarkEnd() };
// Ensure both bookmark start and end are not null
if (bookmarkStart == nullptr || bookmarkEnd == nullptr)
{
return nullptr;
}
// Get the parent sections of the bookmark start and end
SmartPtr<Node> startSection = bookmarkStart->get_ParentNode()->get_Ancestor(NodeType::Section);
SmartPtr<Node> endSection = bookmarkEnd->get_ParentNode()->get_Ancestor(NodeType::Section);
// Check if both bookmark start and end are in the same section
if (startSection != nullptr && startSection == endSection)
{
return System::Cast<Section>(startSection);
}
return nullptr;
}
In this revised version, the function first checks if both the bookmark start and end nodes are valid. Then, it retrieves the parent sections of both nodes and compares them. If they belong to the same section, it returns that section; otherwise, it returns nullptr.
This should help ensure that you only get a section if the bookmark is indeed contained within it. If you continue to experience issues, consider debugging the node traversal to ensure that the correct nodes are being evaluated.