This happens at the time the content is output the browser. At that point, the content is passed through several filters, one of which is called wpautop
. This filter function is defined in wp-includes/formatting.php
. In combination with the other default WordPress filters, this generally means that you can compose content in the HTML (non-wysiwyg) editor as if you were writing plain text, and it will format the final HTML output in a logical, intuitive manner.
On the other hand, you can also feel free to manually compose HTML tags in your output, and WP will preserve your tags. There are some edge-cases that can get you sometimes (using non-standard tags or attributes), but for the most part, the editor and the filters are pretty smart.