Context. Molecular hydrogen (H 2 ) is the main constituent of the gas in the planet-forming disks that surround many pre-mainsequence stars. H 2 can be incorporated in the atmosphere of the nascent giant planets in disks. Deuterium hydride (HD) has been detected in a few disks and can be considered the most reliable tracer of H 2 , provided that its abundance throughout the disks with respect to H 2 is well understood. Aims. We wish to form H 2 and HD efficiently for the varied conditions encountered in protoplanetary disks: the densities vary from 10 4 to 10 16 cm´3; the dust temperatures range from 5 to 1500 K, the gas temperatures go from 5 to a few 1000 Kelvin, and the ultraviolet field can be10 7 stronger than the standard interstellar field. Methods. We implemented a comprehensive model of H 2 and HD formation on cold and warm grain surfaces and via hydrogenated polycyclic aromatic hydrocarbons in the physico-chemical code ProDiMo (PROtoplanetary DIsk MOdel). The H 2 and HD formation on dust grains can proceed via the Langmuir-Hinshelwood and Eley-Ridel mechanisms for physisorbed or chemisorbed H (D) atoms. H 2 and HD also form by H (D) abstraction from hydrogenated neutral and ionised PAHs and via gas phase reactions. Results. H 2 and HD are formed efficiently on dust grain surfaces from 10 to " 700 K. All the deuterium is converted into HD in UV shielded regions as soon as H 2 is formed by gas-phase D abstraction reactions. The detailed model compares well with standard analytical prescriptions for H 2 (HD) formation. At low temperature, H 2 is formed from the encounter of two physisorbed atoms. HD molecules form on the grain surfaces and in the gas-phase. At temperatures greater than 20 K, the meeting between a weakly bound H-(or D-) atom or a gas-phase H (D) atom and a chemisorbed atom is the most efficient H 2 formation route. H 2 formation through hydrogenated PAHs alone is efficient above 80 K. However, the contribution of hydrogenated PAHs to the overall H 2 and HD formation is relatively low if chemisorption on silicate is taken into account and if a small hydrogen abstraction cross-section is used. The H 2 and HD warm grain surface network is a first step in the construction of a network of high-temperature surface reactions.