If your rear derailleur is shifting poorly, not staying in gear, and appears to be bent or out of alignment, check first whether the derailleur hanger is bent.
The derailleur hanger is the piece of metal that the rear derailleur attaches to near the rear axle. On most bikes, this is a replaceable piece of aluminum which is designed to bend or break when stressed rather than causing costly damage to your frame.
Typically the derailleur hanger is supposed to be at right angles to the rear axle when seen from behind. Any deviation from this line will cause your shifting will be “off,” because the chain will be pulled through the pulley wheels at an angle.
Because the piece is designed to break, bending it back “straight” will stress it further, probably causing it to snap. If possible, live with it until the ride is over and you can get it replaced. Fiddling with the High and Low swing adjustment screws on the derailleur may allow you to stay in gear, but the chain will still have a tendency to skip.
If the chain skips really badly, you can try to bend the hanger back. Grab the derailleur body (not the pulley wheels) and apply firm, constant pressure to bend it in the required direction.
An alternative is to remove the derailleur with a 5mm Allen wrench, and then use an adjustable crescent wrench to apply leverage to the hanger. Be careful not to damage the threads in the hanger with the edges of the wrench.
Be prepared for the hanger to break when you do this. If it does, follow the instructions for a broken rear derailleur.
Even if you do manage to bend the hanger straight, it may retain a lateral (front-to-rear) twist, which will still keep it from shifting perfectly.
Once you get back home, buy a new hanger. The stresses of being bent and bent back mean that your current one is weak and could disintegrate at any time. Better still, buy two and carry one with you on your rides.