Mary and Joseph were engaged when Mary found out that she had conceived a son through the Holy Spirit. The couple had not had sex as they were not yet married. It would have been a very big shock for Mary to find out that she was pregnant.
Matthew describes Joseph as a righteous man because he planned to break off the engagement privately rather than expose Mary to public disgrace. This could also potentially save her life, as pre-marital and extra-marital sex was punishable by death.
However, Joseph had a dream in which the angel of the Lord told him to take Mary as his wife because the child she had conceived was from the Holy Spirit. The angel told Joseph that the child was to be called Emmanuel, which means ‘God is with us’.
Joseph took Mary as his wife, but he did not have any sexual relations with her until after Jesus was born in order to fulfil Isaiah’s prophesy of a virgin birth. Isaiah had said, “A virgin will become pregnant and have a son, and he will be called Immanuel.”