Obtain the Currently Selected Element Using the Author API
Question
In Author mode, if an element is fully selected, I want to perform an action on it. If not, I want to perform an action on the node that is located at the cursor position. Is this possible via the API?
Answer
When an element is fully selected by the user the selection start and end offsets
are
actually outside of the node's offset bounds. So using
AuthorDocumentController.getNodeAtOffset
will actually return the
parent of the selected node. We have some special API that makes it easier for you
to
determine this situation:
WSAuthorEditorPageBase.getFullySelectedNode()
.
AuthorDocumentController controller = authorPageAccess.getDocumentController(); AuthorAccess authorAccess = authorPageAccess.getAuthorAccess(); int caretOffset = authorAccess.getEditorAccess().getCaretOffset(); AuthorElement nodeAtCaret = (AuthorElement) authorAccess.getEditorAccess().getFullySelectedNode(); if (nodeAtCaret == null) { //We have no fully selected node. We can look at the cursor offset. nodeAtCaret = (AuthorElement) authorAccess.getDocumentController().getNodeAtOffset(caretOffset); //Or we could look at the selection start and end, see which node is the parent of each offset and get the closest common ancestor. }