Cyanobacteria forming one-dimensional filaments are paradigmatic model organisms of the transition between unicellular and multicellular living forms. Under nitrogen limiting conditions, in filaments of the genus Anabaena, some cells differentiate into heterocysts, which lose the possibility to divide but are able to fix environmental nitrogen for the colony. These heterocysts form a quasi-regular pattern in the filament, representing a prototype of patterning and morphogenesis in prokaryotes. Recent years have seen advances in the identification of the molecular mechanism regulating this pattern. We use this data to build a theory on heterocyst pattern formation, for which both genetic regulation and the effects of cell division and filament growth are key components. The theory is based on the interplay of three generic mechanisms: local autoactivation, early long range inhibition, and late long range inhibition. These mechanisms can be identified with the dynamics of hetR, patS and hetN expression. Our theory reproduces quantitatively the experimental dynamics of pattern formation and maintenance for wild type and mutants. We find that hetN alone is not enough to play the role as the late inhibitory mechanism: a second mechanism, hypothetically the products of nitrogen fixation supplied by heterocysts, must also play a role in late long range inhibition. The preponderance of even intervals between heterocysts arises naturally as a result of the interplay between the timescales of genetic regulation and cell division. We also find that a purely stochastic initiation of the pattern, without a two-stage process, is enough to reproduce experimental observations.