I always cook pasta with the lid of the pot open, because otherwise foam starts to build up and eventually boils over, maikng a huge mess. I would prefer to keep the lid on for energy saving purposes. Is this possible at all? What makes the foam build up, why does it not when the lid is open?
Use the pasta cooking techniques in this answer: Pasta: is simmering equivalent to roiling boil?
Bring just enough water to cover the pasta to a boil, put the lid on and let it sit.
Use less water, less energy, and it can't boil over if it's not boiling.
You can use a larger pot. I always use my 12 qt stock pot to boil pasta in. I fill it anywhere from 1/3 to 2/3 full and have no problems with boil over. I too always use it with the lid on. Granted, you're going to use more energy to heat a larger quantity of water, but meh. I'd bet that your refrigerator and A/C use gobs more energy than your range.
As to why it happens? I'm speculating here, but maybe it's the back pressure on the foam bubbles when the lid is on. With the lid off the bubbles can expand rapidly, and break. With the lid on, there is slight back pressure which could restrict the bubbles ability to expand as quickly.
You can use a boil over preventer, also known as a milk watcher, among other things. It's a disk with a raised edge and a notch at one side, which you place at the bottom of the pot. It works by collecting a lot of the bubbles from the bottom underneath, enclosed by the raised edge, and releasing them as fewer, larger bubbles through the notch, so that they don't cause the foam that leads to boiling over.
Cooking pasta without boiling over is very simple if you have a simple little piece of "pottery" called "Boil Master". I bought this in a shop somewhere when we were traveling. It is approx. 2" in Dia. and Approx. 1/2" thick. The little card that came with it said it was called "Boil Master" and was made in New Mexico by Mountain High Pottery. I have not been able to find the company or the product. It works like magic every time. It has never boiled over and I have used it for years.
If the only reason you put the lid on your cooker is to save energy, then I'd recommend just not putting the lid on. You're not "saving" anything. Your burner will be running the entire time you are cooking, lid on or off. Furthermore, regardless of whether the lid is on or off, you will be cooking your pasta at the same temperature -- 100 deg (C).