How to detect last node is selected. and create a new line after selectionu

I need to wrapIn the selection with a type node, and if it is the last node, then create a new line after it. It make easier to leave(blur) the node with mouse or arrow keyboard