move scanner reference counter to erlang process

I squashed all commits together so that I could rebase it more easily.

All tests are passing, but there are currently errors - for example the outline shows nothing. Will fix those tomorrow, but a review of the existing code doesn't hurt.