Improve code completion, again

this is kinda tricky but I think I now have a correct implementation (have been using it the whole day without noticing a quirck)