Drug-fuelled Kevin Gartland twice discharged a sawn-off pump action shotgun at the room where Robyn Murtagh had been sleeping.
The frightened victim of the shooting was awakened by a loud bang and saw glass on the floor before a second shot rang out seconds later during the early morning terror.
The court heard Gartland, who accused his ex of cheating, sent her a text before the attack saying: “I have nothing to lose now. No one gets away with playing with my emotions like this. I promise.”
The victim had been “very unnerved” by the incident and his behaviour.
But Lord Jones said he had read a letter she had written on his behalf and it appeared she had overcome the incident.
The judge ordered that Gartland be kept under supervision for a further two-year period.
Gartland, 24, had previously sent his a text message stating: “I have nothing to lose now. No one gets away with playing with my emotions like this. I promise.”
Defence solicitor advocate Cameron Tait said Gartland now accepted his behaviour was “reckless and dangerous in the extreme”.
He said: “He had been taking cocaine consistently for three days.”
Broken glass was all over the floor of the bedroom at Miss Murtagh’s flat in Gilmerton Dykes Avenue and on her bed following the shooting.
Miss Murtagh, 24, rolled out of the bed and crawled through to the hall before hearing Gartland make his getaway on a motorbike.
Gartland was later detained by armed police and the gun was found after he handed over a diagram to a visitor in Edinburgh’s Saughton prison of where he had disposed of the weapon.
Unemployed Gartland earlier admitted endangering the life of his former girlfriend by culpably and recklessly discharging a shotgun at a bedroom window of her home on July 13 this year.
He also pleaded guilty to having a prohibited weapon and having a firearm after being sentenced to five years detention by a judge in 2008.
Gartland, of Lower Granton Road, Edinburgh, has twice been jailed for offences of serious violence.
Miss Murtagh had decided to finish the relationship and on July 8 sent him a text. Gartland refused to accept it was over and repeatedly sent her messages before using Facebook to accuse her of cheating and send abusive messages.