Why is it "Here you are!" but "Here comes the teacher." ? I'm quite confused. When should I use inversion?
"Here" in both contexts is simply the present location of the person making the statement. Some examples:
If I'm standing in the kitchen and I say "The kitchen is here", I'm simply saying that where I am is same location as the kitchen.
If I stand next to my brother and say "My brother is here" or even "Here is my brother!", I'm simply saying that my brother is in the same general location as I am.
If my wife and I are looking for my car keys, and I exclaim "Here they are!", I'm simply indicating that I've found the car keys in the location that I'm presently in.
If I then tell my wife "Come over here.", I'm simply telling my wife to move from her location and come to my current location. As she is approaching me, I could say "Here comes my wife.", which is simply indicating that she is in the process of moving to my present location.
The meaning of here is the same in all of these situations. Note however that "Here" can be relative in terms of the scope of the location. I could say "Here in Canada, we like to eat cheese." Again, the meaning of "Here" is the same, it is my present location, but I'm specifying the scope of my location to my country. I could define this scope to whatever I like.
"Here, on planet Earth, we need water."
"Here in my town, we don't like potholes."
"The Pan Am games are coming here."
When you use here as an adverb of place at the start of a sentence and the subject is a personal pronoun, there's no inversion; we don't invert with a pronoun. For examples:
Here he comes.
Here they are.
Here it is.
On the other hand, if the subject is a noun, there's an inversion.
Here comes the bus.
Here comes the teacher.
Here is Adam.