HIGHLIGHTS• An in situ molecular foaming and activation strategy is designed and investigated for the synthesis of hierarchically porous N-doped carbon foams (HPNCFs).• The prepared HPNCFs possess 3D macropores, uniform micropores and mesopores, ultrahigh surface areas and high N contents and show high performances in supercapacitors and CO 2 capture.ABSTRACT Hierarchically porous carbon materials are promising for energy storage, separation and catalysis. It is desirable but fairly challenging to simultaneously create ultrahigh surface areas, large pore volumes and high N contents in these materials. Herein, we demonstrate a facile acid-base enabled in situ molecular foaming and activation strategy for the synthesis of hierarchically macro-/meso-/microporous N-doped carbon foams (HPNCFs). The key design for the synthesis is the selection of histidine (His) and potassium bicarbonate (PBC) to allow the formation of 3D foam structures by in situ foaming, the PBC/His acid-base reaction to enable a molecular mixing and subsequent a uniform chemical activation, and the stable imidazole moiety in His to sustain high N contents after carbonization. The formation mechanism of the HPNCFs is studied in detail. The prepared HPNCFs possess 3D macroporous frameworks with thin well-graphitized carbon walls, ultrahigh surface areas (up to 3200 m 2 g −1 ), large pore volumes (up to 2.0 cm 3 g −1 ), high micropore volumes (up to 0.67 cm 3 g −1 ), narrowly distributed micropores and mesopores and high N contents (up to 14.6 wt%) with pyrrolic N as the predominant N site. The HPNCFs are promising for supercapacitors with high specific capacitances (185-240 F g −1 ), good rate capability and excellent stability. They are also excellent for CO 2 capture with a high adsorption capacity (~ 4.13 mmol g −1 ), a large isosteric heat of adsorption (26.5 kJ mol −1 ) and an excellent CO 2 /N 2 selectivity (~ 24). on the two isotherms wherein the adsorption capacities are the same.