  Non-local thermodynamical equilibrium (NLTE) line formation for Mg I and Mg
II lines is considered in classical 1D-LTE model atmospheres of the Sun and 17
stars with reliable atmospheric parameters and in a broad range of spectral
types: 3900 $\le$ \Teff\ $\le$ 17500~K, 1.1 $\le$ log$g$ $\le$ 4.7, and $-$2.6
$\le$ [Fe/H] $\le$ +0.4.
  We find that, for each star, NLTE leads to smaller line-to-line scatter. For
10 stars, NLTE leads to consistent abundances from Mg I and Mg II, while the
difference in the LTE abundance varies between $-0.21$ and +0.23~dex. We obtain
an abundance discrepancy betweeen Mg I and Mg II in the two very metal-poor
stars, HD 140283 and HD 84937. An origin of these abundance differences remains
unclear.
  Our standard NLTE modelling predicts Mg I emission lines at 7.736, 11.789,
12.224, and 12.321 $\mu$m in the atmospheres with \Teff\ $\le$ 7000 K. We
reproduce well the Mg I 12.2 and 12.3 $\mu$m emission lines in Procyon.
However, for the Sun and 3 K-giants, the predicted Mg I emission lines are too
weak compared with the observations.
  For stars with 7000 K $\le$ \Teff\ $\leq$ 17500 K, we recommend the Mg II
3848, 3850, 4384, 4390, 4427, and 4433 \AA\ lines for Mg abundance
determinations even at the LTE assumption due to their small NLTE effects. The
Mg I 4167, 4571, 4702, 5528, 5167, 5172, and 5183 \AA\ lines can be safely used
in the LTE analysis of stars with 7000 K $<$ \Teff\ $\leq$ 8000 K. For the
hotter stars, with \Teff\ from 8000 to 9500 K, the NLTE effects are minor only
for Mg\ione\ 4167, 4702, and 4528 \AA.
