We present spectroscopy of the ejecta of SN 1987A in 2017 and 2018 from the Hubble Space Telescope and the Very Large Telescope, covering the wavelength range between 1150 and 10000 Å. At 31 years, this is the first epoch with coverage over the ultraviolet-to-near-infrared range since 1995. We create velocity maps of the ejecta in the Hα, Mg ii λλ2796, 2804 and [O i] λλ6302, 6366 (vacuum) emission lines and study their morphology. All three lines have a similar morphology, but Mg ii is blueshifted by ∼1000 km s −1 relative to the others and stronger in the northwest. We also study the evolution of the line fluxes, finding a brightening by a factor of ∼9 since 1999 in Mg ii, while the other line fluxes are similar in 1999 and 2018. We discuss implications for the power sources of emission lines at late times: thermal excitation due to heating by the X-rays from the ejecta-ring interaction is found to dominate the ultraviolet Mg ii lines, while the infrared Mg ii doublet is powered mainly by Lyα fluorescence. The X-ray deposition is calculated based on merger models of SN 1987A. Far-ultraviolet emission lines of H 2 are not detected. Finally, we examine the combined spectrum of recently-discovered hotspots outside the equatorial ring. Their unresolved Balmer emission lines close to zero velocity are consistent with the interaction of fast ejecta and a clumpy, slowly moving outflow. A clump of emission in this spectrum, south of the equatorial ring at ∼1500 km s −1 , is likely associated with the reverse shock.