Contact planning is crucial to the locomotion performance of limbless robots. Typically; the pattern by which contact is made and broken between the mechanism and its environment determines the motion of the robot. The design of these patterns; often called contact patterns; is a difficult problem. In previous work; the prescription of contact patterns was derived from observations of biological systems or determined empirically from black-box optimization algorithms. However; such heuristic-based contact pattern prescription is only applicable to specific mechanisms; and is challenging to generalize. For example; the stable and effective contact pattern prescribed for a 12-link limbless robot can be neither stable nor effective for a 6-link limbless robot. In this paper; using a geometric motion planning scheme; we develop a framework to design; optimize; and analyze contact patterns to generate effective motion in the desired directions. Inspired by prior work in geometric mechanics; we separate the configuration space into a shape space (the internal joint angles); a contact state space; and a position space; then we optimize the function that couples the contact state space and the shape space. Our framework provides physical insights into the contact pattern design and reveals principles of empirically derived contact pattern prescriptions. Applying this framework; we can not only control the direction of motion of a 12-link limbless robot by modulating the contact patterns; but also design effective sidewinding gaits for robots with fewer motors (e.g.; a 6-link robot). We test our designed gaits by robophysical experiments and obtain excellent agreement. We expect our scheme can be broadly applicable to robots which make/break contact.