Hierarchically porous carbons are attracting tremendous attention in sustainable energy systems, such as lithium ion battery (LIB) and fuel cell, due to their excellent transport properties that arise from the high surface area and rich porosity. The state-of-the-art approaches for synthesizing hierarchically porous carbons normally require chemical- and/or template-assisted activation techniques, which is complicate, time consuming, and not feasible for large scale production. Here, a molecular-level design principle toward large-scale synthesis of nitrogen and phosphorus codoped hierarchically porous carbon (NPHPC) through an in situ self-activation process is proposed. The material is fabricated based on the direct pyrolysis of a well-designed polymer, melamine polyphosphate, which is capable of in situ self-activation to generate large specific surface area (1479 m2 g−1) and hierarchical pores in the final NPHPC. As an anode material for LIB, NPHPC delivers a high reversible capacity of 1073 mAh g−1 and an excellent cyclic stability for 300 cycles with negligible capacity decay. The peculiar structural properties and synergistic effect of N and P codopants also enable NPHPC a promising electrocatalyst for oxygen reduction reaction, a key cathodic reaction process of many energy conversion devices (for example, fuel cells and metal air batteries). Electrochemical measurements show NPHPC a comparable electrocatalytic performance to commercial Pt/C catalyst (onset potential of 0.88 V vs reversible hydrogen electrode in alkaline medium) with excellent stability (89.8% retention after 20 000 s continuous operation) and superior methanol tolerance.