I have an old laptop, a 2014 MacBook Pro, which I use with an external display connected by an HDMI-to-DVI cable. The trouble comes when I leave the machine connected for a long time and it goes to sleep. (Full sleep, not display sleep.)
Sometimes, waking the machine while it's connected to the external display causes the computer to hang; it shows a black screen on the external and laptop displays and I can't use it. I have to force-restart the machine to be able to use the computer again.
I don't really want to have to keep restarting my computer because of this, so I'd like to prevent all sleep (including display sleep) while the computer is connected to an external display. However, I also use the computer on power adapter without the external display, and on battery. I'd like it to go to sleep normally in those cases.
Is there an automated way to make this happen?
Note: The machine is running macOS Sierra (10.12), so any solution must run on that OS.